From 02b741239f927f0feee4c13a968c2ca851a4a2a4 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Tue, 28 Jul 2026 11:09:06 -0400 Subject: [PATCH 01/11] Retro console emulation Adds retro console support alongside the existing Wine/PC library: NES, SNES, Game Boy / Color / Advance, Genesis, Master System, Game Gear, N64, PlayStation, PlayStation 2 and GameCube / Wii. Retro games live in the same Library and launch like PC games, but run on a libretro backend, on ARMSX2 in a separate :ps2 process, or on an embedded standalone Dolphin in :gc. No core ships in the APK. Each emulator is built from its own fork under the WinNative-Emu org, WinNative-Emu/Retro-Consoles packs every core plus the Dolphin and ARMSX2 runtime data into one retro-consoles.tzst, and the app downloads and SHA-256-verifies it from Settings > Retro. The forks rebuild every Friday at 17:00 ET and the bundle is packed at 18:00; both compare against what is already published and release nothing when the output is byte-identical, so a quiet week costs users no download. bundle-info.json carries the tag, build date, checksum and size; the installed copy is the marker file, so the app only offers an update when the published checksum actually differs. Also included: - RetroAchievements via rcheevos, softcore only (hardcore needs per-client registration and is hidden until then) - Per-console core options generated from each core's own source, grouped into Display / Sound / Performance / Controls / System tabs - Touch controls, netplay for the libretro cores and Dolphin, save states, cloud save sync and a performance HUD - 22 locales translated --- .gitattributes | 2 + .github/workflows/pr-ci.yml | 7 +- .github/workflows/tag-apk-artifacts.yml | 7 +- .gitignore | 12 +- .gitmodules | 6 + EMULATOR_CREDITS.md | 67 + README.md | 158 +- app/build.gradle | 4 + app/src/main/AndroidManifest.xml | 20 + app/src/main/app/PluviaApp.kt | 26 +- .../main/app/shell/LibraryGameLaunchScreen.kt | 69 +- app/src/main/app/shell/RetroConsoleRibbon.kt | 72 + app/src/main/app/shell/UnifiedActivity.kt | 72 + .../main/app/shell/UnifiedActivityDrawer.kt | 119 +- .../app/shell/UnifiedActivityGameDialogs.kt | 205 +- app/src/main/app/shell/UnifiedActivityHub.kt | 14 +- .../main/app/shell/UnifiedActivityLaunch.kt | 16 + .../main/app/shell/UnifiedActivityStartup.kt | 1 + .../main/app/shell/UnifiedActivityStores.kt | 6 + app/src/main/assets/dnas/dnas_bypass.json | 514 + app/src/main/assets/retro/GLideN64.custom.ini | 360 + app/src/main/feature/library/GameSettings.kt | 40 +- .../main/feature/retro/DolphinCloudSync.kt | 144 + .../main/feature/retro/DolphinEmbedLaunch.kt | 193 + .../main/feature/retro/DolphinGameOverlay.kt | 628 + .../main/feature/retro/DolphinNetplayUi.kt | 135 + app/src/main/feature/retro/Ps2CheatStaging.kt | 71 + app/src/main/feature/retro/Ps2DnasBypass.kt | 174 + app/src/main/feature/retro/Ps2GameOverlay.kt | 1260 + app/src/main/feature/retro/Ps2IsoSerial.kt | 108 + app/src/main/feature/retro/Ps2MenuScreens.kt | 637 + app/src/main/feature/retro/Ps2RaBridge.kt | 28 + .../feature/retro/RetroAchievementOverlay.kt | 200 + .../retro/RetroAchievementsActivity.kt | 718 + .../feature/retro/RetroAchievementsManager.kt | 401 + app/src/main/feature/retro/RetroActivity.kt | 1900 ++ app/src/main/feature/retro/RetroBiosImport.kt | 95 + app/src/main/feature/retro/RetroBoxart.kt | 357 + app/src/main/feature/retro/RetroBundle.kt | 179 + app/src/main/feature/retro/RetroCheats.kt | 72 + .../main/feature/retro/RetroCheatsActivity.kt | 359 + .../main/feature/retro/RetroControlLayouts.kt | 133 + .../main/feature/retro/RetroControlsMenu.kt | 153 + .../main/feature/retro/RetroCoreCatalog.kt | 3228 +++ .../main/feature/retro/RetroCoreManager.kt | 174 + .../main/feature/retro/RetroCoreOptions.kt | 284 + .../main/feature/retro/RetroCreditsScreen.kt | 130 + app/src/main/feature/retro/RetroDefaults.kt | 165 + .../main/feature/retro/RetroDefaultsScreen.kt | 1010 + app/src/main/feature/retro/RetroDrawerMenu.kt | 1796 ++ app/src/main/feature/retro/RetroGameLink.kt | 142 + .../main/feature/retro/RetroGameSettings.kt | 1979 ++ app/src/main/feature/retro/RetroHddImport.kt | 64 + app/src/main/feature/retro/RetroHudSupport.kt | 459 + app/src/main/feature/retro/RetroInputView.kt | 2517 ++ app/src/main/feature/retro/RetroNetplay.kt | 1198 + .../feature/retro/RetroNetplayEditField.kt | 175 + app/src/main/feature/retro/RetroNetplayUi.kt | 683 + .../main/feature/retro/RetroOnlineSupport.kt | 59 + app/src/main/feature/retro/RetroRomArchive.kt | 117 + app/src/main/feature/retro/RetroRomScanner.kt | 55 + app/src/main/feature/retro/RetroSaveImport.kt | 108 + app/src/main/feature/retro/RetroSaveStates.kt | 227 + .../main/feature/retro/RetroSettingsDialog.kt | 269 + app/src/main/feature/retro/RetroShortcuts.kt | 320 + app/src/main/feature/retro/RetroSystem.kt | 201 + .../feature/settings/nav/SettingsNavGraph.kt | 6 + .../settings/nav/SettingsNavSidebar.kt | 5 + .../ShortcutSettingsComposeDialog.kt | 6 + .../feature/shortcuts/ShortcutsFragment.java | 5 + .../sync/google/GameSaveBackupManager.kt | 42 + .../feature/sync/ui/CloudSavesUIContent.kt | 98 +- .../arm64-v8a/libdolphin_libretro_android.so | 3 + app/src/main/res/values-b+es+419/strings.xml | 796 + app/src/main/res/values-da/strings.xml | 796 + app/src/main/res/values-de/strings.xml | 796 + app/src/main/res/values-es/strings.xml | 796 + app/src/main/res/values-fi/strings.xml | 796 + app/src/main/res/values-fr/strings.xml | 796 + app/src/main/res/values-hi/strings.xml | 796 + app/src/main/res/values-it/strings.xml | 796 + app/src/main/res/values-ja/strings.xml | 796 + app/src/main/res/values-ko/strings.xml | 796 + app/src/main/res/values-no/strings.xml | 796 + app/src/main/res/values-pl/strings.xml | 796 + app/src/main/res/values-pt-rBR/strings.xml | 796 + app/src/main/res/values-pt/strings.xml | 796 + app/src/main/res/values-ro/strings.xml | 796 + app/src/main/res/values-ru/strings.xml | 796 + app/src/main/res/values-sv/strings.xml | 796 + app/src/main/res/values-th/strings.xml | 796 + app/src/main/res/values-tr/strings.xml | 796 + app/src/main/res/values-uk/strings.xml | 796 + app/src/main/res/values-zh-rCN/strings.xml | 796 + app/src/main/res/values-zh-rTW/strings.xml | 796 + app/src/main/res/values/refs.xml | 2 + app/src/main/res/values/strings.xml | 803 + app/src/main/res/values/styles.xml | 10 + app/src/main/res/xml/file_paths.xml | 1 + .../runtime/container/ContainerManager.java | 23 + .../display/XServerDisplayActivity.java | 8 + .../main/runtime/display/XServerDrawerMenu.kt | 65 +- .../main/runtime/display/ui/FrameRating.java | 198 +- .../main/shared/theme/SessionDrawerStyle.kt | 60 + .../ui/settings/SharedSettingsWidgets.kt | 151 + armsx2/AndroidManifest.upstream.xml | 110 + armsx2/UPSTREAM.md | 55 + armsx2/build.gradle | 58 + armsx2/src/main/AndroidManifest.xml | 30 + armsx2/src/main/java/com/armsx2/BiosInfo.kt | 22 + .../src/main/java/com/armsx2/CustomDriver.kt | 312 + armsx2/src/main/java/com/armsx2/EmuState.kt | 9 + armsx2/src/main/java/com/armsx2/GameInfo.kt | 310 + armsx2/src/main/java/com/armsx2/Main.kt | 5 + armsx2/src/main/java/com/armsx2/PatchRepo.kt | 295 + ...RetroAchievementsHostOverrideReceiver.java | 151 + .../src/main/java/com/armsx2/ShaderParams.kt | 166 + armsx2/src/main/java/com/armsx2/ShaderRepo.kt | 361 + .../src/main/java/com/armsx2/WinNativeHost.kt | 29 + .../java/com/armsx2/config/ConfigStore.kt | 216 + .../main/java/com/armsx2/config/Settings.kt | 1724 ++ .../main/java/com/armsx2/events/TestResult.kt | 3 + .../com/armsx2/input/AndroidGyroscopeInput.kt | 151 + .../com/armsx2/input/ControllerMappings.kt | 687 + .../main/java/com/armsx2/input/PadRouter.kt | 40 + .../com/armsx2/runtime/EmulationSurface.kt | 89 + .../com/armsx2/runtime/MainActivityRuntime.kt | 2166 ++ .../main/java/com/armsx2/ui/InGameOverlay.kt | 58 + .../src/main/java/com/armsx2/ui/WindowImpl.kt | 12 + .../ui/achievements/AchievementsViewModel.kt | 37 + .../java/com/armsx2/ui/touch/TouchControls.kt | 667 + .../kr/co/iefriends/pcsx2/AssetFiles.java | 82 + .../kr/co/iefriends/pcsx2/HttpClient.java | 79 + .../java/kr/co/iefriends/pcsx2/NativeApp.java | 452 + .../main/java/org/libsdl/app/HIDDevice.java | 21 + .../app/HIDDeviceBLESteamController.java | 751 + .../java/org/libsdl/app/HIDDeviceManager.java | 697 + .../java/org/libsdl/app/HIDDeviceUSB.java | 313 + armsx2/src/main/java/org/libsdl/app/SDL.java | 90 + .../main/java/org/libsdl/app/SDLActivity.java | 2230 ++ .../java/org/libsdl/app/SDLAudioManager.java | 126 + .../org/libsdl/app/SDLControllerManager.java | 935 + .../java/org/libsdl/app/SDLDummyEdit.java | 66 + .../org/libsdl/app/SDLInputConnection.java | 136 + .../main/java/org/libsdl/app/SDLSurface.java | 449 + .../main/jniLibs/arm64-v8a/libEGL_angle.so | Bin 0 -> 311960 bytes .../main/jniLibs/arm64-v8a/libGLESv2_angle.so | Bin 0 -> 6288024 bytes .../arm64-v8a/libSPIRV-Tools-shared.so | Bin 0 -> 2602856 bytes .../jniLibs/arm64-v8a/liblibrashader_capi.so | Bin 0 -> 10032976 bytes .../jniLibs/arm64-v8a/libshaderc_shared.so | Bin 0 -> 6626216 bytes .../res/drawable/ic_launcher_background.xml | 9 + .../res/drawable/ic_launcher_foreground.xml | 19 + .../main/res/drawable/savetowerforeground.png | Bin 0 -> 661224 bytes .../res/mipmap-anydpi-v26/ic_launcher.xml | 6 + .../mipmap-anydpi-v26/ic_launcher_round.xml | 6 + .../main/res/mipmap-anydpi/ic_launcher.xml | 6 + .../res/mipmap-anydpi/ic_launcher_round.xml | 6 + armsx2/src/main/res/values-night/themes.xml | 13 + armsx2/src/main/res/values/colors.xml | 10 + armsx2/src/main/res/values/strings.xml | 3 + armsx2/src/main/res/values/themes.xml | 13 + armsx2/src/main/res/xml/backup_rules.xml | 13 + .../main/res/xml/data_extraction_rules.xml | 19 + .../main/res/xml/network_security_config.xml | 7 + build.gradle | 1 + cores/DOLPHIN.md | 52 + cores/DOLPHIN_EMBED.md | 210 + cores/DOLPHIN_VULKAN.md | 154 + dolphin/.gitignore | 3 + dolphin/build.gradle | 51 + dolphin/src/main/AndroidManifest.xml | 14 + .../dolphinemu/DolphinApplication.kt | 20 + .../dolphinemu/dolphinemu/NativeLibrary.kt | 166 + .../dolphinemu/overlay/InputOverlayPointer.kt | 9 + .../dolphinemu/dolphinemu/utils/Analytics.kt | 9 + .../utils/DirectoryInitialization.kt | 58 + .../dolphinemu/utils/FileBrowserHelper.kt | 12 + .../dolphinemu/utils/PermissionsHandler.kt | 31 + .../dolphinemu/wn/DolphinConfigWriter.kt | 87 + .../dolphinemu/wn/DolphinEmulationActivity.kt | 630 + .../dolphinemu/dolphinemu/wn/DolphinHost.kt | 14 + .../dolphinemu/wn/DolphinNetplay.kt | 215 + .../src/main/res/values/dolphin_strings.xml | 10 + .../features/cheats/model/ARCheat.kt | 52 + .../features/cheats/model/AbstractCheat.kt | 47 + .../dolphinemu/features/cheats/model/Cheat.kt | 42 + .../features/cheats/model/CheatsViewModel.kt | 207 + .../features/cheats/model/GeckoCheat.kt | 72 + .../features/cheats/model/GraphicsMod.kt | 32 + .../features/cheats/model/GraphicsModGroup.kt | 17 + .../features/cheats/model/PatchCheat.kt | 56 + .../features/cheats/model/ReadOnlyCheat.kt | 31 + .../features/infinitybase/InfinityConfig.kt | 24 + .../features/infinitybase/model/Figure.kt | 11 + .../input/model/ControlGroupEnabledSetting.kt | 25 + .../input/model/ControllerInterface.kt | 214 + .../features/input/model/CoreDevice.kt | 30 + .../input/model/DolphinSensorEventListener.kt | 551 + .../input/model/DolphinVibratorManager.kt | 16 + .../model/DolphinVibratorManagerCompat.kt | 24 + .../DolphinVibratorManagerPassthrough.kt | 16 + .../features/input/model/InputDetector.kt | 68 + .../input/model/InputMappingBooleanSetting.kt | 25 + .../input/model/InputMappingDoubleSetting.kt | 25 + .../input/model/InputMappingIntSetting.kt | 23 + .../features/input/model/InputOverrider.kt | 82 + .../features/input/model/MappingCommon.kt | 13 + .../input/model/controlleremu/Control.kt | 18 + .../input/model/controlleremu/ControlGroup.kt | 59 + .../model/controlleremu/ControlReference.kt | 28 + .../model/controlleremu/EmulatedController.kt | 70 + .../model/controlleremu/NumericSetting.kt | 97 + .../features/netplay/NetplaySession.kt | 448 + .../netplay/model/GameDigestProgress.kt | 16 + .../features/netplay/model/NetplayMessage.kt | 36 + .../features/netplay/model/Player.kt | 15 + .../netplay/model/SaveTransferProgress.kt | 15 + .../features/netplay/model/TraversalState.kt | 20 + .../riivolution/model/RiivolutionPatches.kt | 80 + .../settings/model/AbstractBooleanSetting.kt | 9 + .../settings/model/AbstractFloatSetting.kt | 9 + .../settings/model/AbstractIntSetting.kt | 9 + .../settings/model/AbstractSetting.kt | 10 + .../settings/model/AbstractStringSetting.kt | 9 + .../settings/model/AchievementModel.kt | 32 + .../settings/model/AdHocBooleanSetting.kt | 36 + .../settings/model/AdHocStringSetting.kt | 36 + .../features/settings/model/BooleanSetting.kt | 1040 + .../settings/model/ConfigChangedCallback.kt | 33 + .../features/settings/model/FloatSetting.kt | 45 + .../features/settings/model/IntSetting.kt | 253 + .../features/settings/model/NativeConfig.kt | 107 + .../features/settings/model/PostProcessing.kt | 17 + .../settings/model/ScaledIntSetting.kt | 25 + .../features/settings/model/Settings.kt | 129 + .../features/settings/model/StringSetting.kt | 159 + .../features/skylanders/SkylanderConfig.kt | 28 + .../features/skylanders/model/Skylander.kt | 15 + .../skylanders/model/SkylanderPair.kt | 15 + .../dolphinemu/dolphinemu/model/GameFile.kt | 80 + .../dolphinemu/model/GameFileCache.kt | 102 + .../dolphinemu/services/USBPermService.kt | 15 + .../dolphinemu/dolphinemu/utils/AudioUtils.kt | 28 + .../dolphinemu/utils/BooleanSupplier.kt | 16 + .../dolphinemu/utils/CompressCallback.kt | 10 + .../dolphinemu/utils/ContentHandler.kt | 331 + .../dolphinemu/dolphinemu/utils/GCAdapter.kt | 235 + .../org/dolphinemu/dolphinemu/utils/Log.kt | 49 + .../dolphinemu/utils/NetworkHelper.kt | 83 + .../dolphinemu/utils/RateLimiter.kt | 32 + .../dolphinemu/utils/WiiUpdateCallback.kt | 10 + .../dolphinemu/utils/WiimoteAdapter.kt | 153 + gradle/libs.versions.toml | 10 + libretrodroid/.gitignore | 1 + libretrodroid/build.gradle | 56 + libretrodroid/consumer-rules.pro | 0 libretrodroid/proguard-rules.pro | 21 + libretrodroid/src/main/AndroidManifest.xml | 4 + libretrodroid/src/main/cpp/CMakeLists.txt | 175 + libretrodroid/src/main/cpp/SGSR_LICENSE | 29 + libretrodroid/src/main/cpp/audio.cpp | 171 + libretrodroid/src/main/cpp/audio.h | 96 + libretrodroid/src/main/cpp/core.cpp | 80 + libretrodroid/src/main/cpp/core.h | 67 + libretrodroid/src/main/cpp/environment.cpp | 507 + libretrodroid/src/main/cpp/environment.h | 173 + libretrodroid/src/main/cpp/errorcodes.cpp | 30 + libretrodroid/src/main/cpp/errorcodes.h | 30 + libretrodroid/src/main/cpp/fpssync.cpp | 77 + libretrodroid/src/main/cpp/fpssync.h | 57 + libretrodroid/src/main/cpp/immersivemode.cpp | 286 + libretrodroid/src/main/cpp/immersivemode.h | 200 + libretrodroid/src/main/cpp/input.cpp | 241 + libretrodroid/src/main/cpp/input.h | 73 + .../libchdr/deps/lzma-25.01/Asm/arm64/7zAsm.S | 181 + .../deps/lzma-25.01/Asm/arm64/LzmaDecOpt.S | 1487 + .../libchdr/deps/lzma-25.01/Asm/x86/7zAsm.asm | 341 + .../deps/lzma-25.01/Asm/x86/LzmaDecOpt.asm | 1339 + .../libchdr/deps/lzma-25.01/CMakeLists.txt | 29 + .../main/cpp/libchdr/deps/lzma-25.01/LICENSE | 3 + .../libchdr/deps/lzma-25.01/include/LzmaDec.h | 13 + .../deps/lzma-25.01/include/real/7zTypes.h | 597 + .../deps/lzma-25.01/include/real/LzmaDec.h | 237 + .../cpp/libchdr/deps/lzma-25.01/src/LzmaDec.c | 2 + .../deps/lzma-25.01/src/real/LzmaDec.c | 1361 + .../libchdr/deps/zstd-1.5.7/CMakeLists.txt | 7 + .../main/cpp/libchdr/deps/zstd-1.5.7/zstd.h | 3198 +++ .../cpp/libchdr/deps/zstd-1.5.7/zstd_errors.h | 107 + .../cpp/libchdr/deps/zstd-1.5.7/zstddeclib.c | 23644 ++++++++++++++++ .../cpp/libchdr/include/dr_libs/dr_flac.h | 11793 ++++++++ .../cpp/libchdr/include/libchdr/bitstream.h | 43 + .../main/cpp/libchdr/include/libchdr/cdrom.h | 119 + .../main/cpp/libchdr/include/libchdr/chd.h | 430 + .../cpp/libchdr/include/libchdr/chdconfig.h | 18 + .../cpp/libchdr/include/libchdr/codec_cdfl.h | 28 + .../cpp/libchdr/include/libchdr/codec_cdlz.h | 27 + .../cpp/libchdr/include/libchdr/codec_cdzl.h | 26 + .../cpp/libchdr/include/libchdr/codec_cdzs.h | 26 + .../cpp/libchdr/include/libchdr/codec_flac.h | 22 + .../cpp/libchdr/include/libchdr/codec_huff.h | 22 + .../cpp/libchdr/include/libchdr/codec_lzma.h | 35 + .../cpp/libchdr/include/libchdr/codec_zlib.h | 36 + .../cpp/libchdr/include/libchdr/codec_zstd.h | 27 + .../cpp/libchdr/include/libchdr/coretypes.h | 71 + .../main/cpp/libchdr/include/libchdr/flac.h | 51 + .../cpp/libchdr/include/libchdr/huffman.h | 90 + .../main/cpp/libchdr/include/libchdr/macros.h | 24 + .../main/cpp/libchdr/src/libchdr_bitstream.c | 125 + .../src/main/cpp/libchdr/src/libchdr_cdrom.c | 490 + .../src/main/cpp/libchdr/src/libchdr_chd.c | 2190 ++ .../main/cpp/libchdr/src/libchdr_codec_cdfl.c | 100 + .../main/cpp/libchdr/src/libchdr_codec_cdlz.c | 57 + .../main/cpp/libchdr/src/libchdr_codec_cdzl.c | 56 + .../main/cpp/libchdr/src/libchdr_codec_cdzs.c | 57 + .../main/cpp/libchdr/src/libchdr_codec_flac.c | 65 + .../main/cpp/libchdr/src/libchdr_codec_huff.c | 46 + .../main/cpp/libchdr/src/libchdr_codec_lzma.c | 266 + .../main/cpp/libchdr/src/libchdr_codec_zlib.c | 180 + .../main/cpp/libchdr/src/libchdr_codec_zstd.c | 91 + .../src/main/cpp/libchdr/src/libchdr_flac.c | 328 + .../main/cpp/libchdr/src/libchdr_huffman.c | 569 + libretrodroid/src/main/cpp/libchdr/src/link.T | 5 + .../src/main/cpp/libretro/libretro-common | 1 + libretrodroid/src/main/cpp/libretrodroid.cpp | 730 + libretrodroid/src/main/cpp/libretrodroid.h | 203 + .../src/main/cpp/libretrodroidjni.cpp | 699 + libretrodroid/src/main/cpp/libretrodroidjni.h | 56 + libretrodroid/src/main/cpp/log.h | 89 + .../src/main/cpp/microphone/microphone.cpp | 99 + .../src/main/cpp/microphone/microphone.h | 61 + .../cpp/microphone/microphoneinterface.cpp | 84 + .../main/cpp/microphone/microphoneinterface.h | 48 + libretrodroid/src/main/cpp/netpacket.cpp | 440 + libretrodroid/src/main/cpp/netpacket.h | 83 + libretrodroid/src/main/cpp/oboe | 1 + libretrodroid/src/main/cpp/rcheevos/LICENSE | 21 + .../cpp/rcheevos/include/module.modulemap | 70 + .../main/cpp/rcheevos/include/rc_api_editor.h | 345 + .../main/cpp/rcheevos/include/rc_api_info.h | 298 + .../cpp/rcheevos/include/rc_api_request.h | 77 + .../cpp/rcheevos/include/rc_api_runtime.h | 417 + .../main/cpp/rcheevos/include/rc_api_user.h | 262 + .../src/main/cpp/rcheevos/include/rc_client.h | 932 + .../include/rc_client_raintegration.h | 101 + .../main/cpp/rcheevos/include/rc_consoles.h | 138 + .../src/main/cpp/rcheevos/include/rc_error.h | 60 + .../src/main/cpp/rcheevos/include/rc_export.h | 100 + .../src/main/cpp/rcheevos/include/rc_hash.h | 200 + .../main/cpp/rcheevos/include/rc_runtime.h | 148 + .../cpp/rcheevos/include/rc_runtime_types.h | 452 + .../src/main/cpp/rcheevos/include/rc_util.h | 51 + .../src/main/cpp/rcheevos/include/rcheevos.h | 8 + .../cpp/rcheevos/src/rapi/rc_api_common.c | 1516 + .../cpp/rcheevos/src/rapi/rc_api_common.h | 94 + .../cpp/rcheevos/src/rapi/rc_api_editor.c | 725 + .../main/cpp/rcheevos/src/rapi/rc_api_info.c | 612 + .../cpp/rcheevos/src/rapi/rc_api_runtime.c | 898 + .../main/cpp/rcheevos/src/rapi/rc_api_user.c | 475 + .../src/main/cpp/rcheevos/src/rc_client.c | 7151 +++++ .../cpp/rcheevos/src/rc_client_external.c | 282 + .../cpp/rcheevos/src/rc_client_external.h | 177 + .../src/rc_client_external_versions.h | 171 + .../cpp/rcheevos/src/rc_client_internal.h | 409 + .../rcheevos/src/rc_client_raintegration.c | 566 + .../src/rc_client_raintegration_internal.h | 61 + .../cpp/rcheevos/src/rc_client_types.natvis | 396 + .../src/main/cpp/rcheevos/src/rc_compat.c | 251 + .../src/main/cpp/rcheevos/src/rc_compat.h | 121 + .../src/main/cpp/rcheevos/src/rc_libretro.c | 915 + .../src/main/cpp/rcheevos/src/rc_libretro.h | 98 + .../src/main/cpp/rcheevos/src/rc_util.c | 200 + .../src/main/cpp/rcheevos/src/rc_version.c | 11 + .../src/main/cpp/rcheevos/src/rc_version.h | 32 + .../main/cpp/rcheevos/src/rcheevos/alloc.c | 316 + .../cpp/rcheevos/src/rcheevos/condition.c | 754 + .../main/cpp/rcheevos/src/rcheevos/condset.c | 777 + .../cpp/rcheevos/src/rcheevos/consoleinfo.c | 1227 + .../main/cpp/rcheevos/src/rcheevos/format.c | 330 + .../main/cpp/rcheevos/src/rcheevos/lboard.c | 287 + .../main/cpp/rcheevos/src/rcheevos/memref.c | 805 + .../main/cpp/rcheevos/src/rcheevos/operand.c | 607 + .../cpp/rcheevos/src/rcheevos/rc_internal.h | 390 + .../src/rcheevos/rc_runtime_types.natvis | 541 + .../cpp/rcheevos/src/rcheevos/rc_validate.c | 1406 + .../cpp/rcheevos/src/rcheevos/rc_validate.h | 18 + .../cpp/rcheevos/src/rcheevos/richpresence.c | 928 + .../main/cpp/rcheevos/src/rcheevos/runtime.c | 852 + .../rcheevos/src/rcheevos/runtime_progress.c | 1073 + .../main/cpp/rcheevos/src/rcheevos/trigger.c | 344 + .../main/cpp/rcheevos/src/rcheevos/value.c | 941 + .../src/main/cpp/rcheevos/src/rhash/aes.c | 480 + .../src/main/cpp/rcheevos/src/rhash/aes.h | 49 + .../main/cpp/rcheevos/src/rhash/cdreader.c | 863 + .../src/main/cpp/rcheevos/src/rhash/hash.c | 1414 + .../main/cpp/rcheevos/src/rhash/hash_disc.c | 1342 + .../cpp/rcheevos/src/rhash/hash_encrypted.c | 566 + .../main/cpp/rcheevos/src/rhash/hash_rom.c | 512 + .../main/cpp/rcheevos/src/rhash/hash_zip.c | 459 + .../src/main/cpp/rcheevos/src/rhash/md5.c | 382 + .../src/main/cpp/rcheevos/src/rhash/md5.h | 91 + .../cpp/rcheevos/src/rhash/rc_hash_internal.h | 117 + .../cpp/renderers/es2/imagerendereres2.cpp | 130 + .../main/cpp/renderers/es2/imagerendereres2.h | 64 + .../src/main/cpp/renderers/es3/es3utils.cpp | 158 + .../src/main/cpp/renderers/es3/es3utils.h | 65 + .../cpp/renderers/es3/framebufferrenderer.cpp | 180 + .../cpp/renderers/es3/framebufferrenderer.h | 69 + .../cpp/renderers/es3/imagerendereres3.cpp | 153 + .../main/cpp/renderers/es3/imagerendereres3.h | 72 + .../src/main/cpp/renderers/renderer.cpp | 26 + .../src/main/cpp/renderers/renderer.h | 58 + .../main/cpp/resamplers/linearresampler.cpp | 43 + .../src/main/cpp/resamplers/linearresampler.h | 34 + .../src/main/cpp/resamplers/resampler.h | 32 + .../src/main/cpp/resamplers/sincresampler.cpp | 59 + .../src/main/cpp/resamplers/sincresampler.h | 41 + .../src/main/cpp/retro_netpacket_api.h | 55 + .../src/main/cpp/retroachievements.cpp | 547 + libretrodroid/src/main/cpp/rumble.cpp | 51 + libretrodroid/src/main/cpp/rumble.h | 40 + libretrodroid/src/main/cpp/rumblestate.cpp | 26 + libretrodroid/src/main/cpp/rumblestate.h | 34 + libretrodroid/src/main/cpp/shadermanager.cpp | 1788 ++ libretrodroid/src/main/cpp/shadermanager.h | 107 + .../src/main/cpp/utils/javautils.cpp | 105 + libretrodroid/src/main/cpp/utils/javautils.h | 44 + .../src/main/cpp/utils/jnistring.cpp | 35 + libretrodroid/src/main/cpp/utils/jnistring.h | 42 + .../main/cpp/utils/libretrodroidexception.cpp | 22 + .../main/cpp/utils/libretrodroidexception.h | 36 + libretrodroid/src/main/cpp/utils/rect.cpp | 25 + libretrodroid/src/main/cpp/utils/rect.h | 41 + libretrodroid/src/main/cpp/utils/utils.cpp | 63 + libretrodroid/src/main/cpp/utils/utils.h | 40 + libretrodroid/src/main/cpp/vfs/fdwrapper.cpp | 29 + libretrodroid/src/main/cpp/vfs/fdwrapper.h | 44 + libretrodroid/src/main/cpp/vfs/vfs.cpp | 164 + libretrodroid/src/main/cpp/vfs/vfs.h | 79 + libretrodroid/src/main/cpp/vfs/vfsfile.cpp | 34 + libretrodroid/src/main/cpp/vfs/vfsfile.h | 48 + libretrodroid/src/main/cpp/video.cpp | 380 + libretrodroid/src/main/cpp/video.h | 122 + libretrodroid/src/main/cpp/videolayout.cpp | 261 + libretrodroid/src/main/cpp/videolayout.h | 167 + .../com/swordfish/libretrodroid/Controller.kt | 3 + .../libretrodroid/DetachedVirtualFile.kt | 3 + .../swordfish/libretrodroid/GLRetroShader.kt | 20 + .../swordfish/libretrodroid/GLRetroView.kt | 561 + .../libretrodroid/GLRetroViewData.kt | 44 + .../swordfish/libretrodroid/ImmersiveMode.kt | 10 + .../com/swordfish/libretrodroid/KtUtils.kt | 54 + .../libretrodroid/LibretroDroid.java | 177 + .../libretrodroid/RetroAchievements.java | 39 + .../swordfish/libretrodroid/RetroException.kt | 5 + .../swordfish/libretrodroid/RumbleEvent.kt | 6 + .../swordfish/libretrodroid/ShaderConfig.kt | 69 + .../com/swordfish/libretrodroid/Variable.kt | 3 + .../swordfish/libretrodroid/VirtualFile.kt | 5 + .../libretrodroid/gamepad/GamepadsManager.kt | 57 + libretrodroid/src/main/res/values/strings.xml | 3 + settings.gradle | 3 + 461 files changed, 164185 insertions(+), 170 deletions(-) create mode 100644 EMULATOR_CREDITS.md create mode 100644 app/src/main/app/shell/RetroConsoleRibbon.kt create mode 100644 app/src/main/assets/dnas/dnas_bypass.json create mode 100644 app/src/main/assets/retro/GLideN64.custom.ini create mode 100644 app/src/main/feature/retro/DolphinCloudSync.kt create mode 100644 app/src/main/feature/retro/DolphinEmbedLaunch.kt create mode 100644 app/src/main/feature/retro/DolphinGameOverlay.kt create mode 100644 app/src/main/feature/retro/DolphinNetplayUi.kt create mode 100644 app/src/main/feature/retro/Ps2CheatStaging.kt create mode 100644 app/src/main/feature/retro/Ps2DnasBypass.kt create mode 100644 app/src/main/feature/retro/Ps2GameOverlay.kt create mode 100644 app/src/main/feature/retro/Ps2IsoSerial.kt create mode 100644 app/src/main/feature/retro/Ps2MenuScreens.kt create mode 100644 app/src/main/feature/retro/Ps2RaBridge.kt create mode 100644 app/src/main/feature/retro/RetroAchievementOverlay.kt create mode 100644 app/src/main/feature/retro/RetroAchievementsActivity.kt create mode 100644 app/src/main/feature/retro/RetroAchievementsManager.kt create mode 100644 app/src/main/feature/retro/RetroActivity.kt create mode 100644 app/src/main/feature/retro/RetroBiosImport.kt create mode 100644 app/src/main/feature/retro/RetroBoxart.kt create mode 100644 app/src/main/feature/retro/RetroBundle.kt create mode 100644 app/src/main/feature/retro/RetroCheats.kt create mode 100644 app/src/main/feature/retro/RetroCheatsActivity.kt create mode 100644 app/src/main/feature/retro/RetroControlLayouts.kt create mode 100644 app/src/main/feature/retro/RetroControlsMenu.kt create mode 100644 app/src/main/feature/retro/RetroCoreCatalog.kt create mode 100644 app/src/main/feature/retro/RetroCoreManager.kt create mode 100644 app/src/main/feature/retro/RetroCoreOptions.kt create mode 100644 app/src/main/feature/retro/RetroCreditsScreen.kt create mode 100644 app/src/main/feature/retro/RetroDefaults.kt create mode 100644 app/src/main/feature/retro/RetroDefaultsScreen.kt create mode 100644 app/src/main/feature/retro/RetroDrawerMenu.kt create mode 100644 app/src/main/feature/retro/RetroGameLink.kt create mode 100644 app/src/main/feature/retro/RetroGameSettings.kt create mode 100644 app/src/main/feature/retro/RetroHddImport.kt create mode 100644 app/src/main/feature/retro/RetroHudSupport.kt create mode 100644 app/src/main/feature/retro/RetroInputView.kt create mode 100644 app/src/main/feature/retro/RetroNetplay.kt create mode 100644 app/src/main/feature/retro/RetroNetplayEditField.kt create mode 100644 app/src/main/feature/retro/RetroNetplayUi.kt create mode 100644 app/src/main/feature/retro/RetroOnlineSupport.kt create mode 100644 app/src/main/feature/retro/RetroRomArchive.kt create mode 100644 app/src/main/feature/retro/RetroRomScanner.kt create mode 100644 app/src/main/feature/retro/RetroSaveImport.kt create mode 100644 app/src/main/feature/retro/RetroSaveStates.kt create mode 100644 app/src/main/feature/retro/RetroSettingsDialog.kt create mode 100644 app/src/main/feature/retro/RetroShortcuts.kt create mode 100644 app/src/main/feature/retro/RetroSystem.kt create mode 100755 app/src/main/jniLibs/arm64-v8a/libdolphin_libretro_android.so create mode 100644 app/src/main/shared/theme/SessionDrawerStyle.kt create mode 100644 app/src/main/shared/ui/settings/SharedSettingsWidgets.kt create mode 100644 armsx2/AndroidManifest.upstream.xml create mode 100644 armsx2/UPSTREAM.md create mode 100644 armsx2/build.gradle create mode 100644 armsx2/src/main/AndroidManifest.xml create mode 100644 armsx2/src/main/java/com/armsx2/BiosInfo.kt create mode 100644 armsx2/src/main/java/com/armsx2/CustomDriver.kt create mode 100644 armsx2/src/main/java/com/armsx2/EmuState.kt create mode 100644 armsx2/src/main/java/com/armsx2/GameInfo.kt create mode 100644 armsx2/src/main/java/com/armsx2/Main.kt create mode 100644 armsx2/src/main/java/com/armsx2/PatchRepo.kt create mode 100644 armsx2/src/main/java/com/armsx2/RetroAchievementsHostOverrideReceiver.java create mode 100644 armsx2/src/main/java/com/armsx2/ShaderParams.kt create mode 100644 armsx2/src/main/java/com/armsx2/ShaderRepo.kt create mode 100644 armsx2/src/main/java/com/armsx2/WinNativeHost.kt create mode 100644 armsx2/src/main/java/com/armsx2/config/ConfigStore.kt create mode 100644 armsx2/src/main/java/com/armsx2/config/Settings.kt create mode 100644 armsx2/src/main/java/com/armsx2/events/TestResult.kt create mode 100644 armsx2/src/main/java/com/armsx2/input/AndroidGyroscopeInput.kt create mode 100644 armsx2/src/main/java/com/armsx2/input/ControllerMappings.kt create mode 100644 armsx2/src/main/java/com/armsx2/input/PadRouter.kt create mode 100644 armsx2/src/main/java/com/armsx2/runtime/EmulationSurface.kt create mode 100644 armsx2/src/main/java/com/armsx2/runtime/MainActivityRuntime.kt create mode 100644 armsx2/src/main/java/com/armsx2/ui/InGameOverlay.kt create mode 100644 armsx2/src/main/java/com/armsx2/ui/WindowImpl.kt create mode 100644 armsx2/src/main/java/com/armsx2/ui/achievements/AchievementsViewModel.kt create mode 100644 armsx2/src/main/java/com/armsx2/ui/touch/TouchControls.kt create mode 100644 armsx2/src/main/java/kr/co/iefriends/pcsx2/AssetFiles.java create mode 100644 armsx2/src/main/java/kr/co/iefriends/pcsx2/HttpClient.java create mode 100644 armsx2/src/main/java/kr/co/iefriends/pcsx2/NativeApp.java create mode 100644 armsx2/src/main/java/org/libsdl/app/HIDDevice.java create mode 100644 armsx2/src/main/java/org/libsdl/app/HIDDeviceBLESteamController.java create mode 100644 armsx2/src/main/java/org/libsdl/app/HIDDeviceManager.java create mode 100644 armsx2/src/main/java/org/libsdl/app/HIDDeviceUSB.java create mode 100644 armsx2/src/main/java/org/libsdl/app/SDL.java create mode 100644 armsx2/src/main/java/org/libsdl/app/SDLActivity.java create mode 100644 armsx2/src/main/java/org/libsdl/app/SDLAudioManager.java create mode 100644 armsx2/src/main/java/org/libsdl/app/SDLControllerManager.java create mode 100644 armsx2/src/main/java/org/libsdl/app/SDLDummyEdit.java create mode 100644 armsx2/src/main/java/org/libsdl/app/SDLInputConnection.java create mode 100644 armsx2/src/main/java/org/libsdl/app/SDLSurface.java create mode 100644 armsx2/src/main/jniLibs/arm64-v8a/libEGL_angle.so create mode 100644 armsx2/src/main/jniLibs/arm64-v8a/libGLESv2_angle.so create mode 100644 armsx2/src/main/jniLibs/arm64-v8a/libSPIRV-Tools-shared.so create mode 100644 armsx2/src/main/jniLibs/arm64-v8a/liblibrashader_capi.so create mode 100644 armsx2/src/main/jniLibs/arm64-v8a/libshaderc_shared.so create mode 100644 armsx2/src/main/res/drawable/ic_launcher_background.xml create mode 100644 armsx2/src/main/res/drawable/ic_launcher_foreground.xml create mode 100644 armsx2/src/main/res/drawable/savetowerforeground.png create mode 100644 armsx2/src/main/res/mipmap-anydpi-v26/ic_launcher.xml create mode 100644 armsx2/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml create mode 100644 armsx2/src/main/res/mipmap-anydpi/ic_launcher.xml create mode 100644 armsx2/src/main/res/mipmap-anydpi/ic_launcher_round.xml create mode 100644 armsx2/src/main/res/values-night/themes.xml create mode 100644 armsx2/src/main/res/values/colors.xml create mode 100644 armsx2/src/main/res/values/strings.xml create mode 100644 armsx2/src/main/res/values/themes.xml create mode 100644 armsx2/src/main/res/xml/backup_rules.xml create mode 100644 armsx2/src/main/res/xml/data_extraction_rules.xml create mode 100644 armsx2/src/main/res/xml/network_security_config.xml create mode 100644 cores/DOLPHIN.md create mode 100644 cores/DOLPHIN_EMBED.md create mode 100644 cores/DOLPHIN_VULKAN.md create mode 100644 dolphin/.gitignore create mode 100644 dolphin/build.gradle create mode 100644 dolphin/src/main/AndroidManifest.xml create mode 100644 dolphin/src/main/java/org/dolphinemu/dolphinemu/DolphinApplication.kt create mode 100644 dolphin/src/main/java/org/dolphinemu/dolphinemu/NativeLibrary.kt create mode 100644 dolphin/src/main/java/org/dolphinemu/dolphinemu/overlay/InputOverlayPointer.kt create mode 100644 dolphin/src/main/java/org/dolphinemu/dolphinemu/utils/Analytics.kt create mode 100644 dolphin/src/main/java/org/dolphinemu/dolphinemu/utils/DirectoryInitialization.kt create mode 100644 dolphin/src/main/java/org/dolphinemu/dolphinemu/utils/FileBrowserHelper.kt create mode 100644 dolphin/src/main/java/org/dolphinemu/dolphinemu/utils/PermissionsHandler.kt create mode 100644 dolphin/src/main/java/org/dolphinemu/dolphinemu/wn/DolphinConfigWriter.kt create mode 100644 dolphin/src/main/java/org/dolphinemu/dolphinemu/wn/DolphinEmulationActivity.kt create mode 100644 dolphin/src/main/java/org/dolphinemu/dolphinemu/wn/DolphinHost.kt create mode 100644 dolphin/src/main/java/org/dolphinemu/dolphinemu/wn/DolphinNetplay.kt create mode 100644 dolphin/src/main/res/values/dolphin_strings.xml create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/ARCheat.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/AbstractCheat.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/Cheat.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/CheatsViewModel.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/GeckoCheat.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/GraphicsMod.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/GraphicsModGroup.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/PatchCheat.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/ReadOnlyCheat.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/infinitybase/InfinityConfig.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/infinitybase/model/Figure.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/ControlGroupEnabledSetting.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/ControllerInterface.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/CoreDevice.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/DolphinSensorEventListener.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/DolphinVibratorManager.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/DolphinVibratorManagerCompat.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/DolphinVibratorManagerPassthrough.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/InputDetector.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/InputMappingBooleanSetting.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/InputMappingDoubleSetting.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/InputMappingIntSetting.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/InputOverrider.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/MappingCommon.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/controlleremu/Control.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/controlleremu/ControlGroup.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/controlleremu/ControlReference.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/controlleremu/EmulatedController.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/controlleremu/NumericSetting.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/netplay/NetplaySession.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/netplay/model/GameDigestProgress.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/netplay/model/NetplayMessage.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/netplay/model/Player.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/netplay/model/SaveTransferProgress.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/netplay/model/TraversalState.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/riivolution/model/RiivolutionPatches.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AbstractBooleanSetting.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AbstractFloatSetting.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AbstractIntSetting.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AbstractSetting.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AbstractStringSetting.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AchievementModel.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AdHocBooleanSetting.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AdHocStringSetting.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/BooleanSetting.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/ConfigChangedCallback.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/FloatSetting.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/IntSetting.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/NativeConfig.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/PostProcessing.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/ScaledIntSetting.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/Settings.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/StringSetting.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/skylanders/SkylanderConfig.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/skylanders/model/Skylander.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/features/skylanders/model/SkylanderPair.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/model/GameFile.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/model/GameFileCache.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/services/USBPermService.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/AudioUtils.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/BooleanSupplier.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/CompressCallback.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/ContentHandler.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/GCAdapter.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/Log.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/NetworkHelper.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/RateLimiter.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/WiiUpdateCallback.kt create mode 100644 dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/WiimoteAdapter.kt create mode 100644 libretrodroid/.gitignore create mode 100644 libretrodroid/build.gradle create mode 100644 libretrodroid/consumer-rules.pro create mode 100644 libretrodroid/proguard-rules.pro create mode 100644 libretrodroid/src/main/AndroidManifest.xml create mode 100644 libretrodroid/src/main/cpp/CMakeLists.txt create mode 100644 libretrodroid/src/main/cpp/SGSR_LICENSE create mode 100644 libretrodroid/src/main/cpp/audio.cpp create mode 100644 libretrodroid/src/main/cpp/audio.h create mode 100644 libretrodroid/src/main/cpp/core.cpp create mode 100644 libretrodroid/src/main/cpp/core.h create mode 100644 libretrodroid/src/main/cpp/environment.cpp create mode 100644 libretrodroid/src/main/cpp/environment.h create mode 100644 libretrodroid/src/main/cpp/errorcodes.cpp create mode 100644 libretrodroid/src/main/cpp/errorcodes.h create mode 100644 libretrodroid/src/main/cpp/fpssync.cpp create mode 100644 libretrodroid/src/main/cpp/fpssync.h create mode 100644 libretrodroid/src/main/cpp/immersivemode.cpp create mode 100644 libretrodroid/src/main/cpp/immersivemode.h create mode 100644 libretrodroid/src/main/cpp/input.cpp create mode 100644 libretrodroid/src/main/cpp/input.h create mode 100644 libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/Asm/arm64/7zAsm.S create mode 100644 libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/Asm/arm64/LzmaDecOpt.S create mode 100644 libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/Asm/x86/7zAsm.asm create mode 100644 libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/Asm/x86/LzmaDecOpt.asm create mode 100644 libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/CMakeLists.txt create mode 100644 libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/LICENSE create mode 100644 libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/include/LzmaDec.h create mode 100644 libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/include/real/7zTypes.h create mode 100644 libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/include/real/LzmaDec.h create mode 100644 libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/src/LzmaDec.c create mode 100644 libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/src/real/LzmaDec.c create mode 100644 libretrodroid/src/main/cpp/libchdr/deps/zstd-1.5.7/CMakeLists.txt create mode 100644 libretrodroid/src/main/cpp/libchdr/deps/zstd-1.5.7/zstd.h create mode 100644 libretrodroid/src/main/cpp/libchdr/deps/zstd-1.5.7/zstd_errors.h create mode 100644 libretrodroid/src/main/cpp/libchdr/deps/zstd-1.5.7/zstddeclib.c create mode 100644 libretrodroid/src/main/cpp/libchdr/include/dr_libs/dr_flac.h create mode 100644 libretrodroid/src/main/cpp/libchdr/include/libchdr/bitstream.h create mode 100644 libretrodroid/src/main/cpp/libchdr/include/libchdr/cdrom.h create mode 100644 libretrodroid/src/main/cpp/libchdr/include/libchdr/chd.h create mode 100644 libretrodroid/src/main/cpp/libchdr/include/libchdr/chdconfig.h create mode 100644 libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_cdfl.h create mode 100644 libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_cdlz.h create mode 100644 libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_cdzl.h create mode 100644 libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_cdzs.h create mode 100644 libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_flac.h create mode 100644 libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_huff.h create mode 100644 libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_lzma.h create mode 100644 libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_zlib.h create mode 100644 libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_zstd.h create mode 100644 libretrodroid/src/main/cpp/libchdr/include/libchdr/coretypes.h create mode 100644 libretrodroid/src/main/cpp/libchdr/include/libchdr/flac.h create mode 100644 libretrodroid/src/main/cpp/libchdr/include/libchdr/huffman.h create mode 100644 libretrodroid/src/main/cpp/libchdr/include/libchdr/macros.h create mode 100644 libretrodroid/src/main/cpp/libchdr/src/libchdr_bitstream.c create mode 100644 libretrodroid/src/main/cpp/libchdr/src/libchdr_cdrom.c create mode 100644 libretrodroid/src/main/cpp/libchdr/src/libchdr_chd.c create mode 100644 libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_cdfl.c create mode 100644 libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_cdlz.c create mode 100644 libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_cdzl.c create mode 100644 libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_cdzs.c create mode 100644 libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_flac.c create mode 100644 libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_huff.c create mode 100644 libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_lzma.c create mode 100644 libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_zlib.c create mode 100644 libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_zstd.c create mode 100644 libretrodroid/src/main/cpp/libchdr/src/libchdr_flac.c create mode 100644 libretrodroid/src/main/cpp/libchdr/src/libchdr_huffman.c create mode 100644 libretrodroid/src/main/cpp/libchdr/src/link.T create mode 160000 libretrodroid/src/main/cpp/libretro/libretro-common create mode 100644 libretrodroid/src/main/cpp/libretrodroid.cpp create mode 100644 libretrodroid/src/main/cpp/libretrodroid.h create mode 100644 libretrodroid/src/main/cpp/libretrodroidjni.cpp create mode 100644 libretrodroid/src/main/cpp/libretrodroidjni.h create mode 100644 libretrodroid/src/main/cpp/log.h create mode 100644 libretrodroid/src/main/cpp/microphone/microphone.cpp create mode 100644 libretrodroid/src/main/cpp/microphone/microphone.h create mode 100644 libretrodroid/src/main/cpp/microphone/microphoneinterface.cpp create mode 100644 libretrodroid/src/main/cpp/microphone/microphoneinterface.h create mode 100644 libretrodroid/src/main/cpp/netpacket.cpp create mode 100644 libretrodroid/src/main/cpp/netpacket.h create mode 160000 libretrodroid/src/main/cpp/oboe create mode 100644 libretrodroid/src/main/cpp/rcheevos/LICENSE create mode 100644 libretrodroid/src/main/cpp/rcheevos/include/module.modulemap create mode 100644 libretrodroid/src/main/cpp/rcheevos/include/rc_api_editor.h create mode 100644 libretrodroid/src/main/cpp/rcheevos/include/rc_api_info.h create mode 100644 libretrodroid/src/main/cpp/rcheevos/include/rc_api_request.h create mode 100644 libretrodroid/src/main/cpp/rcheevos/include/rc_api_runtime.h create mode 100644 libretrodroid/src/main/cpp/rcheevos/include/rc_api_user.h create mode 100644 libretrodroid/src/main/cpp/rcheevos/include/rc_client.h create mode 100644 libretrodroid/src/main/cpp/rcheevos/include/rc_client_raintegration.h create mode 100644 libretrodroid/src/main/cpp/rcheevos/include/rc_consoles.h create mode 100644 libretrodroid/src/main/cpp/rcheevos/include/rc_error.h create mode 100644 libretrodroid/src/main/cpp/rcheevos/include/rc_export.h create mode 100644 libretrodroid/src/main/cpp/rcheevos/include/rc_hash.h create mode 100644 libretrodroid/src/main/cpp/rcheevos/include/rc_runtime.h create mode 100644 libretrodroid/src/main/cpp/rcheevos/include/rc_runtime_types.h create mode 100644 libretrodroid/src/main/cpp/rcheevos/include/rc_util.h create mode 100644 libretrodroid/src/main/cpp/rcheevos/include/rcheevos.h create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rapi/rc_api_common.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rapi/rc_api_common.h create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rapi/rc_api_editor.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rapi/rc_api_info.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rapi/rc_api_runtime.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rapi/rc_api_user.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rc_client.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rc_client_external.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rc_client_external.h create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rc_client_external_versions.h create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rc_client_internal.h create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rc_client_raintegration.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rc_client_raintegration_internal.h create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rc_client_types.natvis create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rc_compat.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rc_compat.h create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rc_libretro.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rc_libretro.h create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rc_util.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rc_version.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rc_version.h create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rcheevos/alloc.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rcheevos/condition.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rcheevos/condset.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rcheevos/consoleinfo.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rcheevos/format.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rcheevos/lboard.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rcheevos/memref.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rcheevos/operand.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rcheevos/rc_internal.h create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rcheevos/rc_runtime_types.natvis create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rcheevos/rc_validate.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rcheevos/rc_validate.h create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rcheevos/richpresence.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rcheevos/runtime.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rcheevos/runtime_progress.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rcheevos/trigger.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rcheevos/value.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rhash/aes.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rhash/aes.h create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rhash/cdreader.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rhash/hash.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rhash/hash_disc.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rhash/hash_encrypted.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rhash/hash_rom.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rhash/hash_zip.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rhash/md5.c create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rhash/md5.h create mode 100644 libretrodroid/src/main/cpp/rcheevos/src/rhash/rc_hash_internal.h create mode 100644 libretrodroid/src/main/cpp/renderers/es2/imagerendereres2.cpp create mode 100644 libretrodroid/src/main/cpp/renderers/es2/imagerendereres2.h create mode 100644 libretrodroid/src/main/cpp/renderers/es3/es3utils.cpp create mode 100644 libretrodroid/src/main/cpp/renderers/es3/es3utils.h create mode 100644 libretrodroid/src/main/cpp/renderers/es3/framebufferrenderer.cpp create mode 100644 libretrodroid/src/main/cpp/renderers/es3/framebufferrenderer.h create mode 100644 libretrodroid/src/main/cpp/renderers/es3/imagerendereres3.cpp create mode 100644 libretrodroid/src/main/cpp/renderers/es3/imagerendereres3.h create mode 100644 libretrodroid/src/main/cpp/renderers/renderer.cpp create mode 100644 libretrodroid/src/main/cpp/renderers/renderer.h create mode 100644 libretrodroid/src/main/cpp/resamplers/linearresampler.cpp create mode 100644 libretrodroid/src/main/cpp/resamplers/linearresampler.h create mode 100644 libretrodroid/src/main/cpp/resamplers/resampler.h create mode 100644 libretrodroid/src/main/cpp/resamplers/sincresampler.cpp create mode 100644 libretrodroid/src/main/cpp/resamplers/sincresampler.h create mode 100644 libretrodroid/src/main/cpp/retro_netpacket_api.h create mode 100644 libretrodroid/src/main/cpp/retroachievements.cpp create mode 100644 libretrodroid/src/main/cpp/rumble.cpp create mode 100644 libretrodroid/src/main/cpp/rumble.h create mode 100644 libretrodroid/src/main/cpp/rumblestate.cpp create mode 100644 libretrodroid/src/main/cpp/rumblestate.h create mode 100644 libretrodroid/src/main/cpp/shadermanager.cpp create mode 100644 libretrodroid/src/main/cpp/shadermanager.h create mode 100644 libretrodroid/src/main/cpp/utils/javautils.cpp create mode 100644 libretrodroid/src/main/cpp/utils/javautils.h create mode 100644 libretrodroid/src/main/cpp/utils/jnistring.cpp create mode 100644 libretrodroid/src/main/cpp/utils/jnistring.h create mode 100644 libretrodroid/src/main/cpp/utils/libretrodroidexception.cpp create mode 100644 libretrodroid/src/main/cpp/utils/libretrodroidexception.h create mode 100644 libretrodroid/src/main/cpp/utils/rect.cpp create mode 100644 libretrodroid/src/main/cpp/utils/rect.h create mode 100644 libretrodroid/src/main/cpp/utils/utils.cpp create mode 100644 libretrodroid/src/main/cpp/utils/utils.h create mode 100644 libretrodroid/src/main/cpp/vfs/fdwrapper.cpp create mode 100644 libretrodroid/src/main/cpp/vfs/fdwrapper.h create mode 100644 libretrodroid/src/main/cpp/vfs/vfs.cpp create mode 100644 libretrodroid/src/main/cpp/vfs/vfs.h create mode 100644 libretrodroid/src/main/cpp/vfs/vfsfile.cpp create mode 100644 libretrodroid/src/main/cpp/vfs/vfsfile.h create mode 100644 libretrodroid/src/main/cpp/video.cpp create mode 100644 libretrodroid/src/main/cpp/video.h create mode 100644 libretrodroid/src/main/cpp/videolayout.cpp create mode 100644 libretrodroid/src/main/cpp/videolayout.h create mode 100644 libretrodroid/src/main/java/com/swordfish/libretrodroid/Controller.kt create mode 100644 libretrodroid/src/main/java/com/swordfish/libretrodroid/DetachedVirtualFile.kt create mode 100644 libretrodroid/src/main/java/com/swordfish/libretrodroid/GLRetroShader.kt create mode 100644 libretrodroid/src/main/java/com/swordfish/libretrodroid/GLRetroView.kt create mode 100644 libretrodroid/src/main/java/com/swordfish/libretrodroid/GLRetroViewData.kt create mode 100644 libretrodroid/src/main/java/com/swordfish/libretrodroid/ImmersiveMode.kt create mode 100644 libretrodroid/src/main/java/com/swordfish/libretrodroid/KtUtils.kt create mode 100644 libretrodroid/src/main/java/com/swordfish/libretrodroid/LibretroDroid.java create mode 100644 libretrodroid/src/main/java/com/swordfish/libretrodroid/RetroAchievements.java create mode 100644 libretrodroid/src/main/java/com/swordfish/libretrodroid/RetroException.kt create mode 100644 libretrodroid/src/main/java/com/swordfish/libretrodroid/RumbleEvent.kt create mode 100644 libretrodroid/src/main/java/com/swordfish/libretrodroid/ShaderConfig.kt create mode 100644 libretrodroid/src/main/java/com/swordfish/libretrodroid/Variable.kt create mode 100644 libretrodroid/src/main/java/com/swordfish/libretrodroid/VirtualFile.kt create mode 100644 libretrodroid/src/main/java/com/swordfish/libretrodroid/gamepad/GamepadsManager.kt create mode 100644 libretrodroid/src/main/res/values/strings.xml diff --git a/.gitattributes b/.gitattributes index 6fd1589a1..0b6224cf0 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3,3 +3,5 @@ app/src/main/assets/imagefs.tzst filter=lfs diff=lfs merge=lfs -text app/src/main/assets/imagefs.part*.tzst filter=lfs diff=lfs merge=lfs -text reference/tooling/jadx.zip filter=lfs diff=lfs merge=lfs -text reference/tooling/jadx/lib/jadx-1.5.3-all.jar filter=lfs diff=lfs merge=lfs -text + +app/src/main/jniLibs/arm64-v8a/*_libretro_android.so filter=lfs diff=lfs merge=lfs -text diff --git a/.github/workflows/pr-ci.yml b/.github/workflows/pr-ci.yml index c32e0daa6..e13440f96 100644 --- a/.github/workflows/pr-ci.yml +++ b/.github/workflows/pr-ci.yml @@ -91,10 +91,15 @@ jobs: - name: Install Rust Android target run: rustup target add aarch64-linux-android + - name: Validate Gradle wrappers + uses: gradle/actions/wrapper-validation@v6 + with: + allow-checksums: e2b82129ab64751fd40437007bd2f7f2afb3c6e41a9198e628650b22d5824a14 + - name: Set up Gradle uses: gradle/actions/setup-gradle@v6 with: - validate-wrappers: true + validate-wrappers: false cache-cleanup: 'on-success' # PRs restore the Gradle cache read-only; only main pushes write it. cache-read-only: ${{ github.event_name == 'pull_request' }} diff --git a/.github/workflows/tag-apk-artifacts.yml b/.github/workflows/tag-apk-artifacts.yml index ba0955edb..5b3aae746 100644 --- a/.github/workflows/tag-apk-artifacts.yml +++ b/.github/workflows/tag-apk-artifacts.yml @@ -84,10 +84,15 @@ jobs: - name: Install Rust Android target run: rustup target add aarch64-linux-android + - name: Validate Gradle wrappers + uses: gradle/actions/wrapper-validation@v6 + with: + allow-checksums: e2b82129ab64751fd40437007bd2f7f2afb3c6e41a9198e628650b22d5824a14 + - name: Set up Gradle uses: gradle/actions/setup-gradle@v6 with: - validate-wrappers: true + validate-wrappers: false cache-cleanup: 'on-success' - name: Decode keystore and build debug APK diff --git a/.gitignore b/.gitignore index ecf01c18a..d3a4ae7a1 100644 --- a/.gitignore +++ b/.gitignore @@ -53,6 +53,12 @@ signing.properties References/ *.hprof android_sysvshm/build64/ - -# local build artifacts (FEX/Proton wcp) -dist/ + +# local build artifacts (FEX/Proton wcp) +dist/ + +/cores/*/ +!/cores/patches/ + +/armsx2/emucore-src/ +/armsx2/emucore-out/ diff --git a/.gitmodules b/.gitmodules index b5cf369f6..9a403e6ed 100644 --- a/.gitmodules +++ b/.gitmodules @@ -5,3 +5,9 @@ path = app/src/main/cpp/vkbasalt url = https://github.com/WinNative-Emu/vkBasalt.git branch = Test +[submodule "libretrodroid/src/main/cpp/oboe"] + path = libretrodroid/src/main/cpp/oboe + url = https://github.com/google/oboe +[submodule "libretrodroid/src/main/cpp/libretro/libretro-common"] + path = libretrodroid/src/main/cpp/libretro/libretro-common + url = https://github.com/libretro/libretro-common diff --git a/EMULATOR_CREDITS.md b/EMULATOR_CREDITS.md new file mode 100644 index 000000000..588c0b91e --- /dev/null +++ b/EMULATOR_CREDITS.md @@ -0,0 +1,67 @@ +# Emulator & Library Credits + +WinNative's retro-console features are built on open-source emulators and libraries. +This project is distributed under the **GNU General Public License v3.0** (see [LICENSE](LICENSE)). +In compliance with the GPL and the other licenses below, the corresponding source code +for every GPL/copyleft component is available from the upstream projects linked here, +and their copyright and license notices are preserved. + +## PlayStation 2 + +PS2 games are recognized and imported into the library. PS2 emulation is built on +**ARMSX2** (a GPL-3.0 fork of PCSX2) and is in active development. + +| Component | Role | License | Source | +| --- | --- | --- | --- | +| ARMSX2 | PS2 emulation + RetroAchievements | GPL-3.0 | https://github.com/ARMSX2/ARMSX2 | +| PCSX2 | Upstream project ARMSX2 is derived from | GPL-3.0 | https://github.com/pcsx2/pcsx2 | + +## GameCube / Wii + +GameCube and Wii games are recognized and imported into the library. GC/Wii emulation is +built on an embedded build of **Dolphin**, rendered on Vulkan and driven entirely by +WinNative (Dolphin's own UI is stripped). Local and online multiplayer use Dolphin's own +native NetPlay engine. + +| Component | Role | License | Source | +| --- | --- | --- | --- | +| Dolphin | GameCube/Wii emulation + NetPlay | GPL-2.0-or-later | https://github.com/dolphin-emu/dolphin | + +## Bundled libretro cores + +Each core is shipped as an unmodified `arm64-v8a` build and loaded through LibretroDroid. + +| System | Core | License | Source | +| --- | --- | --- | --- | +| Game Boy / Color | Gambatte | GPL-2.0 | https://github.com/libretro/gambatte-libretro | +| Game Boy Advance | mGBA | MPL-2.0 | https://github.com/libretro/mgba | +| Genesis / Master System / Game Gear | Genesis Plus GX | Genesis Plus GX License (non-commercial) | https://github.com/libretro/Genesis-Plus-GX | +| NES | FCEUmm | GPL-2.0 | https://github.com/libretro/libretro-fceumm | +| Nintendo 64 | ParaLLEl N64 | GPL-2.0 | https://github.com/libretro/parallel-n64 | +| Nintendo 64 | Mupen64Plus-Next | GPL-2.0 | https://github.com/libretro/mupen64plus-libretro-nx | +| PlayStation | Beetle PSX (mednafen_psx) | GPL-2.0 | https://github.com/libretro/beetle-psx-libretro | +| SNES | Snes9x | Snes9x License (non-commercial) | https://github.com/libretro/snes9x | + +### Also evaluated for PlayStation + +| Component | License | Source | +| --- | --- | --- | +| SwanStation | GPL-3.0 | https://github.com/libretro/swanstation | + +## Frontend, achievements, and supporting libraries + +| Component | Role | License | Source | +| --- | --- | --- | --- | +| LibretroDroid | libretro frontend the retro backend is built on | GPL-3.0 | https://github.com/Swordfish90/LibretroDroid | +| Oboe | Audio output | Apache-2.0 | https://github.com/google/oboe | +| rcheevos | RetroAchievements client library | MIT | https://github.com/RetroAchievements/rcheevos | +| Snapdragon Game Super Resolution (SGSR) | Upscaling shader | BSD-3-Clause | https://github.com/quic/snapdragon-gsr | +| Winlator | Windows-on-Android base this project forks | GPL-3.0 | https://github.com/brunodev85/winlator | + +## Source availability + +WinNative is released under the GPL-3.0. As required by that license and by the GPL-2.0 +cores above, the complete corresponding source for every copyleft component is obtainable +from the upstream repositories linked in this document, and the bundled license texts are +retained in the source tree (for example `libretrodroid/src/main/cpp/rcheevos/LICENSE`, +`libretrodroid/src/main/cpp/SGSR_LICENSE`, and the top-level `LICENSE`). diff --git a/README.md b/README.md index 5a008d88c..2f15049e8 100644 --- a/README.md +++ b/README.md @@ -1,60 +1,98 @@ -

- WinNative -

-

- - Discord - -

- -## WinNative: A Community Built Windows Emulation App for Android - - **WinNative** is an advanced, high-performance Windows (x86_64) emulation environment for Android. It bridges the gap between desktop gaming and mobile by unifying the best technologies from **Winlator Bionic** and **Pluvia**. - -Designed for enthusiasts and power users, WinNative delivers the full Winlator experience while making it easy to connect your Steam, Epic, and GOG game libraries. - ---- - -### Installation - -1. **Download:** Get the latest APK from the [Releases](https://github.com/WinNative-Emu/WinNative/releases) section. -2. **Variants:** - - `Ludashi`: Forces both Max GPU and CPU clocks on some devices. (Performance Mode trigger). - - `Vanilla`: Standard package name for side-loading with other forks. - - `Antutu`: Forces Max GPU clocks on most devices. (antutu benchmark spoof) - - `Pubg`: Standard pubg package name which allows some Game Booster advanced Features. -3. **Setup:** Launch the app, allow the ImageFS to install, and start adding your games manually or sync your library. - ---- - -### How to Build - -**Requirements:** Android Studio, JDK 17, NDK `27.3.13750724`, and CMake. - -1. **Clone the repository and update submodules** (Required): - ```bash - git clone https://github.com/MaxsTechReview/WinNative.git - cd WinNative - git submodule update --init --recursive - ``` -2. **Build via Android Studio:** Open the `WinNative` directory, let Gradle sync, then select **Build > Build APK(s)**. -3. **Build via CLI:** Run `.\gradlew.bat assembleDebug` (Windows). - ---- - -### Contributing - -We welcome community contributions! Feel free to open a pull request for bug fixes, driver updates, UI improvements, or anything else you'd like to add. - -Please match the existing code style and ensure any AI-assisted code is thoroughly reviewed and tested before submission. - ---- - -### Credits & Acknowledgments - -- **Original Winlator** by [brunodev85](https://github.com/brunodev85/winlator) -- **Winlator Bionic** by [Pipetto-crypto](https://github.com/Pipetto-crypto/winlator) -- **Pluvia** features by the [Pluvia](https://github.com/oxters168/Pluvia) / [GameNative](https://github.com/utkarshdalal/GameNative) community -- **Mesa/Turnip** contributions by the [Mesa3D](https://www.mesa3d.org/) team -- **Goldberg Steam Emulator** by [Mr. Goldberg](https://gitlab.com/Mr_Goldberg/goldberg_emulator), maintained by [Detanup01](https://github.com/Detanup01/gbe_fork) +

+ WinNative +

+

+ + Discord + +

+ +## WinNative: A Community Built Windows Emulation App for Android + +**WinNative** is an advanced, high-performance Windows (x86_64) emulation environment for Android. It bridges the gap between desktop gaming and mobile by unifying the best technologies from **Winlator Bionic** and **Pluvia**. + +Designed for enthusiasts and power users, WinNative delivers the full Winlator experience while making it easy to connect your Steam, Epic, and GOG game libraries. + +--- + +### Installation + +1. **Download:** Get the latest APK from the [Releases](https://github.com/WinNative-Emu/WinNative/releases) section. +2. **Variants:** + - `Ludashi`: Forces both Max GPU and CPU clocks on some devices. (Performance Mode trigger). + - `Vanilla`: Standard package name for side-loading with other forks. + - `Antutu`: Forces Max GPU clocks on most devices. (antutu benchmark spoof) + - `Pubg`: Standard pubg package name which allows some Game Booster advanced Features. +3. **Setup:** Launch the app, allow the ImageFS to install, and start adding your games manually or sync your library. + +--- + +### How to Build + +**Requirements:** Android Studio, JDK 17, and [Git LFS](https://git-lfs.com). The NDK +(`27.3.13750724`) and CMake are only needed if you build native cores from source (see below). + +1. **Clone with submodules and pull LFS objects** (Required): + ```bash + git clone --recursive https://github.com/MaxsTechReview/WinNative.git + cd WinNative + git lfs pull # fetches imagefs + git submodule update --init --recursive + ``` +2. **Build via Android Studio:** Open the `WinNative` directory, let Gradle sync, then select **Build > Build APK(s)**. +3. **Build via CLI:** Run `./gradlew assembleStandardDebug` (or `.\gradlew.bat` on Windows). + +The APK carries no retro console cores. Each core is built from its own fork under the +[WinNative-Emu](https://github.com/WinNative-Emu) org, and +[Retro-Consoles](https://github.com/WinNative-Emu/Retro-Consoles) packs every core plus the +Dolphin and ARMSX2 runtime data into one `retro-consoles.tzst`. The app downloads and +verifies it on demand from **Settings > Retro > Download console cores**, so a core update +no longer needs an app release. To change a core, change its fork and re-run the +Retro-Consoles bundle workflow. + +--- + +### Retro Console Support + +WinNative can also run classic console games alongside your PC library. Retro games live in the same Library and launch just like PC games, but run on an embedded libretro backend instead of Wine. + +Supported systems (bundled cores): + +| System | Core | ROM extensions | +| --- | --- | --- | +| NES | FCEUmm | `.nes` `.unf` `.unif` | +| SNES | Snes9x | `.smc` `.sfc` `.swc` `.fig` | +| Game Boy / Color | Gambatte | `.gb` `.gbc` | +| Game Boy Advance | mGBA | `.gba` | +| Genesis / Mega Drive, Master System, Game Gear | Genesis Plus GX | `.gen` `.md` `.smd` `.sms` `.gg` | +| Nintendo 64 | Mupen64Plus-Next | `.n64` `.z64` `.v64` | +| PlayStation | Beetle PSX | `.cue` `.chd` `.pbp` `.m3u` `.iso` | +| PlayStation 2 | ARMSX2 (PCSX2 fork) | `.iso` `.chd` `.cso` `.bin` | + +Cores ship **prebuilt** (committed via Git LFS) and are used by default; they are built from +source with the opt-in flags above (see `cores/` for the libretro cores and +`armsx2/build-emucore.sh` / `dolphin/build-emucore.sh` for the PS2 and GameCube/Wii cores). +PlayStation 2 online play is supported through the emulated DEV9 network adapter (see the +in-game **Online** tab). + +**How to use:** In the Library, tap **Add Custom Game** and select a ROM instead of an `.exe`. WinNative detects the console and adds the game to your Library. Tap **Play** to launch it with on-screen touch controls and physical gamepad support; the in-game menu (Back button or on-screen **MENU**) offers save/load state, reset, and fast-forward. PlayStation and PlayStation 2 BIOS files can be imported from **Settings → Retro**. + +### Contributing + +We welcome community contributions! Feel free to open a pull request for bug fixes, driver updates, UI improvements, or anything else you'd like to add. + +Please match the existing code style and ensure any AI-assisted code is thoroughly reviewed and tested before submission. + +--- + +### Credits & Acknowledgments + +- **Original Winlator** by [brunodev85](https://github.com/brunodev85/winlator) +- **Winlator Bionic** by [Pipetto-crypto](https://github.com/Pipetto-crypto/winlator) +- **Pluvia** features by the [Pluvia](https://github.com/oxters168/Pluvia) / [GameNative](https://github.com/utkarshdalal/GameNative) community +- **Mesa/Turnip** contributions by the [Mesa3D](https://www.mesa3d.org/) team +- **Goldberg Steam Emulator** by [Mr. Goldberg](https://gitlab.com/Mr_Goldberg/goldberg_emulator), maintained by [Detanup01](https://github.com/Detanup01/gbe_fork) +- **LibretroDroid** by [Filippo Scognamiglio](https://github.com/Swordfish90/LibretroDroid) (GPL-3.0) — the embedded libretro host for retro console support +- **libretro / RetroArch** and the individual core authors, built from source: [FCEUmm](https://github.com/libretro/libretro-fceumm), [Snes9x](https://github.com/libretro/snes9x), [Gambatte](https://github.com/libretro/gambatte-libretro), [mGBA](https://github.com/libretro/mgba), [Genesis Plus GX](https://github.com/libretro/Genesis-Plus-GX), [Mupen64Plus-Next](https://github.com/libretro/mupen64plus-libretro-nx), [Beetle PSX](https://github.com/libretro/beetle-psx-libretro) +- **ARMSX2** by the [ARMSX2](https://github.com/ARMSX2/ARMSX2) team (GPL-3.0) — the PlayStation 2 core, a fork of **[PCSX2](https://github.com/pcsx2/pcsx2)** (GPL-3.0), built from source into `libemucore`. PS2 online play uses PCSX2's DEV9 network adapter diff --git a/app/build.gradle b/app/build.gradle index 62637d031..eb9c0eff2 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -285,6 +285,10 @@ dependencies { implementation libs.playServicesGamesV2 implementation libs.workRuntimeKtx + + implementation project(':libretrodroid') + implementation project(':armsx2') + implementation project(':dolphin') } spotless { diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index dcb6bc9e1..77d3d42b5 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -127,6 +127,26 @@ android:screenOrientation="sensorLandscape" android:exported="false" /> + + + + + + diff --git a/app/src/main/app/PluviaApp.kt b/app/src/main/app/PluviaApp.kt index b52d883b9..7db378cbe 100644 --- a/app/src/main/app/PluviaApp.kt +++ b/app/src/main/app/PluviaApp.kt @@ -24,10 +24,32 @@ import java.io.File class PluviaApp : Application() { private val appScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + private fun isPs2Process(): Boolean { + val name = + if (android.os.Build.VERSION.SDK_INT >= 28) { + Application.getProcessName() + } else { + runCatching { + val pid = android.os.Process.myPid() + val am = getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager + am.runningAppProcesses?.firstOrNull { it.pid == pid }?.processName + }.getOrNull() + } + return name?.endsWith(":ps2") == true || name?.endsWith(":gc") == true + } + override fun onCreate() { super.onCreate() instance = this + Thread.setDefaultUncaughtExceptionHandler { thread, throwable -> + Log.e("PluviaApp", "CRASH in thread ${thread.name}", throwable) + } + + com.winlator.cmod.feature.retro.Ps2GameOverlay.install() + com.winlator.cmod.feature.retro.DolphinGameOverlay.install() + if (isPs2Process()) return + // Cached probe for devices whose native stack still needs system libjpeg preloaded. preloadSystemLibraries() @@ -39,10 +61,6 @@ class PluviaApp : Application() { com.winlator.cmod.app.service.NetworkMonitor .init(this) scheduleColdStartWarmups() - - Thread.setDefaultUncaughtExceptionHandler { thread, throwable -> - Log.e("PluviaApp", "CRASH in thread ${thread.name}", throwable) - } } companion object { diff --git a/app/src/main/app/shell/LibraryGameLaunchScreen.kt b/app/src/main/app/shell/LibraryGameLaunchScreen.kt index 66f62fb8f..27edd2bad 100644 --- a/app/src/main/app/shell/LibraryGameLaunchScreen.kt +++ b/app/src/main/app/shell/LibraryGameLaunchScreen.kt @@ -43,7 +43,9 @@ import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.outlined.ArrowBack import androidx.compose.material.icons.automirrored.outlined.FactCheck import androidx.compose.material.icons.outlined.ArrowDropDown +import androidx.compose.material.icons.outlined.Bolt import androidx.compose.material.icons.outlined.CloudSync +import androidx.compose.material.icons.outlined.SaveAlt import androidx.compose.material.icons.outlined.Construction import androidx.compose.material.icons.outlined.Delete import androidx.compose.material.icons.outlined.DesktopWindows @@ -134,6 +136,9 @@ internal fun LibraryGameLaunchScreen( lastPlayedMillis: Long, installSizeText: String?, isCustom: Boolean, + isRetro: Boolean = false, + showBootToDesktop: Boolean = !isRetro, + showSaveTransfer: Boolean = false, hasPinnedShortcut: Boolean, steamMenuEnabled: Boolean = false, areSteamActionsEnabled: Boolean = true, @@ -147,8 +152,11 @@ internal fun LibraryGameLaunchScreen( onSettings: () -> Unit, onBootToDesktop: () -> Unit, onAchievements: (() -> Unit)? = null, + onCheats: (() -> Unit)? = null, + cheatsEnabled: Boolean = true, onShortcut: () -> Unit, onCloudSaves: () -> Unit, + onSaveTransfer: (() -> Unit)? = null, onUninstall: () -> Unit, onVerifyFiles: () -> Unit = {}, onCheckForUpdate: () -> Unit = {}, @@ -156,6 +164,15 @@ internal fun LibraryGameLaunchScreen( ) { val context = LocalContext.current var uninstallMenuOpen by remember { mutableStateOf(false) } + val saveTransferVisible = showSaveTransfer && onSaveTransfer != null + val bootVisible = showBootToDesktop + val actionIconCount = + 1 + + (if (saveTransferVisible) 1 else 0) + + 1 + + (if (bootVisible) 1 else 0) + + 1 + + 1 LaunchScreenCutoutMode() @@ -164,9 +181,7 @@ internal fun LibraryGameLaunchScreen( val bottomPadding = 20.dp val actionIconSize = 46.dp val actionIconSpacing = 8.dp - // Action icons: Settings, Boot, CloudSync, Shortcut, Delete. - val actionIconCount = 5 - val actionWidth = actionIconSize * actionIconCount + actionIconSpacing * (actionIconCount - 1) + val actionWidth = actionIconSize * actionIconCount + actionIconSpacing * (actionIconCount - 1).coerceAtLeast(0) val playHeight = 56.dp val contentGap = 18.dp val horizontalNavInsets = WindowInsets.navigationBars.only(WindowInsetsSides.Horizontal) @@ -278,11 +293,14 @@ internal fun LibraryGameLaunchScreen( showCheckForUpdate = showCheckForUpdate, showWorkshop = showWorkshop, showAchievements = onAchievements != null, + showCheats = onCheats != null, + cheatsEnabled = cheatsEnabled, areSteamActionsEnabled = areSteamActionsEnabled, onVerifyFiles = onVerifyFiles, onCheckForUpdate = onCheckForUpdate, onWorkshop = onWorkshop, onAchievements = { onAchievements?.invoke() }, + onCheats = { onCheats?.invoke() }, ) } @@ -391,18 +409,28 @@ internal fun LibraryGameLaunchScreen( size = actionIconSize, onClick = onSettings, ) - LaunchIconActionButton( - icon = Icons.Outlined.DesktopWindows, - contentDescription = stringResource(R.string.hero_boot_to_desktop_title), - size = actionIconSize, - onClick = onBootToDesktop, - ) + if (saveTransferVisible) { + LaunchIconActionButton( + icon = Icons.Outlined.SaveAlt, + contentDescription = stringResource(R.string.retro_save_transfer_title), + size = actionIconSize, + onClick = { onSaveTransfer?.invoke() }, + ) + } LaunchIconActionButton( icon = Icons.Outlined.CloudSync, contentDescription = stringResource(R.string.cloud_saves_title), size = actionIconSize, onClick = onCloudSaves, ) + if (bootVisible) { + LaunchIconActionButton( + icon = Icons.Outlined.DesktopWindows, + contentDescription = stringResource(R.string.hero_boot_to_desktop_title), + size = actionIconSize, + onClick = onBootToDesktop, + ) + } LaunchIconActionButton( icon = Icons.Outlined.Home, contentDescription = @@ -821,14 +849,18 @@ private fun SourceTag( showCheckForUpdate: Boolean = true, showWorkshop: Boolean = true, showAchievements: Boolean = false, + showCheats: Boolean = false, + cheatsEnabled: Boolean = true, areSteamActionsEnabled: Boolean = true, onVerifyFiles: () -> Unit = {}, onCheckForUpdate: () -> Unit = {}, onWorkshop: () -> Unit = {}, onAchievements: () -> Unit = {}, + onCheats: () -> Unit = {}, ) { var menuOpen by remember { mutableStateOf(false) } var anchorHeightPx by remember { mutableStateOf(0) } + val menuInteractive = menuEnabled || showAchievements || showCheats Box { Surface( color = Color.White.copy(alpha = 0.1f), @@ -837,7 +869,7 @@ private fun SourceTag( modifier = Modifier .onSizeChanged { anchorHeightPx = it.height } - .then(if (menuEnabled) Modifier.clickable { menuOpen = true } else Modifier), + .then(if (menuInteractive) Modifier.clickable { menuOpen = true } else Modifier), ) { Row( modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp), @@ -858,7 +890,7 @@ private fun SourceTag( maxLines = 1, overflow = TextOverflow.Ellipsis, ) - if (menuEnabled) { + if (menuInteractive) { Icon( Icons.Outlined.ArrowDropDown, contentDescription = stringResource(R.string.store_game_steam_options), @@ -868,28 +900,28 @@ private fun SourceTag( } } } - if (menuEnabled) { + if (menuInteractive) { val gapPx = with(LocalDensity.current) { 6.dp.roundToPx() } LaunchSourceActionPopup( expanded = menuOpen, onDismissRequest = { menuOpen = false }, offset = IntOffset(0, anchorHeightPx + gapPx), ) { - if (showVerifyFiles) { + if (menuEnabled && showVerifyFiles) { LaunchSourceMenuItem( icon = Icons.AutoMirrored.Outlined.FactCheck, label = stringResource(R.string.store_game_verify_files), enabled = areSteamActionsEnabled, ) { menuOpen = false; onVerifyFiles() } } - if (showCheckForUpdate) { + if (menuEnabled && showCheckForUpdate) { LaunchSourceMenuItem( icon = Icons.Outlined.Refresh, label = stringResource(R.string.store_game_check_for_update), enabled = areSteamActionsEnabled, ) { menuOpen = false; onCheckForUpdate() } } - if (showWorkshop) { + if (menuEnabled && showWorkshop) { LaunchSourceMenuItem( icon = Icons.Outlined.Construction, label = stringResource(R.string.store_game_workshop), @@ -902,6 +934,13 @@ private fun SourceTag( label = stringResource(R.string.steam_achievements_title), ) { menuOpen = false; onAchievements() } } + if (showCheats) { + LaunchSourceMenuItem( + icon = Icons.Outlined.Bolt, + label = stringResource(R.string.retro_cheats_title), + enabled = cheatsEnabled, + ) { menuOpen = false; onCheats() } + } } } } diff --git a/app/src/main/app/shell/RetroConsoleRibbon.kt b/app/src/main/app/shell/RetroConsoleRibbon.kt new file mode 100644 index 000000000..7b2d6c04f --- /dev/null +++ b/app/src/main/app/shell/RetroConsoleRibbon.kt @@ -0,0 +1,72 @@ +package com.winlator.cmod.app.shell + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.width +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.layout +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp + +internal val retroLibrarySystemIds = mutableStateOf>(emptyMap()) + +internal fun libraryBadgeLabel( + appId: Int, + isCustom: Boolean, +): String? { + val systemId = retroLibrarySystemIds.value[appId] + if (systemId != null) { + return com.winlator.cmod.feature.retro.RetroSystems + .fromId(systemId) + ?.badgeLabel + ?: systemId + } + return if (isCustom) "PC" else null +} + +@Composable +internal fun RetroConsoleRibbon( + label: String, + modifier: Modifier = Modifier, +) { + Box( + modifier = + modifier + .fillMaxHeight() + .width(14.dp) + .background(Color(0xD9090C10)), + contentAlignment = Alignment.Center, + ) { + Text( + text = label, + color = Color(0xFFE6EDF3), + fontSize = 8.sp, + fontWeight = FontWeight.Bold, + letterSpacing = 1.2.sp, + maxLines = 1, + softWrap = false, + modifier = Modifier.verticalRibbonText(), + ) + } +} + +private fun Modifier.verticalRibbonText(): Modifier = + this.layout { measurable, _ -> + val placeable = measurable.measure(androidx.compose.ui.unit.Constraints()) + + layout(placeable.height, placeable.width) { + placeable.placeWithLayer( + x = -(placeable.width - placeable.height) / 2, + y = -(placeable.height - placeable.width) / 2, + ) { + rotationZ = -90f + } + } + } diff --git a/app/src/main/app/shell/UnifiedActivity.kt b/app/src/main/app/shell/UnifiedActivity.kt index ab661f60d..d0c4076af 100644 --- a/app/src/main/app/shell/UnifiedActivity.kt +++ b/app/src/main/app/shell/UnifiedActivity.kt @@ -430,6 +430,7 @@ class UnifiedActivity : private var dpadHeld = false private var joystickActive = false + @Volatile private var retroCloudUploadBusy = false internal val settingsNavBridge = SettingsNavBridge() internal val downloadsNavBridge = DownloadsNavBridge() @@ -628,6 +629,7 @@ class UnifiedActivity : } UpdateChecker.startBackgroundLoop(this) + processPendingRetroCloudBackup() } override fun onWindowFocusChanged(hasFocus: Boolean) { @@ -911,6 +913,74 @@ class UnifiedActivity : handleSettingsIntent(intent) } + internal fun retryPendingRetroCloudBackup() = processPendingRetroCloudBackup() + + private fun processPendingRetroCloudBackup() { + val prefs = androidx.preference.PreferenceManager.getDefaultSharedPreferences(this) + val hasLegacy = prefs.getString("retro_pending_backup_id", null) != null + val hasDolphin = com.winlator.cmod.feature.retro.DolphinCloudSync.peekPending(this) != null + if (!hasLegacy && !hasDolphin) return + if (!com.winlator.cmod.feature.sync.google.GameSaveBackupManager.isDriveConnected(this)) return + runCatching { + com.winlator.cmod.feature.sync.google.PlayGamesBootstrap.ensureInitialized(this) + com.google.android.gms.games.PlayGames + .getGamesSignInClient(this) + .signIn() + .addOnCompleteListener { runPendingRetroUploads() } + }.onFailure { runPendingRetroUploads() } + } + + private fun runPendingRetroUploads() { + if (retroCloudUploadBusy) return + val prefs = androidx.preference.PreferenceManager.getDefaultSharedPreferences(this) + val pendingId = prefs.getString("retro_pending_backup_id", null) + val pendingName = prefs.getString("retro_pending_backup_name", null) + val dolphinPending = com.winlator.cmod.feature.retro.DolphinCloudSync.peekPending(this) + if ((pendingId == null || pendingName == null) && dolphinPending == null) return + retroCloudUploadBusy = true + lifecycleScope.launch(Dispatchers.IO) { + try { + dolphinPending?.let { p -> + if (uploadRetroCloudBackup(p.cloudId, p.gameName)) { + com.winlator.cmod.feature.retro.DolphinCloudSync.clearPending(this@UnifiedActivity) + if (p.fingerprint.isNotEmpty()) { + prefs.edit().putString("retro_cloud_fp_${p.cloudId}", p.fingerprint).apply() + } + } + } + if (pendingId != null && pendingName != null && + uploadRetroCloudBackup(pendingId, pendingName) + ) { + prefs.edit().remove("retro_pending_backup_id").remove("retro_pending_backup_name").apply() + } + } finally { + retroCloudUploadBusy = false + } + } + } + + private suspend fun uploadRetroCloudBackup(cloudId: String, gameName: String): Boolean { + val result = + runCatching { + GameSaveBackupManager.backupSaveToGoogle( + this@UnifiedActivity, + GameSaveBackupManager.GameSource.CUSTOM, + cloudId, + gameName, + GameSaveBackupManager.BackupOrigin.AUTO, + com.winlator.cmod.feature.sync.google.GoogleAuthMode.RESUME, + customSaveDir = com.winlator.cmod.feature.retro.RetroSaveStates.gameDir(this, gameName), + ) + }.getOrNull() + android.util.Log.i("WnDolphin", "upload id=$cloudId success=${result?.success} msg=${result?.message}") + if (result?.success == true) { + androidx.preference.PreferenceManager.getDefaultSharedPreferences(this) + .edit().putLong("retro_cloud_mark_$cloudId", System.currentTimeMillis()).apply() + return true + } + return false + } + override fun onCreate(savedInstanceState: Bundle?) { instance = this super.onCreate(savedInstanceState) @@ -931,6 +1001,7 @@ class UnifiedActivity : com.winlator.cmod.runtime.display.GlassesManager.init(this) bootstrapStartupState() maybeAutoSignInGoogleOnLaunch() + processPendingRetroCloudBackup() // Surface store-session events as toasts. lifecycleScope.launch { @@ -1191,6 +1262,7 @@ class UnifiedActivity : internal data class HomeShortcutUiState( val shortcut: Shortcut? = null, val isPinned: Boolean = false, + val loaded: Boolean = false, ) internal data class ArtworkCacheId( diff --git a/app/src/main/app/shell/UnifiedActivityDrawer.kt b/app/src/main/app/shell/UnifiedActivityDrawer.kt index 3f749527a..0fd85a29f 100644 --- a/app/src/main/app/shell/UnifiedActivityDrawer.kt +++ b/app/src/main/app/shell/UnifiedActivityDrawer.kt @@ -776,6 +776,7 @@ internal fun UnifiedActivity.AddCustomGameDialog(onDismiss: () -> Unit) { var selectedExePath by remember { mutableStateOf(null) } var gameName by remember { mutableStateOf("") } var gameFolder by remember { mutableStateOf(null) } + var retroSystem by remember { mutableStateOf(null) } var isAdding by remember { mutableStateOf(false) } var nameEditing by remember { mutableStateOf(false) } val nameFocus = remember { FocusRequester() } @@ -787,26 +788,46 @@ internal fun UnifiedActivity.AddCustomGameDialog(onDismiss: () -> Unit) { } } val registry = remember { PaneNavRegistry() } - val addEnabled = selectedExePath != null && gameName.isNotBlank() && gameFolder != null && !isAdding + val addEnabled = + selectedExePath != null && gameName.isNotBlank() && !isAdding && + (retroSystem != null || gameFolder != null) val doAdd: () -> Unit = { isAdding = true + val chosenRetro = retroSystem scope.launch(Dispatchers.IO) { - addCustomGame(context, gameName.trim(), selectedExePath!!, gameFolder!!) + val added = + if (chosenRetro != null) { + com.winlator.cmod.feature.retro.RetroShortcuts + .create(context, gameName.trim(), selectedExePath!!, chosenRetro) + } else { + addCustomGame(context, gameName.trim(), selectedExePath!!, gameFolder!!) + true + } withContext(Dispatchers.Main) { isAdding = false - com.winlator.cmod.shared.ui.toast.WinToast.show( - context, - "$gameName added!", - android.widget.Toast.LENGTH_SHORT, - ) - onDismiss() + if (added) { + com.winlator.cmod.shared.ui.toast.WinToast.show( + context, + "$gameName added!", + android.widget.Toast.LENGTH_SHORT, + ) + onDismiss() + } else { + com.winlator.cmod.shared.ui.toast.WinToast.show( + context, + "Could not add game", + android.widget.Toast.LENGTH_SHORT, + ) + } } } } fun selectExecutable(path: String) { + val detectedRetro = com.winlator.cmod.feature.retro.RetroSystems.detectForFile(path) val file = java.io.File(path) - if (!file.isFile || file.extension.lowercase() !in DirectoryPickerDialog.ExecutableExtensions) { + val launchable = file.extension.lowercase() in DirectoryPickerDialog.ExecutableExtensions + if (!file.isFile || (!launchable && detectedRetro == null)) { com.winlator.cmod.shared.ui.toast.WinToast.show( context, R.string.common_ui_select_valid_exe_file, @@ -816,7 +837,13 @@ internal fun UnifiedActivity.AddCustomGameDialog(onDismiss: () -> Unit) { } selectedExePath = path - gameFolder = LibraryShortcutUtils.detectCustomGameFolder(path) + retroSystem = detectedRetro + gameFolder = + if (detectedRetro != null) { + java.io.File(path).parent + } else { + LibraryShortcutUtils.detectCustomGameFolder(path) + } // Auto-generate a game name from the EXE name (without extension) if (gameName.isBlank()) { gameName = @@ -886,7 +913,8 @@ internal fun UnifiedActivity.AddCustomGameDialog(onDismiss: () -> Unit) { android.os.Environment.DIRECTORY_DOWNLOADS, ).absolutePath, title = getString(R.string.common_ui_select_exe), - allowedExtensions = DirectoryPickerDialog.ExecutableExtensions, + allowedExtensions = DirectoryPickerDialog.ExecutableExtensions + + com.winlator.cmod.feature.retro.RetroSystems.allExtensions, dimAmount = 0.5f, preserveBackdropBlur = true, extraRoots = driveRoots(includeInternal = true), @@ -899,7 +927,7 @@ internal fun UnifiedActivity.AddCustomGameDialog(onDismiss: () -> Unit) { Icon(Icons.Outlined.FolderOpen, contentDescription = null, tint = Accent, modifier = Modifier.size(16.dp)) Spacer(Modifier.width(8.dp)) Text( - selectedExePath ?: "Select Executable", + selectedExePath ?: "Select Executable or Console ROM", color = if (selectedExePath == null) TextSecondary else TextPrimary, maxLines = if (selectedExePath == null) 1 else Int.MAX_VALUE, overflow = if (selectedExePath == null) TextOverflow.Ellipsis else TextOverflow.Visible, @@ -947,6 +975,72 @@ internal fun UnifiedActivity.AddCustomGameDialog(onDismiss: () -> Unit) { Spacer(Modifier.height(8.dp)) + if (retroSystem != null) { + val activeRetroSystem = retroSystem + var consoleMenuOpen by remember { mutableStateOf(false) } + Box { + Row( + modifier = + Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(10.dp)) + .background(Color.White.copy(alpha = 0.05f)) + .paneNavItem( + cornerRadius = 10.dp, + tapToSelect = true, + onActivate = { consoleMenuOpen = true }, + ).clickable { consoleMenuOpen = true } + .padding(horizontal = 10.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon( + Icons.Outlined.SportsEsports, + contentDescription = null, + tint = StatusOnline.copy(alpha = 0.7f), + modifier = Modifier.size(14.dp), + ) + Spacer(Modifier.width(6.dp)) + Column(Modifier.weight(1f)) { + Text("Console", color = TextSecondary, fontSize = 9.sp) + Text( + activeRetroSystem?.displayName ?: "", + color = TextPrimary, + fontSize = 10.sp, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + Icon( + Icons.Outlined.Edit, + contentDescription = stringResource(R.string.common_ui_change), + tint = Accent, + modifier = Modifier.size(14.dp), + ) + } + DropdownMenu( + expanded = consoleMenuOpen, + onDismissRequest = { consoleMenuOpen = false }, + containerColor = Color(0xFF1C232E), + ) { + com.winlator.cmod.feature.retro.RetroSystems.ALL.forEach { candidate -> + DropdownMenuItem( + text = { + Text( + candidate.displayName, + color = + if (candidate.id == activeRetroSystem?.id) Accent else TextPrimary, + fontSize = 12.sp, + ) + }, + onClick = { + retroSystem = candidate + consoleMenuOpen = false + }, + ) + } + } + } + } else { // Game folder — single compact row Row( modifier = @@ -1006,6 +1100,7 @@ internal fun UnifiedActivity.AddCustomGameDialog(onDismiss: () -> Unit) { ) } } + } } } diff --git a/app/src/main/app/shell/UnifiedActivityGameDialogs.kt b/app/src/main/app/shell/UnifiedActivityGameDialogs.kt index 8d19bc398..14e238890 100644 --- a/app/src/main/app/shell/UnifiedActivityGameDialogs.kt +++ b/app/src/main/app/shell/UnifiedActivityGameDialogs.kt @@ -899,6 +899,7 @@ internal fun UnifiedActivity.GameSettingsDialog( HomeShortcutUiState( shortcut = shortcut, isPinned = shortcut?.let { LibraryShortcutUtils.hasPinnedHomeShortcut(context, it) } == true, + loaded = true, ) } } @@ -1265,6 +1266,7 @@ internal fun UnifiedActivity.GameSettingsDialog( gameId = gameIdStr, gameName = app.name, shortcut = shortcut, + retroSaveDir = com.winlator.cmod.feature.sync.google.GameSaveBackupManager.retroSaveDir(context, shortcut), onCloudSyncToggle = { enabled -> cloudSyncEnabled = enabled setShortcutCloudSyncEnabled(shortcut, enabled) @@ -1426,6 +1428,7 @@ internal fun UnifiedActivity.GOGGameSettingsDialog( HomeShortcutUiState( shortcut = shortcut, isPinned = shortcut?.let { LibraryShortcutUtils.hasPinnedHomeShortcut(context, it) } == true, + loaded = true, ) } } @@ -1761,6 +1764,7 @@ internal fun UnifiedActivity.LibraryGameDetailDialog( HomeShortcutUiState( shortcut = shortcut, isPinned = shortcut?.let { LibraryShortcutUtils.hasPinnedHomeShortcut(context, it) } == true, + loaded = true, ) } } @@ -1781,6 +1785,32 @@ internal fun UnifiedActivity.LibraryGameDetailDialog( } } val hasPinnedShortcut = pinnedShortcutOverride ?: homeShortcutState.isPinned + val librarySystemIdHint = if (isCustom) retroLibrarySystemIds.value[app.id] else null + val retroCaps = + remember(homeShortcutState.shortcut, homeShortcutState.loaded, isCustom, librarySystemIdHint) { + when { + !isCustom -> com.winlator.cmod.feature.retro.RetroShortcuts.LibraryCapabilities() + homeShortcutState.loaded -> + com.winlator.cmod.feature.retro.RetroShortcuts.libraryCapabilities(homeShortcutState.shortcut) + else -> + com.winlator.cmod.feature.retro.RetroShortcuts.libraryCapabilitiesForSystemId(librarySystemIdHint) + } + } + val isRetro = retroCaps.isRetro + val isExternalRetro = retroCaps.isExternal + val retroSystemId = retroCaps.systemId + val retroRomPath = + retroCaps.romPath + ?: homeShortcutState.shortcut + ?.getExtra(com.winlator.cmod.feature.retro.RetroShortcuts.KEY_ROM) + ?.takeIf { it.isNotEmpty() } + LaunchedEffect(retroSystemId, retroRomPath, isExternalRetro) { + val sid = retroSystemId + val rp = retroRomPath + if (sid != null && rp != null && !isExternalRetro) { + com.winlator.cmod.feature.retro.RetroAchievementsManager.prefetch(context, sid, rp) + } + } BackHandler(enabled = activePopup != null) { activePopup = null @@ -1870,7 +1900,14 @@ internal fun UnifiedActivity.LibraryGameDetailDialog( when { isGog -> "GOG" isEpic -> "Epic Games" - isCustom -> "Custom" + isCustom -> + retroCaps.sourceLabel + ?: librarySystemIdHint?.let { + com.winlator.cmod.feature.retro.RetroSystems + .fromId(it) + ?.badgeLabel + } + ?: "Custom" else -> "Steam" } @@ -2313,6 +2350,81 @@ internal fun UnifiedActivity.LibraryGameDetailDialog( ) } } + var showSaveTransfer by remember(app.id) { mutableStateOf(false) } + val retroSaveImportLauncher = + rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> + if (uri != null) { + val sourceName = + context.contentResolver.query(uri, arrayOf(android.provider.OpenableColumns.DISPLAY_NAME), null, null, null)?.use { + if (it.moveToFirst()) it.getString(0) else null + } ?: "save" + val result = + runCatching { + val bytes = + context.contentResolver.openInputStream(uri)?.use { it.readBytes() } + ?: return@runCatching com.winlator.cmod.feature.retro.RetroSaveImport.Result.Invalid("Could not read the file.") + com.winlator.cmod.feature.retro.RetroSaveImport.import(context, app.name, sourceName, bytes) + }.getOrElse { com.winlator.cmod.feature.retro.RetroSaveImport.Result.Invalid("Could not read the file.") } + val message = + when (result) { + is com.winlator.cmod.feature.retro.RetroSaveImport.Result.Success -> + "Imported save (${result.name}, ${result.bytes / 1024} KB)" + is com.winlator.cmod.feature.retro.RetroSaveImport.Result.Invalid -> + "Import failed: ${result.reason}" + } + android.widget.Toast.makeText(context, message, android.widget.Toast.LENGTH_LONG).show() + } + } + val retroSaveExportLauncher = + rememberLauncherForActivityResult( + ActivityResultContracts.CreateDocument("application/octet-stream"), + ) { uri -> + if (uri != null) { + val ok = + runCatching { + val sram = + com.winlator.cmod.feature.retro.RetroSaveStates.sramFile(context, app.name) + if (!sram.isFile) return@runCatching false + context.contentResolver.openOutputStream(uri)?.use { it.write(sram.readBytes()) } + true + }.getOrDefault(false) + android.widget.Toast.makeText( + context, + context.getString( + if (ok) R.string.retro_save_transfer_export_ok else R.string.retro_save_transfer_export_failed, + ), + android.widget.Toast.LENGTH_SHORT, + ).show() + } + } + if (showSaveTransfer) { + androidx.compose.material3.AlertDialog( + onDismissRequest = { showSaveTransfer = false }, + title = { androidx.compose.material3.Text(stringResource(R.string.retro_save_transfer_title)) }, + text = { androidx.compose.material3.Text(stringResource(R.string.retro_save_transfer_message)) }, + confirmButton = { + androidx.compose.material3.TextButton(onClick = { + showSaveTransfer = false + retroSaveImportLauncher.launch(arrayOf("*/*")) + }) { androidx.compose.material3.Text(stringResource(R.string.retro_save_transfer_import)) } + }, + dismissButton = { + androidx.compose.material3.TextButton(onClick = { + val sram = com.winlator.cmod.feature.retro.RetroSaveStates.sramFile(context, app.name) + showSaveTransfer = false + if (!sram.isFile) { + android.widget.Toast.makeText( + context, + context.getString(R.string.retro_save_transfer_none), + android.widget.Toast.LENGTH_SHORT, + ).show() + } else { + retroSaveExportLauncher.launch("${app.name}.srm") + } + }) { androidx.compose.material3.Text(stringResource(R.string.retro_save_transfer_export)) } + }, + ) + } LibraryGameLaunchScreen( appName = launchAppName, subtitle = subtitle, @@ -2325,6 +2437,9 @@ internal fun UnifiedActivity.LibraryGameDetailDialog( lastPlayedMillis = lastPlayed, installSizeText = installSizeText, isCustom = isCustom, + isRetro = isRetro, + showBootToDesktop = retroCaps.showBootToDesktop, + showSaveTransfer = retroCaps.showSaveTransfer, hasPinnedShortcut = hasPinnedShortcut, playEnabled = playEnabled, playDisabledLabel = playDisabledLabel, @@ -2345,7 +2460,6 @@ internal fun UnifiedActivity.LibraryGameDetailDialog( onSettings = { val shortcut = resolveOrCreateShortcut() if (shortcut != null) { - // Layer the settings dialog on top; keep the detail dialog open underneath. ShortcutSettingsComposeDialog(this@LibraryGameDetailDialog, shortcut).show() } }, @@ -2362,9 +2476,46 @@ internal fun UnifiedActivity.LibraryGameDetailDialog( ) } }, - onAchievements = if (!isCustom && !isEpic && !isGog) { - { showAchievements = true } - } else null, + onAchievements = + when { + isRetro -> { + val sysId = retroSystemId + val rom = retroRomPath + if (sysId != null && rom != null && retroCaps.showAchievements) { + { + context.startActivity( + android.content.Intent( + context, + com.winlator.cmod.feature.retro.RetroAchievementsActivity::class.java, + ).apply { + putExtra( + com.winlator.cmod.feature.retro.RetroAchievementsActivity.EXTRA_SYSTEM_ID, + sysId, + ) + putExtra( + com.winlator.cmod.feature.retro.RetroAchievementsActivity.EXTRA_ROM_PATH, + rom, + ) + putExtra( + com.winlator.cmod.feature.retro.RetroAchievementsActivity.EXTRA_GAME_NAME, + app.name, + ) + putExtra( + com.winlator.cmod.feature.retro.RetroAchievementsActivity.EXTRA_IN_SESSION, + false, + ) + }, + ) + } + } else { + null + } + } + !isCustom && !isEpic && !isGog -> { + { showAchievements = true } + } + else -> null + }, onShortcut = { if (hasPinnedShortcut) { heroPopup = HeroLaunchPopup.RemoveShortcut @@ -2399,9 +2550,41 @@ internal fun UnifiedActivity.LibraryGameDetailDialog( } }, onCloudSaves = { activePopup = LibraryDetailPopup.CloudSaves }, + onSaveTransfer = + if (retroCaps.showSaveTransfer) { + { showSaveTransfer = true } + } else { + null + }, + onCheats = + if (retroCaps.showCheats && retroSystemId != null) { + { + context.startActivity( + android.content.Intent( + context, + com.winlator.cmod.feature.retro.RetroCheatsActivity::class.java, + ).apply { + putExtra( + com.winlator.cmod.feature.retro.RetroCheatsActivity.EXTRA_SYSTEM_ID, + retroSystemId, + ) + putExtra( + com.winlator.cmod.feature.retro.RetroCheatsActivity.EXTRA_GAME_NAME, + app.name, + ) + }, + ) + } + } else { + null + }, + cheatsEnabled = + !( + com.winlator.cmod.feature.retro.RetroAchievementsManager.isEnabled(context) && + com.winlator.cmod.feature.retro.RetroAchievementsManager.isLoggedIn(context) && + com.winlator.cmod.feature.retro.RetroAchievementsManager.isHardcorePreferred(context) + ), onUninstall = uninstallGame, - // Store source tag actions. Steam exposes verify/update/workshop; - // Epic and GOG expose verify/update for installed games. steamMenuEnabled = !isCustom && (!isEpic || epicGame?.isInstalled == true) && (!isGog || gogGame?.isInstalled == true), @@ -2411,7 +2594,7 @@ internal fun UnifiedActivity.LibraryGameDetailDialog( showCheckForUpdate = !isCustom && (!isEpic || epicGame?.isInstalled == true) && (!isGog || gogGame?.isInstalled == true), - showWorkshop = !isEpic && !isGog, + showWorkshop = !isCustom && !isEpic && !isGog, areSteamActionsEnabled = when { isEpic -> !hasBlockingEpicDownloadForLibrary @@ -2430,8 +2613,6 @@ internal fun UnifiedActivity.LibraryGameDetailDialog( } } if (started != null) { - // Hand off to the activity-root host so the - // pop-up + completion notice outlive this dialog. showTaskProgressPopup( started, if (isGog) gogGame!!.title else app.name, @@ -2457,7 +2638,7 @@ internal fun UnifiedActivity.LibraryGameDetailDialog( else -> startUpdateCheck(app.id, app.name) } }, - onWorkshop = { if (!isEpic && !isGog) showWorkshopDialog = true }, + onWorkshop = { if (!isEpic && !isGog && !isCustom) showWorkshopDialog = true }, ) when (heroPopup) { @@ -2631,6 +2812,7 @@ internal fun UnifiedActivity.LibraryGameDetailDialog( gameId = detailGameId, gameName = app.name, shortcut = detailShortcut, + retroSaveDir = com.winlator.cmod.feature.sync.google.GameSaveBackupManager.retroSaveDir(context, detailShortcut), onCloudSyncToggle = { enabled -> cloudSyncEnabled = enabled setShortcutCloudSyncEnabled(detailShortcut, enabled) @@ -2824,6 +3006,7 @@ internal fun UnifiedActivity.LibraryGameDetailDialog( gameId = detailGameId, gameName = app.name, shortcut = detailShortcut, + retroSaveDir = com.winlator.cmod.feature.sync.google.GameSaveBackupManager.retroSaveDir(context, detailShortcut), onCloudSyncToggle = { enabled -> cloudSyncEnabled = enabled setShortcutCloudSyncEnabled(detailShortcut, enabled) diff --git a/app/src/main/app/shell/UnifiedActivityHub.kt b/app/src/main/app/shell/UnifiedActivityHub.kt index 755c4987f..6f3744af4 100644 --- a/app/src/main/app/shell/UnifiedActivityHub.kt +++ b/app/src/main/app/shell/UnifiedActivityHub.kt @@ -1837,7 +1837,7 @@ internal fun UnifiedActivity.LibraryCarousel( var localLibraryRefreshKey by remember { mutableIntStateOf(0) } var shortcutsLoaded by remember { mutableStateOf(false) } var pullRefreshing by remember { mutableStateOf(false) } - LaunchedEffect(shortcutRefreshKey, localLibraryRefreshKey) { + LaunchedEffect(shortcutRefreshKey, localLibraryRefreshKey, com.winlator.cmod.feature.retro.RetroBoxart.artVersion.value) { shortcutsLoaded = false // Pull-to-refresh only: rescan disk so a manually moved game is picked up without faking a re-download. @@ -1851,11 +1851,13 @@ internal fun UnifiedActivity.LibraryCarousel( val shortcutScanResult = runCatching { withContext(Dispatchers.IO) { + runCatching { com.winlator.cmod.feature.retro.RetroRomScanner.scanConfiguredFolder(context) } val cm = ContainerManager(context) cm.upgradeShortcuts { localLibraryRefreshKey++ } val allShortcuts = cm.loadShortcuts() + val badges = HashMap() val apps = allShortcuts .mapNotNull { shortcut -> @@ -1875,6 +1877,13 @@ internal fun UnifiedActivity.LibraryCarousel( -(displayName.hashCode().and(0x7FFFFFFF) + 1) } + com.winlator.cmod.feature.retro.RetroSystems + .fromId( + shortcut.getExtra( + com.winlator.cmod.feature.retro.RetroShortcuts.KEY_SYSTEM, + ), + )?.let { badges[customId] = it.id } + SteamApp( id = customId, name = displayName, @@ -1887,13 +1896,14 @@ internal fun UnifiedActivity.LibraryCarousel( ) } - allShortcuts to apps + Triple(allShortcuts, apps, badges) } }.getOrNull() if (shortcutScanResult != null) { cachedShortcuts = shortcutScanResult.first customApps = shortcutScanResult.second + retroLibrarySystemIds.value = shortcutScanResult.third } shortcutsLoaded = true diff --git a/app/src/main/app/shell/UnifiedActivityLaunch.kt b/app/src/main/app/shell/UnifiedActivityLaunch.kt index d7691b39b..d486a0558 100644 --- a/app/src/main/app/shell/UnifiedActivityLaunch.kt +++ b/app/src/main/app/shell/UnifiedActivityLaunch.kt @@ -923,6 +923,22 @@ internal fun UnifiedActivity.launchCustomGame( return@launch } + if (com.winlator.cmod.feature.retro.RetroShortcuts.isRetroShortcut(shortcut)) { + val retroSystem = com.winlator.cmod.feature.retro.RetroShortcuts.systemForShortcut(shortcut) + val embeddedDolphin = + com.winlator.cmod.feature.retro.RetroCoreManager.usesDolphinCore(retroSystem) && + com.winlator.cmod.feature.retro.RetroShortcuts.embeddedDolphinEnabled(context) + if ((retroSystem != null && retroSystem.isExternal) || embeddedDolphin) { + withContext(Dispatchers.Main) { + com.winlator.cmod.feature.retro.RetroShortcuts.launch(context, shortcut) + } + return@launch + } + val retroIntent = com.winlator.cmod.feature.retro.RetroShortcuts.launchIntent(context, shortcut) + withContext(Dispatchers.Main) { launchGame(context, retroIntent) } + return@launch + } + // Backfill custom_name if missing (legacy shortcuts) if (shortcut.getExtra("custom_name").isEmpty()) { shortcut.putExtra("custom_name", gameName) diff --git a/app/src/main/app/shell/UnifiedActivityStartup.kt b/app/src/main/app/shell/UnifiedActivityStartup.kt index 0c587030d..887ef156d 100644 --- a/app/src/main/app/shell/UnifiedActivityStartup.kt +++ b/app/src/main/app/shell/UnifiedActivityStartup.kt @@ -464,6 +464,7 @@ internal fun UnifiedActivity.maybeAutoSignInGoogleOnLaunch() { if (authed) { com.winlator.cmod.feature.sync.google.GameSaveBackupManager .setDriveConnected(applicationContext, true) + retryPendingRetroCloudBackup() } } }.onFailure { diff --git a/app/src/main/app/shell/UnifiedActivityStores.kt b/app/src/main/app/shell/UnifiedActivityStores.kt index dc1441e8c..f466d40da 100644 --- a/app/src/main/app/shell/UnifiedActivityStores.kt +++ b/app/src/main/app/shell/UnifiedActivityStores.kt @@ -538,6 +538,9 @@ internal fun UnifiedActivity.GameCapsule( .clip(RoundedCornerShape(8.dp)), ) { ArtContent(Modifier.fillMaxSize()) + libraryBadgeLabel(app.id, isCustom)?.let { badge -> + RetroConsoleRibbon(badge, Modifier.align(Alignment.CenterStart)) + } } Spacer(Modifier.width(14.dp)) @@ -585,6 +588,9 @@ internal fun UnifiedActivity.GameCapsule( .clip(RoundedCornerShape(topStart = 12.dp, topEnd = 12.dp)), ) { ArtContent(Modifier.fillMaxSize()) + libraryBadgeLabel(app.id, isCustom)?.let { badge -> + RetroConsoleRibbon(badge, Modifier.align(Alignment.CenterStart)) + } } Text( diff --git a/app/src/main/assets/dnas/dnas_bypass.json b/app/src/main/assets/dnas/dnas_bypass.json new file mode 100644 index 000000000..fb7610484 --- /dev/null +++ b/app/src/main/assets/dnas/dnas_bypass.json @@ -0,0 +1,514 @@ +{ + "SCES-51706": { + "title": "Amplitude", + "cheats": [ + { + "name": "DNAS Patch", + "codes": [ + "D04E7BFA 00000001", + "2025BE18 14400013" + ], + "auto": true + } + ] + }, + "SLUS-21165": { + "title": "Arc the Lad: End of Darkness", + "cheats": [ + { + "name": "DNAS Bypass by Harry62", + "codes": [ + "2011AF84 00000000" + ], + "auto": true + } + ] + }, + "SLES-53729": { + "title": "Battlefield 2: Modern Combat", + "cheats": [ + { + "name": "DNAS Bypass Code", + "codes": [ + "2021A268 00000000" + ], + "crc": "185D22A9", + "auto": true + }, + { + "name": "DNAS Bypass Code", + "codes": [ + "2021A078 00000000" + ], + "crc": "89CDE501", + "auto": true + } + ] + }, + "SLES-53730": { + "title": "Battlefield 2: Modern Combat", + "cheats": [ + { + "name": "DNAS Bypass Code", + "codes": [ + "2021A268 00000000" + ], + "auto": true + } + ] + }, + "SLPM-66206": { + "title": "Battlefield 2: Modern Combat", + "cheats": [ + { + "name": "DNAS Bypass Code", + "codes": [ + "2021A078 00000000" + ], + "auto": true + } + ] + }, + "SLUS-21026": { + "title": "Battlefield 2: Modern Combat", + "cheats": [ + { + "name": "DNAS Bypass", + "codes": [ + "2021A240 00000000" + ], + "auto": true + } + ] + }, + "SLES-52782": { + "title": "Call of Duty: Finest Hour", + "cheats": [ + { + "name": "DNAS Bypass Code", + "codes": [ + "D02942F0 0000F0B6", + "202942F0 00000000" + ], + "auto": true + } + ] + }, + "SCES-50781": { + "title": "Destruction Derby Arenas", + "cheats": [ + { + "name": "[MODE 3] DNAS Patch", + "codes": [ + "D1D8139C 24020006", + "01D81390 00000000", + "D1D8139C 24020006", + "01D8139C 00000005" + ], + "auto": true + } + ] + }, + "SCES-53033": { + "title": "Formula One 05", + "cheats": [ + { + "name": "DNAS bypass", + "codes": [ + "D039FBA4 24020006", + "0039FB98 00000000", + "D039FBA4 24020006", + "0039FBA4 00000005" + ], + "auto": true + } + ] + }, + "SLES-53667": { + "title": "Gauntlet: Seven Sorrows", + "cheats": [ + { + "name": "DNAS Bypass", + "codes": [ + "203842E0 03E00008", + "203842E4 00000000" + ], + "auto": true + } + ] + }, + "PAPX-90523": { + "title": "Gran Turismo 4 Online (Beta)", + "cheats": [ + { + "name": "DNAS Bypass Code", + "codes": [ + "D188D734 24020006", + "0188D728 00000000", + "D188D734 24020006", + "0188D734 00000005" + ], + "auto": true + } + ] + }, + "SCES-51977": { + "title": "Hardware: Online Arena", + "cheats": [ + { + "name": "DNAS Bypass", + "codes": [ + "D1D424A8 00000007", + "01D424A8 00000005", + "D1D424A8 00000006", + "01D424A8 00000005" + ], + "auto": true + } + ] + }, + "SLES-53585": { + "title": "Marvel Nemesis: Rise of the Imperfects", + "cheats": [ + { + "name": "DNAS Bypass", + "codes": [ + "2020249C 00000000" + ], + "auto": true + } + ] + }, + "SLUS-21281": { + "title": "Marvel Nemesis: Rise of the Imperfects", + "cheats": [ + { + "name": "DNAS Bypass", + "codes": [ + "2020249C 00000000", + "20509B9C 00000000" + ], + "auto": true + } + ] + }, + "SCES-51677": { + "title": "MyStreet", + "cheats": [ + { + "name": "DNAS Patch", + "codes": [ + "D19A40B4 24020006", + "019A40A8 00000000", + "D19A40B4 24020006", + "019A40B4 00000005" + ], + "auto": true + } + ] + }, + "SCES-52456": { + "title": "Ratchet & Clank 3", + "cheats": [ + { + "name": "DNAS Patch", + "codes": [ + "D04D55E4 24020006", + "004D55D8 00000000", + "D04D55E4 24020006", + "004D55E4 00000005" + ], + "auto": true + }, + { + "name": "DNAS Patch", + "codes": [ + "D178CAF4 24020006", + "0178CAE8 00000000", + "D178CAF4 24020006", + "0178CAF4 00000005" + ], + "auto": false + } + ] + }, + "SCUS-97474": { + "title": "SOCOM 3: U.S. Navy SEALs", + "cheats": [ + { + "name": "DNAS Bypass (Base version of the game)", + "codes": [ + "202859A0 03E00008", + "202859A4 00000000" + ], + "auto": true + }, + { + "name": "DNAS Bypass (Patch 2.3)", + "codes": [ + "2028AE10 03E00008", + "2028AE14 00000000" + ], + "auto": false + } + ] + }, + "SCUS-97489": { + "title": "SOCOM 3: U.S. Navy SEALs", + "cheats": [ + { + "name": "DNAS Bypass", + "codes": [ + "202461E0 03E00008", + "202461E4 00000000" + ], + "auto": true + } + ] + }, + "SCUS-97545": { + "title": "SOCOM: U.S. Navy SEALs Combined Assault", + "cheats": [ + { + "name": "DNAS Bypass (Works for both 1.0 and 1.4 version of the game)", + "codes": [ + "2029A2DC 24020001", + "2029BD90 03E00008", + "2029BD94 00000000" + ], + "auto": true + } + ] + }, + "SCES-52306": { + "title": "SOCOM II: U.S. Navy SEALs", + "cheats": [ + { + "name": "DNAS Bypass", + "codes": [ + "202D61B0 03E00008", + "202D61B4 00000000" + ], + "auto": true + } + ] + }, + "SCKA-20020": { + "title": "SOCOM II: U.S. Navy SEALs", + "cheats": [ + { + "name": "DNAS Bypass", + "codes": [ + "202D7818 24020001" + ], + "auto": true + } + ] + }, + "SCPS-15065": { + "title": "SOCOM II: U.S. Navy SEALs", + "cheats": [ + { + "name": "DNAS Bypass", + "codes": [ + "202DD648 24020001" + ], + "auto": true + } + ] + }, + "SCUS-97275": { + "title": "SOCOM II: U.S. Navy SEALs", + "cheats": [ + { + "name": "DNAS Bypass r0001", + "codes": [ + "202CC670 03E00008", + "202CC674 00000000" + ], + "auto": true + }, + { + "name": "DNAS Bypass r0004", + "codes": [ + "203953C0 03E00008", + "203953C4 00000000" + ], + "auto": true + } + ] + }, + "SCUS-97366": { + "title": "SOCOM II: U.S. Navy SEALs", + "cheats": [ + { + "name": "DNAS Bypass(Harry62)", + "codes": [ + "203953C0 03E00008", + "203953C4 00000000" + ], + "auto": true + } + ] + }, + "TCES-51904": { + "title": "SOCOM II: U.S. Navy SEALs", + "cheats": [ + { + "name": "DNAS Bypass", + "codes": [ + "2040F1C0 03E00008", + "2040F1C4 00000000" + ], + "auto": true + } + ] + }, + "SCKA-24008": { + "title": "SOCOM: U.S. Navy SEALs", + "cheats": [ + { + "name": "DNAS Bypass", + "codes": [ + "20379C48 00000000" + ], + "auto": true + } + ] + }, + "SCKA-90010": { + "title": "SOCOM: U.S. Navy SEALs", + "cheats": [ + { + "name": "DNAS Bypass", + "codes": [ + "20379548 00000000" + ], + "auto": true + } + ] + }, + "SCPS-15044": { + "title": "SOCOM: U.S. Navy SEALs", + "cheats": [ + { + "name": "DNAS Bypass", + "codes": [ + "203814C8 00000000" + ], + "auto": true + } + ] + }, + "SCES-52033": { + "title": "Syphon Filter: The Omega Strain", + "cheats": [ + { + "name": "DNAS Bypass", + "codes": [ + "20382390 03E00008", + "20382394 00000000" + ], + "auto": true + } + ] + }, + "SCKA-20032": { + "title": "Syphon Filter: The Omega Strain", + "cheats": [ + { + "name": "DNAS Bypass", + "codes": [ + "20384D30 03E00008", + "20384D34 00000000" + ], + "auto": true + } + ] + }, + "SCUS-97264": { + "title": "Syphon Filter: The Omega Strain", + "cheats": [ + { + "name": "DNAS Bypass", + "codes": [ + "2044B7A0 03E00008", + "2044B7A4 00000000" + ], + "auto": true + }, + { + "name": "DNAS Bypass", + "codes": [ + "20343940 03E00008", + "20343944 00000000" + ], + "auto": false + } + ] + }, + "SCUS-97397": { + "title": "Syphon Filter: The Omega Strain", + "cheats": [ + { + "name": "DNAS Bypass", + "codes": [ + "203563C0 03E00008", + "203563C4 00000000" + ], + "auto": true + } + ] + }, + "TCES-52033": { + "title": "Syphon Filter: The Omega Strain", + "cheats": [ + { + "name": "DNAS Bypass", + "codes": [ + "2037B960 03E00008", + "2037B964 00000000" + ], + "auto": true + } + ] + }, + "SCES-52389": { + "title": "WRC 4", + "cheats": [ + { + "name": "DNAS Bypass", + "codes": [ + "D05B4C88 00000000", + "205B4C88 00000001" + ], + "crc": "CDE7C999", + "auto": true + }, + { + "name": "DNAS Bypass", + "codes": [ + "D05B4E88 00000000", + "205B4E88 00000001" + ], + "crc": "AFD06CBA", + "auto": true + } + ] + }, + "TCES-53247": { + "title": "WRC: Rally Evolved", + "cheats": [ + { + "name": "DNAS Patch", + "codes": [ + "D19606AC 24020006", + "019606A0 00000000", + "D19606AC 24020006", + "019606AC 00000005" + ], + "auto": true + } + ] + } +} \ No newline at end of file diff --git a/app/src/main/assets/retro/GLideN64.custom.ini b/app/src/main/assets/retro/GLideN64.custom.ini new file mode 100644 index 000000000..842d2d54b --- /dev/null +++ b/app/src/main/assets/retro/GLideN64.custom.ini @@ -0,0 +1,360 @@ +; Custom game settings +[General] +version=13 + +[TWINE] +Good_Name=007 - The World Is Not Enough (E)(U) +frameBufferEmulation\N64DepthCompare=1 + +[40%20WINKS] +Good_Name=40 Winks (E) (M3) (Prototype) +graphics2D\enableNativeResTexrects=1 + +[BAKU-BOMBERMAN] +Good_Name=Baku Bomberman (J) [!] +generalEmulation\enableLegacyBlending=0 + +[BIOFREAKS] +Good_Name=Bio F.R.E.A.K.S. (E)(U) +frameBufferEmulation\copyToRDRAM=1 + +[BIOHAZARD%20II] +Good_Name=Biohazard 2 (J) +frameBufferEmulation\copyFromRDRAM=1 +frameBufferEmulation\copyToRDRAM=0 +frameBufferEmulation\copyDepthToRDRAM=0 + +[BOMBERMAN64E] +Good_Name=Bomberman 64 (E) [!] +generalEmulation\enableLegacyBlending=0 + +[BOMBERMAN64U] +Good_Name=Bomberman 64 (U) [!] +generalEmulation\enableLegacyBlending=0 + +[362D06B6] +Good_Name=Densha de Go! 64 (J) +generalEmulation\enableLegacyBlending=0 + +[68D128AE] +Good_Name=Densha de Go! 64 (J) (Localization Patch v1.01) +generalEmulation\enableLegacyBlending=0 + +[52150A67] +Good_Name=Bokujou Monogatari 2 (J) +frameBufferEmulation\N64DepthCompare=1 + +[67000C2B] +Good_Name=Eikou no Saint Andrews (J) +frameBufferEmulation\forceDepthBufferClear=1 + +[CAL%20SPEED] +Good_Name=California Speed (U) +frameBufferEmulation\bufferSwapMode=1 + +[CASTLEVANIA2] +Good_Name=Castlevania - Legacy Of Darkness (E)(U) +frameBufferEmulation\copyToRDRAM=1 + +[DMPJ] +Good_Name=Mario Artist Paint Studio (J) (64DD) +frameBufferEmulation\copyAuxToRDRAM=1 +frameBufferEmulation\copyFromRDRAM=1 +frameBufferEmulation\nativeResFactor=1 +generalEmulation\rdramImageDitheringMode=0 + +[DMTJ] +Good_Name=Mario Artist Talent Studio (J) (64DD) +frameBufferEmulation\copyAuxToRDRAM=1 + +[DINO%20PLANET] +Good_Name=Dinosaur Planet (Dec 2000 Beta) +frameBufferEmulation\copyToRDRAM=1 +frameBufferEmulation\copyAuxToRDRAM=1 + +[DONKEY%20KONG%2064] +Good_Name=Donkey Kong 64 (E)(J)(U) +frameBufferEmulation\copyDepthToRDRAM=0 +frameBufferEmulation\N64DepthCompare=0 + +[DR.MARIO%2064] +Good_Name=Dr. Mario 64 (U) +frameBufferEmulation\fbInfoDisabled=0 +frameBufferEmulation\copyFromRDRAM=1 +frameBufferEmulation\copyToRDRAM=0 + +[EXTREME_G] +Good_Name=Extreme-G (E) +frameBufferEmulation\N64DepthCompare=1 + +[EXTREME-G] +Good_Name=Extreme-G (J) +frameBufferEmulation\N64DepthCompare=1 + +[EXTREMEG] +Good_Name=Extreme-G (U) +frameBufferEmulation\N64DepthCompare=1 + +[EXTREME%20G%202] +Good_Name=Extreme-G XG2 (E) (U) +frameBufferEmulation\N64DepthCompare=1 + +[208E05CD] +Good_Name=Extreme-G XG2 (J) +frameBufferEmulation\N64DepthCompare=1 + +[F1%20POLE%20POSITION%2064] +Good_Name=F-1 Pole Position 64 (E)(U) +frameBufferEmulation\copyToRDRAM=1 + +[FLAPPYBIRD64] +Good_Name=FlappyBird64 +frameBufferEmulation\fbInfoDisabled=0 +frameBufferEmulation\copyFromRDRAM=1 +frameBufferEmulation\copyToRDRAM=0 + +[GOEMON2%20DERODERO] +Good_Name=Ganbare Goemon - Dero Dero Douchuu Obake Tenkomori (J) +graphics2D\enableNativeResTexrects=1 + +[GOEMONS%20GREAT%20ADV] +Good_Name=Goemons Great Adventure (U) +graphics2D\enableNativeResTexrects=1 + +[HARVESTMOON64] +Good_Name=Harvest Moon 64 (U) +frameBufferEmulation\N64DepthCompare=1 + +[5CFA0A2E] +Good_Name=Heiwa Pachinko World 64 (J) +frameBufferEmulation\copyToRDRAM=1 + +[HEXEN] +Good_Name=Hexen (E)(F)(G)(J)(U) +frameBufferEmulation\copyToRDRAM=1 + +[HUMAN%20GRAND%20PRIX] +Good_Name=Human Grand Prix - New Generation (J) +frameBufferEmulation\copyToRDRAM=1 + +[I%20S%20S%2064] +Good_Name=International Superstar Soccer 64 (E) (U) +frameBufferEmulation\N64DepthCompare=1 + +[JET%20FORCE%20GEMINI] +Good_Name=Jet Force Gemini (E)(U) +frameBufferEmulation\fbInfoDisabled=0 +frameBufferEmulation\copyAuxToRDRAM=1 +frameBufferEmulation\copyToRDRAM=0 + +[J%20F%20G%20DISPLAY] +Good_Name=Jet Force Gemini Kiosk Demo (U) +frameBufferEmulation\fbInfoDisabled=0 +frameBufferEmulation\copyAuxToRDRAM=1 +frameBufferEmulation\copyToRDRAM=0 + +[J%20WORLD%20SOCCER3] +Good_Name=Jikkyou World Soccer 3 (J) +frameBufferEmulation\N64DepthCompare=1 + +[301E07CC] +Good_Name=Mahjong Master (J) +frameBufferEmulation\N64DepthCompare=1 + +[DMGJ] +Good_Name=Mario Artist Polygon Studio (J) +frameBufferEmulation\copyAuxToRDRAM=1 + +[KEN%20GRIFFEY%20SLUGFEST] +Good_Name=Ken Griffey Jr.'s Slugfest +frameBufferEmulation\fbInfoDisabled=0 + +[KIRBY64] +Good_Name=Kirby 64 - The Crystal Shards (E)(J)(U) +graphics2D\enableNativeResTexrects=1 + +[MARIOGOLF64] +Good_Name=Mario Golf (E)(J)(U) +frameBufferEmulation\copyDepthToRDRAM=0 + +[MARIOKART64] +Good_Name=Mario Kart 64 (E)(J)(U) +graphics2D\enableNativeResTexrects=1 +graphics2D\enableTexCoordBounds=1 +frameBufferEmulation\copyToRDRAM=2 + +[MARIO%20STORY] +Good_Name=Mario Story (J) +frameBufferEmulation\copyToRDRAM=1 + +[MEGA%20MAN%2064] +Good_Name=Mega Man 64 (U) +graphics2D\correctTexrectCoords=2 + +[MEGAMAN%2064] +Good_Name=Mega Man 64 (Proto) +graphics2D\correctTexrectCoords=2 + +[MLB%20FEATURING%20K%20G%20JR] +Good_Name=Major League Baseball Featuring Ken Griffey Jr. +frameBufferEmulation\fbInfoDisabled=0 + +[MYSTICAL%20NINJA2%20SG] +Good_Name=Mystical Ninja 2 Starring Goemon (E) +graphics2D\enableNativeResTexrects=1 + +[NASCAR%202000] +Good_Name=NASCAR 2000 (U) +frameBufferEmulation\copyToRDRAM=1 + +[NASCAR%2099] +Good_Name=NASCAR 99 (U) +frameBufferEmulation\copyToRDRAM=1 + +[NUD-DMPJ-JPN_convert] +Good_Name=Mario Paint Studio (cart hack) +frameBufferEmulation\copyFromRDRAM=1 + +[NUD-DMTJ-JPN_convert] +Good_Name=Mario Artist Talent Studio (cart hack) +frameBufferEmulation\copyAuxToRDRAM=1 + +[OGREBATTLE64] +Good_Name=Ogre Battle 64 - Person of Lordly Caliber (U) +graphics2D\enableTexCoordBounds=1 + +[OLYMPIC%20HOCKEY] +Good_Name=Olympic Hockey Nagano '98 (E)(J)(U) +frameBufferEmulation\bufferSwapMode=1 + +[PAPER%20MARIO] +Good_Name=Paper Mario (E)(U) +frameBufferEmulation\copyToRDRAM=1 +graphics2D\enableTexCoordBounds=1 + +[PENNY%20RACERS] +Good_Name=Penny Racers (E)(U) +frameBufferEmulation\copyToRDRAM=0 + +[PERFECT%20STRIKER] +Good_Name=Jikkyou J.League Perfect Striker (J) +frameBufferEmulation\N64DepthCompare=1 + +[POKEMON%20SNAP] +Good_Name=Pokemon Snap (U) +generalEmulation\rdramImageDitheringMode=1 +frameBufferEmulation\copyAuxToRDRAM=1 +frameBufferEmulation\copyToRDRAM=1 +frameBufferEmulation\fbInfoDisabled=0 + +[POKEMON%20STADIUM] +Good_Name=Pokemon Stadium (U) +frameBufferEmulation\copyDepthToRDRAM=0 + +[POKEMON%20STADIUM%202] +Good_Name=Pokemon Stadium 2 (E)(F)(G)(I)(J)(S)(U) +frameBufferEmulation\copyToRDRAM=0 +frameBufferEmulation\copyDepthToRDRAM=0 + +[POKEMON%20STADIUM%20G%26S] +Good_Name=Pokemon Stadium Kin Gin (J) +frameBufferEmulation\copyToRDRAM=0 +frameBufferEmulation\copyDepthToRDRAM=0 + +[PUZZLE%20LEAGUE%20N64] +Good_Name=Pokemon Puzzle League (E)(F)(G)(U) +texture\enableHalosRemoval=1 + +[RAT%20ATTACK] +Good_Name=Rat Attack +frameBufferEmulation\fbInfoDisabled=0 + +[RESIDENT%20EVIL%20II] +Good_Name=Resident Evil 2 (E)(U) +frameBufferEmulation\copyFromRDRAM=1 +frameBufferEmulation\copyToRDRAM=0 +frameBufferEmulation\copyDepthToRDRAM=0 + +[ROCKMAN%20DASH] +Good_Name=Rockman Dash - Hagane no Boukenshin (J) +graphics2D\correctTexrectCoords=2 + +[RUSH%202] +Good_Name=Rush 2 - Extreme Racing USA (E)(U) +frameBufferEmulation\bufferSwapMode=1 +graphics2D\correctTexrectCoords=2 + +[SAN%20FRANCISCO%20RUSH] +Good_Name=San Francisco Rush Extreme Racing (U) +frameBufferEmulation\bufferSwapMode=1 +graphics2D\enableNativeResTexrects=2 + +[S.F.RUSH] +Good_Name=San Francisco Rush Extreme Racing (E) +frameBufferEmulation\bufferSwapMode=1 +graphics2D\enableNativeResTexrects=2 + +[S.F.%20RUSH] +Good_Name=San Francisco Rush Extreme Racing (U) +frameBufferEmulation\bufferSwapMode=1 +graphics2D\enableNativeResTexrects=2 + +[SHADOWMAN] +Good_Name=Shadow Man (B)(E)(F)(G)(U) +frameBufferEmulation\copyDepthToRDRAM=0 + +[SPACE%20INVADERS] +Good_Name=Space Invaders (U) +frameBufferEmulation\copyToRDRAM=0 + +[SILICON%20VALLEY] +Good_Name=Space Station Silicon Valley (U) +frameBufferEmulation\copyToRDRAM=1 + +[STAR%20TWINS] +Good_Name=Star Twins (J) +frameBufferEmulation\fbInfoDisabled=0 +frameBufferEmulation\copyAuxToRDRAM=1 +frameBufferEmulation\copyToRDRAM=0 + +[TEST] +Good_Name=Mario Artist Paint Studio (J) (1999-02-11 Prototype) (64DD) +frameBufferEmulation\copyAuxToRDRAM=1 +frameBufferEmulation\copyFromRDRAM=1 +generalEmulation\rdramImageDitheringMode=0 + +[TETRISPHERE] +Good_Name=Tetrisphere (E)(U) +graphics2D\correctTexrectCoords=2 + +[TIGGER%27S%20HONEY%20HUNT] +Good_Name=Tiggers Honey Hunt (E)(U) +frameBufferEmulation\N64DepthCompare=1 + +[TONIC%20TROUBLE] +Good_Name=Tonic Trouble (E)(U) +frameBufferEmulation\copyToRDRAM=1 + +[TG%20RALLY%202] +Good_Name=TG Rally 2 (E) +frameBufferEmulation\copyToRDRAM=1 + +[TOP%20GEAR%20RALLY%202] +Good_Name=Top Gear Rally 2 (E)(J)(U) +frameBufferEmulation\copyToRDRAM=1 + +[TUROK_DINOSAUR_HUNTE] +Good_Name=Turok - Dinosaur Hunter (E)(G)(U)(J) +frameBufferEmulation\copyDepthToRDRAM=1 + +[WAVE%20RACE%2064] +Good_Name=Wave Race 64 (E)(U)(J) +frameBufferEmulation\copyToRDRAM=1 + +[W.G.%203DHOCKEY] +Good_Name=Wayne Gretzky's 3D Hockey (E)(U) +frameBufferEmulation\bufferSwapMode=1 + +[WGHOCKEY] +Good_Name=Wayne Gretzky's 3D Hockey (J) +frameBufferEmulation\bufferSwapMode=1 diff --git a/app/src/main/feature/library/GameSettings.kt b/app/src/main/feature/library/GameSettings.kt index c79f8eca3..c5a119b11 100644 --- a/app/src/main/feature/library/GameSettings.kt +++ b/app/src/main/feature/library/GameSettings.kt @@ -136,6 +136,7 @@ import com.winlator.cmod.runtime.reshade.ReshadeCatalogEntry import com.winlator.cmod.runtime.reshade.ReshadeDownloader import com.winlator.cmod.runtime.reshade.ReshadeLoadout import com.winlator.cmod.runtime.reshade.ReshadeManager +import com.winlator.cmod.shared.theme.GameSettingsStyle import com.winlator.cmod.runtime.wine.WineThemeManager import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch @@ -166,27 +167,26 @@ import com.winlator.cmod.shared.ui.widget.EnvVarsView import com.winlator.cmod.shared.ui.widget.chasingBorder import kotlin.math.roundToInt -private val BgDeep = Color(0xFF11111C) -private val SidebarBg = Color(0xFF11111C) -private val ContentBg = Color(0xFF11111C) -private val CardSurface = Color(0xFF1C1C2A) -private val CardBorder = Color(0xFF2A2A3A) -private val InputSurface = Color(0xFF171722) -private val InputBorder = Color(0xFF2A2A3A) -private val AccentBlue = Color(0xFF1A9FFF) -private val TextPrimary = Color(0xFFF0F4FF) -private val TextSecondary = Color(0xFF7A8FA8) -private val TextDim = Color(0xFF6E7681) -private val DividerColor = Color(0xFF2A2A3A) -private val CheckBorder = Color(0xFF2A2A3A) -private val SliderInactive = Color(0xFF21212A) -private val ChipSurface = Color(0xFF171722) -private val ChipBorder = Color(0xFF2A2A3A) -private val DangerRed = Color(0xFFFF6B6B) -private val WarningAmber = Color(0xFFFFB74D) +private val BgDeep = GameSettingsStyle.BgDeep +private val SidebarBg = GameSettingsStyle.SidebarBg +private val ContentBg = GameSettingsStyle.ContentBg +private val CardSurface = GameSettingsStyle.CardSurface +private val CardBorder = GameSettingsStyle.CardBorder +private val InputSurface = GameSettingsStyle.InputSurface +private val InputBorder = GameSettingsStyle.InputBorder +private val AccentBlue = GameSettingsStyle.AccentBlue +private val TextPrimary = GameSettingsStyle.TextPrimary +private val TextSecondary = GameSettingsStyle.TextSecondary +private val TextDim = GameSettingsStyle.TextDim +private val DividerColor = GameSettingsStyle.Divider +private val CheckBorder = GameSettingsStyle.CheckBorder +private val SliderInactive = GameSettingsStyle.SliderInactive +private val ChipSurface = GameSettingsStyle.ChipSurface +private val ChipBorder = GameSettingsStyle.ChipBorder +private val DangerRed = GameSettingsStyle.DangerRed +private val WarningAmber = GameSettingsStyle.WarningAmber private val SelectableDriveLetters = ('D'..'Y').filter { it != 'E' }.map { "$it" } - -private val NavHighlight = Color(0xFF4FC3F7) +private val NavHighlight = GameSettingsStyle.NavHighlight @Stable class GameSettingsNav { diff --git a/app/src/main/feature/retro/DolphinCloudSync.kt b/app/src/main/feature/retro/DolphinCloudSync.kt new file mode 100644 index 000000000..9ef05973f --- /dev/null +++ b/app/src/main/feature/retro/DolphinCloudSync.kt @@ -0,0 +1,144 @@ +package com.winlator.cmod.feature.retro + +import android.content.Context +import org.dolphinemu.dolphinemu.wn.DolphinEmulationActivity +import java.io.File + +object DolphinCloudSync { + private fun userDir(context: Context) = File(context.filesDir, "dolphin-embed/User") + + fun stagingDir(context: Context, cloudId: String): File = + File(context.filesDir, "dolphin-embed/cloud/$cloudId") + + private fun pendingFile(context: Context) = File(context.filesDir, "dolphin-embed/.pending_cloud") + + fun stage(context: Context, stageKey: String, gameId: String?): Boolean = + runCatching { + val user = userDir(context) + val staging = stagingDir(context, stageKey) + staging.deleteRecursively() + var any = false + fun copy(f: File) { + f.copyTo(File(staging, f.relativeTo(user).path).apply { parentFile?.mkdirs() }, overwrite = true) + any = true + } + fun copyTree(root: File, accept: (File) -> Boolean) { + if (!root.isDirectory) return + root.walkTopDown().filter { it.isFile && accept(it) }.forEach(::copy) + } + copyTree(File(user, "GC")) { it.extension.equals("gci", true) || it.name.equals("SRAM.raw", true) } + copyTree(File(user, "Wii/title")) { true } + if (!gameId.isNullOrBlank()) { + File(user, "StateSaves").listFiles() + ?.filter { it.isFile && it.name.startsWith(gameId) } + ?.forEach(::copy) + } + any + }.getOrDefault(false) + + fun stagedFingerprint(context: Context, stageKey: String): String { + val staging = stagingDir(context, stageKey) + if (!staging.isDirectory) return "" + val md = java.security.MessageDigest.getInstance("SHA-256") + staging.walkTopDown().filter { it.isFile }.sortedBy { it.path }.forEach { f -> + md.update("${f.relativeTo(staging).path}:${f.length()}:${f.lastModified()}".toByteArray()) + } + return md.digest().joinToString("") { "%02x".format(it) } + } + + fun refreshForBackup(context: Context, systemId: String, gameName: String) { + val system = RetroSystems.fromId(systemId) ?: return + if (!RetroCoreManager.usesDolphinCore(system)) return + val stageKey = RetroSaveStates.cloudGameId(system.id, gameName) + val gameId = + androidx.preference.PreferenceManager.getDefaultSharedPreferences(context) + .getString("retro_gc_gameid_$stageKey", "") + stage(context, stageKey, gameId) + } + + fun applyStaged(context: Context, cloudId: String) { + runCatching { + val user = userDir(context) + val staging = stagingDir(context, cloudId) + if (!staging.isDirectory) return + staging.walkTopDown().filter { it.isFile }.forEach { f -> + val rel = f.relativeTo(staging).path + f.copyTo(File(user, rel).apply { parentFile?.mkdirs() }, overwrite = true) + } + } + } + + fun localTimestamp(context: Context, cloudId: String): Long { + val staging = stagingDir(context, cloudId) + if (!staging.isDirectory) return 0L + return staging.walkTopDown().filter { it.isFile }.maxOfOrNull { it.lastModified() } ?: 0L + } + + fun writePending(context: Context, cloudId: String, gameName: String, fingerprint: String) { + runCatching { pendingFile(context).writeText("$cloudId\n$gameName\n$fingerprint") } + } + + fun stageAndQueue(activity: android.app.Activity) { + val intent = activity.intent + val systemId = intent.getStringExtra(DolphinEmulationActivity.EXTRA_SYSTEM_ID) + val system = RetroSystems.fromId(systemId) ?: return + val gameName = intent.getStringExtra(DolphinEmulationActivity.EXTRA_GAME_NAME) ?: return + val shortcutPath = intent.getStringExtra(DolphinEmulationActivity.EXTRA_SHORTCUT_PATH) ?: return + val enabled = + runCatching { + val cm = com.winlator.cmod.runtime.container.ContainerManager(activity) + val cid = intent.getIntExtra(DolphinEmulationActivity.EXTRA_CONTAINER_ID, 0) + val container = + if (cid == com.winlator.cmod.runtime.container.ContainerManager.RETRO_CONTAINER_ID) { + cm.retroContainer + } else { + cm.getContainerById(cid) + } + container?.let { com.winlator.cmod.runtime.container.Shortcut(it, java.io.File(shortcutPath)) } + ?.getExtra("cloud_sync_enabled", "1") != "0" + }.getOrDefault(true) + if (!enabled) { + android.util.Log.i("WnDolphin", "cloud stage skipped (sync disabled)") + return + } + val stageKey = RetroSaveStates.cloudGameId(system.id, gameName) + val cloudId = + com.winlator.cmod.feature.sync.google.GameSaveBackupManager.customGameId( + intent.getIntExtra(DolphinEmulationActivity.EXTRA_CONTAINER_ID, 0), + java.io.File(shortcutPath).name, + ) + val gameId = DolphinEmulationActivity.currentGameId + androidx.preference.PreferenceManager.getDefaultSharedPreferences(activity) + .edit().putString("retro_gc_gameid_$stageKey", gameId).apply() + if (!stage(activity, stageKey, gameId)) { + android.util.Log.i("WnDolphin", "cloud stage found no save files (gameId=$gameId)") + return + } + val fingerprint = stagedFingerprint(activity, stageKey) + val prefs = androidx.preference.PreferenceManager.getDefaultSharedPreferences(activity) + if (fingerprint == prefs.getString("retro_cloud_fp_$cloudId", null)) { + android.util.Log.i("WnDolphin", "cloud stage unchanged, skip upload id=$cloudId") + return + } + writePending(activity, cloudId, gameName, fingerprint) + android.util.Log.i("WnDolphin", "cloud staged id=$cloudId gameId=$gameId") + } + + data class Pending(val cloudId: String, val gameName: String, val fingerprint: String) + + fun peekPending(context: Context): Pending? = + runCatching { + val f = pendingFile(context) + if (!f.isFile) return null + val lines = f.readText().split('\n') + if (lines.size >= 2 && lines[0].isNotBlank()) { + Pending(lines[0], lines[1], lines.getOrElse(2) { "" }) + } else { + null + } + }.getOrNull() + + fun clearPending(context: Context) { + runCatching { pendingFile(context).delete() } + } +} diff --git a/app/src/main/feature/retro/DolphinEmbedLaunch.kt b/app/src/main/feature/retro/DolphinEmbedLaunch.kt new file mode 100644 index 000000000..f3d442db5 --- /dev/null +++ b/app/src/main/feature/retro/DolphinEmbedLaunch.kt @@ -0,0 +1,193 @@ +package com.winlator.cmod.feature.retro + +import android.content.Context +import android.content.Intent +import com.winlator.cmod.R +import com.winlator.cmod.runtime.container.Shortcut +import org.dolphinemu.dolphinemu.wn.DolphinEmulationActivity +import org.dolphinemu.dolphinemu.wn.DolphinNetplay + +object DolphinEmbedLaunch { + const val DRIVER_PREF = "wn.gc.driver" + + private fun syncCloudSaves(context: Context, shortcut: Shortcut) { + if (context !is android.app.Activity) return + if (shortcut.getExtra("cloud_sync_enabled", "1") == "0") return + val system = RetroShortcuts.systemForShortcut(shortcut) ?: return + val gameName = shortcut.getExtra("custom_name", shortcut.name) + val stageKey = RetroSaveStates.cloudGameId(system.id, gameName) + val cloudId = + com.winlator.cmod.feature.sync.google.GameSaveBackupManager.customGameId( + shortcut.container.id, + shortcut.file.name, + ) + val prefs = androidx.preference.PreferenceManager.getDefaultSharedPreferences(context) + runCatching { + kotlinx.coroutines.runBlocking { + kotlinx.coroutines.withTimeout(12_000L) { + val entries = + com.winlator.cmod.feature.sync.google.GameSaveBackupManager.listGoogleHistory( + context, + com.winlator.cmod.feature.sync.google.GameSaveBackupManager.GameSource.CUSTOM, + cloudId, + com.winlator.cmod.feature.sync.google.GoogleAuthMode.RESUME, + ) + val latest = entries.maxByOrNull { it.timestampMs } ?: return@withTimeout + val localTs = DolphinCloudSync.localTimestamp(context, stageKey) + val mark = prefs.getLong("retro_cloud_mark_$cloudId", 0L) + val restore: suspend () -> Unit = { + val result = + com.winlator.cmod.feature.sync.google.GameSaveBackupManager.restoreFromGoogle( + context, + latest, + com.winlator.cmod.feature.sync.google.GameSaveBackupManager.GameSource.CUSTOM, + cloudId, + com.winlator.cmod.feature.sync.google.GoogleAuthMode.RESUME, + customSaveDir = DolphinCloudSync.stagingDir(context, stageKey), + ) + if (result.success) { + DolphinCloudSync.applyStaged(context, stageKey) + prefs.edit().putLong("retro_cloud_mark_$cloudId", latest.timestampMs).apply() + } + } + if (localTs == 0L) { + restore() + } else if (latest.timestampMs > localTs + 120_000L && latest.timestampMs > mark) { + val useCloud = askCloudConflict(context, gameName) + if (useCloud) { + restore() + } else { + prefs.edit().putLong("retro_cloud_mark_$cloudId", latest.timestampMs).apply() + } + } + } + } + } + } + + private fun askCloudConflict(activity: android.app.Activity, gameName: String): Boolean { + val latch = java.util.concurrent.CountDownLatch(1) + val useCloud = java.util.concurrent.atomic.AtomicBoolean(false) + activity.runOnUiThread { + androidx.appcompat.app.AlertDialog.Builder(activity) + .setTitle(activity.getString(R.string.retro_lr_cloud_save)) + .setMessage(activity.getString(R.string.retro_lr_cloud_conflict_message, gameName)) + .setCancelable(false) + .setPositiveButton(activity.getString(R.string.retro_lr_use_cloud_save)) { _, _ -> + useCloud.set(true) + latch.countDown() + } + .setNegativeButton(activity.getString(R.string.retro_scr_keep_local_save)) { _, _ -> + latch.countDown() + } + .show() + } + latch.await() + return useCloud.get() + } + + private fun gcProcess(context: Context): android.app.ActivityManager.RunningAppProcessInfo? = + runCatching { + val am = context.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager + am.runningAppProcesses?.firstOrNull { it.processName.endsWith(":gc") } + }.getOrNull() + + fun launch(context: Context, shortcut: Shortcut) { + val romPath = RetroShortcuts.romPath(shortcut) + val newTask = context !is android.app.Activity + kotlin.concurrent.thread(name = "WnDolphinLaunch") { + syncCloudSaves(context, shortcut) + val intent = launchIntent(context, shortcut) + if (newTask) intent.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK) + val proc = gcProcess(context) + if (proc != null) { + val marker = java.io.File(context.filesDir, "dolphin-embed/.running_rom") + val running = runCatching { marker.takeIf { it.isFile }?.readText() }.getOrNull() + if (running != romPath) { + if (running != null) { + android.util.Log.i("WnDolphin", "killing running :gc pid=" + proc.pid) + android.os.Process.killProcess(proc.pid) + } + val deadline = android.os.SystemClock.uptimeMillis() + 12000 + while (android.os.SystemClock.uptimeMillis() < deadline && gcProcess(context) != null) { + Thread.sleep(150) + } + } + } + android.os.Handler(android.os.Looper.getMainLooper()).post { + runCatching { context.startActivity(intent) } + } + } + } + + fun launchIntent( + context: Context, + shortcut: Shortcut, + ): Intent { + val system = RetroShortcuts.systemForShortcut(shortcut) + val sysId = system?.id ?: RetroSystems.GAMECUBE.id + val vars = RetroShortcuts.resolvedCoreVariables(context, shortcut) + applyGpuDriver(context, vars) + vars["wn_touch"] = + shortcut.getExtra(RetroShortcuts.KEY_TOUCH_CONTROLS).ifEmpty { + if (RetroDefaults.touchControls(context, sysId)) "1" else "0" + } + vars["wn_audio"] = + shortcut.getExtra(RetroShortcuts.KEY_AUDIO).ifEmpty { + if (RetroDefaults.audio(context, sysId)) "1" else "0" + } + vars["wn_hud"] = if (RetroDefaults.hud(context, sysId)) "1" else "0" + vars["wn_adaptive"] = + shortcut.getExtra(RetroShortcuts.KEY_ADAPTIVE_STICKS).ifEmpty { + if (RetroDefaults.adaptiveSticks(context, sysId)) "1" else "0" + } + val netplayArmed = RetroDefaults.netplayEnabled(context, sysId) + val netplayHost = RetroDefaults.netplayHostMode(context, sysId) + val netplayTraversal = RetroDefaults.netplayTraversal(context, sysId) + val netplayAddress = RetroDefaults.netplayHost(context, sysId) + val netplayHostCode = RetroDefaults.netplayHostCode(context, sysId) + val netplayPort = RetroDefaults.netplayPort(context, sysId) + val netplayNick = RetroDefaults.netplayPlayerName(context) + if (netplayArmed) RetroDefaults.setNetplayEnabled(context, sysId, false) + return Intent(context, DolphinEmulationActivity::class.java).apply { + putExtra(DolphinEmulationActivity.EXTRA_ROM_PATH, RetroShortcuts.romPath(shortcut)) + putExtra(DolphinEmulationActivity.EXTRA_SYSTEM_ID, system?.id) + putExtra( + DolphinEmulationActivity.EXTRA_GAME_NAME, + shortcut.getExtra("custom_name", shortcut.name), + ) + putExtra(DolphinEmulationActivity.EXTRA_SHORTCUT_PATH, shortcut.file.absolutePath) + putExtra(DolphinEmulationActivity.EXTRA_CONTAINER_ID, shortcut.container.id) + putExtra(DolphinEmulationActivity.EXTRA_VARIABLES, vars) + if (netplayArmed) { + putExtra(DolphinNetplay.EXTRA_ENABLE, true) + putExtra(DolphinNetplay.EXTRA_HOST, netplayHost) + putExtra(DolphinNetplay.EXTRA_TRAVERSAL, netplayTraversal) + putExtra(DolphinNetplay.EXTRA_ADDRESS, netplayAddress) + putExtra(DolphinNetplay.EXTRA_HOST_CODE, netplayHostCode) + putExtra(DolphinNetplay.EXTRA_PORT, netplayPort) + putExtra(DolphinNetplay.EXTRA_NICKNAME, netplayNick) + } + if (RetroAchievementsManager.isEnabled(context) && RetroAchievementsManager.isLoggedIn(context)) { + putExtra(DolphinEmulationActivity.EXTRA_RA_ENABLED, true) + putExtra(DolphinEmulationActivity.EXTRA_RA_USER, RetroAchievementsManager.username(context) ?: "") + putExtra(DolphinEmulationActivity.EXTRA_RA_TOKEN, RetroAchievementsManager.apiToken(context) ?: "") + putExtra(DolphinEmulationActivity.EXTRA_RA_HARDCORE, RetroAchievementsManager.isHardcorePreferred(context)) + } + } + } + + private fun applyGpuDriver( + context: Context, + vars: HashMap, + ) { + val prefs = androidx.preference.PreferenceManager.getDefaultSharedPreferences(context) + val driverId = (prefs.getString(DRIVER_PREF, "") ?: "").trim() + if (driverId.isEmpty() || driverId.equals("system", ignoreCase = true)) return + val driver = + com.armsx2.CustomDriver.listInstalled(context).firstOrNull { it.id == driverId } + ?: return + vars["dolphin_gpu_driver"] = driver.driverDir.absolutePath + vars["dolphin_gpu_driver_lib"] = driver.libraryName + } +} diff --git a/app/src/main/feature/retro/DolphinGameOverlay.kt b/app/src/main/feature/retro/DolphinGameOverlay.kt new file mode 100644 index 000000000..36878747e --- /dev/null +++ b/app/src/main/feature/retro/DolphinGameOverlay.kt @@ -0,0 +1,628 @@ +package com.winlator.cmod.feature.retro + +import android.widget.FrameLayout +import android.widget.Toast +import androidx.activity.addCallback +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Home +import androidx.compose.material.icons.outlined.Person +import androidx.compose.material.icons.outlined.Wifi +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.ComposeView +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.winlator.cmod.R +import com.winlator.cmod.shared.theme.GameSettingsStyle +import com.winlator.cmod.runtime.container.ContainerManager +import com.winlator.cmod.runtime.container.Shortcut +import com.winlator.cmod.runtime.display.ui.FrameRating +import com.winlator.cmod.shared.theme.WinNativeTheme +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.launch +import org.dolphinemu.dolphinemu.wn.DolphinEmulationActivity +import org.dolphinemu.dolphinemu.wn.DolphinHost +import org.dolphinemu.dolphinemu.wn.DolphinNetplay +import java.io.File + +object DolphinGameOverlay { + private const val SLOT_COUNT = 4 + + private fun dolphinAnyController(): Boolean = + android.view.InputDevice.getDeviceIds().any { + com.winlator.cmod.runtime.input.controls.ExternalController.isGameController( + android.view.InputDevice.getDevice(it), + ) + } + + private fun buildDolphinNetplay(activity: DolphinEmulationActivity): List = + buildList { + add( + RetroMenuEntry.Action( + label = + activity.getString( + if (DolphinNetplayHud.hosting) { + R.string.retro_netplay_hosting_room + } else { + R.string.retro_netplay_in_room + }, + ), + icon = Icons.Outlined.Wifi, + active = true, + onClick = {}, + ), + ) + DolphinNetplayHud.hostCode?.let { code -> + add( + RetroMenuEntry.Action( + label = "${activity.getString(R.string.retro_netplay_host_code)}: $code", + icon = Icons.Outlined.Wifi, + onClick = {}, + ), + ) + } + val members = DolphinNetplayHud.members + if (members.isEmpty()) { + add( + RetroMenuEntry.Action( + label = activity.getString(R.string.retro_netplay_waiting_players), + icon = Icons.Outlined.Person, + onClick = {}, + ), + ) + } else { + members.forEach { name -> + add(RetroMenuEntry.Action(label = name, icon = Icons.Outlined.Person, onClick = {})) + } + } + } + + @Composable + private fun DolphinNetplayBanner(hosting: Boolean, hostCode: String?, members: List) { + AnimatedVisibility( + visible = hosting && members.size < 2, + enter = fadeIn(), + exit = fadeOut(), + ) { + Box( + Modifier.fillMaxSize().padding(top = 56.dp), + contentAlignment = Alignment.TopCenter, + ) { + val parts = + buildList { + add(stringResource(R.string.retro_netplay_hosting_room)) + if (hostCode != null) { + add("${stringResource(R.string.retro_netplay_host_code)}: $hostCode") + } + add(stringResource(R.string.retro_netplay_waiting_players)) + } + Text( + parts.joinToString(" · "), + color = GameSettingsStyle.TextPrimary, + fontSize = 13.sp, + modifier = + Modifier + .background(Color(0xF0121824), RoundedCornerShape(10.dp)) + .padding(horizontal = 16.dp, vertical = 10.dp), + ) + } + } + } + + fun install() { + DolphinHost.attachOverlay = { activity -> + if (activity is DolphinEmulationActivity) attach(activity) + } + DolphinHost.onStageSaves = { activity -> DolphinCloudSync.stageAndQueue(activity) } + val main = android.os.Handler(android.os.Looper.getMainLooper()) + DolphinHost.onNetplayStatus = { hosting, code, members -> + main.post { DolphinNetplayHud.update(hosting, code, members) } + } + } + + private fun loadShortcut(activity: DolphinEmulationActivity): Shortcut? { + val containerId = activity.intent.getIntExtra(DolphinEmulationActivity.EXTRA_CONTAINER_ID, -1) + val path = activity.intent.getStringExtra(DolphinEmulationActivity.EXTRA_SHORTCUT_PATH) + if (containerId < 0 || path.isNullOrBlank()) return null + val file = File(path) + if (!file.isFile) return null + return runCatching { + val cm = ContainerManager(activity) + val container = + if (containerId == ContainerManager.RETRO_CONTAINER_ID) cm.retroContainer else cm.getContainerById(containerId) + container?.let { Shortcut(it, file) } + }.getOrNull() + } + + private fun attach(activity: DolphinEmulationActivity) { + val root = activity.findViewById(android.R.id.content) ?: return + val system = + RetroSystems.fromId(activity.intent.getStringExtra(DolphinEmulationActivity.EXTRA_SYSTEM_ID)) + ?: RetroSystems.GAMECUBE + var shortcut: Shortcut? = null + val pendingExtras = linkedMapOf() + val menu = RetroMenuController() + val dolphinScreen = mutableStateOf(null) + lateinit var input: RetroInputView + val vars = DolphinEmulationActivity.currentVariables + var touchControls = vars["wn_touch"] != "0" + var adaptiveSticks = vars["wn_adaptive"] == "1" + var audioOn = vars["wn_audio"] != "0" + var hudOn = vars["wn_hud"] == "1" + var savesLoadMode = false + var frameRating: FrameRating? = null + var hudStyle = RetroHudSupport.loadGlobalHudStyle(activity) + var hudElements = RetroHudSupport.loadGlobalHudElements(activity) + @Suppress("OPT_IN_USAGE") + GlobalScope.launch(Dispatchers.IO) { + val sc = loadShortcut(activity) + activity.runOnUiThread { + shortcut = sc + if (sc != null && pendingExtras.isNotEmpty()) { + val queued = pendingExtras.toMap() + pendingExtras.clear() + GlobalScope.launch(Dispatchers.IO) { + runCatching { + queued.forEach { (k, v) -> sc.putExtra(k, v) } + sc.saveData() + } + } + } + } + } + + val gameName = + activity.intent.getStringExtra(DolphinEmulationActivity.EXTRA_GAME_NAME) ?: "game" + val stageKey = RetroSaveStates.cloudGameId(system.id, gameName) + val cloudId = + activity.intent.getStringExtra(DolphinEmulationActivity.EXTRA_SHORTCUT_PATH)?.let { path -> + com.winlator.cmod.feature.sync.google.GameSaveBackupManager.customGameId( + activity.intent.getIntExtra(DolphinEmulationActivity.EXTRA_CONTAINER_ID, 0), + java.io.File(path).name, + ) + } ?: stageKey + + fun cloudSyncEnabled(): Boolean = shortcut?.getExtra("cloud_sync_enabled", "1") != "0" + + fun stageCloudBackup(onDone: (() -> Unit)? = null) { + if (!cloudSyncEnabled()) { + onDone?.let { activity.runOnUiThread(it) } + return + } + val gameId = DolphinEmulationActivity.currentGameId + @Suppress("OPT_IN_USAGE") + GlobalScope.launch(Dispatchers.IO) { + if (DolphinCloudSync.stage(activity, stageKey, gameId)) { + val fp = DolphinCloudSync.stagedFingerprint(activity, stageKey) + val prefs = androidx.preference.PreferenceManager.getDefaultSharedPreferences(activity) + if (fp != prefs.getString("retro_cloud_fp_$cloudId", null)) { + DolphinCloudSync.writePending(activity, cloudId, gameName, fp) + } + } + onDone?.let { activity.runOnUiThread(it) } + } + } + + fun persistExtra(key: String, value: String) { + val sc = shortcut + if (sc == null) { + pendingExtras[key] = value + return + } + @Suppress("OPT_IN_USAGE") + GlobalScope.launch(Dispatchers.IO) { + runCatching { + sc.putExtra(key, value) + sc.saveData() + } + } + } + + fun applyVar(key: String, value: String) { + activity.applyVariable(key, value) + persistExtra(RetroShortcuts.VAR_PREFIX + key, value) + } + + fun showHud() { + var rating = frameRating + if (rating == null) { + rating = RetroHudSupport.createFrameRating(activity, "Vulkan") + frameRating = rating + RetroHudSupport.attachFrameRating(root, rating) + RetroHudSupport.applyStyle(rating, hudStyle, hudElements) + org.dolphinemu.dolphinemu.NativeLibrary.frameListener = + Runnable { frameRating?.recordGameFrame() } + } + rating.visibility = android.view.View.VISIBLE + rating.reset() + } + + fun setHudVisible(value: Boolean) { + hudOn = value + activity.applyVariable("wn_hud", if (value) "1" else "0") + RetroDefaults.setHud(activity, system.id, value) + if (value) showHud() else frameRating?.visibility = android.view.View.GONE + } + + val listener = + object : RetroInputView.Listener { + override fun onButton(keyCode: Int, down: Boolean) { + if (!menu.visible) activity.sendOverlayButton(keyCode, down) + } + + override fun onDpad(x: Float, y: Float) { + if (!menu.visible) activity.sendOverlayDpad(x, y) + } + + override fun onStick(x: Float, y: Float) { + if (!menu.visible) activity.sendOverlayLeftStick(x, y) + } + + override fun onRightStick(x: Float, y: Float) { + if (!menu.visible) activity.sendOverlayRightStick(x, y) + } + + override fun onMenu() { + activity.runOnUiThread { + input.releaseAll() + menu.open() + } + } + } + + input = RetroInputView(activity, listener, system) + input.hapticStrength = + androidx.preference.PreferenceManager + .getDefaultSharedPreferences(activity) + .getFloat("retro_haptic_strength", 0.4f) + input.adaptiveSticks = adaptiveSticks + input.showL3R3 = + androidx.preference.PreferenceManager + .getDefaultSharedPreferences(activity) + .getBoolean(RetroControlsMenu.l3r3PrefKey(system.id), true) + input.setCustomColors(RetroControlLayouts.loadColors(activity, system.id)) + input.loadStickInversion() + var controllerConnected = dolphinAnyController() + var manualTouchOverride = false + fun touchEffective() = touchControls && (!controllerConnected || manualTouchOverride) + input.visibility = if (touchEffective()) android.view.View.VISIBLE else android.view.View.GONE + fun updateGameArea() { + val w = root.width.toFloat() + val h = root.height.toFloat() + if (w <= 0f || h <= 0f) return + val gameWidth = (h * 4f / 3f).coerceAtMost(w) + val left = (w - gameWidth) * 0.5f + val box = android.graphics.RectF(left, 0f, left + gameWidth, h) + input.setGameArea(box) + activity.setSurfaceBounds(if (touchEffective()) box else null) + } + root.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> updateGameArea() } + root.post { updateGameArea() } + fun refreshDolphinController() { + val was = controllerConnected + controllerConnected = dolphinAnyController() + if (controllerConnected != was) manualTouchOverride = false + val show = touchEffective() + input.visibility = if (show) android.view.View.VISIBLE else android.view.View.GONE + updateGameArea() + if (show) input.post { updateGameArea(); input.relayout() } + } + activity.getSystemService(android.hardware.input.InputManager::class.java) + ?.registerInputDeviceListener( + object : android.hardware.input.InputManager.InputDeviceListener { + override fun onInputDeviceAdded(deviceId: Int) = refreshDolphinController() + + override fun onInputDeviceRemoved(deviceId: Int) = refreshDolphinController() + + override fun onInputDeviceChanged(deviceId: Int) = refreshDolphinController() + }, + null, + ) + root.addView( + input, + FrameLayout.LayoutParams( + FrameLayout.LayoutParams.MATCH_PARENT, + FrameLayout.LayoutParams.MATCH_PARENT, + ), + ) + + menu.tabs = RetroDrawerTabs.build(activity, includeNetplay = DolphinNetplay.active) + menu.entriesProvider = { pane -> + when (pane) { + null -> + buildMain( + activity, + menu, + hudOn, + system.id == RetroSystems.WII.id, + onAchievements = { + dolphinScreen.value = "achievements" + menu.close() + }, + onHud = ::setHudVisible, + ) { load -> + savesLoadMode = load + menu.showPane(RetroPane.SAVES) + } + RetroPane.SAVES -> buildMemoryCards(activity, menu, savesLoadMode) { stageCloudBackup() } + RetroPane.NETWORK -> buildDolphinNetplay(activity) + RetroPane.DISPLAY -> buildDisplay(activity, menu, system, ::applyVar) + RetroPane.HUD -> + RetroHudSupport.buildHudEntries( + context = activity, + hudVisible = hudOn, + style = hudStyle, + elements = hudElements, + onMaster = { setHudVisible(it) }, + onStyle = { next -> + hudStyle = next + frameRating?.let { RetroHudSupport.applyStyle(it, next, hudElements) } + RetroHudSupport.saveGlobalHudStyle(activity, next) + }, + onElements = { next -> + hudElements = next + frameRating?.let { RetroHudSupport.applyStyle(it, hudStyle, next) } + RetroHudSupport.saveGlobalHudElements(activity, next) + }, + onRebuild = { menu.rebuild() }, + ) + RetroPane.SOUND -> + listOf( + RetroMenuEntry.Toggle(activity.getString(R.string.retro_lr_sound), checked = audioOn) { value -> + audioOn = value + applyVar("wn_audio", if (value) "1" else "0") + persistExtra(RetroShortcuts.KEY_AUDIO, if (value) "1" else "0") + menu.rebuild() + }, + ) + RetroPane.CONTROLS -> + RetroControlsMenu.build( + RetroControlsMenu.Host( + context = activity, + overlay = input, + menu = menu, + systemId = system.id, + touchControls = { touchControls }, + onTouchControls = { value -> + touchControls = value + if (controllerConnected) manualTouchOverride = true + input.visibility = + if (touchEffective()) android.view.View.VISIBLE else android.view.View.GONE + updateGameArea() + persistExtra(RetroShortcuts.KEY_TOUCH_CONTROLS, if (value) "1" else "0") + }, + adaptiveSticks = { adaptiveSticks }, + onAdaptiveSticks = { value -> + adaptiveSticks = value + persistExtra(RetroShortcuts.KEY_ADAPTIVE_STICKS, if (value) "1" else "0") + }, + orientationLabel = { activity.getString(R.string.retro_lr_landscape) }, + onCloseMenu = { menu.close() }, + showStickInversion = true, + ), + ) + else -> emptyList() + } + } + menu.bottomProvider = { buildBottom(activity, menu) { activity.stopGame() } } + + val compose = + ComposeView(activity).apply { + elevation = 2000f + setContent { + WinNativeTheme { + Box(Modifier.fillMaxSize()) { + val screen by dolphinScreen + if (screen == "achievements") { + val dismiss = { dolphinScreen.value = null } + androidx.activity.compose.BackHandler(enabled = true) { dismiss() } + RetroAchievementsScreen( + systemId = system.id, + gameName = activity.intent.getStringExtra( + DolphinEmulationActivity.EXTRA_GAME_NAME, + ) ?: system.displayName, + romPath = activity.intent.getStringExtra( + DolphinEmulationActivity.EXTRA_ROM_PATH, + ).orEmpty(), + inSession = true, + onClose = dismiss, + floatingOverGame = true, + nativeJson = { + org.dolphinemu.dolphinemu.features.settings.model.AchievementModel + .getAchievementsJSON() + }, + ) + } else { + val hosting = DolphinNetplayHud.hosting + val code = DolphinNetplayHud.hostCode + val members = DolphinNetplayHud.members + LaunchedEffect(hosting, code, members) { + if (menu.visible && menu.pane == RetroPane.NETWORK) menu.rebuild() + } + DolphinNetplayBanner(hosting, code, members) + RetroDrawerMenu(menu) + } + } + } + } + } + root.addView( + compose, + FrameLayout.LayoutParams( + FrameLayout.LayoutParams.MATCH_PARENT, + FrameLayout.LayoutParams.MATCH_PARENT, + ), + ) + + if (hudOn) root.post { showHud() } + + activity.onBackPressedDispatcher.addCallback(activity) { + when { + input.editMode -> input.finishEdit() + menu.visible -> menu.close() + else -> menu.open() + } + } + activity.menuButtonHandler = { if (menu.visible) menu.close() else menu.open() } + } + + private fun buildMain( + activity: DolphinEmulationActivity, + menu: RetroMenuController, + hudOn: Boolean, + isWii: Boolean, + onAchievements: () -> Unit, + onHud: (Boolean) -> Unit, + openMemoryCards: (load: Boolean) -> Unit, + ): List = + buildList { + if (isWii) { + add( + RetroMenuEntry.Action(activity.getString(R.string.retro_dolphin_wii_home), Icons.Outlined.Home) { + activity.pressWiiHome() + menu.close() + }, + ) + } + add( + RetroMenuEntry.Action(activity.getString(R.string.retro_ps2_achievements), RetroDrawerIcons.Achievements) { + onAchievements() + }, + ) + add( + RetroMenuEntry.Action(activity.getString(R.string.retro_lr_save_state), RetroDrawerIcons.Save) { + openMemoryCards(false) + }, + ) + add( + RetroMenuEntry.Action(activity.getString(R.string.retro_lr_load_save_state), RetroDrawerIcons.Load) { + openMemoryCards(true) + }, + ) + add( + RetroMenuEntry.Action(activity.getString(R.string.retro_lr_screenshot), RetroDrawerIcons.Hud) { + runCatching { org.dolphinemu.dolphinemu.NativeLibrary.SaveScreenShot() } + menu.close() + }, + ) + add( + RetroMenuEntry.Toggle(activity.getString(R.string.retro_lr_hud), checked = hudOn) { value -> + onHud(value) + menu.rebuild() + }, + ) + } + + private fun buildMemoryCards( + activity: DolphinEmulationActivity, + menu: RetroMenuController, + loadMode: Boolean, + onSaved: () -> Unit, + ): List = + (1..SLOT_COUNT).map { slot -> + val ts = activity.stateSlotTime(slot) + RetroMenuEntry.SaveSlot( + slot = slot, + title = activity.getString(R.string.retro_lr_memory_card_slot, slot), + subtitle = RetroSaveStates.relativeTime(ts * 1000), + filled = ts > 0L, + onClick = { + if (loadMode) { + if (ts > 0L) { + activity.loadStateSlot(slot) + menu.close() + Toast + .makeText(activity, activity.getString(R.string.retro_lr_loaded_slot, slot), Toast.LENGTH_SHORT) + .show() + } + } else { + activity.saveStateSlot(slot) + onSaved() + Toast + .makeText(activity, activity.getString(R.string.retro_lr_saved_to_slot, slot), Toast.LENGTH_SHORT) + .show() + menu.rebuild() + } + }, + onRename = {}, + ) + } + + private fun buildDisplay( + activity: DolphinEmulationActivity, + menu: RetroMenuController, + system: RetroSystem, + applyVar: (String, String) -> Unit, + ): List = + buildList { + val vars = DolphinEmulationActivity.currentVariables + RetroCoreOptions.forSystem(system).forEach { option -> + val current = vars[option.key] ?: option.defaultValue + val index = option.values.indexOf(current).coerceAtLeast(0) + add( + RetroMenuEntry.Choice( + option.labelText(activity), + option.valueLabels, + index, + ) { next -> + applyVar(option.key, option.values[next]) + menu.rebuild() + }, + ) + } + } + + private fun buildBottom( + activity: DolphinEmulationActivity, + menu: RetroMenuController, + onExit: () -> Unit, + ): List = + listOf( + if (activity.gamePaused) { + RetroMenuEntry.Action(activity.getString(R.string.retro_lr_resume), RetroDrawerIcons.Resume, active = true) { + activity.resumeGame() + menu.close() + } + } else { + RetroMenuEntry.Action(activity.getString(R.string.retro_lr_pause), RetroDrawerIcons.Pause) { + activity.pauseGame() + menu.close() + } + }, + RetroMenuEntry.Action(activity.getString(R.string.retro_lr_exit), RetroDrawerIcons.Exit, danger = true) { + onExit() + }, + ) +} + +object DolphinNetplayHud { + var hosting by mutableStateOf(false) + private set + var hostCode by mutableStateOf(null) + private set + var members by mutableStateOf>(emptyList()) + private set + + fun update(hosting: Boolean, hostCode: String?, members: List) { + this.hosting = hosting + this.hostCode = hostCode + this.members = members + } +} diff --git a/app/src/main/feature/retro/DolphinNetplayUi.kt b/app/src/main/feature/retro/DolphinNetplayUi.kt new file mode 100644 index 000000000..963aa0d42 --- /dev/null +++ b/app/src/main/feature/retro/DolphinNetplayUi.kt @@ -0,0 +1,135 @@ +package com.winlator.cmod.feature.retro + +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.compose.material3.Text +import com.winlator.cmod.R +import com.winlator.cmod.shared.theme.GameSettingsStyle +import org.dolphinemu.dolphinemu.wn.DolphinNetplay + +@Composable +fun DolphinNetplaySettingsSection( + systemId: String, + version: Int, + onChanged: () -> Unit, +) { + val context = LocalContext.current + @Suppress("UNUSED_EXPRESSION") + version + + val enabled = RetroDefaults.netplayEnabled(context, systemId) + val isHost = RetroDefaults.netplayHostMode(context, systemId) + val traversal = RetroDefaults.netplayTraversal(context, systemId) + val player = RetroDefaults.netplayPlayerName(context) + val host = RetroDefaults.netplayHost(context, systemId) + val hostCode = RetroDefaults.netplayHostCode(context, systemId) + val port = RetroDefaults.netplayPort(context, systemId) + + RetroSettingGroup { + RetroSettingSwitch( + stringResource(R.string.retro_gs_netplay_enable), + enabled, + subtitle = stringResource(R.string.retro_gs_netplay_enable_subtitle), + ) { + RetroDefaults.setNetplayEnabled(context, systemId, it) + onChanged() + } + + if (enabled) { + RetroSettingTextField( + stringResource(R.string.retro_netplay_player_name), + player, + stringResource(R.string.retro_netplay_player_name_hint), + ) { + RetroDefaults.setNetplayPlayerName(context, it) + onChanged() + } + + RetroSettingDropdown( + stringResource(R.string.retro_netplay_launch_mode), + listOf( + stringResource(R.string.retro_netplay_mode_host), + stringResource(R.string.retro_netplay_mode_join), + ), + if (isHost) 0 else 1, + ) { index -> + RetroDefaults.setNetplayHostMode(context, systemId, index == 0) + onChanged() + } + + RetroSettingDropdown( + stringResource(R.string.retro_netplay_connection), + listOf( + stringResource(R.string.retro_netplay_conn_direct), + stringResource(R.string.retro_netplay_conn_traversal), + ), + if (traversal) 1 else 0, + ) { index -> + RetroDefaults.setNetplayTraversal(context, systemId, index == 1) + onChanged() + } + + if (!isHost && traversal) { + RetroNetplayEditField( + label = stringResource(R.string.retro_netplay_host_code), + value = hostCode, + placeholder = stringResource(R.string.retro_netplay_host_code_hint), + ) { + RetroDefaults.setNetplayHostCode(context, systemId, it) + onChanged() + } + } else if (!isHost) { + RetroNetplayEditField( + label = stringResource(R.string.retro_gs_netplay_host), + value = host, + placeholder = stringResource(R.string.retro_gs_netplay_host_hint), + ) { + RetroDefaults.setNetplayHost(context, systemId, it) + onChanged() + } + } + + if (!traversal) { + RetroNetplayEditField( + label = stringResource(R.string.retro_gs_netplay_port), + value = port.toString(), + placeholder = DolphinNetplay.DEFAULT_PORT.toString(), + numeric = true, + ) { entered -> + val p = entered.toIntOrNull() ?: DolphinNetplay.DEFAULT_PORT + RetroDefaults.setNetplayPort(context, systemId, p) + onChanged() + } + } + + val hint = + when { + isHost && traversal -> R.string.retro_netplay_dolphin_host_online_hint + isHost -> R.string.retro_netplay_dolphin_host_lan_hint + traversal -> R.string.retro_netplay_dolphin_join_online_hint + else -> R.string.retro_netplay_dolphin_join_lan_hint + } + Spacer(Modifier.height(8.dp)) + Text( + stringResource(hint), + color = GameSettingsStyle.TextDim, + fontSize = 11.sp, + lineHeight = 15.sp, + ) + Text( + stringResource(R.string.retro_netplay_dolphin_help), + color = GameSettingsStyle.TextDim, + fontSize = 11.sp, + lineHeight = 15.sp, + modifier = Modifier.padding(top = 6.dp), + ) + } + } +} diff --git a/app/src/main/feature/retro/Ps2CheatStaging.kt b/app/src/main/feature/retro/Ps2CheatStaging.kt new file mode 100644 index 000000000..70785faf1 --- /dev/null +++ b/app/src/main/feature/retro/Ps2CheatStaging.kt @@ -0,0 +1,71 @@ +package com.winlator.cmod.feature.retro + +import android.content.Context +import com.armsx2.PatchRepo +import com.armsx2.runtime.MainActivityRuntime +import kr.co.iefriends.pcsx2.NativeApp +import java.io.File + +object Ps2CheatStaging { + private fun dir(ctx: Context, isPatch: Boolean): File = + File(MainActivityRuntime.assetCopyRoot(ctx), if (isPatch) "patches" else "cheats").apply { mkdirs() } + + private fun stagingFile(ctx: Context, serial: String, isPatch: Boolean): File = + File(dir(ctx, isPatch), "$serial.pnach") + + fun read(ctx: Context, serial: String, isPatch: Boolean): List { + val f = stagingFile(ctx, serial, isPatch) + if (!f.isFile) return emptyList() + val src = if (isPatch) "patches" else "custom" + return runCatching { + PatchRepo.parseInstalled(f.readText(), if (isPatch) "patches" else "cheats").second + .map { PatchRepo.Entry(it.name, it.description, it.body, src) } + }.getOrDefault(emptyList()) + } + + fun write(ctx: Context, serial: String, isPatch: Boolean, title: String, entries: List) { + val f = stagingFile(ctx, serial, isPatch) + if (entries.isEmpty()) { + f.delete() + return + } + runCatching { f.writeText(PatchRepo.buildPnach(title.ifBlank { serial }, entries)) } + } + + fun applyAll(ctx: Context, serialRaw: String, crcRaw: String) { + val serial = serialRaw.trim().uppercase() + val crc = crcRaw.trim().uppercase() + if (serial.isBlank() || crc.length != 8) return + val suffix = "_$crc" + + val stagedPatches = read(ctx, serial, true) + val dnas = Ps2DnasBypass.sectionsFor(ctx, serial, crc) + val patchByName = LinkedHashMap() + stagedPatches.forEach { patchByName[it.name] = it } + dnas.forEach { s -> if (s.name !in patchByName) patchByName[s.name] = PatchRepo.Entry(s.name, "", s.body, "patches") } + val patchFile = File(dir(ctx, true), "$serial$suffix.pnach") + if (patchByName.isEmpty()) { + runCatching { patchFile.delete() } + } else { + runCatching { patchFile.writeText(PatchRepo.buildPnach(serial, patchByName.values.toList())) } + } + val enabledPatches = (stagedPatches.map { it.name } + dnas.filter { it.enabledByDefault }.map { it.name }).distinct() + runCatching { NativeApp.setEnabledPatches(false, patchByName.keys.toTypedArray(), enabledPatches.toTypedArray()) } + + val stagedCheats = read(ctx, serial, false) + val cheatFile = File(dir(ctx, false), "$serial$suffix.pnach") + if (stagedCheats.isEmpty()) { + runCatching { cheatFile.delete() } + } else { + runCatching { cheatFile.writeText(PatchRepo.buildPnach(serial, stagedCheats)) } + runCatching { + NativeApp.setSetting("EmuCore", "EnableCheats", "bool", "true") + NativeApp.commitSettings() + } + } + val cheatNames = stagedCheats.map { it.name }.toTypedArray() + runCatching { NativeApp.setEnabledPatches(true, cheatNames, cheatNames) } + + runCatching { NativeApp.reloadPatches() } + } +} diff --git a/app/src/main/feature/retro/Ps2DnasBypass.kt b/app/src/main/feature/retro/Ps2DnasBypass.kt new file mode 100644 index 000000000..386f571b1 --- /dev/null +++ b/app/src/main/feature/retro/Ps2DnasBypass.kt @@ -0,0 +1,174 @@ +package com.winlator.cmod.feature.retro + +import android.content.Context +import com.armsx2.runtime.MainActivityRuntime +import kr.co.iefriends.pcsx2.NativeApp +import org.json.JSONObject +import java.io.File + +object Ps2DnasBypass { + const val PREF = "wn.ps2.net.dnasbypass" + + @Volatile + private var db: Map? = null + + private data class Variant(val name: String, val codes: List, val crc: String?, val auto: Boolean) + + private data class Game(val title: String, val variants: List) + + private fun loadDb(ctx: Context): Map { + db?.let { return it } + val parsed = + runCatching { + val text = ctx.assets.open("dnas/dnas_bypass.json").bufferedReader().use { it.readText() } + val root = JSONObject(text) + val map = HashMap() + val keys = root.keys() + while (keys.hasNext()) { + val serial = keys.next() + val g = root.getJSONObject(serial) + val vs = g.getJSONArray("cheats") + val variants = ArrayList() + for (i in 0 until vs.length()) { + val v = vs.getJSONObject(i) + val codesArr = v.getJSONArray("codes") + val codes = (0 until codesArr.length()).map { codesArr.getString(it) } + variants.add( + Variant( + v.getString("name"), + codes, + v.optString("crc").takeIf { it.isNotBlank() }, + v.optBoolean("auto", false), + ), + ) + } + map[serial.uppercase()] = Game(g.getString("title"), variants) + } + map + }.getOrDefault(emptyMap()) + db = parsed + return parsed + } + + fun hasBypass(ctx: Context, serial: String?): Boolean = + serial != null && loadDb(ctx).containsKey(serial.trim().uppercase()) + + fun isEnabled(ctx: Context): Boolean = + ctx.getSharedPreferences("ARMSX2", Context.MODE_PRIVATE).getBoolean(PREF, true) + + fun setEnabled(ctx: Context, on: Boolean) { + ctx.getSharedPreferences("ARMSX2", Context.MODE_PRIVATE).edit().putBoolean(PREF, on).apply() + } + + data class BypassEntry(val name: String, val body: String, val auto: Boolean) + + private fun disabledKey(serial: String) = "wn.ps2.dnas.disabled.${serial.trim().uppercase()}" + + fun disabledNames(ctx: Context, serial: String): Set { + val raw = ctx.getSharedPreferences("ARMSX2", Context.MODE_PRIVATE).getString(disabledKey(serial), "") ?: "" + if (raw.isBlank()) return emptySet() + return runCatching { + val arr = org.json.JSONArray(raw) + (0 until arr.length()).map { arr.getString(it) }.toSet() + }.getOrDefault(emptySet()) + } + + fun setDisabledNames(ctx: Context, serial: String, names: Set) { + val arr = org.json.JSONArray() + names.forEach { arr.put(it) } + ctx.getSharedPreferences("ARMSX2", Context.MODE_PRIVATE).edit() + .putString(disabledKey(serial), arr.toString()).apply() + } + + fun ensureSingleDnasEnabled(ctx: Context, serial: String, allNames: Set): Set { + if (allNames.isEmpty()) return emptySet() + val disabled = disabledNames(ctx, serial).toMutableSet() + val enabled = allNames.filter { it !in disabled } + if (enabled.size <= 1) return disabled + val keep = enabled.first() + val next = allNames - keep + setDisabledNames(ctx, serial, next) + return next + } + + fun bypassEntries(ctx: Context, serial: String?): List { + val game = loadDb(ctx)[serial?.trim()?.uppercase()] ?: return emptyList() + val used = HashMap() + return game.variants.mapNotNull { v -> + val base = v.name + val n = (used[base] ?: 0) + 1 + used[base] = n + val nm = if (n > 1) "$base ($n)" else base + val lines = v.codes.mapNotNull { toPatchLine(it) } + if (lines.isEmpty()) { + null + } else { + val body = buildString { + append("[").append(nm).append("]\n") + lines.forEach { append(it).append('\n') } + } + BypassEntry(nm, body, v.auto) + } + } + } + + private fun toPatchLine(raw: String): String? { + val parts = raw.trim().split(Regex("\\s+")) + if (parts.size != 2) return null + val a = parts[0].uppercase() + val v = parts[1].uppercase() + if (a.length != 8 || v.length != 8) return null + if (!a.all { it.isDigit() || it in 'A'..'F' } || !v.all { it.isDigit() || it in 'A'..'F' }) return null + return "patch=1,EE,$a,extended,$v" + } + + data class Section(val name: String, val body: String, val enabledByDefault: Boolean) + + fun sectionsFor(ctx: Context, serialRaw: String, crcRaw: String): List
{ + val serial = serialRaw.trim().uppercase() + val crc = crcRaw.trim().uppercase() + val game = loadDb(ctx)[serial] ?: return emptyList() + val globalOn = isEnabled(ctx) + val disabled = disabledNames(ctx, serial) + val used = HashMap() + val out = ArrayList
() + for (v in game.variants) { + val base = v.name + val n = (used[base] ?: 0) + 1 + used[base] = n + val nm = if (n > 1) "$base ($n)" else base + val lines = v.codes.mapNotNull { toPatchLine(it) } + if (lines.isEmpty()) continue + val body = buildString { + append("[").append(nm).append("]\n") + lines.forEach { append(it).append('\n') } + } + val crcOk = v.crc == null || v.crc.equals(crc, ignoreCase = true) + val on = globalOn && v.auto && nm !in disabled && crcOk + out.add(Section(nm, body, on)) + } + val enabled = out.filter { it.enabledByDefault } + if (enabled.size <= 1) return out + val keep = enabled.first().name + return out.map { if (it.enabledByDefault && it.name != keep) it.copy(enabledByDefault = false) else it } + } + + fun applyWhenReady(ctx: Context) { + var tries = 0 + while (tries < 60) { + val s = runCatching { NativeApp.getGameSerial() }.getOrNull()?.takeIf { it.isNotBlank() } + val c = runCatching { NativeApp.getGameCRC() }.getOrNull()?.takeIf { it.length == 8 && it != "00000000" } + if (s != null && c != null) { + runCatching { Ps2CheatStaging.applyAll(ctx, s, c) } + .onFailure { android.util.Log.w("Ps2DnasBypass", "applyAll failed for $s/$c", it) } + return + } + try { + Thread.sleep(500) + } catch (e: InterruptedException) { + return + } + tries++ + } + } +} diff --git a/app/src/main/feature/retro/Ps2GameOverlay.kt b/app/src/main/feature/retro/Ps2GameOverlay.kt new file mode 100644 index 000000000..8e4c7cab4 --- /dev/null +++ b/app/src/main/feature/retro/Ps2GameOverlay.kt @@ -0,0 +1,1260 @@ +package com.winlator.cmod.feature.retro + +import android.view.KeyEvent +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import androidx.activity.ComponentActivity +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.ComposeView +import androidx.compose.ui.viewinterop.AndroidView +import com.armsx2.WinNativeHost +import com.winlator.cmod.R +import com.armsx2.runtime.MainActivityRuntime +import com.armsx2.ui.WindowImpl +import com.winlator.cmod.runtime.display.ui.FrameRating +import com.winlator.cmod.shared.theme.WinNativeTheme +import kr.co.iefriends.pcsx2.NativeApp + +const val PS2_DEFAULT_DNS = "45.7.228.197" + +data class Ps2NetHost(val url: String, val ip: String) + +object Ps2GameOverlay { + private const val FULL = 32767 + + @Volatile + private var overlayAttached = false + + fun install() { + overlayAttached = false + WinNativeHost.attachOverlay = attach@{ activity -> + if (overlayAttached) return@attach + overlayAttached = true + attach(activity) + } + WinNativeHost.applyBootSettings = { ctx -> applyBootConfig(ctx) } + } + + private fun ps2Prefs(ctx: android.content.Context) = + ctx.getSharedPreferences("ARMSX2", android.content.Context.MODE_PRIVATE) + + private fun fmvAspectName(value: Int): String = + when (value) { + 1 -> "Auto 4:3/3:2" + 2 -> "4:3" + 3 -> "16:9" + else -> "Off" + } + + private fun writePatchSettings(ctx: android.content.Context) { + val prefs = ps2Prefs(ctx) + NativeApp.setSetting("EmuCore", "EnableWideScreenPatches", "bool", prefs.getBoolean("wn.ps2.widescreen", false).toString()) + NativeApp.setSetting("EmuCore", "EnableNoInterlacingPatches", "bool", prefs.getBoolean("wn.ps2.nointerlace", false).toString()) + NativeApp.setSetting("EmuCore", "EnableFastBoot", "bool", prefs.getBoolean("wn.ps2.fastboot", true).toString()) + } + + private fun blankHddFile(ctx: android.content.Context): java.io.File = + java.io.File(ctx.filesDir, "hdd/DEV9hdd.raw") + + private fun resolveHdd(ctx: android.content.Context): Pair { + val prefs = ps2Prefs(ctx) + val image = RetroHddImport.imageFile(ctx, prefs.getString("wn.ps2.hddimage", "")) + if (image != null) return image to true + if (prefs.getBoolean("wn.ps2.hdd", false)) return blankHddFile(ctx) to true + return null to false + } + + private fun ensureHddImage(ctx: android.content.Context) { + val prefs = ps2Prefs(ctx) + if (RetroHddImport.imageFile(ctx, prefs.getString("wn.ps2.hddimage", "")) != null) return + if (!prefs.getBoolean("wn.ps2.hdd", false)) return + val img = blankHddFile(ctx) + if (img.exists() && img.length() > 0L) return + runCatching { + img.parentFile?.mkdirs() + java.io.RandomAccessFile(img, "rw").use { it.setLength(8L * 1024 * 1024 * 1024) } + } + } + + private fun readHosts(prefs: android.content.SharedPreferences): List { + val raw = prefs.getString("wn.ps2.net.hosts", "") ?: "" + if (raw.isBlank()) return emptyList() + return runCatching { + val arr = org.json.JSONArray(raw) + (0 until arr.length()).map { i -> + val o = arr.getJSONObject(i) + Ps2NetHost(o.optString("url"), o.optString("ip", "0.0.0.0")) + }.filter { it.url.isNotBlank() } + }.getOrDefault(emptyList()) + } + + private fun writeDev9Settings(ctx: android.content.Context) { + val prefs = ps2Prefs(ctx) + val on = prefs.getBoolean("wn.ps2.net.enable", true) + NativeApp.setSetting("DEV9/Eth", "EthEnable", "bool", on.toString()) + NativeApp.setSetting("DEV9/Eth", "EthApi", "string", "Sockets") + NativeApp.setSetting("DEV9/Eth", "EthDevice", "string", (prefs.getString("wn.ps2.net.ethdevice", "Auto") ?: "Auto").ifBlank { "Auto" }) + NativeApp.setSetting("DEV9/Eth", "InterceptDHCP", "bool", prefs.getBoolean("wn.ps2.net.dhcp", true).toString()) + NativeApp.setSetting("DEV9/Eth", "AutoMask", "bool", "true") + NativeApp.setSetting("DEV9/Eth", "AutoGateway", "bool", "true") + val hosts = readHosts(prefs) + val chosen = prefs.getString("wn.ps2.net.dnsmode", "Manual") ?: "Manual" + val mode = + when { + hosts.isNotEmpty() -> "Internal" + chosen.equals("Manual", ignoreCase = true) -> "Manual" + else -> "Internal" + } + NativeApp.setSetting("DEV9/Eth", "ModeDNS1", "string", mode) + NativeApp.setSetting("DEV9/Eth", "ModeDNS2", "string", "Auto") + NativeApp.setSetting("DEV9/Eth", "DNS1", "string", (prefs.getString("wn.ps2.net.dns1", PS2_DEFAULT_DNS) ?: PS2_DEFAULT_DNS).ifBlank { PS2_DEFAULT_DNS }) + NativeApp.setSetting("DEV9/Eth", "DNS2", "string", (prefs.getString("wn.ps2.net.dns2", "") ?: "").ifBlank { "0.0.0.0" }) + NativeApp.setSetting("DEV9/Eth/Hosts", "Count", "int", hosts.size.toString()) + hosts.forEachIndexed { i, h -> + NativeApp.setSetting("DEV9/Eth/Hosts/Host$i", "Url", "string", h.url) + NativeApp.setSetting("DEV9/Eth/Hosts/Host$i", "Desc", "string", "WinNative") + NativeApp.setSetting("DEV9/Eth/Hosts/Host$i", "Address", "string", h.ip.ifBlank { "0.0.0.0" }) + NativeApp.setSetting("DEV9/Eth/Hosts/Host$i", "Enabled", "bool", "true") + } + val (hddFile, hddOn) = resolveHdd(ctx) + NativeApp.setSetting("DEV9/Hdd", "HddEnable", "bool", hddOn.toString()) + NativeApp.setSetting("DEV9/Hdd", "HddFile", "string", (hddFile ?: blankHddFile(ctx)).absolutePath) + } + + fun applyBootConfig(ctx: android.content.Context) { + runCatching { + applyTurnipDebug(ctx) + ensureHddImage(ctx) + writeDev9Settings(ctx) + writePatchSettings(ctx) + RetroHudSupport.suppressNativePs2Osd() + applyDisplayAspect(ctx, live = false) + } + } + + private fun applyDisplayAspect( + ctx: android.content.Context, + live: Boolean, + ) { + val prefs = ps2Prefs(ctx) + val aspect = resolveBootAspect(prefs) + val name = + when (aspect) { + 3 -> "16:9" + else -> "4:3" + } + runCatching { + NativeApp.setSetting("EmuCore/GS", "AspectRatio", "string", name) + NativeApp.setAspectRatio(aspect) + if (!live) { + NativeApp.commitSettings() + } + } + } + + private fun resolveBootAspect(prefs: android.content.SharedPreferences): Int { + val aspect = prefs.getInt("wn.ps2.aspect", 1).coerceIn(0, 3) + return when (aspect) { + 3 -> 3 + 2 -> 2 + else -> 2 + } + } + + private fun applyTurnipDebug(ctx: android.content.Context) { + val prefs = ps2Prefs(ctx) + val driver = (prefs.getString("wn.ps2.driver", "") ?: "").trim() + val usingTurnip = driver.isNotEmpty() && !driver.equals("system", ignoreCase = true) + val flags = (prefs.getString("wn.ps2.turnipflags", "") ?: "").trim() + runCatching { + if (usingTurnip && flags.isNotEmpty()) { + android.system.Os.setenv("TU_DEBUG", flags, true) + } else { + android.system.Os.unsetenv("TU_DEBUG") + } + } + } + + private fun mapFace(keyCode: Int): Int = + when (keyCode) { + KeyEvent.KEYCODE_BUTTON_X -> KeyEvent.KEYCODE_BUTTON_Y + KeyEvent.KEYCODE_BUTTON_B -> KeyEvent.KEYCODE_BUTTON_A + KeyEvent.KEYCODE_BUTTON_Y -> KeyEvent.KEYCODE_BUTTON_X + KeyEvent.KEYCODE_BUTTON_A -> KeyEvent.KEYCODE_BUTTON_B + else -> keyCode + } + + private fun emitAxis(pos: Int, neg: Int, v: Float) { + val mag = (kotlin.math.abs(v) * FULL).toInt().coerceAtMost(FULL) + NativeApp.setPadButton(pos, if (v > 0f) mag else 0, v > 0f) + NativeApp.setPadButton(neg, if (v < 0f) mag else 0, v < 0f) + } + + private fun attach(activity: ComponentActivity) { + val menu = RetroMenuController() + val ps2Screen = mutableStateOf(null) + var savesLoadMode = false + var pad: RetroInputView? = null + val touchVisible = + mutableStateOf( + ps2Prefs(activity).getBoolean("wn.ps2.touchcontrols", RetroDefaults.touchControls(activity, RetroSystems.PS2.id)), + ) + fun anyGameController(): Boolean = + android.view.InputDevice.getDeviceIds().any { + com.winlator.cmod.runtime.input.controls.ExternalController.isGameController(android.view.InputDevice.getDevice(it)) + } + val controllerConnected = mutableStateOf(anyGameController()) + val manualTouchOverride = mutableStateOf(false) + val launchRomPath = activity.intent?.getStringExtra(RetroShortcuts.EXTRA_PS2_ROM_PATH).orEmpty() + val launchGameName = activity.intent?.getStringExtra(RetroShortcuts.EXTRA_PS2_GAME_NAME).orEmpty() + val inputManager = activity.getSystemService(android.hardware.input.InputManager::class.java) + inputManager?.registerInputDeviceListener( + object : android.hardware.input.InputManager.InputDeviceListener { + private fun refreshPadPresence() { + val was = controllerConnected.value + controllerConnected.value = anyGameController() + if (controllerConnected.value != was) manualTouchOverride.value = false + val showPad = touchVisible.value && (!controllerConnected.value || manualTouchOverride.value) + RetroAchievementOverlayState.syncPlacement(showPad, controllerConnected.value) + MainActivityRuntime.runWhenNativeReady { + runCatching { RetroPs2OsdPlacement.apply(showPad, controllerConnected.value) } + } + } + + override fun onInputDeviceAdded(deviceId: Int) = refreshPadPresence() + + override fun onInputDeviceRemoved(deviceId: Int) = refreshPadPresence() + + override fun onInputDeviceChanged(deviceId: Int) = refreshPadPresence() + }, + null, + ) + var customColors = RetroControlLayouts.loadColors(activity, RetroSystems.PS2.id) + var wnPaused = false + val prefs = activity.getSharedPreferences("ARMSX2", android.content.Context.MODE_PRIVATE) + var frameRating: FrameRating? = null + var hudVisible = RetroHudSupport.resolvePs2HudEnabled(activity) + var hudStyle = RetroHudSupport.loadPs2HudStyle(activity) + var hudElements = RetroHudSupport.loadPs2Elements(activity) + val menuToggleGate = RetroHudSupport.MenuToggleGate() + val frameSource = + RetroHudSupport.Ps2FrameSource( + ratingProvider = { frameRating }, + enabledProvider = { hudVisible }, + ) + + fun persistColors() { + RetroControlLayouts.saveColors(activity, RetroSystems.PS2.id, customColors) + pad?.setCustomColors(customColors) + menu.rebuild() + } + + fun applyHudToRating() { + val rating = frameRating ?: return + RetroHudSupport.applyStyle(rating, hudStyle, hudElements) + } + + fun showHud() { + var rating = frameRating + if (rating == null) { + val root = activity.findViewById(android.R.id.content) ?: return + val renderer = + when (prefs.getString("wn.ps2.renderer", "vulkan")) { + "opengl" -> "OpenGL" + "software" -> "Software" + else -> "Vulkan" + } + rating = RetroHudSupport.createFrameRating(activity, renderer) + frameRating = rating + RetroHudSupport.attachFrameRating(root, rating) + applyHudToRating() + } + rating.visibility = View.VISIBLE + rating.reset() + frameSource.start() + } + + fun hideHud() { + frameRating?.visibility = View.GONE + } + + fun setHudVisible(value: Boolean) { + hudVisible = value + RetroHudSupport.setPs2HudEnabled(activity, value) + if (value) showHud() else hideHud() + menu.rebuild() + } + + fun gsSet(key: String, type: String, value: String) { + runCatching { + NativeApp.setSetting("EmuCore/GS", key, type, value) + NativeApp.commitSettings() + NativeApp.applyGSSettingsLive() + } + } + + fun bg(block: () -> Unit) { + MainActivityRuntime.runWhenNativeReady { runCatching { block() } } + } + + fun nativeUp(): Boolean = MainActivityRuntime.isNativeReady() + + fun gsSetAsync(key: String, type: String, value: String) = bg { gsSet(key, type, value) } + + fun spSet(key: String, type: String, value: String) { + bg { + NativeApp.setSetting("EmuCore/Speedhacks", key, type, value) + NativeApp.commitSettings() + } + } + + fun spu2Set(key: String, type: String, value: String) { + bg { + NativeApp.setSetting("SPU2/Output", key, type, value) + NativeApp.commitSettings() + } + } + + fun ensureHddImage() = ensureHddImage(activity) + + fun writeNetworkSettings() = writeDev9Settings(activity) + + MainActivityRuntime.runWhenNativeReady { + kotlin.concurrent.thread(name = "ps2-dnas-bypass") { + Ps2DnasBypass.applyWhenReady(activity) + } + } + + bg { + NativeApp.setAudioVolume(prefs.getInt("wn.ps2.volume", 100)) + NativeApp.setAudioMuted(prefs.getBoolean("wn.ps2.muted", false)) + NativeApp.setAudioSwapChannels(prefs.getBoolean("wn.ps2.swap", false)) + val customDriver = (prefs.getString("wn.ps2.driver", "") ?: "").trim() + .let { it.isNotEmpty() && !it.equals("system", ignoreCase = true) } + when { + customDriver -> NativeApp.renderVulkan() + prefs.getString("wn.ps2.renderer", "vulkan") == "opengl" -> NativeApp.renderOpenGL() + prefs.getString("wn.ps2.renderer", "vulkan") == "software" -> NativeApp.renderSoftware() + else -> NativeApp.renderVulkan() + } + NativeApp.renderUpscalemultiplier(prefs.getFloat("wn.ps2.upscale", 1f)) + RetroHudSupport.suppressNativePs2Osd() + val touchOn = prefs.getBoolean("wn.ps2.touchcontrols", RetroDefaults.touchControls(activity, RetroSystems.PS2.id)) + RetroPs2OsdPlacement.apply(touchOn, false) + applyDisplayAspect(activity, live = true) + NativeApp.setFrameSkip(prefs.getInt("wn.ps2.frameskip", 0).coerceIn(0, 3)) + NativeApp.speedhackEecyclerate(prefs.getInt("wn.ps2.eeRate", 0).coerceIn(-3, 3)) + NativeApp.speedhackEecycleskip(prefs.getInt("wn.ps2.eeSkip", 0).coerceIn(0, 3)) + NativeApp.setInstantVU1(prefs.getBoolean("wn.ps2.instantVu1", true)) + NativeApp.renderTvShader(prefs.getInt("wn.ps2.tvshader", 0).coerceIn(0, 7)) + NativeApp.setSetting("EmuCore/GS", "linear_present_mode", "int", prefs.getInt("wn.ps2.displayfilter", 1).coerceIn(0, 2).toString()) + NativeApp.setSetting("EmuCore/GS", "filter", "int", prefs.getInt("wn.ps2.filter", 2).coerceIn(0, 3).toString()) + NativeApp.setSetting("EmuCore/GS", "accurate_blending_unit", "int", prefs.getInt("wn.ps2.blend", 1).coerceIn(0, 5).toString()) + NativeApp.setSetting("EmuCore/GS", "hw_mipmap", "bool", prefs.getBoolean("wn.ps2.mipmap", true).toString()) + NativeApp.setSetting("EmuCore/Speedhacks", "vuThread", "bool", prefs.getBoolean("wn.ps2.mtvu", true).toString()) + NativeApp.setSetting("EmuCore/Speedhacks", "fastCDVD", "bool", prefs.getBoolean("wn.ps2.fastCdvd", false).toString()) + NativeApp.setSetting("EmuCore/GS", "deinterlace_mode", "int", prefs.getInt("wn.ps2.deinterlace", 0).coerceIn(0, 9).toString()) + NativeApp.setSetting("EmuCore/GS", "FMVAspectRatioSwitch", "string", fmvAspectName(prefs.getInt("wn.ps2.fmvaspect", 0))) + NativeApp.setSetting("EmuCore/GS", "pcrtc_antiblur", "bool", prefs.getBoolean("wn.ps2.antiblur", true).toString()) + NativeApp.setSetting("EmuCore/Speedhacks", "vuFlagHack", "bool", prefs.getBoolean("wn.ps2.vuFlagHack", true).toString()) + NativeApp.setSetting("EmuCore/Speedhacks", "IntcStat", "bool", prefs.getBoolean("wn.ps2.intc", true).toString()) + NativeApp.setSetting("EmuCore/Speedhacks", "WaitLoop", "bool", prefs.getBoolean("wn.ps2.waitloop", true).toString()) + NativeApp.setSetting("SPU2/Output", "SyncMode", "string", if (prefs.getBoolean("wn.ps2.timestretch", true)) "TimeStretch" else "Disabled") + NativeApp.setSetting("SPU2/Output", "BufferMS", "int", prefs.getInt("wn.ps2.audiobuffer", 50).coerceIn(10, 200).toString()) + NativeApp.setSetting("SPU2/Output", "OutputLatencyMS", "int", prefs.getInt("wn.ps2.audiolatency", 20).coerceIn(5, 200).toString()) + prefs.getString("wn.ps2.mc.slot1", null)?.takeIf { it.isNotBlank() }?.let { name -> + NativeApp.setSetting("MemoryCards", "Slot1_Filename", "string", name) + NativeApp.setSetting("MemoryCards", "Slot1_Enable", "bool", "true") + } + prefs.getString("wn.ps2.mc.slot2", null)?.takeIf { it.isNotBlank() }?.let { name -> + NativeApp.setSetting("MemoryCards", "Slot2_Filename", "string", name) + NativeApp.setSetting("MemoryCards", "Slot2_Enable", "bool", "true") + } + ensureHddImage() + writeNetworkSettings() + runCatching { NativeApp.applyGSSettingsLive() } + applyDisplayAspect(activity, live = true) + } + + fun openWinNativeScreen(screen: String) { + menu.close() + ps2Screen.value = screen + } + + fun mainEntries(): List = + buildList { + add( + RetroMenuEntry.Action(activity.getString(R.string.retro_ps2_save_state), RetroDrawerIcons.Save) { + savesLoadMode = false + menu.showPane(RetroPane.SAVES) + }, + ) + add( + RetroMenuEntry.Action(activity.getString(R.string.retro_ps2_load_save_state), RetroDrawerIcons.Load) { + savesLoadMode = true + menu.showPane(RetroPane.SAVES) + }, + ) + add(RetroMenuEntry.Action(activity.getString(R.string.retro_ps2_achievements), RetroDrawerIcons.Achievements) { openWinNativeScreen("achievements") }) + add(RetroMenuEntry.Action(activity.getString(R.string.retro_ps2_cheats), RetroDrawerIcons.Cheats) { openWinNativeScreen("cheats") }) + add(RetroMenuEntry.Action(activity.getString(R.string.retro_ps2_memory_cards), RetroDrawerIcons.Save) { menu.showPane(RetroPane.MEMCARDS) }) + add( + RetroMenuEntry.Toggle(activity.getString(R.string.retro_ps2_fast_forward), checked = MainActivityRuntime.fastForwardToggleActive) { + (activity as? MainActivityRuntime)?.toggleFastForward() + menu.rebuild() + }, + ) + add( + RetroMenuEntry.Action(activity.getString(R.string.retro_ps2_reset), RetroDrawerIcons.Reset) { + menu.close() + MainActivityRuntime.restart() + }, + ) + add( + RetroMenuEntry.Action(activity.getString(R.string.retro_ps2_swap_disc), RetroDrawerIcons.Disc) { + menu.close() + MainActivityRuntime.promptSwapDisc() + }, + ) + } + + fun saveSlotEntries(): List = + (1..8).map { ui -> + val slot = ui - 1 + val filled = runCatching { + NativeApp.getGamePathSlot(slot)?.takeIf { it.isNotBlank() }?.let { java.io.File(it).exists() } + }.getOrNull() == true + RetroMenuEntry.SaveSlot( + slot = ui, + title = activity.getString(R.string.retro_ps2_slot, ui), + subtitle = + when { + savesLoadMode && filled -> activity.getString(R.string.retro_ps2_slot_tap_to_load) + savesLoadMode -> activity.getString(R.string.retro_ps2_slot_empty) + filled -> activity.getString(R.string.retro_ps2_slot_tap_to_overwrite) + else -> activity.getString(R.string.retro_ps2_slot_empty_tap_to_save) + }, + filled = filled, + onClick = { + if (savesLoadMode) { + if (!filled) { + Toast.makeText(activity, activity.getString(R.string.retro_ps2_slot_is_empty, ui), Toast.LENGTH_SHORT).show() + } else { + menu.close() + Thread { + val ok = runCatching { NativeApp.loadStateFromSlot(slot) }.getOrDefault(false) + activity.runOnUiThread { + Toast.makeText(activity, if (ok) activity.getString(R.string.retro_ps2_loaded_slot, ui) else activity.getString(R.string.retro_ps2_could_not_load_slot, ui), Toast.LENGTH_SHORT).show() + if (ok) { wnPaused = false; MainActivityRuntime.resume() } + } + }.start() + } + } else { + Thread { + val ok = runCatching { NativeApp.saveStateToSlot(slot) }.getOrDefault(false) + activity.runOnUiThread { + Toast.makeText(activity, if (ok) activity.getString(R.string.retro_ps2_saved_to_slot, ui) else activity.getString(R.string.retro_ps2_save_failed), Toast.LENGTH_SHORT).show() + menu.rebuild() + } + }.start() + } + }, + onRename = {}, + ) + } + + var launchMemcardImport: (() -> Unit)? = null + + fun applyMemSlot(slot: Int, name: String?) { + prefs.edit().apply { + if (name == null) remove("wn.ps2.mc.slot$slot") else putString("wn.ps2.mc.slot$slot", name) + }.apply() + bg { + NativeApp.setSetting("MemoryCards", "Slot${slot}_Enable", "bool", "false") + if (name != null) { + NativeApp.setSetting("MemoryCards", "Slot${slot}_Filename", "string", name) + NativeApp.setSetting("MemoryCards", "Slot${slot}_Enable", "bool", "true") + } + NativeApp.commitSettings() + } + } + + fun memcardEntries(): List = + buildList { + val cards = runCatching { listMemcards(activity) }.getOrDefault(emptyList()) + val slot1 = prefs.getString("wn.ps2.mc.slot1", "").orEmpty() + val slot2 = prefs.getString("wn.ps2.mc.slot2", "").orEmpty() + cards.forEach { card -> + val assigned = when (card.name) { slot1 -> 1; slot2 -> 2; else -> 0 } + add( + RetroMenuEntry.SaveSlot( + slot = assigned, + title = card.name.removeSuffix(".ps2"), + subtitle = humanSize(card.length()) + + when (assigned) { 1 -> activity.getString(R.string.retro_ps2_slot_1_suffix); 2 -> activity.getString(R.string.retro_ps2_slot_2_suffix); else -> activity.getString(R.string.retro_ps2_tap_to_use_suffix) }, + filled = assigned != 0, + onClick = { + when (assigned) { + 0 -> applyMemSlot(1, card.name) + 1 -> { applyMemSlot(1, null); applyMemSlot(2, card.name) } + else -> applyMemSlot(2, null) + } + menu.rebuild() + }, + onRename = {}, + ), + ) + } + add( + RetroMenuEntry.Action(activity.getString(R.string.retro_ps2_new_memory_card), RetroDrawerIcons.Save) { + bg { + val existing = runCatching { listMemcards(activity).map { it.name }.toHashSet() }.getOrDefault(hashSetOf()) + var n = 1 + var name = "Mcd%03d.ps2".format(n) + while (name in existing) { n++; name = "Mcd%03d.ps2".format(n) } + runCatching { NativeApp.createMemoryCard(name, 1, 1) } + activity.runOnUiThread { menu.rebuild() } + } + }, + ) + add(RetroMenuEntry.Action(activity.getString(R.string.retro_ps2_import_card), RetroDrawerIcons.Load) { launchMemcardImport?.invoke() }) + } + + fun controlsEntries(): List = + buildList { + add( + RetroMenuEntry.Toggle(activity.getString(R.string.retro_ps2_onscreen_controls), checked = touchVisible.value) { value -> + touchVisible.value = value + if (controllerConnected.value) manualTouchOverride.value = true + ps2Prefs(activity).edit().putBoolean("wn.ps2.touchcontrols", value).apply() + RetroDefaults.setTouchControls(activity, RetroSystems.PS2.id, value) + val showPad = value && (!controllerConnected.value || manualTouchOverride.value) + RetroAchievementOverlayState.syncPlacement(showPad, controllerConnected.value) + bg { + RetroPs2OsdPlacement.apply(showPad, controllerConnected.value) + } + menu.rebuild() + }, + ) + add( + RetroMenuEntry.Toggle( + activity.getString(R.string.retro_ps2_adaptive_sticks), + subtitle = activity.getString(R.string.retro_ps2_adaptive_sticks_subtitle), + checked = ps2Prefs(activity).getBoolean("wn.ps2.adaptivesticks", false), + ) { value -> + ps2Prefs(activity).edit().putBoolean("wn.ps2.adaptivesticks", value).apply() + RetroDefaults.setAdaptiveSticks(activity, RetroSystems.PS2.id, value) + pad?.adaptiveSticks = value + pad?.invalidate() + menu.rebuild() + }, + ) + add( + RetroMenuEntry.Toggle( + activity.getString(R.string.retro_ps2_show_l3r3), + subtitle = activity.getString(R.string.retro_ps2_show_l3r3_subtitle), + checked = ps2Prefs(activity).getBoolean("wn.ps2.showl3r3", true), + ) { value -> + ps2Prefs(activity).edit().putBoolean("wn.ps2.showl3r3", value).apply() + pad?.showL3R3 = value + menu.rebuild() + }, + ) + add( + RetroMenuEntry.Action(activity.getString(R.string.retro_ps2_edit_layout), RetroDrawerIcons.EditLayout) { + menu.close() + touchVisible.value = true + pad?.enterEdit() + }, + ) + add( + RetroMenuEntry.Action(activity.getString(R.string.retro_ps2_reset_layout), RetroDrawerIcons.Reset) { + pad?.resetLayout() + Toast.makeText(activity, activity.getString(R.string.retro_ps2_layout_reset), Toast.LENGTH_SHORT).show() + }, + ) + val invPrefs = androidx.preference.PreferenceManager.getDefaultSharedPreferences(activity) + fun invToggle(label: String, key: String) = + RetroMenuEntry.Toggle(label, checked = invPrefs.getBoolean(key, false)) { value -> + invPrefs.edit().putBoolean(key, value).apply() + pad?.loadStickInversion() + menu.rebuild() + } + add(invToggle(activity.getString(R.string.retro_ps2_left_stick_invert_x), "retro_inv_lx_ps2")) + add(invToggle(activity.getString(R.string.retro_ps2_left_stick_invert_y), "retro_inv_ly_ps2")) + add(invToggle(activity.getString(R.string.retro_ps2_right_stick_invert_x), "retro_inv_rx_ps2")) + add(invToggle(activity.getString(R.string.retro_ps2_right_stick_invert_y), "retro_inv_ry_ps2")) + add( + RetroMenuEntry.ColorPick(activity.getString(R.string.retro_ps2_button_color), customColors.button) { value -> + customColors = customColors.copy(button = value) + persistColors() + }, + ) + add( + RetroMenuEntry.ColorPick(activity.getString(R.string.retro_ps2_letter_color), customColors.text) { value -> + customColors = customColors.copy(text = value) + persistColors() + }, + ) + add( + RetroMenuEntry.ColorPick(activity.getString(R.string.retro_ps2_shadow_color), customColors.shadow) { value -> + customColors = customColors.copy(shadow = value) + persistColors() + }, + ) + add( + RetroMenuEntry.ColorPick(activity.getString(R.string.retro_ps2_background_color), customColors.body) { value -> + customColors = customColors.copy(body = value) + persistColors() + }, + ) + add( + RetroMenuEntry.Action(activity.getString(R.string.retro_ps2_reset_colors), RetroDrawerIcons.Reset) { + customColors = RetroCustomColors() + persistColors() + }, + ) + } + + fun displayEntries(): List = + buildList { + val scales = listOf(1f, 1.5f, 2f, 3f, 4f) + val scaleLabels = listOf( + activity.getString(R.string.retro_ps2_scale_1x_native), + activity.getString(R.string.retro_ps2_scale_1_5x), + activity.getString(R.string.retro_ps2_scale_2x), + activity.getString(R.string.retro_ps2_scale_3x), + activity.getString(R.string.retro_ps2_scale_4x), + ) + val scaleIdx = scales.indexOfFirst { kotlin.math.abs(it - prefs.getFloat("wn.ps2.upscale", 1f)) < 0.01f }.coerceAtLeast(0) + add( + RetroMenuEntry.Choice(activity.getString(R.string.retro_ps2_resolution_scale), scaleLabels, scaleIdx) { next -> + prefs.edit().putFloat("wn.ps2.upscale", scales[next]).apply() + bg { NativeApp.renderUpscalemultiplier(scales[next]) } + menu.rebuild() + }, + ) + add( + RetroMenuEntry.Choice( + activity.getString(R.string.retro_ps2_aspect_ratio), + listOf( + activity.getString(R.string.retro_ps2_aspect_stretch), + activity.getString(R.string.retro_ps2_aspect_auto_standard), + activity.getString(R.string.retro_ps2_aspect_4_3), + activity.getString(R.string.retro_ps2_aspect_16_9), + ), + prefs.getInt("wn.ps2.aspect", 1).coerceIn(0, 3), + ) { next -> + prefs.edit().putInt("wn.ps2.aspect", next).apply() + bg { NativeApp.setAspectRatio(next) } + menu.rebuild() + }, + ) + add( + RetroMenuEntry.Choice( + activity.getString(R.string.retro_ps2_fmv_aspect_ratio), + listOf( + activity.getString(R.string.retro_ps2_shader_off), + activity.getString(R.string.retro_ps2_aspect_auto_standard), + activity.getString(R.string.retro_ps2_aspect_4_3), + activity.getString(R.string.retro_ps2_aspect_16_9), + ), + prefs.getInt("wn.ps2.fmvaspect", 0).coerceIn(0, 3), + ) { next -> + prefs.edit().putInt("wn.ps2.fmvaspect", next).apply() + gsSetAsync("FMVAspectRatioSwitch", "string", fmvAspectName(next)) + menu.rebuild() + }, + ) + val deintLabels = listOf( + activity.getString(R.string.retro_ps2_deint_auto), + activity.getString(R.string.retro_ps2_deint_off), + activity.getString(R.string.retro_ps2_deint_weave_tff), + activity.getString(R.string.retro_ps2_deint_weave_bff), + activity.getString(R.string.retro_ps2_deint_bob_tff), + activity.getString(R.string.retro_ps2_deint_bob_bff), + activity.getString(R.string.retro_ps2_deint_blend_tff), + activity.getString(R.string.retro_ps2_deint_blend_bff), + activity.getString(R.string.retro_ps2_deint_adaptive_tff), + activity.getString(R.string.retro_ps2_deint_adaptive_bff), + ) + add( + RetroMenuEntry.Choice(activity.getString(R.string.retro_ps2_deinterlace_mode), deintLabels, prefs.getInt("wn.ps2.deinterlace", 0).coerceIn(0, 9)) { next -> + prefs.edit().putInt("wn.ps2.deinterlace", next).apply() + gsSetAsync("deinterlace_mode", "int", next.toString()) + menu.rebuild() + }, + ) + add( + RetroMenuEntry.Choice( + activity.getString(R.string.retro_ps2_display_filter), + listOf( + activity.getString(R.string.retro_ps2_filter_nearest), + activity.getString(R.string.retro_ps2_filter_bilinear_smooth), + activity.getString(R.string.retro_ps2_filter_bilinear_sharp), + ), + prefs.getInt("wn.ps2.displayfilter", 1).coerceIn(0, 2), + ) { next -> + prefs.edit().putInt("wn.ps2.displayfilter", next).apply() + gsSetAsync("linear_present_mode", "int", next.toString()) + menu.rebuild() + }, + ) + add( + RetroMenuEntry.Choice( + activity.getString(R.string.retro_ps2_texture_filter), + listOf( + activity.getString(R.string.retro_ps2_filter_nearest), + activity.getString(R.string.retro_ps2_filter_bilinear_forced), + activity.getString(R.string.retro_ps2_filter_bilinear_ps2), + activity.getString(R.string.retro_ps2_filter_bilinear_sprites), + ), + prefs.getInt("wn.ps2.filter", 2).coerceIn(0, 3), + ) { next -> + prefs.edit().putInt("wn.ps2.filter", next).apply() + gsSetAsync("filter", "int", next.toString()) + menu.rebuild() + }, + ) + add( + RetroMenuEntry.Toggle(activity.getString(R.string.retro_ps2_mipmapping), checked = prefs.getBoolean("wn.ps2.mipmap", true)) { value -> + prefs.edit().putBoolean("wn.ps2.mipmap", value).apply() + gsSetAsync("hw_mipmap", "bool", value.toString()) + menu.rebuild() + }, + ) + add( + RetroMenuEntry.Choice( + activity.getString(R.string.retro_ps2_blending_accuracy), + listOf( + activity.getString(R.string.retro_ps2_blend_minimum), + activity.getString(R.string.retro_ps2_blend_basic), + activity.getString(R.string.retro_ps2_blend_medium), + activity.getString(R.string.retro_ps2_blend_high), + activity.getString(R.string.retro_ps2_blend_full), + activity.getString(R.string.retro_ps2_blend_maximum), + ), + prefs.getInt("wn.ps2.blend", 1).coerceIn(0, 5), + ) { next -> + prefs.edit().putInt("wn.ps2.blend", next).apply() + gsSetAsync("accurate_blending_unit", "int", next.toString()) + menu.rebuild() + }, + ) + add( + RetroMenuEntry.Toggle(activity.getString(R.string.retro_ps2_anti_blur), checked = prefs.getBoolean("wn.ps2.antiblur", true)) { value -> + prefs.edit().putBoolean("wn.ps2.antiblur", value).apply() + gsSetAsync("pcrtc_antiblur", "bool", value.toString()) + menu.rebuild() + }, + ) + add( + RetroMenuEntry.Choice( + activity.getString(R.string.retro_ps2_crt_tv_shader), + listOf( + activity.getString(R.string.retro_ps2_shader_off), + activity.getString(R.string.retro_ps2_shader_scanline), + activity.getString(R.string.retro_ps2_shader_diagonal), + activity.getString(R.string.retro_ps2_shader_triangular), + activity.getString(R.string.retro_ps2_shader_wave), + activity.getString(R.string.retro_ps2_shader_lottes), + activity.getString(R.string.retro_ps2_shader_4xrgss), + activity.getString(R.string.retro_ps2_shader_nxagss), + ), + prefs.getInt("wn.ps2.tvshader", 0).coerceIn(0, 7), + ) { next -> + prefs.edit().putInt("wn.ps2.tvshader", next).apply() + bg { NativeApp.renderTvShader(next) } + menu.rebuild() + }, + ) + add( + RetroMenuEntry.Choice( + activity.getString(R.string.retro_ps2_frame_skip), + listOf( + activity.getString(R.string.retro_ps2_frameskip_off), + activity.getString(R.string.retro_ps2_frameskip_1), + activity.getString(R.string.retro_ps2_frameskip_2), + activity.getString(R.string.retro_ps2_frameskip_3), + ), + prefs.getInt("wn.ps2.frameskip", 0).coerceIn(0, 3), + ) { next -> + prefs.edit().putInt("wn.ps2.frameskip", next).apply() + bg { NativeApp.setFrameSkip(next) } + menu.rebuild() + }, + ) + add( + RetroMenuEntry.Toggle(activity.getString(R.string.retro_ps2_widescreen_patches), checked = prefs.getBoolean("wn.ps2.widescreen", false)) { value -> + prefs.edit().putBoolean("wn.ps2.widescreen", value).apply() + bg { + NativeApp.setSetting("EmuCore", "EnableWideScreenPatches", "bool", value.toString()) + NativeApp.commitSettings() + NativeApp.reloadPatches() + } + menu.rebuild() + }, + ) + add( + RetroMenuEntry.Toggle(activity.getString(R.string.retro_ps2_no_interlace_patches), checked = prefs.getBoolean("wn.ps2.nointerlace", false)) { value -> + prefs.edit().putBoolean("wn.ps2.nointerlace", value).apply() + bg { + NativeApp.setSetting("EmuCore", "EnableNoInterlacingPatches", "bool", value.toString()) + NativeApp.commitSettings() + NativeApp.reloadPatches() + } + menu.rebuild() + }, + ) + } + + fun soundEntries(): List = + buildList { + val muted = prefs.getBoolean("wn.ps2.muted", false) + val volume = prefs.getInt("wn.ps2.volume", 100) + val swap = prefs.getBoolean("wn.ps2.swap", false) + add( + RetroMenuEntry.Slider( + label = activity.getString(R.string.retro_ps2_volume), + valueText = activity.getString(R.string.retro_ps2_volume_percent, volume), + value = volume.toFloat(), + min = 0f, + max = 200f, + step = 5f, + ) { value -> + val v = value.toInt() + prefs.edit().putInt("wn.ps2.volume", v).apply() + bg { NativeApp.setAudioVolume(v) } + menu.rebuild() + }, + ) + add( + RetroMenuEntry.Toggle(activity.getString(R.string.retro_ps2_mute), checked = muted) { value -> + prefs.edit().putBoolean("wn.ps2.muted", value).apply() + bg { NativeApp.setAudioMuted(value) } + menu.rebuild() + }, + ) + add( + RetroMenuEntry.Toggle(activity.getString(R.string.retro_ps2_time_stretch), checked = prefs.getBoolean("wn.ps2.timestretch", true)) { value -> + prefs.edit().putBoolean("wn.ps2.timestretch", value).apply() + spu2Set("SyncMode", "string", if (value) "TimeStretch" else "Disabled") + menu.rebuild() + }, + ) + add( + RetroMenuEntry.Toggle(activity.getString(R.string.retro_ps2_swap_stereo_channels), checked = swap) { value -> + prefs.edit().putBoolean("wn.ps2.swap", value).apply() + bg { NativeApp.setAudioSwapChannels(value) } + menu.rebuild() + }, + ) + } + + fun performanceEntries(): List = + buildList { + val rateValues = listOf(-3, -2, -1, 0, 1, 2, 3) + val rateLabels = listOf( + activity.getString(R.string.retro_ps2_rate_50), + activity.getString(R.string.retro_ps2_rate_60), + activity.getString(R.string.retro_ps2_rate_75), + activity.getString(R.string.retro_ps2_rate_100_default), + activity.getString(R.string.retro_ps2_rate_130), + activity.getString(R.string.retro_ps2_rate_180), + activity.getString(R.string.retro_ps2_rate_300), + ) + val curRate = prefs.getInt("wn.ps2.eeRate", 0).coerceIn(-3, 3) + add( + RetroMenuEntry.Choice(activity.getString(R.string.retro_ps2_ee_cycle_rate), rateLabels, rateValues.indexOf(curRate).coerceAtLeast(0)) { next -> + prefs.edit().putInt("wn.ps2.eeRate", rateValues[next]).apply() + bg { NativeApp.speedhackEecyclerate(rateValues[next]) } + spSet("EECycleRate", "int", rateValues[next].toString()) + menu.rebuild() + }, + ) + val skipLabels = listOf( + activity.getString(R.string.retro_ps2_skip_off), + activity.getString(R.string.retro_ps2_skip_1), + activity.getString(R.string.retro_ps2_skip_2), + activity.getString(R.string.retro_ps2_skip_3), + ) + add( + RetroMenuEntry.Choice(activity.getString(R.string.retro_ps2_ee_cycle_skip), skipLabels, prefs.getInt("wn.ps2.eeSkip", 0).coerceIn(0, 3)) { next -> + prefs.edit().putInt("wn.ps2.eeSkip", next).apply() + bg { NativeApp.speedhackEecycleskip(next) } + spSet("EECycleSkip", "int", next.toString()) + menu.rebuild() + }, + ) + add( + RetroMenuEntry.Toggle(activity.getString(R.string.retro_ps2_instant_vu1), checked = prefs.getBoolean("wn.ps2.instantVu1", true)) { value -> + prefs.edit().putBoolean("wn.ps2.instantVu1", value).apply() + bg { NativeApp.setInstantVU1(value) } + menu.rebuild() + }, + ) + add( + RetroMenuEntry.Toggle(activity.getString(R.string.retro_ps2_vu_flag_hack), checked = prefs.getBoolean("wn.ps2.vuFlagHack", true)) { value -> + prefs.edit().putBoolean("wn.ps2.vuFlagHack", value).apply() + spSet("vuFlagHack", "bool", value.toString()) + menu.rebuild() + }, + ) + add( + RetroMenuEntry.Toggle(activity.getString(R.string.retro_ps2_intc_spin), checked = prefs.getBoolean("wn.ps2.intc", true)) { value -> + prefs.edit().putBoolean("wn.ps2.intc", value).apply() + spSet("IntcStat", "bool", value.toString()) + menu.rebuild() + }, + ) + add( + RetroMenuEntry.Toggle(activity.getString(R.string.retro_ps2_wait_loop), checked = prefs.getBoolean("wn.ps2.waitloop", true)) { value -> + prefs.edit().putBoolean("wn.ps2.waitloop", value).apply() + spSet("WaitLoop", "bool", value.toString()) + menu.rebuild() + }, + ) + add( + RetroMenuEntry.Toggle(activity.getString(R.string.retro_ps2_fast_cdvd), checked = prefs.getBoolean("wn.ps2.fastCdvd", false)) { value -> + prefs.edit().putBoolean("wn.ps2.fastCdvd", value).apply() + spSet("fastCDVD", "bool", value.toString()) + menu.rebuild() + }, + ) + } + + fun hudEntries(): List = + RetroHudSupport.buildHudEntries( + context = activity, + hudVisible = hudVisible, + style = hudStyle, + elements = hudElements, + onMaster = { setHudVisible(it) }, + onStyle = { next -> + hudStyle = next + RetroHudSupport.savePs2HudStyle(activity, next) + applyHudToRating() + }, + onElements = { next -> + hudElements = next + RetroHudSupport.savePs2Elements(activity, next) + applyHudToRating() + }, + onRebuild = { menu.rebuild() }, + ) + + menu.tabs = RetroDrawerTabs.build(activity, includePerformance = true) + menu.entriesProvider = { pane -> + when (pane) { + null -> mainEntries() + RetroPane.DISPLAY -> displayEntries() + RetroPane.PERFORMANCE -> performanceEntries() + RetroPane.SOUND -> soundEntries() + RetroPane.SAVES -> saveSlotEntries() + RetroPane.MEMCARDS -> memcardEntries() + RetroPane.CONTROLS -> controlsEntries() + RetroPane.HUD -> hudEntries() + RetroPane.NETWORK -> emptyList() + RetroPane.SYSTEM -> emptyList() + } + } + menu.bottomProvider = { + listOf( + if (wnPaused) { + RetroMenuEntry.Action(activity.getString(R.string.retro_ps2_resume), RetroDrawerIcons.Resume, active = true) { + wnPaused = false + MainActivityRuntime.resume() + menu.close() + } + } else { + RetroMenuEntry.Action(activity.getString(R.string.retro_ps2_pause), RetroDrawerIcons.Pause) { + wnPaused = true + menu.rebuild() + } + }, + RetroMenuEntry.Action(activity.getString(R.string.retro_ps2_exit), RetroDrawerIcons.Exit, danger = true) { + menu.close() + runCatching { NativeApp.shutdown() } + activity.finish() + }, + ) + } + + val listener = + object : RetroInputView.Listener { + override fun onButton(keyCode: Int, down: Boolean) { + if (!nativeUp()) return + NativeApp.setPadButton(mapFace(keyCode), if (down) FULL else 0, down) + } + + override fun onDpad(x: Float, y: Float) { + if (!nativeUp()) return + NativeApp.setPadButton(KeyEvent.KEYCODE_DPAD_LEFT, if (x < -0.3f) FULL else 0, x < -0.3f) + NativeApp.setPadButton(KeyEvent.KEYCODE_DPAD_RIGHT, if (x > 0.3f) FULL else 0, x > 0.3f) + NativeApp.setPadButton(KeyEvent.KEYCODE_DPAD_UP, if (y < -0.3f) FULL else 0, y < -0.3f) + NativeApp.setPadButton(KeyEvent.KEYCODE_DPAD_DOWN, if (y > 0.3f) FULL else 0, y > 0.3f) + } + + override fun onStick(x: Float, y: Float) { + if (!nativeUp()) return + emitAxis(111, 113, x) + emitAxis(112, 110, y) + } + + override fun onRightStick(x: Float, y: Float) { + if (!nativeUp()) return + emitAxis(121, 123, x) + emitAxis(122, 120, y) + } + + override fun onMenu() { + if (!nativeUp()) return + activity.runOnUiThread { + pad?.releaseAll() + menu.rebuild() + menu.open() + } + } + } + + WinNativeHost.openMenu = { + activity.runOnUiThread { + if (activity.isFinishing || activity.isDestroyed) return@runOnUiThread + if (!nativeUp()) return@runOnUiThread + if (menu.visible) { + if (!menuToggleGate.allow()) return@runOnUiThread + menu.close() + } else { + pad?.releaseAll() + menu.rebuild() + menu.open() + } + } + } + WinNativeHost.isMenuOpen = { menu.visible && ps2Screen.value == null } + WinNativeHost.menuKeyHandler = handler@{ event -> + if (!menu.visible || ps2Screen.value != null) return@handler false + if (event.keyCode == KeyEvent.KEYCODE_BACK) return@handler false + menu.handleKey(event.keyCode, event.action) + } + WinNativeHost.menuAxisHandler = { x, y -> + if (!menu.visible || ps2Screen.value != null) false + else menu.handleAxis(x, y) + } + + if (hudVisible) { + activity.window.decorView.post { + if (!activity.isFinishing && !activity.isDestroyed && hudVisible) showHud() + } + } + + bg { + Ps2RaBridge.pushSharedLogin(activity) + NativeApp.setAchievementsOption("notifications", false) + NativeApp.setAchievementsOption("leaderboardNotifications", false) + NativeApp.setSetting("Achievements", "Notifications", "bool", "false") + NativeApp.setSetting("Achievements", "LeaderboardNotifications", "bool", "false") + NativeApp.commitSettings() + } + + val achievementPollHandler = android.os.Handler(android.os.Looper.getMainLooper()) + var knownUnlocked = emptySet() + var achievementsSeeded = false + val achievementPoll = + object : Runnable { + override fun run() { + if (activity.isFinishing || activity.isDestroyed) return + if (!nativeUp()) { + achievementPollHandler.postDelayed(this, 1500L) + return + } + if (ps2Screen.value == null) { + runCatching { + val json = NativeApp.getAchievementsJSON() ?: return@runCatching + val items = com.armsx2.ui.achievements.parseAchievementItems(json) + val unlocked = items.filter { it.unlocked }.map { it.id }.toSet() + if (!achievementsSeeded) { + knownUnlocked = unlocked + achievementsSeeded = true + } else { + val newly = unlocked - knownUnlocked + if (newly.isNotEmpty()) { + knownUnlocked = unlocked + items.filter { it.id in newly }.forEach { item -> + val showPad = + touchVisible.value && + (pad?.editMode == true || (!controllerConnected.value || manualTouchOverride.value)) + RetroAchievementOverlayState.syncPlacement(showPad, controllerConnected.value) + RetroAchievementOverlayState.show(item.title, item.points, item.description) + } + } + } + } + } + achievementPollHandler.postDelayed(this, 1500L) + } + } + achievementPollHandler.postDelayed(achievementPoll, 3000L) + + val overlayView = + ComposeView(activity).apply { + elevation = 2000f + setContent { + WinNativeTheme { + androidx.compose.foundation.layout.Box( + modifier = Modifier.fillMaxSize(), + ) { + val memImport = androidx.activity.compose.rememberLauncherForActivityResult( + androidx.activity.result.contract.ActivityResultContracts.OpenDocument(), + ) { uri -> + if (uri != null) { + Thread { + runCatching { + val name = queryName(activity, uri) ?: "Imported.ps2" + val fileName = if (name.endsWith(".ps2", true)) name else "$name.ps2" + val target = uniqueMemcard(memcardDir(activity), fileName) + activity.contentResolver.openInputStream(uri)?.use { input -> target.outputStream().use(input::copyTo) } + } + activity.runOnUiThread { menu.rebuild() } + }.start() + } + } + androidx.compose.runtime.LaunchedEffect(Unit) { + launchMemcardImport = { memImport.launch(arrayOf("*/*")) } + } + val menuVisible = menu.visible + androidx.compose.runtime.LaunchedEffect(menuVisible) { + if (!menuVisible && !wnPaused && ps2Screen.value == null) { + MainActivityRuntime.resume() + } + } + val screen by ps2Screen + BackHandler(enabled = screen == null) { + when { + pad?.editMode == true -> pad?.finishEdit() + menu.visible -> menu.handleKey(KeyEvent.KEYCODE_BACK, KeyEvent.ACTION_UP) + else -> { + pad?.releaseAll() + menu.rebuild() + menu.open() + } + } + } + if (screen != null) { + val dismiss = { + ps2Screen.value = null + wnPaused = false + MainActivityRuntime.resume() + } + BackHandler(enabled = true) { dismiss() } + when (screen) { + "cheats" -> Ps2CheatsScreen(activity, dismiss) + "achievements" -> + Ps2AchievementsScreen( + activity, + romPath = launchRomPath, + launchGameName = launchGameName, + onBack = dismiss, + ) + } + return@WinNativeTheme + } + val covered = WindowImpl.frontendCovers + val showPad = touchVisible.value && (pad?.editMode == true || (!controllerConnected.value || manualTouchOverride.value)) + if (!covered && showPad) { + AndroidView( + modifier = Modifier.fillMaxSize(), + factory = { ctx -> + RetroInputView(ctx, listener, RetroSystems.PS2).also { view -> + view.loadStickInversion() + view.adaptiveSticks = ps2Prefs(ctx).getBoolean("wn.ps2.adaptivesticks", false) + view.showL3R3 = ps2Prefs(ctx).getBoolean("wn.ps2.showl3r3", true) + view.hapticStrength = + androidx.preference.PreferenceManager + .getDefaultSharedPreferences(ctx) + .getFloat("retro_haptic_strength", 0.4f) + view.setCustomColors(customColors) + view.addOnLayoutChangeListener { v, _, _, _, _, _, _, _, _ -> + val w = v.width.toFloat() + val h = v.height.toFloat() + if (w > 0f && h > 0f) { + val aspect = 4f / 3f + val gw = (h * aspect).coerceAtMost(w) + val gh = gw / aspect + val left = (w - gw) * 0.5f + val top = (h - gh) * 0.5f + view.setGameArea(android.graphics.RectF(left, top, left + gw, top + gh)) + } + } + pad = view + } + }, + ) + } + if (!covered) { + val showPadForHud = touchVisible.value && (pad?.editMode == true || (!controllerConnected.value || manualTouchOverride.value)) + RetroAchievementOverlayState.syncPlacement(showPadForHud, controllerConnected.value) + RetroAchievementOverlayBanner() + RetroDrawerMenu(menu) + } + } + } + } + } + activity.addContentView( + overlayView, + ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT), + ) + + val aspectPinHandler = android.os.Handler(android.os.Looper.getMainLooper()) + var aspectPinTicks = 0 + val aspectPin = + object : Runnable { + override fun run() { + if (activity.isFinishing || activity.isDestroyed) return + applyDisplayAspect(activity, live = true) + aspectPinTicks++ + if (aspectPinTicks < 20) { + aspectPinHandler.postDelayed(this, 100L) + } + } + } + aspectPinHandler.post(aspectPin) + + val prevCallback = activity.window.callback + if (prevCallback != null) { + activity.window.callback = + object : android.view.Window.Callback by prevCallback { + override fun dispatchKeyEvent(event: KeyEvent): Boolean { + if (ps2Screen.value == null && menu.visible && + event.keyCode != KeyEvent.KEYCODE_BACK && + menu.handleKey(event.keyCode, event.action) + ) { + return true + } + return prevCallback.dispatchKeyEvent(event) + } + + override fun dispatchGenericMotionEvent(event: android.view.MotionEvent): Boolean { + if (ps2Screen.value == null && menu.visible && + event.source and android.view.InputDevice.SOURCE_JOYSTICK == android.view.InputDevice.SOURCE_JOYSTICK + ) { + val x = event.getAxisValue(android.view.MotionEvent.AXIS_HAT_X).takeIf { kotlin.math.abs(it) > 0.5f } + ?: event.getAxisValue(android.view.MotionEvent.AXIS_X) + val y = event.getAxisValue(android.view.MotionEvent.AXIS_HAT_Y).takeIf { kotlin.math.abs(it) > 0.5f } + ?: event.getAxisValue(android.view.MotionEvent.AXIS_Y) + activity.runOnUiThread { menu.handleAxis(x, y) } + return true + } + return prevCallback.dispatchGenericMotionEvent(event) + } + } + } + } +} diff --git a/app/src/main/feature/retro/Ps2IsoSerial.kt b/app/src/main/feature/retro/Ps2IsoSerial.kt new file mode 100644 index 000000000..29d64d6a0 --- /dev/null +++ b/app/src/main/feature/retro/Ps2IsoSerial.kt @@ -0,0 +1,108 @@ +package com.winlator.cmod.feature.retro + +import java.io.File +import java.io.RandomAccessFile + +object Ps2IsoSerial { + private const val LOGICAL = 2048 + + private data class Layout(val sectorSize: Int, val dataOffset: Int) + + fun serialOf(file: File): String? { + if (!file.isFile || file.length() < 17L * LOGICAL) return null + return runCatching { + RandomAccessFile(file, "r").use { raf -> + val layout = detectLayout(raf) ?: return null + val pvd = readLogical(raf, layout, 16) + val rootLba = le32(pvd, 156 + 2) + val rootSize = le32(pvd, 156 + 10) + if (rootLba <= 0 || rootSize <= 0) return null + val cnf = findFile(raf, layout, rootLba, rootSize, "SYSTEM.CNF") ?: return null + val text = readExtent(raf, layout, cnf.first, cnf.second.coerceAtMost(64 * 1024)) + .toString(Charsets.US_ASCII) + parseBoot(text) + } + }.getOrNull() + } + + private fun detectLayout(raf: RandomAccessFile): Layout? { + for (layout in listOf(Layout(2048, 0), Layout(2352, 16), Layout(2352, 24))) { + val sec = runCatching { readLogical(raf, layout, 16) }.getOrNull() ?: continue + if (sec[0].toInt() == 1 && + sec[1] == 'C'.code.toByte() && sec[2] == 'D'.code.toByte() && + sec[3] == '0'.code.toByte() && sec[4] == '0'.code.toByte() && sec[5] == '1'.code.toByte() + ) { + return layout + } + } + return null + } + + private fun readLogical(raf: RandomAccessFile, layout: Layout, lba: Int): ByteArray { + val buf = ByteArray(LOGICAL) + raf.seek(lba.toLong() * layout.sectorSize + layout.dataOffset) + raf.readFully(buf) + return buf + } + + private fun readExtent(raf: RandomAccessFile, layout: Layout, lba: Int, size: Int): ByteArray { + val out = ByteArray(size) + var done = 0 + var sector = lba + while (done < size) { + val sec = readLogical(raf, layout, sector) + val n = minOf(LOGICAL, size - done) + System.arraycopy(sec, 0, out, done, n) + done += n + sector++ + } + return out + } + + private fun findFile( + raf: RandomAccessFile, + layout: Layout, + dirLba: Int, + dirSize: Int, + target: String, + ): Pair? { + var remaining = dirSize + var sector = dirLba + while (remaining > 0) { + val sec = readLogical(raf, layout, sector) + var off = 0 + while (off < LOGICAL) { + val recLen = sec[off].toInt() and 0xFF + if (recLen == 0) break + val nameLen = sec[off + 32].toInt() and 0xFF + if (nameLen > 0 && off + 33 + nameLen <= LOGICAL) { + val rawName = String(sec, off + 33, nameLen, Charsets.US_ASCII) + val name = rawName.substringBefore(';').trim() + if (name.equals(target, ignoreCase = true)) { + return le32(sec, off + 2) to le32(sec, off + 10) + } + } + off += recLen + } + remaining -= LOGICAL + sector++ + } + return null + } + + private fun le32(b: ByteArray, off: Int): Int = + (b[off].toInt() and 0xFF) or + ((b[off + 1].toInt() and 0xFF) shl 8) or + ((b[off + 2].toInt() and 0xFF) shl 16) or + ((b[off + 3].toInt() and 0xFF) shl 24) + + private fun parseBoot(text: String): String? { + val line = text.lineSequence().firstOrNull { it.trimStart().startsWith("BOOT", ignoreCase = true) && it.contains("cdrom", ignoreCase = true) } + ?: return null + val afterColon = line.substringAfter("cdrom0:", "").trimStart('\\', '/', ' ') + val token = afterColon.substringBefore(';').substringBefore(' ').trim() + if (token.isBlank()) return null + val serial = token.replace("_", "-").replace(".", "").uppercase() + return serial.takeIf { it.length in 8..12 && it.contains('-') } + } +} diff --git a/app/src/main/feature/retro/Ps2MenuScreens.kt b/app/src/main/feature/retro/Ps2MenuScreens.kt new file mode 100644 index 000000000..dbf776d77 --- /dev/null +++ b/app/src/main/feature/retro/Ps2MenuScreens.kt @@ -0,0 +1,637 @@ +package com.winlator.cmod.feature.retro + +import android.content.Context +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.outlined.ArrowBack +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.outlined.Delete +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.armsx2.runtime.MainActivityRuntime +import com.winlator.cmod.R +import com.winlator.cmod.shared.ui.nav.LocalPaneNav +import com.winlator.cmod.shared.ui.nav.PaneNavRegistry +import com.winlator.cmod.shared.ui.nav.bindPaneNav +import com.winlator.cmod.shared.ui.nav.paneNavItem +import java.io.File +import kotlinx.coroutines.launch +import kr.co.iefriends.pcsx2.NativeApp + +internal fun memcardDir(context: Context): File = + File(MainActivityRuntime.assetCopyRoot(context), "memcards").apply { mkdirs() } + +internal fun listMemcards(context: Context): List = + memcardDir(context).listFiles().orEmpty() + .filter { it.isFile && it.extension.equals("ps2", true) } + .sortedBy { it.name.lowercase() } + +internal fun humanSize(bytes: Long): String = + when { + bytes >= 1_048_576 -> "${bytes / 1_048_576} MB" + bytes >= 1024 -> "${bytes / 1024} KB" + else -> "$bytes B" + } + +internal fun queryName(context: Context, uri: android.net.Uri): String? = + runCatching { + context.contentResolver.query(uri, arrayOf(android.provider.OpenableColumns.DISPLAY_NAME), null, null, null)?.use { + if (it.moveToFirst()) it.getString(0) else null + } + }.getOrNull() + +internal fun uniqueMemcard(dir: File, name: String): File { + dir.mkdirs() + val base = name.substringBeforeLast('.', name) + val ext = name.substringAfterLast('.', "").let { if (it.isEmpty()) "" else ".$it" } + var target = File(dir, name) + var i = 2 + while (target.exists()) target = File(dir, "$base-$i$ext").also { i++ } + return target +} + +@Composable +fun Ps2CheatsScreen( + context: Context, + onBack: () -> Unit, +) { + val scope = androidx.compose.runtime.rememberCoroutineScope() + var loading by remember { mutableStateOf(true) } + var status by remember { mutableStateOf("") } + var title by remember { mutableStateOf("") } + var serial by remember { mutableStateOf("") } + var crc by remember { mutableStateOf("") } + var entries by remember { mutableStateOf>(emptyList()) } + var selected by remember { mutableStateOf>(emptySet()) } + var patchEntries by remember { mutableStateOf>(emptyList()) } + var selectedPatches by remember { mutableStateOf>(emptySet()) } + var repoCheatNames by remember { mutableStateOf>(emptySet()) } + var repoPatchNames by remember { mutableStateOf>(emptySet()) } + var dnasEntries by remember { mutableStateOf>(emptyList()) } + var dnasGlobalOn by remember { mutableStateOf(true) } + var dnasDisabled by remember { mutableStateOf>(emptySet()) } + + androidx.compose.runtime.LaunchedEffect(Unit) { + data class LocalCheats( + val s: String, + val c: String?, + val stagedC: List, + val stagedP: List, + val dnas: List, + val globalOn: Boolean, + val disabled: Set, + ) + val local = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { + val s = runCatching { NativeApp.getGameSerial() }.getOrNull()?.takeIf { it.isNotBlank() } + val c = runCatching { NativeApp.getGameCRC() }.getOrNull()?.takeIf { it.length == 8 } + if (s == null) null + else { + val stagedC = Ps2CheatStaging.read(context, s, false) + val stagedP = Ps2CheatStaging.read(context, s, true) + val dnas = Ps2DnasBypass.bypassEntries(context, s).filter { it.auto } + val globalOn = context.getSharedPreferences("ARMSX2", Context.MODE_PRIVATE).getBoolean(Ps2DnasBypass.PREF, true) + val disabled = Ps2DnasBypass.ensureSingleDnasEnabled(context, s, dnas.map { it.name }.toSet()) + LocalCheats(s, c, stagedC, stagedP, dnas, globalOn, disabled) + } + } + if (local == null) { + status = context.getString(R.string.retro_scr_no_game_serial) + loading = false + } else { + serial = local.s + crc = local.c.orEmpty() + title = local.s + entries = local.stagedC + patchEntries = local.stagedP + selected = local.stagedC.map { it.name }.toSet() + selectedPatches = local.stagedP.map { it.name }.toSet() + dnasEntries = local.dnas + dnasGlobalOn = local.globalOn + dnasDisabled = local.disabled + loading = false + val remote = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { + runCatching { + if (local.c != null) com.armsx2.PatchRepo.fetchForGame(local.s, local.c) + else com.armsx2.PatchRepo.fetchForSerial(local.s) + }.getOrNull() + } + if (remote != null) { + title = remote.gametitle.takeIf { it.isNotBlank() } ?: local.s + status = remote.error.orEmpty() + val repoCheats = remote.entries.filter { it.source != "patches" } + val repoPatches = remote.entries.filter { it.source == "patches" } + repoCheatNames = repoCheats.map { it.name }.toSet() + repoPatchNames = repoPatches.map { it.name }.toSet() + entries = repoCheats + local.stagedC.filter { st -> repoCheats.none { it.name == st.name } } + patchEntries = repoPatches + local.stagedP.filter { st -> repoPatches.none { it.name == st.name } } + } + } + } + + fun persist() { + if (serial.isBlank()) return + Ps2CheatStaging.write(context, serial, false, serial, entries.filter { it.name in selected }) + Ps2CheatStaging.write(context, serial, true, serial, patchEntries.filter { it.name in selectedPatches }) + } + + fun apply() { + persist() + val s = serial + val c = crc + scope.launch { + val ok = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { + runCatching { Ps2CheatStaging.applyAll(context, s, c); true }.getOrDefault(false) + } + status = if (ok) { + context.getString(R.string.retro_scr_applied_both, selected.size, selectedPatches.size + dnasEntries.count { dnasGlobalOn && it.name !in dnasDisabled }) + } else { + context.getString(R.string.retro_scr_couldnt_apply_cheats) + } + } + } + + fun toggleDnas(name: String, currentlyOn: Boolean) { + if (serial.isBlank()) return + if (currentlyOn) { + dnasDisabled = dnasDisabled + name + } else { + if (!dnasGlobalOn) { Ps2DnasBypass.setEnabled(context, true); dnasGlobalOn = true } + val all = dnasEntries.map { it.name }.toSet() + dnasDisabled = all - name + } + Ps2DnasBypass.setDisabledNames(context, serial, dnasDisabled) + } + + var showAdd by remember { mutableStateOf(false) } + var newName by remember { mutableStateOf("") } + var newCodes by remember { mutableStateOf("") } + var newIsPatch by remember { mutableStateOf(false) } + + val importLauncher = androidx.activity.compose.rememberLauncherForActivityResult( + androidx.activity.result.contract.ActivityResultContracts.OpenDocument(), + ) { uri -> + if (uri != null) { + scope.launch { + val text = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { + runCatching { context.contentResolver.openInputStream(uri)?.bufferedReader()?.use { it.readText() } }.getOrNull() + } + val imported = if (text != null) parsePnachFile(text, if (newIsPatch) "patches" else "custom") else emptyList() + if (imported.isNotEmpty()) { + if (newIsPatch) { + patchEntries = patchEntries.filterNot { e -> imported.any { it.name == e.name } } + imported + selectedPatches = selectedPatches + imported.map { it.name } + } else { + entries = entries.filterNot { e -> imported.any { it.name == e.name } } + imported + selected = selected + imported.map { it.name } + } + persist() + status = "" + showAdd = false + } else { + status = context.getString(R.string.retro_scr_cheat_invalid) + } + } + } + } + + Ps2WindowedScaffold(title = stringResource(R.string.retro_scr_cheats), onBack = onBack, header = { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + val openAdd = { newName = ""; newCodes = ""; newIsPatch = false; showAdd = true } + OutlinedButton( + onClick = openAdd, + modifier = Modifier.paneNavItem(onActivate = openAdd), + contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 12.dp), + ) { + Icon(Icons.Filled.Add, contentDescription = null, modifier = Modifier.width(18.dp).height(18.dp)) + Spacer(Modifier.width(6.dp)) + Text(stringResource(R.string.retro_scr_add)) + } + if (!loading && (entries.isNotEmpty() || patchEntries.isNotEmpty() || serial.isNotBlank())) { + OutlinedButton(onClick = { apply() }, modifier = Modifier.paneNavItem(onActivate = { apply() })) { + Text(stringResource(R.string.retro_scr_apply)) + } + } + } + }) { + when { + loading -> Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + androidx.compose.material3.CircularProgressIndicator() + } + entries.isEmpty() && patchEntries.isEmpty() && dnasEntries.isEmpty() -> Box(Modifier.fillMaxSize().padding(24.dp), contentAlignment = Alignment.Center) { + Text(status.ifBlank { stringResource(R.string.retro_scr_no_cheats_or_patches) }, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + else -> Column(Modifier.fillMaxSize()) { + if (status.isNotBlank()) { + Text(status, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.primary, modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp)) + } + LazyColumn( + Modifier.fillMaxSize().padding(horizontal = 16.dp, vertical = 4.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + if (dnasEntries.isNotEmpty()) { + item(key = "hdr_dnas") { Ps2SectionHeader(stringResource(R.string.retro_gs_dnas_group)) } + items(dnasEntries, key = { "dnas_" + it.name }) { e -> + val on = dnasGlobalOn && e.name !in dnasDisabled + Ps2CheatRow( + com.armsx2.PatchRepo.Entry(e.name, stringResource(R.string.retro_gs_dnas_entry_desc), e.body, "dnas"), + on, isPatch = true, onToggle = { toggleDnas(e.name, on) }, + ) + } + } + if (entries.isNotEmpty()) { + item(key = "hdr_cheats") { Ps2SectionHeader(stringResource(R.string.retro_scr_cheats_section)) } + items(entries, key = { "cheat_" + it.name }) { entry -> + val checked = entry.name in selected + val toggle = { + selected = if (entry.name in selected) selected - entry.name else selected + entry.name + persist() + } + val isCustom = entry.name !in repoCheatNames + Ps2CheatRow( + entry, checked, isPatch = false, onToggle = toggle, + onDelete = if (isCustom) { + { + entries = entries.filterNot { it.name == entry.name } + selected = selected - entry.name + persist() + } + } else null, + ) + } + } + if (patchEntries.isNotEmpty()) { + item(key = "hdr_patches") { Ps2SectionHeader(stringResource(R.string.retro_scr_patches_section)) } + items(patchEntries, key = { "patch_" + it.name }) { entry -> + val checked = entry.name in selectedPatches + val toggle = { + selectedPatches = if (entry.name in selectedPatches) selectedPatches - entry.name else selectedPatches + entry.name + persist() + } + val isCustom = entry.name !in repoPatchNames + Ps2CheatRow( + entry, checked, isPatch = true, onToggle = toggle, + onDelete = if (isCustom) { + { + patchEntries = patchEntries.filterNot { it.name == entry.name } + selectedPatches = selectedPatches - entry.name + persist() + } + } else null, + ) + } + } + } + } + } + } + + if (showAdd) { + AlertDialog( + onDismissRequest = { showAdd = false }, + title = { Text(stringResource(R.string.retro_scr_add_cheat)) }, + text = { + Column { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) { + val selCheat = { newIsPatch = false } + val selPatch = { newIsPatch = true } + OutlinedButton( + onClick = selCheat, + modifier = Modifier.weight(1f).paneNavItem(onActivate = selCheat), + colors = if (!newIsPatch) + androidx.compose.material3.ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.secondaryContainer, contentColor = MaterialTheme.colorScheme.onSecondaryContainer) + else androidx.compose.material3.ButtonDefaults.outlinedButtonColors(), + ) { Text(stringResource(R.string.retro_scr_target_cheat)) } + OutlinedButton( + onClick = selPatch, + modifier = Modifier.weight(1f).paneNavItem(onActivate = selPatch), + colors = if (newIsPatch) + androidx.compose.material3.ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.secondaryContainer, contentColor = MaterialTheme.colorScheme.onSecondaryContainer) + else androidx.compose.material3.ButtonDefaults.outlinedButtonColors(), + ) { Text(stringResource(R.string.retro_scr_target_patch)) } + } + androidx.compose.foundation.layout.Spacer(Modifier.padding(4.dp)) + OutlinedTextField( + value = newName, + onValueChange = { newName = it }, + label = { Text(stringResource(R.string.retro_scr_cheat_name)) }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + androidx.compose.foundation.layout.Spacer(Modifier.padding(4.dp)) + OutlinedTextField( + value = newCodes, + onValueChange = { newCodes = it }, + label = { Text(stringResource(R.string.retro_scr_cheat_codes)) }, + placeholder = { Text("2021A268 00000000") }, + modifier = Modifier.fillMaxWidth(), + minLines = 3, + ) + androidx.compose.foundation.layout.Spacer(Modifier.padding(4.dp)) + OutlinedButton( + onClick = { importLauncher.launch(arrayOf("*/*")) }, + modifier = Modifier.fillMaxWidth().paneNavItem(onActivate = { importLauncher.launch(arrayOf("*/*")) }), + ) { Text(stringResource(R.string.retro_scr_import_from_file)) } + } + }, + confirmButton = { + TextButton(onClick = { + val entry = buildCustomPnachEntry(context, newName, newCodes, if (newIsPatch) "patches" else "custom") + if (entry != null) { + if (newIsPatch) { + patchEntries = patchEntries.filterNot { it.name == entry.name } + entry + selectedPatches = selectedPatches + entry.name + } else { + entries = entries.filterNot { it.name == entry.name } + entry + selected = selected + entry.name + } + persist() + status = "" + showAdd = false + } else { + status = context.getString(R.string.retro_scr_cheat_invalid) + } + }) { Text(stringResource(R.string.retro_scr_add)) } + }, + dismissButton = { + TextButton(onClick = { showAdd = false }) { Text(stringResource(R.string.retro_scr_cancel)) } + }, + ) + } +} + +internal fun buildCustomPnachEntry(context: Context, name: String, codes: String, source: String): com.armsx2.PatchRepo.Entry? { + val lines = + codes.lineSequence().mapNotNull { raw -> + val t = raw.trim() + when { + t.isEmpty() || t.startsWith("//") -> null + t.startsWith("patch=") -> t + else -> { + val parts = t.split(Regex("\\s+")) + if (parts.size == 2 && parts[0].length == 8 && parts[1].length == 8 && + parts[0].all { it.isDigit() || it.uppercaseChar() in 'A'..'F' } && + parts[1].all { it.isDigit() || it.uppercaseChar() in 'A'..'F' } + ) { + "patch=1,EE,${parts[0].uppercase()},extended,${parts[1].uppercase()}" + } else { + null + } + } + } + }.toList() + if (name.isBlank() || lines.isEmpty()) return null + val body = buildString { + append("[").append(name.trim()).append("]\n") + lines.forEach { append(it).append("\n") } + } + val desc = context.getString(if (source == "patches") R.string.retro_scr_custom_patch else R.string.retro_scr_custom_cheat) + return com.armsx2.PatchRepo.Entry(name.trim(), desc, body, source) +} + +internal fun parsePnachFile(text: String, source: String): List = + runCatching { + com.armsx2.PatchRepo.parseInstalled(text, if (source == "patches") "patches" else "cheats").second + .map { com.armsx2.PatchRepo.Entry(it.name, it.description, it.body, source) } + }.getOrDefault(emptyList()) + +@Composable +internal fun Ps2SectionHeader(text: String) { + Text( + text, + style = MaterialTheme.typography.labelLarge, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.padding(top = 4.dp, bottom = 2.dp), + ) +} + +@Composable +internal fun Ps2CheatRow( + entry: com.armsx2.PatchRepo.Entry, + checked: Boolean, + isPatch: Boolean, + onToggle: () -> Unit, + onDelete: (() -> Unit)? = null, +) { + Surface( + onClick = onToggle, + modifier = Modifier.fillMaxWidth().paneNavItem(cornerRadius = 12.dp, onActivate = onToggle), + shape = RoundedCornerShape(12.dp), + color = if (checked) MaterialTheme.colorScheme.secondaryContainer else MaterialTheme.colorScheme.surfaceVariant, + border = if (checked) null else BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant), + ) { + Row( + Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { + if (isPatch) { + Surface( + shape = RoundedCornerShape(4.dp), + color = if (checked) MaterialTheme.colorScheme.onSecondaryContainer.copy(alpha = 0.15f) else MaterialTheme.colorScheme.primary.copy(alpha = 0.15f), + ) { + Text( + stringResource(R.string.retro_scr_patch_badge), + style = MaterialTheme.typography.labelSmall, + fontWeight = FontWeight.Bold, + color = if (checked) MaterialTheme.colorScheme.onSecondaryContainer else MaterialTheme.colorScheme.primary, + modifier = Modifier.padding(horizontal = 6.dp, vertical = 1.dp), + ) + } + } + Text( + entry.name, + fontWeight = FontWeight.SemiBold, + color = if (checked) MaterialTheme.colorScheme.onSecondaryContainer else MaterialTheme.colorScheme.onSurface, + ) + } + if (entry.description.isNotBlank()) { + Text( + entry.description, + style = MaterialTheme.typography.bodySmall, + color = if (checked) MaterialTheme.colorScheme.onSecondaryContainer.copy(alpha = 0.75f) else MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + if (checked) { + Spacer(Modifier.width(12.dp)) + Icon( + Icons.Filled.Check, + contentDescription = null, + tint = if (checked) MaterialTheme.colorScheme.onSecondaryContainer else MaterialTheme.colorScheme.onSurface, + ) + } + if (onDelete != null) { + Spacer(Modifier.width(4.dp)) + IconButton(onClick = onDelete, modifier = Modifier.paneNavItem(onActivate = onDelete)) { + Icon( + Icons.Outlined.Delete, + contentDescription = stringResource(R.string.retro_scr_delete), + tint = if (checked) MaterialTheme.colorScheme.onSecondaryContainer else MaterialTheme.colorScheme.error, + ) + } + } + } + } +} + +@Composable +fun Ps2AchievementsScreen( + context: Context, + romPath: String, + launchGameName: String, + onBack: () -> Unit, +) { + val gameName = + remember(romPath, launchGameName) { + launchGameName.takeIf { it.isNotBlank() } + ?: romPath.takeIf { it.isNotBlank() }?.let { java.io.File(it).nameWithoutExtension } + ?: context.getString(R.string.retro_ps2_tab_menu) + } + RetroAchievementsScreen( + systemId = RetroSystems.PS2.id, + gameName = gameName, + romPath = romPath, + inSession = true, + onClose = onBack, + useNativePs2 = true, + floatingOverGame = true, + ) +} + +@Composable +fun Ps2WindowedScaffold( + title: String, + onBack: () -> Unit, + header: @Composable (() -> Unit)? = null, + content: @Composable () -> Unit, +) { + val context = androidx.compose.ui.platform.LocalContext.current + val registry = remember { PaneNavRegistry() } + androidx.compose.runtime.DisposableEffect(Unit) { + val activity = context as? android.app.Activity + val restore = activity?.window?.bindPaneNav(registry, onDismiss = onBack) + onDispose { restore?.invoke() } + } + androidx.compose.runtime.CompositionLocalProvider(LocalPaneNav provides registry) { + Box( + Modifier + .fillMaxSize() + .background(androidx.compose.ui.graphics.Color.Transparent) + .clickable( + interactionSource = remember { MutableInteractionSource() }, + indication = null, + onClick = onBack, + ), + contentAlignment = Alignment.Center, + ) { + Surface( + modifier = Modifier + .padding(24.dp) + .widthIn(max = 560.dp) + .fillMaxWidth() + .fillMaxHeight(0.8f) + .clickable( + interactionSource = remember { MutableInteractionSource() }, + indication = null, + onClick = {}, + ), + shape = RoundedCornerShape(20.dp), + color = MaterialTheme.colorScheme.surface, + tonalElevation = 3.dp, + shadowElevation = 8.dp, + border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant), + ) { + Column(Modifier.fillMaxSize()) { + Row( + Modifier.fillMaxWidth().height(56.dp).padding(start = 8.dp, end = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + IconButton(onClick = onBack, modifier = Modifier.paneNavItem(onActivate = onBack)) { + Icon(Icons.AutoMirrored.Outlined.ArrowBack, contentDescription = stringResource(R.string.retro_scr_back), tint = MaterialTheme.colorScheme.onSurface) + } + Text(title, style = MaterialTheme.typography.titleLarge, color = MaterialTheme.colorScheme.onSurface, modifier = Modifier.padding(start = 4.dp)) + Spacer(Modifier.weight(1f)) + header?.invoke() + } + Box(Modifier.fillMaxSize()) { content() } + } + } + } + } +} + +@Composable +fun Ps2OverlayScaffold( + title: String, + onBack: () -> Unit, + action: @Composable (() -> Unit)? = null, + content: @Composable () -> Unit, +) { + val context = androidx.compose.ui.platform.LocalContext.current + val registry = remember { PaneNavRegistry() } + androidx.compose.runtime.DisposableEffect(Unit) { + val activity = context as? android.app.Activity + val restore = activity?.window?.bindPaneNav(registry, onDismiss = onBack) + onDispose { restore?.invoke() } + } + androidx.compose.runtime.CompositionLocalProvider(LocalPaneNav provides registry) { + Column( + Modifier + .fillMaxSize() + .background(MaterialTheme.colorScheme.surface), + ) { + Row( + Modifier.fillMaxWidth().height(56.dp).padding(horizontal = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + IconButton(onClick = onBack, modifier = Modifier.paneNavItem(onActivate = onBack)) { + Icon(Icons.AutoMirrored.Outlined.ArrowBack, contentDescription = stringResource(R.string.retro_scr_back), tint = MaterialTheme.colorScheme.onSurface) + } + Text(title, style = MaterialTheme.typography.titleLarge, color = MaterialTheme.colorScheme.onSurface, modifier = Modifier.padding(start = 4.dp)) + Spacer(Modifier.width(0.dp).weight(1f)) + action?.invoke() + } + Box(Modifier.fillMaxSize()) { content() } + } + } +} diff --git a/app/src/main/feature/retro/Ps2RaBridge.kt b/app/src/main/feature/retro/Ps2RaBridge.kt new file mode 100644 index 000000000..14448615c --- /dev/null +++ b/app/src/main/feature/retro/Ps2RaBridge.kt @@ -0,0 +1,28 @@ +package com.winlator.cmod.feature.retro + +import android.content.Context +import kr.co.iefriends.pcsx2.NativeApp + +object Ps2RaBridge { + private const val EMUCORE_HARDCORE_REGISTERED = false + + fun pushSharedLogin(context: Context): Boolean { + if (!RetroAchievementsManager.isLoggedIn(context)) return false + val ra = context.getSharedPreferences("retro_achievements", Context.MODE_PRIVATE) + val user = ra.getString("username", null)?.takeIf { it.isNotBlank() } ?: return false + val token = ra.getString("token", null)?.takeIf { it.isNotBlank() } ?: return false + val hardcore = + EMUCORE_HARDCORE_REGISTERED && RetroAchievementsManager.isHardcorePreferred(context) + return runCatching { + NativeApp.setSetting("Achievements", "Enabled", "bool", "true") + NativeApp.setSetting("Achievements", "Username", "string", user) + NativeApp.setSetting("Achievements", "Token", "string", token) + NativeApp.setSetting("Achievements", "ChallengeMode", "bool", hardcore.toString()) + NativeApp.setSetting("Achievements", "HardcoreMode", "bool", hardcore.toString()) + NativeApp.commitSettings() + runCatching { NativeApp.setHardcoreMode(hardcore) } + NativeApp.clearAchievementsHostOverride() + true + }.getOrDefault(false) + } +} diff --git a/app/src/main/feature/retro/RetroAchievementOverlay.kt b/app/src/main/feature/retro/RetroAchievementOverlay.kt new file mode 100644 index 000000000..267b094c2 --- /dev/null +++ b/app/src/main/feature/retro/RetroAchievementOverlay.kt @@ -0,0 +1,200 @@ +package com.winlator.cmod.feature.retro + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.slideInVertically +import androidx.compose.animation.slideOutVertically +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.BoxScope +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.compose.ui.zIndex +import kotlinx.coroutines.delay + +object RetroAchievementOverlayState { + data class Banner( + val title: String, + val points: Int, + val description: String = "", + ) + + var banner by mutableStateOf(null) + private set + var sessionMessage by mutableStateOf(null) + private set + var useDisplayArea by mutableStateOf(false) + + fun syncPlacement( + touchControlsVisible: Boolean, + controllerConnected: Boolean, + ) { + useDisplayArea = touchControlsVisible && !controllerConnected + } + + fun show( + title: String, + points: Int, + description: String = "", + ) { + if (title.contains("Unknown Emulator", ignoreCase = true)) return + banner = Banner(title, points, description) + } + + fun showMessage(message: String) { + val trimmed = message.trim() + if (trimmed.isEmpty()) return + sessionMessage = trimmed + } + + fun clear() { + banner = null + } + + fun clearMessage() { + sessionMessage = null + } +} + +object RetroPs2OsdPlacement { + const val TOP_LEFT = 1 + const val TOP_CENTER = 2 + + fun messagePos(touchControlsVisible: Boolean, controllerConnected: Boolean): Int = + if (touchControlsVisible && !controllerConnected) TOP_CENTER else TOP_LEFT + + fun apply( + touchControlsVisible: Boolean, + controllerConnected: Boolean, + ) { + val pos = messagePos(touchControlsVisible, controllerConnected) + runCatching { + kr.co.iefriends.pcsx2.NativeApp.setSetting("EmuCore/GS", "OsdMessagesPos", "int", pos.toString()) + kr.co.iefriends.pcsx2.NativeApp.commitSettings() + kr.co.iefriends.pcsx2.NativeApp.applyGSSettingsLive() + } + } +} + +@Composable +fun BoxScope.RetroAchievementOverlayBanner() { + val banner = RetroAchievementOverlayState.banner + val message = RetroAchievementOverlayState.sessionMessage + val displayArea = RetroAchievementOverlayState.useDisplayArea + + LaunchedEffect(banner) { + if (banner != null) { + delay(4500) + if (RetroAchievementOverlayState.banner == banner) { + RetroAchievementOverlayState.clear() + } + } + } + LaunchedEffect(message) { + if (message != null) { + delay(2800) + if (RetroAchievementOverlayState.sessionMessage == message) { + RetroAchievementOverlayState.clearMessage() + } + } + } + + val align = if (displayArea) Alignment.TopCenter else Alignment.TopStart + val hPad = if (displayArea) 60.dp else 10.dp + val tPad = if (displayArea) 18.dp else 10.dp + + Column( + modifier = + Modifier + .align(align) + .zIndex(1000f) + .padding(start = hPad, end = hPad, top = tPad) + .widthIn(max = 285.dp), + horizontalAlignment = if (displayArea) Alignment.CenterHorizontally else Alignment.Start, + ) { + AnimatedVisibility( + visible = banner != null, + enter = fadeIn() + slideInVertically { -it / 2 }, + exit = fadeOut() + slideOutVertically { -it / 2 }, + ) { + val b = banner + if (b != null) { + Column( + modifier = + Modifier + .background(Color(0xF0121824), RoundedCornerShape(9.dp)) + .border(1.dp, Color(0xFF1A9FFF).copy(alpha = 0.55f), RoundedCornerShape(9.dp)) + .padding(horizontal = 10.dp, vertical = 7.dp), + ) { + Text( + "ACHIEVEMENT UNLOCKED", + color = Color(0xFF1A9FFF), + fontSize = 8.sp, + fontWeight = FontWeight.Bold, + letterSpacing = 1.sp, + ) + Text( + b.title, + color = Color(0xFFF0F4FF), + fontSize = 11.sp, + fontWeight = FontWeight.SemiBold, + modifier = Modifier.padding(top = 2.dp), + ) + if (b.description.isNotBlank()) { + Text( + b.description, + color = Color(0xFF93A6BC), + fontSize = 9.sp, + modifier = Modifier.padding(top = 2.dp), + ) + } + Text( + "+${b.points}", + color = Color(0xFF35D0BA), + fontSize = 9.sp, + fontWeight = FontWeight.Bold, + modifier = Modifier.padding(top = 3.dp), + ) + } + } + } + AnimatedVisibility( + visible = message != null, + enter = fadeIn() + slideInVertically { -it / 2 }, + exit = fadeOut() + slideOutVertically { -it / 2 }, + modifier = Modifier.padding(top = if (banner != null) 8.dp else 0.dp), + ) { + val text = message + if (text != null) { + Text( + text = text, + color = Color(0xFFF0F4FF), + fontSize = 13.sp, + fontWeight = FontWeight.Medium, + modifier = + Modifier + .fillMaxWidth() + .background(Color(0xE0121824), RoundedCornerShape(10.dp)) + .border(1.dp, Color.White.copy(alpha = 0.12f), RoundedCornerShape(10.dp)) + .padding(horizontal = 12.dp, vertical = 8.dp), + ) + } + } + } +} diff --git a/app/src/main/feature/retro/RetroAchievementsActivity.kt b/app/src/main/feature/retro/RetroAchievementsActivity.kt new file mode 100644 index 000000000..82735eff8 --- /dev/null +++ b/app/src/main/feature/retro/RetroAchievementsActivity.kt @@ -0,0 +1,718 @@ +package com.winlator.cmod.feature.retro + +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.navigationBars +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.statusBars +import androidx.compose.foundation.layout.systemBars +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Close +import androidx.compose.material.icons.outlined.EmojiEvents +import androidx.compose.material.icons.outlined.Lock +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Switch +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.compose.material3.OutlinedTextFieldDefaults +import coil.compose.AsyncImage +import com.winlator.cmod.R +import com.winlator.cmod.shared.ui.nav.bindPaneNav +import com.winlator.cmod.shared.ui.nav.paneNavItem +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +private val BgDark = Color(0xFF12121B) +private val SurfaceDark = Color(0xFF171722) +private val CardBorder = Color(0xFF2A2A3A) +private val Accent = Color(0xFF1A9FFF) +private val AccentGlow = Color(0xFF58A6FF) +private val TextPrimary = Color(0xFFF0F4FF) +private val TextSecondary = Color(0xFF93A6BC) +private val Gold = Color(0xFFF2C14E) +private val Scrim = Color(0xFF000000) +private val StatusOnline = Color(0xFF3FB950) + +class RetroAchievementsActivity : ComponentActivity() { + companion object { + const val EXTRA_SYSTEM_ID = "system_id" + const val EXTRA_GAME_NAME = "game_name" + const val EXTRA_ROM_PATH = "rom_path" + const val EXTRA_IN_SESSION = "in_session" + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + androidx.core.view.WindowCompat.setDecorFitsSystemWindows(window, false) + val controller = androidx.core.view.WindowInsetsControllerCompat(window, window.decorView) + controller.hide(androidx.core.view.WindowInsetsCompat.Type.systemBars()) + controller.systemBarsBehavior = + androidx.core.view.WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE + val systemId = intent.getStringExtra(EXTRA_SYSTEM_ID) + val gameName = intent.getStringExtra(EXTRA_GAME_NAME) ?: "Retro Game" + val romPath = intent.getStringExtra(EXTRA_ROM_PATH) ?: "" + val inSession = intent.getBooleanExtra(EXTRA_IN_SESSION, false) + setContent { + com.winlator.cmod.shared.theme.WinNativeTheme { + androidx.compose.runtime.CompositionLocalProvider( + com.winlator.cmod.shared.ui.nav.LocalPaneNav provides navRegistry, + ) { + RetroAchievementsScreen( + systemId = systemId, + gameName = gameName, + romPath = romPath, + inSession = inSession, + onClose = { finish() }, + ) + } + } + } + } + + private val navRegistry = com.winlator.cmod.shared.ui.nav.PaneNavRegistry() + private var restoreNav: (() -> Unit)? = null + + override fun onResume() { + super.onResume() + restoreNav = window.bindPaneNav(navRegistry, onDismiss = { finish() }) + } + + override fun onPause() { + restoreNav?.invoke() + restoreNav = null + super.onPause() + } +} + +@Composable +internal fun RetroAchievementsScreen( + systemId: String?, + gameName: String, + romPath: String, + inSession: Boolean, + onClose: () -> Unit, + useNativePs2: Boolean = false, + floatingOverGame: Boolean = false, + nativeJson: (() -> String)? = null, +) { + val context = LocalContext.current + val refreshScope = rememberCoroutineScope() + val nativeMode = useNativePs2 || nativeJson != null + fun nativeAchievementsJson(): String = + nativeJson?.invoke() ?: kr.co.iefriends.pcsx2.NativeApp.getAchievementsJSON().orEmpty() + var loggedIn by remember { + mutableStateOf( + RetroAchievementsManager.isLoggedIn(context) || + (useNativePs2 && + runCatching { + val raw = kr.co.iefriends.pcsx2.NativeApp.getAchievementsJSON().orEmpty() + if (raw.isBlank()) false else org.json.JSONObject(raw).optBoolean("loggedIn") + }.getOrDefault(false)), + ) + } + var enabled by remember { mutableStateOf(RetroAchievementsManager.isEnabled(context)) } + var hardcore by remember { mutableStateOf(RetroAchievementsManager.isHardcorePreferred(context)) } + var confirmHardcore by remember { mutableStateOf(false) } + var loading by remember { mutableStateOf(loggedIn) } + var summary by remember { mutableStateOf(null) } + var achievements by remember { mutableStateOf>(emptyList()) } + + fun refreshFromManager() { + refreshScope.launch { + val s = withContext(Dispatchers.IO) { RetroAchievementsManager.getSummary() } + val a = withContext(Dispatchers.IO) { RetroAchievementsManager.getAchievements() } + if (s != null) summary = s + if (a.isNotEmpty()) achievements = a + } + } + + fun refreshFromPs2Native() { + refreshScope.launch { + val pair = + withContext(Dispatchers.IO) { + runCatching { + val raw = nativeAchievementsJson() + if (raw.isBlank()) return@runCatching null + val root = org.json.JSONObject(raw) + val items = + runCatching { com.armsx2.ui.achievements.parseAchievementItems(raw) } + .getOrDefault(emptyList()) + val mapped = + items.map { a -> + RetroAchievement( + id = a.id.toLong(), + title = a.title, + description = a.description, + unlocked = a.unlocked, + points = a.points, + progress = a.progress, + badgeUrl = a.iconUrl, + badgeLockedUrl = a.iconUrl, + bucket = a.subsetId, + ) + } + val unlocked = mapped.count { it.unlocked } + val pointsUnlocked = mapped.filter { it.unlocked }.sumOf { it.points } + val pointsTotal = mapped.sumOf { it.points } + val s = + RetroGameSummary( + gameId = 0, + title = root.optString("gameTitle").ifBlank { gameName }, + badgeUrl = root.optString("gameIconUrl"), + total = mapped.size, + unlocked = unlocked, + pointsTotal = pointsTotal, + pointsUnlocked = pointsUnlocked, + ) + Triple(root.optBoolean("loggedIn"), s, mapped) + }.getOrNull() + } + if (pair != null) { + if (pair.first || RetroAchievementsManager.isLoggedIn(context)) { + loggedIn = true + } + summary = pair.second + if (pair.third.isNotEmpty()) achievements = pair.third + } else if (RetroAchievementsManager.isLoggedIn(context)) { + loggedIn = true + } + } + } + + fun refresh() { + if (nativeMode) refreshFromPs2Native() else refreshFromManager() + } + + DisposableEffect(Unit) { + if (!nativeMode) { + RetroAchievementsManager.stateListener = { refresh() } + } + onDispose { RetroAchievementsManager.stateListener = null } + } + + LaunchedEffect(Unit) { + if (useNativePs2 && RetroAchievementsManager.isLoggedIn(context)) { + loggedIn = true + if (!inSession) withContext(Dispatchers.IO) { Ps2RaBridge.pushSharedLogin(context) } + } + } + + LaunchedEffect(loggedIn) { + if (!loggedIn) { + loading = false + return@LaunchedEffect + } + if (nativeMode) { + loading = true + if (useNativePs2 && !inSession) withContext(Dispatchers.IO) { Ps2RaBridge.pushSharedLogin(context) } + var attempts = 0 + var last: List = emptyList() + while (attempts < 24) { + last = + withContext(Dispatchers.IO) { + runCatching { + val raw = nativeAchievementsJson() + com.armsx2.ui.achievements.parseAchievementItems(raw).map { a -> + RetroAchievement( + id = a.id.toLong(), + title = a.title, + description = a.description, + unlocked = a.unlocked, + points = a.points, + progress = a.progress, + badgeUrl = a.iconUrl, + badgeLockedUrl = a.iconUrl, + bucket = a.subsetId, + ) + } + }.getOrDefault(emptyList()) + } + if (last.isNotEmpty()) break + delay(400) + attempts++ + } + achievements = last + if (last.isNotEmpty()) { + val unlocked = last.count { it.unlocked } + summary = + RetroGameSummary( + gameId = 0, + title = gameName, + badgeUrl = "", + total = last.size, + unlocked = unlocked, + pointsTotal = last.sumOf { it.points }, + pointsUnlocked = last.filter { it.unlocked }.sumOf { it.points }, + ) + loading = false + return@LaunchedEffect + } + if (romPath.isNotBlank()) { + RetroAchievementsManager.loadGameForBrowsing(context, systemId, romPath) + var browseAttempts = 0 + while (RetroAchievementsManager.loadState == RetroAchievementsManager.LOAD_LOADING && + browseAttempts < 80 + ) { + delay(250) + browseAttempts++ + } + withContext(Dispatchers.IO) { RetroAchievementsManager.getSummary() } + ?.let { summary = it } + withContext(Dispatchers.IO) { RetroAchievementsManager.getAchievements() } + .takeIf { it.isNotEmpty() } + ?.let { achievements = it } + } + loading = false + return@LaunchedEffect + } + if (!inSession) { + RetroAchievementsManager.loadGameForBrowsing(context, systemId, romPath) + } + loading = RetroAchievementsManager.loadState == RetroAchievementsManager.LOAD_LOADING + var attempts = 0 + while (RetroAchievementsManager.loadState == RetroAchievementsManager.LOAD_LOADING && attempts < 80) { + delay(250) + attempts++ + } + summary = withContext(Dispatchers.IO) { RetroAchievementsManager.getSummary() } + achievements = withContext(Dispatchers.IO) { RetroAchievementsManager.getAchievements() } + loading = false + } + + if (confirmHardcore) { + RetroHardcoreConfirmDialog( + onConfirm = { + confirmHardcore = false + hardcore = true + RetroAchievementsManager.setHardcorePreferred(context, true) + }, + onDismiss = { confirmHardcore = false }, + ) + } + + BoxWithConstraints( + modifier = + Modifier + .fillMaxSize() + .then( + if (floatingOverGame) { + Modifier.background(Color.Transparent) + } else { + Modifier + .background(Scrim.copy(alpha = 0.62f)) + .windowInsetsPadding(WindowInsets.systemBars) + }, + ) + .clickable(indication = null, interactionSource = remember { MutableInteractionSource() }) { onClose() }, + contentAlignment = Alignment.Center, + ) { + val dialogWidth = (maxWidth - if (floatingOverGame) 48.dp else 32.dp).coerceAtMost(560.dp) + val dialogHeight = + if (floatingOverGame) { + maxHeight * 0.8f + } else { + (maxHeight - 40.dp).coerceIn(340.dp, 680.dp) + } + Surface( + modifier = + Modifier + .then(if (floatingOverGame) Modifier.padding(24.dp) else Modifier) + .widthIn(min = 320.dp, max = dialogWidth) + .fillMaxWidth() + .then( + if (floatingOverGame) { + Modifier.fillMaxHeight(0.8f) + } else { + Modifier.height(dialogHeight) + }, + ) + .clickable(indication = null, interactionSource = remember { MutableInteractionSource() }) {}, + shape = RoundedCornerShape(if (floatingOverGame) 20.dp else 16.dp), + color = BgDark, + border = BorderStroke(1.dp, CardBorder), + tonalElevation = if (floatingOverGame) 3.dp else 8.dp, + shadowElevation = if (floatingOverGame) 8.dp else 0.dp, + ) { + Column(Modifier.fillMaxSize()) { + Header(gameName, summary, onClose) + HorizontalDivider(color = CardBorder, thickness = 0.5.dp) + Box(Modifier.fillMaxWidth().weight(1f)) { + when { + !loggedIn -> + LoginPane { user, pass, onResult -> + RetroAchievementsManager.login(context, user, pass) { ok, msg -> + if (ok && useNativePs2) { + refreshScope.launch(Dispatchers.IO) { + runCatching { Ps2RaBridge.pushSharedLogin(context) } + } + } + onResult(ok, msg) + if (ok) loggedIn = true + } + } + loading -> + Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + CircularProgressIndicator(color = Accent, modifier = Modifier.size(32.dp)) + } + else -> + AchievementsList( + achievements = achievements, + summary = summary, + enabled = enabled, + hardcore = hardcore, + onEnabledChange = { + enabled = it + RetroAchievementsManager.setEnabled(context, it) + }, + onHardcoreChange = { + if (it) { + confirmHardcore = true + } else { + hardcore = false + RetroAchievementsManager.setHardcorePreferred(context, false) + } + }, + onLogout = { + RetroAchievementsManager.logout(context) + loggedIn = false + summary = null + achievements = emptyList() + }, + ) + } + } + } + } + } +} + +@Composable +private fun Header(gameName: String, summary: RetroGameSummary?, onClose: () -> Unit) { + Row( + modifier = Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp, top = 12.dp, bottom = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Box( + Modifier.size(38.dp).clip(RoundedCornerShape(10.dp)).background(Gold.copy(alpha = 0.16f)), + contentAlignment = Alignment.Center, + ) { + Icon(Icons.Outlined.EmojiEvents, contentDescription = null, tint = Gold, modifier = Modifier.size(22.dp)) + } + Column(Modifier.weight(1f)) { + Text( + stringResource(R.string.retro_ach_brand), + color = TextSecondary, + fontSize = 9.sp, + fontWeight = FontWeight.Bold, + letterSpacing = 1.sp, + ) + Text( + gameName, + style = MaterialTheme.typography.titleMedium, + color = TextPrimary, + fontWeight = FontWeight.Bold, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + if (summary != null && summary.total > 0) { + Surface(color = Gold.copy(alpha = 0.14f), shape = RoundedCornerShape(8.dp)) { + Text( + "${summary.unlocked} / ${summary.total}", + color = Gold, + fontSize = 12.sp, + fontWeight = FontWeight.Bold, + modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp), + ) + } + } + IconButton(onClick = onClose, modifier = Modifier.size(40.dp).paneNavItem(onActivate = onClose)) { + Icon(Icons.Outlined.Close, contentDescription = "Close", tint = TextSecondary, modifier = Modifier.size(22.dp)) + } + } +} + +@Composable +private fun LoginPane(onLogin: (String, String, (Boolean, String?) -> Unit) -> Unit) { + val context = LocalContext.current + var username by remember { mutableStateOf("") } + var password by remember { mutableStateOf("") } + var busy by remember { mutableStateOf(false) } + var error by remember { mutableStateOf(null) } + Column( + Modifier.fillMaxSize().padding(24.dp).verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(14.dp), + ) { + Text( + stringResource(R.string.retro_ach_login_intro), + color = TextSecondary, + style = MaterialTheme.typography.bodyMedium, + ) + val fieldColors = + OutlinedTextFieldDefaults.colors( + focusedTextColor = TextPrimary, + unfocusedTextColor = TextPrimary, + disabledTextColor = TextSecondary, + cursorColor = AccentGlow, + focusedBorderColor = AccentGlow, + unfocusedBorderColor = CardBorder, + focusedLabelColor = AccentGlow, + unfocusedLabelColor = TextSecondary, + focusedContainerColor = SurfaceDark, + unfocusedContainerColor = SurfaceDark, + ) + OutlinedTextField( + value = username, + onValueChange = { username = it }, + label = { Text(stringResource(R.string.retro_ach_username)) }, + singleLine = true, + colors = fieldColors, + modifier = Modifier.fillMaxWidth(), + ) + OutlinedTextField( + value = password, + onValueChange = { password = it }, + label = { Text(stringResource(R.string.retro_ach_password)) }, + singleLine = true, + visualTransformation = PasswordVisualTransformation(), + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), + colors = fieldColors, + modifier = Modifier.fillMaxWidth(), + ) + error?.let { Text(it, color = Color(0xFFE07B6B), style = MaterialTheme.typography.labelMedium) } + val submit = { + if (username.isBlank() || password.isBlank()) { + error = context.getString(R.string.retro_ach_enter_credentials) + } else { + busy = true + error = null + onLogin(username.trim(), password) { ok, msg -> + busy = false + if (!ok) error = msg ?: context.getString(R.string.retro_ach_login_failed) + } + } + } + Button( + onClick = submit, + enabled = !busy, + colors = androidx.compose.material3.ButtonDefaults.buttonColors(containerColor = Accent, contentColor = Color.White), + modifier = Modifier.fillMaxWidth().paneNavItem(isEntry = true, onActivate = { submit() }), + ) { + if (busy) { + CircularProgressIndicator(color = Color.White, modifier = Modifier.size(18.dp)) + } else { + Text(stringResource(R.string.retro_ach_sign_in)) + } + } + Text( + stringResource(R.string.retro_ach_password_disclaimer), + color = TextSecondary, + style = MaterialTheme.typography.labelSmall, + ) + } +} + +@Composable +private fun AchievementsList( + achievements: List, + summary: RetroGameSummary?, + enabled: Boolean, + hardcore: Boolean, + onEnabledChange: (Boolean) -> Unit, + onHardcoreChange: (Boolean) -> Unit, + onLogout: () -> Unit, +) { + val ordered = achievements.sortedWith( + compareByDescending { it.unlocked }.thenBy { it.title }, + ) + Column(Modifier.fillMaxSize()) { + if (summary != null && summary.total > 0) { + LinearProgressIndicator( + progress = { summary.unlocked.toFloat() / summary.total }, + color = Gold, + trackColor = SurfaceDark, + modifier = Modifier.fillMaxWidth().height(4.dp), + ) + } + Column( + Modifier.fillMaxWidth().weight(1f).verticalScroll(rememberScrollState()).padding(12.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + SettingsRow(stringResource(R.string.retro_ach_achievements_enabled), enabled, onEnabledChange) + if (RetroAchievementsManager.HARDCORE_SUPPORTED) { + SettingsRow(stringResource(R.string.retro_ach_hardcore_mode), hardcore, onHardcoreChange) + } + if (summary != null) { + Text( + stringResource(R.string.retro_ach_points, summary.pointsUnlocked, summary.pointsTotal), + color = TextSecondary, + style = MaterialTheme.typography.labelMedium, + modifier = Modifier.padding(top = 2.dp, start = 4.dp), + ) + } + if (achievements.isEmpty()) { + Text( + stringResource(R.string.retro_ach_none_found), + color = TextSecondary, + style = MaterialTheme.typography.bodyMedium, + modifier = Modifier.padding(24.dp), + ) + } else { + ordered.forEach { AchievementRow(it) } + } + Spacer(Modifier.height(8.dp)) + TextButton(onClick = onLogout, modifier = Modifier.fillMaxWidth().paneNavItem(onActivate = onLogout)) { + Text(stringResource(R.string.retro_ach_sign_out), color = TextSecondary) + } + } + } +} + +@Composable +private fun SettingsRow(label: String, checked: Boolean, onChange: (Boolean) -> Unit) { + Surface( + shape = RoundedCornerShape(12.dp), + color = SurfaceDark.copy(alpha = 0.5f), + border = BorderStroke(1.dp, CardBorder), + modifier = Modifier.fillMaxWidth().paneNavItem(cornerRadius = 12.dp, onActivate = { onChange(!checked) }), + ) { + Row( + Modifier.padding(horizontal = 14.dp, vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text(label, color = TextPrimary, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f)) + Switch( + checked = checked, + onCheckedChange = onChange, + colors = + androidx.compose.material3.SwitchDefaults.colors( + checkedThumbColor = Color.White, + checkedTrackColor = Accent, + uncheckedTrackColor = SurfaceDark, + uncheckedBorderColor = CardBorder, + ), + ) + } + } +} + +@Composable +private fun AchievementRow(ach: RetroAchievement) { + val url = if (ach.unlocked) ach.badgeUrl else ach.badgeLockedUrl.ifBlank { ach.badgeUrl } + Surface( + shape = RoundedCornerShape(12.dp), + color = if (ach.unlocked) Gold.copy(alpha = 0.07f) else SurfaceDark.copy(alpha = 0.5f), + border = BorderStroke(1.dp, if (ach.unlocked) Gold.copy(alpha = 0.25f) else CardBorder), + modifier = Modifier.fillMaxWidth(), + ) { + Row(Modifier.padding(10.dp), verticalAlignment = Alignment.CenterVertically) { + Box( + Modifier.size(52.dp).clip(RoundedCornerShape(8.dp)).background(BgDark), + contentAlignment = Alignment.Center, + ) { + if (url.isNotBlank()) { + AsyncImage( + model = url, + contentDescription = null, + contentScale = ContentScale.Crop, + modifier = Modifier.size(52.dp).clip(RoundedCornerShape(8.dp)), + alpha = if (ach.unlocked) 1f else 0.5f, + ) + } else { + Icon(Icons.Outlined.Lock, contentDescription = null, tint = TextSecondary, modifier = Modifier.size(24.dp)) + } + } + Spacer(Modifier.width(12.dp)) + Column(Modifier.weight(1f)) { + Text( + ach.title, + color = if (ach.unlocked) TextPrimary else TextSecondary, + fontWeight = FontWeight.SemiBold, + style = MaterialTheme.typography.bodyMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (ach.description.isNotBlank()) { + Text( + ach.description, + color = TextSecondary, + style = MaterialTheme.typography.labelMedium, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + if (ach.progress.isNotBlank() && !ach.unlocked) { + Text( + ach.progress, + color = AccentGlow, + style = MaterialTheme.typography.labelSmall, + modifier = Modifier.padding(top = 2.dp), + ) + } + } + Text( + "${ach.points}", + color = if (ach.unlocked) Gold else TextSecondary, + fontWeight = FontWeight.Bold, + style = MaterialTheme.typography.labelLarge, + modifier = Modifier.padding(start = 8.dp), + ) + } + } +} diff --git a/app/src/main/feature/retro/RetroAchievementsManager.kt b/app/src/main/feature/retro/RetroAchievementsManager.kt new file mode 100644 index 000000000..161e0ea45 --- /dev/null +++ b/app/src/main/feature/retro/RetroAchievementsManager.kt @@ -0,0 +1,401 @@ +package com.winlator.cmod.feature.retro + +import android.content.Context +import android.os.Handler +import android.os.Looper +import com.swordfish.libretrodroid.RetroAchievements +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.ByteArrayOutputStream +import java.net.HttpURLConnection +import java.net.URL + +data class RetroAchievement( + val id: Long, + val title: String, + val description: String, + val unlocked: Boolean, + val points: Int, + val progress: String, + val badgeUrl: String, + val badgeLockedUrl: String, + val bucket: Int, +) + +data class RetroGameSummary( + val gameId: Long, + val title: String, + val badgeUrl: String, + val total: Int, + val unlocked: Int, + val pointsTotal: Int, + val pointsUnlocked: Int, +) + +data class RetroUnlock( + val id: Long, + val title: String, + val description: String, + val points: Int, + val badgeUrl: String, +) + +object RetroAchievementsManager { + private const val PREFS_NAME = "retro_achievements" + private const val KEY_USERNAME = "username" + private const val KEY_TOKEN = "token" + private const val KEY_DISPLAY = "display_name" + private const val KEY_ENABLED = "enabled" + private const val KEY_HARDCORE = "hardcore" + + private const val CLIENT_VERSION = "1.0.0" + private const val RCHEEVOS_VERSION = "12.3.0" + + @Volatile private var userAgent = "WinNative/$CLIENT_VERSION rcheevos/$RCHEEVOS_VERSION" + + private fun coreTag(systemId: String?): String { + val core = RetroSystems.fromId(systemId)?.coreFileName ?: return "unknown" + return core.removePrefix("lib").removeSuffix(".so").removeSuffix("_libretro_android") + } + + private fun buildUserAgent(systemId: String?): String = + "WinNative/$CLIENT_VERSION (Android ${android.os.Build.VERSION.RELEASE}) ${coreTag(systemId)} rcheevos/$RCHEEVOS_VERSION" + + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + private val mainHandler = Handler(Looper.getMainLooper()) + private var pumpJob: Job? = null + + private fun postMain(block: () -> Unit) = mainHandler.post(block) + + const val LOAD_IDLE = 0 + const val LOAD_LOADING = 1 + const val LOAD_LOADED = 2 + const val LOAD_EMPTY = 3 + + @Volatile private var clientReady = false + @Volatile private var loadedRomPath: String? = null + @Volatile var loadState = LOAD_IDLE + private set + @Volatile var connected = true + private set + + var unlockListener: ((RetroUnlock) -> Unit)? = null + var stateListener: (() -> Unit)? = null + var resetListener: (() -> Unit)? = null + var hardcoreNoticeListener: ((String) -> Unit)? = null + + private var loginCallback: ((Boolean, String?) -> Unit)? = null + private var appContext: Context? = null + + private fun prefs(context: Context) = + context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + + fun isEnabled(context: Context): Boolean = prefs(context).getBoolean(KEY_ENABLED, true) + + fun setEnabled(context: Context, value: Boolean) { + prefs(context).edit().putBoolean(KEY_ENABLED, value).apply() + } + + const val HARDCORE_SUPPORTED = false + + fun isHardcorePreferred(context: Context): Boolean = + HARDCORE_SUPPORTED && prefs(context).getBoolean(KEY_HARDCORE, false) + + fun setHardcorePreferred(context: Context, value: Boolean) { + prefs(context).edit().putBoolean(KEY_HARDCORE, value).apply() + if (clientReady) RetroAchievements.INSTANCE.nativeSetHardcore(value) + } + + fun isLoggedIn(context: Context): Boolean = + prefs(context).getString(KEY_TOKEN, null).isNullOrBlank().not() + + fun displayName(context: Context): String? = prefs(context).getString(KEY_DISPLAY, null) + ?: prefs(context).getString(KEY_USERNAME, null) + + fun username(context: Context): String? = prefs(context).getString(KEY_USERNAME, null) + + fun apiToken(context: Context): String? = prefs(context).getString(KEY_TOKEN, null) + + fun consoleId(systemId: String?): Int = + when (systemId) { + RetroSystems.NES.id -> 7 + RetroSystems.SNES.id -> 3 + RetroSystems.GAMEBOY.id -> 4 + RetroSystems.GAMEBOY_COLOR.id -> 6 + RetroSystems.GBA.id -> 5 + RetroSystems.GENESIS.id -> 1 + RetroSystems.MASTER_SYSTEM.id -> 11 + RetroSystems.GAME_GEAR.id -> 15 + RetroSystems.N64.id -> 2 + RetroSystems.PSX.id -> 12 + RetroSystems.PS2.id -> 21 + RetroSystems.GAMECUBE.id -> 16 + RetroSystems.WII.id -> 19 + else -> 0 + } + + private fun ensureClient(context: Context) { + appContext = context.applicationContext + if (!clientReady) { + RetroAchievements.INSTANCE.nativeInit(isHardcorePreferred(context)) + clientReady = true + } + startPumps() + } + + fun login(context: Context, username: String, password: String, onResult: (Boolean, String?) -> Unit) { + ensureClient(context) + prefs(context).edit().putString(KEY_USERNAME, username).apply() + loginCallback = onResult + RetroAchievements.INSTANCE.nativeLoginPassword(username, password) + } + + fun logout(context: Context) { + prefs(context).edit() + .remove(KEY_TOKEN) + .remove(KEY_DISPLAY) + .apply() + loadedRomPath = null + loadState = LOAD_IDLE + endSession() + } + + fun prefetch(context: Context, systemId: String?, romPath: String) { + if (!isEnabled(context) || !isLoggedIn(context)) return + if (consoleId(systemId) == 0) return + loadGameForBrowsing(context, systemId, romPath) + } + + fun startSession(context: Context, systemId: String?, romPath: String) { + if (!isEnabled(context) || !isLoggedIn(context)) return + val console = consoleId(systemId) + if (console == 0) return + ensureClient(context) + val username = prefs(context).getString(KEY_USERNAME, null) ?: return + val token = prefs(context).getString(KEY_TOKEN, null) ?: return + RetroAchievements.active = true + userAgent = buildUserAgent(systemId) + if (loadedRomPath == romPath && loadState != LOAD_LOADING) return + loadedRomPath = romPath + loadState = LOAD_LOADING + scope.launch { + RetroAchievements.INSTANCE.nativeLoginToken(username, token) + RetroAchievements.INSTANCE.nativeLoadGame(console, romPath) + } + } + + fun loadGameForBrowsing(context: Context, systemId: String?, romPath: String) { + if (!isLoggedIn(context)) return + val console = consoleId(systemId) + if (console == 0) return + ensureClient(context) + val username = prefs(context).getString(KEY_USERNAME, null) ?: return + val token = prefs(context).getString(KEY_TOKEN, null) ?: return + userAgent = buildUserAgent(systemId) + if (loadedRomPath == romPath && loadState != LOAD_LOADING) return + loadedRomPath = romPath + loadState = LOAD_LOADING + scope.launch { + RetroAchievements.INSTANCE.nativeLoginToken(username, token) + RetroAchievements.INSTANCE.nativeLoadGame(console, romPath) + } + } + + fun endSession() { + RetroAchievements.active = false + loadedRomPath = null + loadState = LOAD_IDLE + stopPumps() + if (clientReady) RetroAchievements.INSTANCE.nativeUnloadGame() + } + + fun idle() { + if (clientReady) RetroAchievements.INSTANCE.nativeIdle() + } + + fun onEmulatorReset() { + if (clientReady) RetroAchievements.INSTANCE.nativeReset() + } + + fun isHardcoreActive(): Boolean = + HARDCORE_SUPPORTED && clientReady && RetroAchievements.INSTANCE.nativeGetHardcore() + + fun getAchievements(): List { + if (!clientReady) return emptyList() + return RetroAchievements.INSTANCE.nativeGetAchievements().mapNotNull { row -> + val parts = row.split('\t') + if (parts.size < 9) return@mapNotNull null + RetroAchievement( + id = parts[0].toLongOrNull() ?: 0L, + title = parts[1], + description = parts[2], + unlocked = parts[3] == "1", + points = parts[4].toIntOrNull() ?: 0, + progress = parts[5], + badgeUrl = parts[6], + badgeLockedUrl = parts[7], + bucket = parts[8].toIntOrNull() ?: 0, + ) + } + } + + fun getSummary(): RetroGameSummary? { + if (!clientReady) return null + val text = RetroAchievements.INSTANCE.nativeGetGameSummary() + if (text.isBlank()) return null + val parts = text.split('\t') + if (parts.size < 7) return null + return RetroGameSummary( + gameId = parts[0].toLongOrNull() ?: 0L, + title = parts[1], + badgeUrl = parts[2], + total = parts[3].toIntOrNull() ?: 0, + unlocked = parts[4].toIntOrNull() ?: 0, + pointsTotal = parts[5].toIntOrNull() ?: 0, + pointsUnlocked = parts[6].toIntOrNull() ?: 0, + ) + } + + private fun startPumps() { + if (pumpJob?.isActive == true) return + pumpJob = scope.launch { + while (isActive && clientReady) { + pumpHttp() + pumpEvents() + delay(50) + } + } + } + + private fun stopPumps() { + pumpJob?.cancel() + pumpJob = null + } + + fun stopPolling() = stopPumps() + + private suspend fun CoroutineScope.pumpHttp() { + while (isActive) { + val request = RetroAchievements.INSTANCE.nativePollHttpRequest() ?: break + val id = request[0].toIntOrNull() ?: continue + val url = request[1] + val postData = request[2] + val contentType = request[3] + launch { performHttp(id, url, postData, contentType) } + } + } + + private suspend fun performHttp(id: Int, url: String, postData: String, contentType: String) { + var status = 0 + var body: ByteArray? = null + try { + val connection = (URL(url).openConnection() as HttpURLConnection).apply { + connectTimeout = 30000 + readTimeout = 30000 + setRequestProperty("User-Agent", userAgent) + if (postData.isNotEmpty()) { + doOutput = true + requestMethod = "POST" + if (contentType.isNotEmpty()) setRequestProperty("Content-Type", contentType) + outputStream.use { it.write(postData.toByteArray(Charsets.UTF_8)) } + } else { + requestMethod = "GET" + } + } + status = connection.responseCode + val stream = if (status in 200..299) connection.inputStream else connection.errorStream + body = stream?.use { input -> + val buffer = ByteArrayOutputStream() + val chunk = ByteArray(8192) + while (true) { + val read = input.read(chunk) + if (read < 0) break + buffer.write(chunk, 0, read) + } + buffer.toByteArray() + } + connection.disconnect() + } catch (e: Exception) { + status = 0 + body = null + } + withContext(Dispatchers.IO) { + RetroAchievements.INSTANCE.nativeProvideResponse(id, status, body) + } + } + + private fun pumpEvents() { + val events = RetroAchievements.INSTANCE.nativePollEvents() + for (event in events) { + val parts = event.split('\t') + when (parts.getOrNull(0)) { + "unlock" -> { + val unlock = RetroUnlock( + id = parts.getOrNull(1)?.toLongOrNull() ?: 0L, + title = parts.getOrNull(2) ?: "", + description = parts.getOrNull(3) ?: "", + points = parts.getOrNull(4)?.toIntOrNull() ?: 0, + badgeUrl = parts.getOrNull(5) ?: "", + ) + postMain { + unlockListener?.invoke(unlock) + stateListener?.invoke() + } + } + "login_ok" -> { + val display = parts.getOrNull(1) ?: "" + val token = parts.getOrNull(2) ?: "" + appContext?.let { ctx -> + prefs(ctx).edit() + .putString(KEY_DISPLAY, display) + .putString(KEY_TOKEN, token) + .apply() + } + val callback = loginCallback + loginCallback = null + postMain { callback?.invoke(true, display) } + } + "login_failed" -> { + val message = parts.getOrNull(2) ?: "Login failed" + val callback = loginCallback + loginCallback = null + postMain { callback?.invoke(false, message) } + } + "game_loaded" -> { + loadState = LOAD_LOADED + if (RetroAchievements.INSTANCE.nativeGetHardcore() && + !RetroAchievements.INSTANCE.nativeHardcoreCompatible() + ) { + RetroAchievements.INSTANCE.nativeSetHardcore(false) + postMain { + hardcoreNoticeListener?.invoke( + "Hardcore disabled: a core option is not allowed in hardcore mode", + ) + } + } + postMain { stateListener?.invoke() } + } + "game_unidentified", "game_load_failed" -> { + loadState = LOAD_EMPTY + postMain { stateListener?.invoke() } + } + "game_completed" -> postMain { stateListener?.invoke() } + "reset" -> postMain { resetListener?.invoke() } + "disconnected" -> { + connected = false + postMain { stateListener?.invoke() } + } + "reconnected" -> { + connected = true + postMain { stateListener?.invoke() } + } + } + } + } +} diff --git a/app/src/main/feature/retro/RetroActivity.kt b/app/src/main/feature/retro/RetroActivity.kt new file mode 100644 index 000000000..a9101f4ca --- /dev/null +++ b/app/src/main/feature/retro/RetroActivity.kt @@ -0,0 +1,1900 @@ +package com.winlator.cmod.feature.retro + +import android.content.SharedPreferences +import android.content.pm.ActivityInfo +import android.content.res.Configuration +import android.graphics.RectF +import android.hardware.input.InputManager +import android.os.Bundle +import android.view.InputDevice +import android.view.KeyEvent +import android.view.MotionEvent +import android.view.View +import android.view.WindowManager +import android.widget.FrameLayout +import android.widget.Toast +import androidx.activity.OnBackPressedCallback +import androidx.activity.addCallback +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.ComposeView +import androidx.compose.ui.unit.dp +import androidx.core.view.WindowCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.WindowInsetsControllerCompat +import androidx.lifecycle.lifecycleScope +import com.swordfish.libretrodroid.GLRetroView +import com.swordfish.libretrodroid.GLRetroViewData +import com.swordfish.libretrodroid.LibretroDroid +import com.swordfish.libretrodroid.ShaderConfig +import com.swordfish.libretrodroid.Variable +import com.swordfish.libretrodroid.ViewportAlignment +import com.winlator.cmod.R +import com.winlator.cmod.feature.sync.google.GameSaveBackupManager +import com.winlator.cmod.feature.sync.google.GoogleAuthMode +import com.winlator.cmod.runtime.container.ContainerManager +import com.winlator.cmod.runtime.container.Shortcut +import com.winlator.cmod.runtime.display.ui.FrameRating +import com.winlator.cmod.runtime.input.controls.ExternalController +import com.winlator.cmod.shared.android.FixedFontScaleAppCompatActivity +import com.winlator.cmod.shared.theme.WinNativeTheme +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeout +import java.io.File +import kotlin.math.abs + +class RetroActivity : FixedFontScaleAppCompatActivity(), RetroInputView.Listener { + companion object { + const val EXTRA_ROM_PATH = "retro_rom_path" + const val EXTRA_SYSTEM_ID = "retro_system_id" + const val EXTRA_GAME_NAME = "retro_game_name" + const val EXTRA_SHORTCUT_PATH = "retro_shortcut_path" + const val EXTRA_CONTAINER_ID = "retro_container_id" + const val EXTRA_SHADER = "retro_shader" + const val EXTRA_TOUCH_CONTROLS = "retro_touch_controls" + const val EXTRA_ADAPTIVE_STICKS = "retro_adaptive_sticks" + const val EXTRA_AUDIO = "retro_audio" + const val EXTRA_HUD = "retro_hud" + const val EXTRA_VARIABLES = "retro_variables" + + const val EXTRA_UPSCALE = "retro_upscale" + const val EXTRA_SGSR = "retro_sgsr" + + private val SHADER_KEYS = listOf("default", "crt", "lcd", "sharp") + private val SHADER_LABEL_RES = + listOf(R.string.retro_lr_shader_default, R.string.retro_lr_shader_crt, R.string.retro_lr_shader_lcd, R.string.retro_lr_shader_sharp) + private val UPSCALE_KEYS = listOf("2x", "4x", "native") + } + + private lateinit var retroView: GLRetroView + private var overlay: RetroInputView? = null + private val menu = RetroMenuController() + private var retroReady = false + private var gameName = "game" + private var fastForward = false + private var audioEnabledSetting = true + private var touchControlsSetting = true + private var adaptiveSticksSetting = false + private var currentShaderKey = "default" + private var sgsrEnabled = false + private var coreVars = HashMap() + private var diskCount = 0 + private var currentDisk = 0 + private var system: RetroSystem? = null + private var persistShortcut: Shortcut? = null + private var playtimePrefs: SharedPreferences? = null + private var sessionStart = 0L + private var emulationPaused = false + private var controllerConnected = false + private var manualTouchOverride = false + private var inputManager: InputManager? = null + private var hudVisible = false + private var currentUpscaleKey = "native" + private var hudAlpha = 1f + private var hudBgDecoupled = false + private var hudBgAlpha = 1f + private var hudScale = 1f + private var hudElements = booleanArrayOf(true, true, true, true, true, true, true, true, false) + private var hudFrametimeNumeric = false + private var hudDualBattery = false + private var frameRating: FrameRating? = null + private val biosPicker = + registerForActivityResult(androidx.activity.result.contract.ActivityResultContracts.OpenDocument()) { uri -> + if (uri != null) { + RetroBiosImport.importFromUri(this, uri) + .onSuccess { + Toast.makeText(this, getString(R.string.retro_lr_bios_imported, it), Toast.LENGTH_SHORT).show() + recreate() + } + .onFailure { + Toast.makeText(this, it.message ?: getString(R.string.retro_lr_invalid_bios_file), Toast.LENGTH_LONG).show() + } + } else { + finish() + } + } + private var rootLayout: FrameLayout? = null + private var menuComposeView: ComposeView? = null + private var surfaceReady = false + private var customColors = RetroCustomColors() + private var savesLoadMode = false + private var achievementsSessionStarted = false + private var cloudSyncEnabled = false + private var conflictChecked = false + private var retroCloudId = "" + private var netplayLocalPort = 0 + private var netplayArmedThisSession = false + + private val isPortrait: Boolean + get() = resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT + + private val gameAspect: Float + get() = + when (system?.id) { + RetroSystems.GAMEBOY.id, RetroSystems.GAMEBOY_COLOR.id -> 10f / 9f + RetroSystems.GBA.id -> 3f / 2f + else -> 4f / 3f + } + + private fun overlayPush(): Float = 0f + + private fun updateOverlayArea() { + val rootWidth = rootLayout?.width ?: 0 + val rootHeight = rootLayout?.height ?: 0 + if (rootWidth <= 0 || rootHeight <= 0) return + val push = overlayPush() + val area = + if (isPortrait) { + val top = push * rootHeight + val gameHeight = rootWidth / gameAspect + RectF(0f, top, rootWidth.toFloat(), (top + gameHeight).coerceAtMost(rootHeight.toFloat())) + } else { + val availHeight = rootHeight * (1f - push) + val gameWidth = (availHeight * gameAspect).coerceAtMost(rootWidth.toFloat()) + val left = (rootWidth - gameWidth) * 0.5f + val gameHeight = gameWidth / gameAspect + val top = push * rootHeight + (availHeight - gameHeight) * 0.5f + RectF(left, top, left + gameWidth, top + gameHeight) + } + overlay?.setGameArea(area) + } + + private fun applyDisplayGeometry() { + updateOverlayArea() + if (!surfaceReady || !retroReady) return + retroView.viewportAlignment = if (isPortrait) ViewportAlignment.TOP else ViewportAlignment.CENTER + retroView.viewport = RectF(0f, overlayPush(), 1f, 1f) + } + + override fun onConfigurationChanged(newConfig: Configuration) { + super.onConfigurationChanged(newConfig) + overlay?.releaseAll() + rootLayout?.post { + overlay?.relayout() + applyDisplayGeometry() + } + } + + private val inputDeviceListener = + object : InputManager.InputDeviceListener { + override fun onInputDeviceAdded(deviceId: Int) = refreshControllerPresence() + + override fun onInputDeviceRemoved(deviceId: Int) = refreshControllerPresence() + + override fun onInputDeviceChanged(deviceId: Int) = refreshControllerPresence() + } + + private val stickIsAnalog: Boolean + get() = system?.id == RetroSystems.N64.id || RetroCoreManager.usesDolphinCore(system) + + private fun anyGameControllerConnected(): Boolean = + InputDevice.getDeviceIds().any { id -> + ExternalController.isGameController(InputDevice.getDevice(id)) + } + + private fun refreshControllerPresence() { + val wasConnected = controllerConnected + controllerConnected = anyGameControllerConnected() + if (controllerConnected != wasConnected) manualTouchOverride = false + updateOverlayVisibility() + syncInGameOverlayPlacement() + } + + private val touchControlsEffective: Boolean + get() = touchControlsSetting && (!controllerConnected || manualTouchOverride) + + private fun updateOverlayVisibility() { + overlay?.visibility = + if (overlay?.editMode == true || touchControlsEffective) View.VISIBLE else View.GONE + } + + private fun pauseEmulation() { + if (emulationPaused || !retroReady) return + emulationPaused = true + retroView.onPause() + LibretroDroid.pause() + RetroAchievementsManager.idle() + } + + private fun resumeEmulation() { + if (!emulationPaused || !retroReady) return + emulationPaused = false + LibretroDroid.resume() + retroView.onResume() + } + + private fun startAchievementsSession() { + if (achievementsSessionStarted) return + val sys = system ?: return + val rom = intent.getStringExtra(EXTRA_ROM_PATH) ?: return + if (!RetroAchievementsManager.isEnabled(this) || !RetroAchievementsManager.isLoggedIn(this)) return + achievementsSessionStarted = true + RetroAchievementsManager.unlockListener = { unlock -> + runOnUiThread { showAchievementUnlock(unlock) } + } + syncInGameOverlayPlacement() + RetroAchievementsManager.resetListener = { + runOnUiThread { + if (retroReady) retroView.reset() + RetroAchievementsManager.onEmulatorReset() + } + } + RetroAchievementsManager.hardcoreNoticeListener = { message -> + runOnUiThread { showInGameMessage(message) } + } + RetroAchievementsManager.startSession(this, sys.id, rom) + } + + private fun syncInGameOverlayPlacement() { + RetroAchievementOverlayState.syncPlacement( + touchControlsVisible = touchControlsEffective, + controllerConnected = controllerConnected, + ) + } + + private fun showInGameMessage(message: String) { + syncInGameOverlayPlacement() + if (RetroAchievementOverlayState.useDisplayArea) { + RetroAchievementOverlayState.showMessage(message) + } else { + Toast.makeText(this, message, Toast.LENGTH_SHORT).show() + } + } + + private fun showAchievementUnlock(unlock: RetroUnlock) { + syncInGameOverlayPlacement() + RetroAchievementOverlayState.show(unlock.title, unlock.points, unlock.description) + } + + fun cheatsAllowed(): Boolean = !(achievementsSessionStarted && RetroAchievementsManager.isHardcoreActive()) + + private fun applyCheats() { + if (!retroReady) return + runCatching { retroView.resetCheat() } + if (!cheatsAllowed()) return + val enabled = RetroCheats.load(this, gameName).filter { it.enabled } + if (enabled.isEmpty()) return + enabled.forEachIndexed { index, cheat -> + runCatching { retroView.setCheat(index, true, cheat.code) } + } + if (achievementsSessionStarted) { + RetroAchievementsManager.endSession() + achievementsSessionStarted = false + Toast.makeText(this, getString(R.string.retro_lr_cheats_enabled_achievements_disabled), Toast.LENGTH_LONG).show() + } + } + + private fun openCheatsScreen() { + val sys = system ?: return + startActivity( + android.content.Intent(this, RetroCheatsActivity::class.java).apply { + putExtra(RetroCheatsActivity.EXTRA_SYSTEM_ID, sys.id) + putExtra(RetroCheatsActivity.EXTRA_GAME_NAME, gameName) + }, + ) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + WindowCompat.setDecorFitsSystemWindows(window, false) + window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + hideSystemBars() + + val romPath = intent.getStringExtra(EXTRA_ROM_PATH) + val systemId = intent.getStringExtra(EXTRA_SYSTEM_ID) + gameName = intent.getStringExtra(EXTRA_GAME_NAME) ?: "game" + val resolvedSystem = RetroSystems.fromId(systemId) + system = resolvedSystem + + if (romPath.isNullOrBlank() || resolvedSystem == null) { + Toast.makeText(this, getString(R.string.retro_lr_invalid_retro_game), Toast.LENGTH_LONG).show() + finish() + return + } + + val sourceFile = File(romPath) + if (!sourceFile.isFile) { + Toast.makeText(this, getString(R.string.retro_lr_rom_not_found, romPath), Toast.LENGTH_LONG).show() + finish() + return + } + val romFile = + if (RetroRomArchive.isArchive(romPath)) { + RetroRomArchive.extractTo(this, romPath) ?: run { + Toast.makeText(this, getString(R.string.retro_lr_could_not_read_rom_archive), Toast.LENGTH_LONG).show() + finish() + return + } + } else { + sourceFile + } + + requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_FULL_USER + + netplayArmedThisSession = RetroDefaults.netplayEnabled(this, resolvedSystem.id) + if (!netplayArmedThisSession && RetroNetplayLobby.isInRoomSession()) { + RetroNetplayLobby.leave(silent = true) + } + val wantGbaMulti = + resolvedSystem.id == RetroSystems.GBA.id && + netplayArmedThisSession && + ( + RetroDefaults.netplayLaunchMode(this, resolvedSystem.id) == "host" || + RetroDefaults.netplayLaunchMode(this, resolvedSystem.id) == "join" || + RetroNetplayLobby.isGameLink || + RetroNetplayLobby.isInRoomSession() + ) + val coreFile = + if (wantGbaMulti) { + RetroCoreManager.multiplayerCoreFile(this, resolvedSystem) + } else { + RetroCoreManager.coreFile(this, resolvedSystem) + } + if (!coreFile.isFile) { + val name = + if (wantGbaMulti) RetroSystems.GBA_MULTIPLAYER_CORE else resolvedSystem.coreFileName + val message = + if (RetroBundle.isInstalled(this)) { + getString(R.string.retro_lr_core_not_installed, name) + } else { + getString(R.string.retro_bundle_required) + } + Toast.makeText(this, message, Toast.LENGTH_LONG).show() + finish() + return + } + + if (RetroCoreManager.missingBios(this, resolvedSystem)) { + showBiosRequiredDialog(resolvedSystem) + return + } + + if (resolvedSystem.id == RetroSystems.N64.id) RetroCoreManager.ensureGlideN64Ini(this) + if (RetroCoreManager.usesDolphinCore(resolvedSystem)) { + RetroCoreManager.ensureDolphinSys(this) + RetroCoreManager.ensureDolphinUser(this) + } + val savesDir = RetroCoreManager.savesDir(this) + RetroSaveStates.migrateLegacy(this, gameName) + RetroSaveStates.recordIdentity(this, gameName, resolvedSystem.id) + val sramFile = RetroSaveStates.sramFile(this, gameName) + currentShaderKey = intent.getStringExtra(EXTRA_SHADER)?.lowercase() ?: "default" + sgsrEnabled = intent.getBooleanExtra(EXTRA_SGSR, false) + if (currentShaderKey == "sgsr") { + currentShaderKey = "default" + sgsrEnabled = true + } + if (currentShaderKey !in SHADER_KEYS) currentShaderKey = "default" + currentUpscaleKey = intent.getStringExtra(EXTRA_UPSCALE)?.lowercase() ?: "native" + if (currentUpscaleKey !in UPSCALE_KEYS) currentUpscaleKey = "native" + audioEnabledSetting = intent.getBooleanExtra(EXTRA_AUDIO, true) + touchControlsSetting = intent.getBooleanExtra(EXTRA_TOUCH_CONTROLS, true) + adaptiveSticksSetting = intent.getBooleanExtra(EXTRA_ADAPTIVE_STICKS, false) + @Suppress("UNCHECKED_CAST", "DEPRECATION") + coreVars = (intent.getSerializableExtra(EXTRA_VARIABLES) as? HashMap) ?: HashMap() + RetroCoreOptions.defaultVariables(resolvedSystem).forEach { (key, value) -> + if (!coreVars.containsKey(key)) coreVars[key] = value + } + if (RetroCoreManager.usesDolphinCore(resolvedSystem)) { + RetroCoreOptions.sanitizeDolphinVariables(coreVars) + } + + val root = FrameLayout(this) + rootLayout = root + + val callback = object : OnBackPressedCallback(true) { + override fun handleOnBackPressed() { + if (retroReady) { + if (menu.visible) { + menu.close() + return + } + overlay?.releaseAll() + menu.open() + } + } + } + + onBackPressedDispatcher.addCallback(this, callback) + + val inputView = RetroInputView(this, this, resolvedSystem) + inputView.loadStickInversion() + inputView.hapticStrength = + androidx.preference.PreferenceManager + .getDefaultSharedPreferences(this) + .getFloat("retro_haptic_strength", 0.4f) + inputView.adaptiveSticks = adaptiveSticksSetting + inputView.showL3R3 = + androidx.preference.PreferenceManager + .getDefaultSharedPreferences(this) + .getBoolean(RetroControlsMenu.l3r3PrefKey(resolvedSystem.id), true) + customColors = RetroControlLayouts.loadColors(this, resolvedSystem.id) + inputView.setCustomColors(customColors) + inputView.onEditStateChanged = { editing -> + runOnUiThread { + frameRating?.visibility = + if (!editing && hudVisible) View.VISIBLE else View.GONE + updateOverlayVisibility() + menu.rebuild() + } + } + overlay = inputView + root.addView( + inputView, + FrameLayout.LayoutParams( + FrameLayout.LayoutParams.MATCH_PARENT, + FrameLayout.LayoutParams.MATCH_PARENT, + ), + ) + root.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> updateOverlayArea() } + + menu.entriesProvider = { pane -> buildEntriesFor(pane) } + menu.bottomProvider = { buildBottomEntries() } + val coreOpts = RetroCoreOptions.forSystem(system) + menu.tabs = + RetroDrawerTabs.build( + this, + includePerformance = coreOpts.any { it.category == RetroOptionCategory.PERFORMANCE }, + includeNetplay = RetroOnlineSupport.supportsMultiplayerUi(system?.id), + includeSystem = coreOpts.any { it.category == RetroOptionCategory.SYSTEM }, + ) + hudVisible = intent.getBooleanExtra(EXTRA_HUD, false) + RetroNetplayLobby.bindLocalName(this) + val menuView = + ComposeView(this).apply { + elevation = 2000f + setContent { + WinNativeTheme { + Box(Modifier.fillMaxSize()) { + syncInGameOverlayPlacement() + RetroAchievementOverlayBanner() + val netPhase = RetroNetplayLobby.phase + val netMembers = RetroNetplayLobby.members + val netDiscovered = RetroNetplayLobby.discovered + val netStatus = RetroNetplayLobby.statusText + LaunchedEffect(netPhase, netMembers, netDiscovered, netStatus) { + if (menu.visible && menu.pane == RetroPane.NETWORK) { + menu.rebuild() + } + } + Box( + Modifier + .fillMaxSize() + .padding(top = 56.dp), + contentAlignment = Alignment.TopCenter, + ) { + RetroNetplayRoomBanner( + onLeave = { leaveNetplayRoom() }, + onJoinRoom = { room -> joinDiscoveredRoom(room) }, + ) + } + Box( + Modifier.fillMaxSize(), + contentAlignment = Alignment.BottomCenter, + ) { + RetroNetplayEventToast( + Modifier.padding(bottom = 72.dp), + ) + } + RetroDrawerMenu(menu) + } + } + } + } + menuComposeView = menuView + root.addView( + menuView, + FrameLayout.LayoutParams( + FrameLayout.LayoutParams.MATCH_PARENT, + FrameLayout.LayoutParams.MATCH_PARENT, + ), + ) + + setContentView(root) + inputManager = getSystemService(InputManager::class.java) + inputManager?.registerInputDeviceListener(inputDeviceListener, null) + refreshControllerPresence() + retroReady = false + if (hudVisible) { + root.post { + if (!isFinishing && !isDestroyed && hudVisible) showHud() + } + } + onBackPressedDispatcher.addCallback( + this, + object : androidx.activity.OnBackPressedCallback(true) { + override fun handleOnBackPressed() { + if (overlay?.editMode == true) { + overlay?.finishEdit() + } else if (menu.visible) { + menu.handleKey(KeyEvent.KEYCODE_BACK, KeyEvent.ACTION_UP) + } else { + openMenu() + } + } + }, + ) + loadHudSettings() + recordLaunchStats() + + val sixtyRequested = requestSixtyHzDisplayMode() + var waitAttempts = 0 + lateinit var startWhenReady: Runnable + startWhenReady = + Runnable { + if (isFinishing || isDestroyed) return@Runnable + val rate = + runCatching { windowManager.defaultDisplay.refreshRate }.getOrDefault(60f) + if (sixtyRequested && abs(rate - 60f) > 2f && waitAttempts < 12) { + waitAttempts++ + root.postDelayed(startWhenReady, 100) + return@Runnable + } + val data = + GLRetroViewData(this).apply { + coreFilePath = coreFile.absolutePath + gameFilePath = romFile.absolutePath + systemDirectory = RetroCoreManager.systemDir(this@RetroActivity).absolutePath + savesDirectory = savesDir.absolutePath + shader = effectiveShader() + variables = coreVars.map { Variable(it.key, it.value) }.toTypedArray() + rumbleEventsEnabled = true + preferLowLatencyAudio = !RetroCoreManager.usesDolphinCore(resolvedSystem) + skipDuplicateFrames = false + viewportAlignment = + if (resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) { + ViewportAlignment.TOP + } else { + ViewportAlignment.CENTER + } + if (sramFile.isFile) saveRAMState = runCatching { sramFile.readBytes() }.getOrNull() + } + val view = GLRetroView(this, data) + if (android.os.Build.VERSION.SDK_INT >= 30) { + view.holder.addCallback( + object : android.view.SurfaceHolder.Callback { + override fun surfaceCreated(holder: android.view.SurfaceHolder) { + runCatching { + holder.surface.setFrameRate( + 60f, + android.view.Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE, + ) + } + } + + override fun surfaceChanged( + holder: android.view.SurfaceHolder, + format: Int, + width: Int, + height: Int, + ) {} + + override fun surfaceDestroyed(holder: android.view.SurfaceHolder) {} + }, + ) + } + retroView = view + root.addView( + view, + 0, + FrameLayout.LayoutParams( + FrameLayout.LayoutParams.MATCH_PARENT, + FrameLayout.LayoutParams.MATCH_PARENT, + ), + ) + lifecycle.addObserver(view) + retroReady = true + refreshControllerPresence() + observeErrors() + observeEvents() + scheduleCloudConflictCheck() + } + retroCloudId = + intent.getStringExtra(EXTRA_SHORTCUT_PATH)?.let { path -> + GameSaveBackupManager.customGameId(intent.getIntExtra(EXTRA_CONTAINER_ID, 0), File(path).name) + } ?: RetroSaveStates.cloudGameId(resolvedSystem.id, gameName) + lifecycleScope.launch(Dispatchers.IO) { + cloudSyncEnabled = + runCatching { loadShortcut()?.getExtra("cloud_sync_enabled", "1") != "0" }.getOrDefault(true) + if (cloudSyncEnabled && !RetroSaveStates.sramFile(this@RetroActivity, gameName).isFile) { + runCatching { + withTimeout(12_000L) { + val entries = + GameSaveBackupManager.listGoogleHistory( + this@RetroActivity, + GameSaveBackupManager.GameSource.CUSTOM, + retroCloudId, + GoogleAuthMode.RESUME, + ) + val latest = entries.maxByOrNull { it.timestampMs } + if (latest != null) { + val result = + GameSaveBackupManager.restoreFromGoogle( + this@RetroActivity, + latest, + GameSaveBackupManager.GameSource.CUSTOM, + retroCloudId, + GoogleAuthMode.RESUME, + customSaveDir = RetroSaveStates.gameDir(this@RetroActivity, gameName), + ) + if (result.success) { + RetroSaveStates.migrateLegacyCloudLayout(this@RetroActivity, gameName) + setCloudMark(latest.timestampMs) + runOnUiThread { + Toast + .makeText(this@RetroActivity, getString(R.string.retro_lr_cloud_save_restored), Toast.LENGTH_SHORT) + .show() + } + } + } + } + } + } + runOnUiThread { + if (!isFinishing && !isDestroyed) root.post(startWhenReady) + } + } + } + + private fun scheduleCloudConflictCheck() { + if (!cloudSyncEnabled || conflictChecked) return + conflictChecked = true + lifecycleScope.launch(Dispatchers.IO) { + runCatching { + val sram = RetroSaveStates.sramFile(this@RetroActivity, gameName) + val localTs = if (sram.isFile) sram.lastModified() else 0L + if (localTs <= 0L) return@runCatching + val entries = + GameSaveBackupManager.listGoogleHistory( + this@RetroActivity, + GameSaveBackupManager.GameSource.CUSTOM, + retroCloudId, + GoogleAuthMode.RESUME, + ) + val mark = cloudMark() + val newer = + entries + .filter { it.timestampMs > localTs + 120_000L && it.timestampMs > mark } + .sortedByDescending { it.timestampMs } + if (newer.isEmpty()) return@runCatching + val top = newer.take(5) + runOnUiThread { + if (isFinishing || isDestroyed) return@runOnUiThread + pauseEmulation() + menu.conflictPrompt = + RetroConflictPrompt( + message = getString(R.string.retro_lr_cloud_conflict_message, gameName), + options = + top.map { entry -> + (entry.label ?: getString(R.string.retro_lr_cloud_save)) + " — " + + RetroSaveStates.relativeTime(entry.timestampMs) + }, + onKeepLocal = { + setCloudMark(top.first().timestampMs) + menu.conflictPrompt = null + resumeEmulation() + }, + onPick = { index -> + menu.conflictPrompt = null + restoreCloudEntry(top[index]) + }, + ) + } + } + } + } + + private fun restoreCloudEntry(entry: GameSaveBackupManager.BackupHistoryEntry) { + lifecycleScope.launch(Dispatchers.IO) { + val result = + runCatching { + GameSaveBackupManager.restoreFromGoogle( + this@RetroActivity, + entry, + GameSaveBackupManager.GameSource.CUSTOM, + retroCloudId, + GoogleAuthMode.INTERACTIVE, + customSaveDir = RetroSaveStates.gameDir(this@RetroActivity, gameName), + ) + }.getOrNull() + runOnUiThread { + if (isFinishing || isDestroyed) return@runOnUiThread + if (result?.success == true) { + RetroSaveStates.migrateLegacyCloudLayout(this@RetroActivity, gameName) + setCloudMark(entry.timestampMs) + runCatching { + val sram = RetroSaveStates.sramFile(this@RetroActivity, gameName) + if (sram.isFile) retroView.unserializeSRAM(sram.readBytes()) + } + Toast.makeText(this@RetroActivity, getString(R.string.retro_lr_cloud_save_restored), Toast.LENGTH_SHORT).show() + } else { + Toast + .makeText(this@RetroActivity, result?.message ?: getString(R.string.retro_lr_restore_failed), Toast.LENGTH_SHORT) + .show() + } + resumeEmulation() + menu.rebuild() + } + } + } + + private fun cloudMark(): Long = + androidx.preference.PreferenceManager + .getDefaultSharedPreferences(this) + .getLong("retro_cloud_mark_$retroCloudId", 0L) + + private fun setCloudMark(value: Long) { + androidx.preference.PreferenceManager + .getDefaultSharedPreferences(this) + .edit() + .putLong("retro_cloud_mark_$retroCloudId", value) + .apply() + } + + private fun launchExitCloudBackup() { + if (!cloudSyncEnabled) return + val hasSaves = + RetroSaveStates.gameDir(this, gameName).walkTopDown().any { it.isFile } + if (!hasSaves) return + androidx.preference.PreferenceManager + .getDefaultSharedPreferences(this) + .edit() + .putString("retro_pending_backup_id", retroCloudId) + .putString("retro_pending_backup_name", gameName) + .apply() + } + + override fun onDestroy() { + inputManager?.unregisterInputDeviceListener(inputDeviceListener) + shutdownNetplaySession(callNativeStop = false) + RetroAchievementsManager.stopPolling() + if (achievementsSessionStarted) { + RetroAchievementsManager.unlockListener = null + RetroAchievementsManager.resetListener = null + RetroAchievementsManager.hardcoreNoticeListener = null + RetroAchievementsManager.endSession() + } + super.onDestroy() + } + + private fun shutdownNetplaySession(callNativeStop: Boolean = true) { + val sysId = system?.id + val view = + if (callNativeStop && ::retroView.isInitialized && retroReady) retroView else null + runCatching { + RetroNetplayLobby.leave(silent = true, retroView = view) + } + netplayLocalPort = 0 + netplayArmedThisSession = false + if (sysId != null) { + RetroDefaults.clearNetplayArm(this, sysId) + } + } + + private fun showHud() { + var rating = frameRating + if (rating == null) { + val root = rootLayout ?: return + rating = + RetroHudSupport.createFrameRating( + this, + RetroHudSupport.libretroRendererLabel(), + ) + frameRating = rating + val menuIndex = menuComposeView?.let { root.indexOfChild(it) } ?: -1 + if (menuIndex >= 0) root.addView(rating, menuIndex) else root.addView(rating) + rating.addOnLayoutChangeListener { _, _, top, _, bottom, _, oldTop, _, oldBottom -> + if (bottom - top != oldBottom - oldTop) rootLayout?.post { applyDisplayGeometry() } + } + applyRetroHudSettings(rating) + } + rating.visibility = View.VISIBLE + rating.reset() + rating.post { applyDisplayGeometry() } + } + + private fun applyRetroHudSettings(rating: FrameRating) { + rating.setHudAlpha(hudAlpha) + rating.setBackgroundAlphaDecoupled(hudBgDecoupled) + rating.setHudBackgroundAlpha(hudBgAlpha) + rating.setHudScale(hudScale) + rating.setFrametimeNumericMode(hudFrametimeNumeric) + rating.setDualSeriesBattery(hudDualBattery) + hudElements.forEachIndexed { index, enabled -> rating.toggleElement(index, enabled) } + } + + private fun loadHudSettings() { + val style = RetroHudSupport.loadGlobalHudStyle(this) + hudAlpha = style.alpha + hudBgDecoupled = style.bgDecoupled + hudBgAlpha = style.bgAlpha + hudScale = style.scale + hudFrametimeNumeric = style.frametimeNumeric + hudDualBattery = style.dualBattery + hudElements = RetroHudSupport.loadGlobalHudElements(this) + } + + private fun saveHudSettings() { + RetroHudSupport.saveGlobalHudStyle( + this, + HudStyle(hudAlpha, hudBgDecoupled, hudBgAlpha, hudScale, hudFrametimeNumeric, hudDualBattery), + ) + RetroHudSupport.saveGlobalHudElements(this, hudElements) + } + + private fun recordLaunchStats() { + val prefs = getSharedPreferences("playtime_stats", MODE_PRIVATE) + playtimePrefs = prefs + sessionStart = System.currentTimeMillis() + prefs + .edit() + .putInt("${gameName}_play_count", prefs.getInt("${gameName}_play_count", 0) + 1) + .putLong("${gameName}_last_played", sessionStart) + .apply() + } + + private fun accumulatePlaytime() { + val prefs = playtimePrefs ?: return + val now = System.currentTimeMillis() + val delta = now - sessionStart + if (delta > 0) { + prefs + .edit() + .putLong("${gameName}_playtime", prefs.getLong("${gameName}_playtime", 0L) + delta) + .apply() + } + sessionStart = now + } + + private fun observeEvents() { + retroView + .getGLRetroEvents() + .onEach { event -> + when (event) { + is GLRetroView.GLRetroEvents.FrameRendered -> { + if (hudVisible) frameRating?.recordGameFrame() + RetroNetplayLobby.onFrameRendered() + } + is GLRetroView.GLRetroEvents.SurfaceCreated -> { + if (!audioEnabledSetting) retroView.audioEnabled = false + surfaceReady = true + applyDisplayGeometry() + if (RetroCoreManager.usesDolphinCore(system)) { + runCatching { + val joypad = 1 + retroView.setControllerType(0, joypad) + retroView.setControllerType(1, joypad) + retroView.setControllerType(2, joypad) + retroView.setControllerType(3, joypad) + } + } + lifecycleScope.launch(Dispatchers.Default) { + runCatching { + diskCount = retroView.getAvailableDisks() + currentDisk = retroView.getCurrentDisk() + } + } + startAchievementsSession() + applyCheats() + startNetplayIfNeeded() + } + } + }.launchIn(lifecycleScope) + } + + private fun startNetplayIfNeeded() { + val sysId = system?.id ?: return + if (!RetroOnlineSupport.supportsMultiplayerUi(sysId)) return + + if (!netplayArmedThisSession && !RetroDefaults.netplayEnabled(this, sysId)) { + if (RetroNetplayLobby.isInRoomSession() || + RetroNetplayLobby.phase == RetroNetplayPhase.SCANNING || + RetroNetplayLobby.phase == RetroNetplayPhase.SCAN_RESULTS + ) { + RetroNetplayLobby.leave(silent = true, retroView = retroView) + } + return + } + netplayArmedThisSession = true + + if (RetroNetplayLobby.attachEmulator(retroView)) { + if (!RetroNetplayLobby.isGameLink) { + RetroNetplayLobby.prepareMultiplayerPads(retroView) + } + netplayLocalPort = + when { + RetroNetplayLobby.isGameLink -> 0 + RetroNetplayLobby.isHost -> 0 + else -> 1 + } + menu.rebuild() + return + } + + if (!RetroNetplayLobby.canStartSession() || + RetroNetplayLobby.phase == RetroNetplayPhase.SCANNING + ) { + return + } + val mode = RetroDefaults.netplayLaunchMode(this, sysId) + if (mode != "host" && mode != "join") return + + val port = + if (RetroOnlineSupport.supportsGameLink(sysId)) { + RetroGameLink.clampPort(RetroDefaults.netplayPort(this, sysId)) + } else { + RetroDefaults.netplayPort(this, sysId) + } + val name = RetroNetplayLobby.defaultPlayerName(this) + if (!RetroOnlineSupport.supportsGameLink(sysId)) { + RetroNetplayLobby.prepareMultiplayerPads(retroView) + } + when (mode) { + "host" -> { + netplayLocalPort = 0 + RetroNetplayLobby.host( + systemId = sysId, + gameName = gameName, + playerName = name, + port = port, + context = this, + retroView = retroView, + ) + } + "join" -> { + val host = RetroDefaults.netplayHost(this, sysId).trim() + if (host.isBlank()) return + netplayLocalPort = if (RetroOnlineSupport.supportsGameLink(sysId)) 0 else 1 + RetroNetplayLobby.join( + host = host, + port = port, + playerName = name, + gameName = gameName, + systemId = sysId, + retroView = retroView, + ) + } + } + menu.rebuild() + } + + private fun leaveNetplayRoom() { + when (RetroNetplayLobby.phase) { + RetroNetplayPhase.SCANNING -> RetroNetplayLobby.stopScan() + RetroNetplayPhase.SCAN_RESULTS -> RetroNetplayLobby.dismissScanResults() + RetroNetplayPhase.IDLE -> { + if (RetroNetplayLobby.discovered.isNotEmpty() || + RetroNetplayLobby.statusText.isNotBlank() + ) { + RetroNetplayLobby.dismissScanResults() + } + } + else -> { + RetroNetplayLobby.leave( + silent = false, + retroView = if (retroReady) retroView else null, + ) + netplayLocalPort = 0 + } + } + menu.rebuild() + } + + private fun joinDiscoveredRoom(room: RetroNetplayDiscoveredRoom) { + if (!retroReady) return + val sysId = system?.id + val name = RetroNetplayLobby.defaultPlayerName(this) + netplayLocalPort = if (RetroOnlineSupport.supportsGameLink(sysId)) 0 else 1 + RetroNetplayLobby.join( + host = room.hostAddress, + port = room.port, + playerName = name, + gameName = room.gameName.ifBlank { gameName }, + systemId = sysId, + retroView = retroView, + ) + menu.close() + menu.rebuild() + } + + private fun localNetplayPort(): Int { + if (RetroNetplayLobby.isGameLink) return 0 + return when (RetroNetplayLobby.phase) { + RetroNetplayPhase.HOSTING, RetroNetplayPhase.IN_ROOM, RetroNetplayPhase.CONNECTING -> + if (RetroNetplayLobby.isHost) 0 else 1 + else -> netplayLocalPort + } + } + + private fun observeErrors() { + retroView + .getGLRetroErrors() + .onEach { error -> + val message = + when (error) { + GLRetroView.ERROR_LOAD_LIBRARY -> getString(R.string.retro_lr_failed_load_core) + GLRetroView.ERROR_LOAD_GAME -> getString(R.string.retro_lr_failed_load_rom) + GLRetroView.ERROR_GL_NOT_COMPATIBLE -> getString(R.string.retro_lr_graphics_not_supported) + else -> getString(R.string.retro_lr_emulator_error) + } + Toast.makeText(this@RetroActivity, message, Toast.LENGTH_LONG).show() + finish() + }.launchIn(lifecycleScope) + } + + private fun sgsrPrePasses(): Int = + when (currentUpscaleKey) { + "4x" -> 2 + "native" -> 3 + else -> 1 + } + + private fun effectiveShader(): ShaderConfig = + if (sgsrEnabled) { + ShaderConfig.SGSR(sgsrPrePasses(), currentShaderKey) + } else { + when (currentShaderKey) { + "crt" -> ShaderConfig.CRT + "lcd" -> ShaderConfig.LCD + "sharp" -> ShaderConfig.Sharp + else -> ShaderConfig.Default + } + } + + private fun loadShortcut(): Shortcut? { + persistShortcut?.let { return it } + val containerId = intent.getIntExtra(EXTRA_CONTAINER_ID, 0) + val path = intent.getStringExtra(EXTRA_SHORTCUT_PATH) + if (containerId < 0 || path.isNullOrBlank()) return null + val file = File(path) + if (!file.isFile) return null + return runCatching { + val cm = ContainerManager(this) + val container = + if (containerId == ContainerManager.RETRO_CONTAINER_ID) cm.retroContainer else cm.getContainerById(containerId) + container?.let { Shortcut(it, file) } + }.getOrNull()?.also { persistShortcut = it } + } + + private fun persistExtra( + key: String, + value: String, + ) { + lifecycleScope.launch(Dispatchers.IO) { + runCatching { + val shortcut = loadShortcut() + shortcut?.putExtra(key, value) + shortcut?.saveData() + } + } + } + + private fun buildEntriesFor(pane: RetroPane?): List = + when (pane) { + null -> buildMainEntries() + RetroPane.DISPLAY -> + buildList { + SHADER_KEYS.forEachIndexed { index, key -> + add( + RetroMenuEntry.Radio( + label = getString(SHADER_LABEL_RES[index]), + selected = currentShaderKey == key, + ) { + currentShaderKey = key + retroView.shader = effectiveShader() + persistExtra(RetroShortcuts.KEY_SHADER, key) + menu.rebuild() + }, + ) + } + add( + RetroMenuEntry.Toggle(getString(R.string.retro_lr_sgsr), checked = sgsrEnabled) { value -> + sgsrEnabled = value + retroView.shader = effectiveShader() + persistExtra(RetroShortcuts.KEY_SGSR, if (value) "1" else "0") + menu.rebuild() + }, + ) + val upscaleIndex = UPSCALE_KEYS.indexOf(currentUpscaleKey).coerceAtLeast(0) + add( + RetroMenuEntry.Choice( + getString(R.string.retro_lr_sgsr_upscale), + listOf("2x", "4x", getString(R.string.retro_lr_upscale_native)), + upscaleIndex, + visible = sgsrEnabled, + ) { next -> + currentUpscaleKey = UPSCALE_KEYS[next] + persistExtra(RetroShortcuts.KEY_UPSCALE, currentUpscaleKey) + if (sgsrEnabled) retroView.shader = effectiveShader() + menu.rebuild() + }, + ) + addAll(coreOptionEntries(RetroOptionCategory.DISPLAY)) + } + RetroPane.SOUND -> + buildList { + add( + RetroMenuEntry.Toggle(getString(R.string.retro_lr_sound), checked = audioEnabledSetting) { value -> + audioEnabledSetting = value + retroView.audioEnabled = value + persistExtra(RetroShortcuts.KEY_AUDIO, if (value) "1" else "0") + menu.rebuild() + }, + ) + addAll(coreOptionEntries(RetroOptionCategory.SOUND)) + } + RetroPane.CONTROLS -> buildControlsEntries() + coreOptionEntries(RetroOptionCategory.CONTROLS) + RetroPane.HUD -> buildHudEntries() + RetroPane.SAVES -> buildSaveSlotEntries() + RetroPane.PERFORMANCE -> coreOptionEntries(RetroOptionCategory.PERFORMANCE) + RetroPane.SYSTEM -> coreOptionEntries(RetroOptionCategory.SYSTEM) + RetroPane.MEMCARDS -> emptyList() + RetroPane.NETWORK -> buildNetplayEntries() + } + + private fun coreOptionEntries(category: RetroOptionCategory): List { + val options = + RetroCoreOptions.forSystem(system) + .filter { it.category == category } + .filter { opt -> opt.isApplicable { key -> coreVars[key] ?: optionDefault(key) } } + if (options.isEmpty()) return emptyList() + + fun entryFor(option: RetroCoreOption): RetroMenuEntry { + val current = coreVars[option.key] ?: option.defaultValue + val index = option.values.indexOf(current).coerceAtLeast(0) + return RetroMenuEntry.Choice(option.labelText(this), option.valueLabels, index) { next -> + val newValue = option.values[next] + coreVars[option.key] = newValue + retroView.updateVariables(Variable(option.key, newValue)) + persistExtra(RetroShortcuts.VAR_PREFIX + option.key, newValue) + menu.rebuild() + } + } + + return (options.filterNot { it.advanced } + options.filter { it.advanced }) + .map(::entryFor) + } + + private fun optionDefault(key: String): String? = + RetroCoreOptions.forSystem(system).firstOrNull { it.key == key }?.defaultValue + + private fun buildNetplayEntries(): List { + val sysId = system?.id ?: return emptyList() + if (!RetroOnlineSupport.supportsMultiplayerUi(sysId)) return emptyList() + val phase = RetroNetplayLobby.phase + val port = + if (RetroOnlineSupport.supportsGameLink(sysId)) { + RetroGameLink.clampPort(RetroDefaults.netplayPort(this, sysId)) + } else { + RetroDefaults.netplayPort(this, sysId) + } + val name = RetroNetplayLobby.defaultPlayerName(this) + val savedHost = RetroDefaults.netplayHost(this, sysId) + val entries = mutableListOf() + + when (phase) { + RetroNetplayPhase.HOSTING, RetroNetplayPhase.CONNECTING, RetroNetplayPhase.IN_ROOM -> { + val localIp = RetroNetplayLobby.localIpv4Addresses().firstOrNull() + entries += + RetroMenuEntry.Action( + label = + when (phase) { + RetroNetplayPhase.HOSTING -> getString(R.string.retro_netplay_hosting_room) + RetroNetplayPhase.CONNECTING -> getString(R.string.retro_netplay_connecting) + else -> getString(R.string.retro_netplay_in_room) + }, + icon = RetroDrawerIcons.Group, + active = true, + subtitle = + when (phase) { + RetroNetplayPhase.HOSTING -> + if (localIp != null) { + "$localIp:$port" + } else { + getString(R.string.retro_netplay_waiting_players) + } + else -> + RetroNetplayLobby.roomTitle.ifBlank { gameName } + }, + ) {} + val members = + RetroNetplayLobby.members.ifEmpty { + listOf(RetroNetplayMember(name, isHost = RetroNetplayLobby.isHost, isLocal = true)) + } + members.forEach { member -> + val title = + buildString { + append(member.name) + if (member.isHost) append(" · Host") + if (member.isLocal) append(" · You") + if (!member.isHost && !member.isLocal) append(" · Joined") + } + entries += + RetroMenuEntry.Action( + label = title, + icon = RetroDrawerIcons.Group, + active = member.isLocal, + ) {} + } + entries += + RetroMenuEntry.Action( + label = getString(R.string.retro_netplay_leave), + icon = RetroDrawerIcons.Exit, + danger = true, + ) { + leaveNetplayRoom() + } + } + + RetroNetplayPhase.IDLE, RetroNetplayPhase.SCANNING, RetroNetplayPhase.SCAN_RESULTS -> { + if (!netplayArmedThisSession) { + entries += + RetroMenuEntry.Action( + label = getString(R.string.retro_netplay_title), + icon = RetroDrawerIcons.Group, + subtitle = getString(R.string.retro_netplay_enable_before_launch), + ) {} + return entries + } + entries += + RetroMenuEntry.Action( + label = getString(R.string.retro_netplay_title), + icon = RetroDrawerIcons.Group, + active = phase != RetroNetplayPhase.IDLE, + subtitle = + when (phase) { + RetroNetplayPhase.SCANNING -> getString(R.string.retro_netplay_scanning) + RetroNetplayPhase.SCAN_RESULTS -> + RetroNetplayLobby.statusText.ifBlank { + getString(R.string.retro_netplay_scan_results) + } + else -> + if (RetroOnlineSupport.supportsGameLink(sysId)) { + getString(R.string.retro_netplay_game_link_hint) + } else { + getString(R.string.retro_netplay_menu_hint) + } + }, + ) {} + if (phase != RetroNetplayPhase.SCANNING) { + val hostIp = RetroNetplayLobby.localIpv4Addresses().firstOrNull() + entries += + RetroMenuEntry.Action( + label = getString(R.string.retro_netplay_host_action), + icon = RetroDrawerIcons.Add, + subtitle = + if (hostIp != null) { + "${getString(R.string.retro_gs_netplay_port)} $port\n$hostIp" + } else { + "${getString(R.string.retro_gs_netplay_port)} $port" + }, + ) { + netplayLocalPort = 0 + RetroNetplayLobby.host( + systemId = sysId, + gameName = gameName, + playerName = name, + port = port, + context = this, + retroView = retroView, + ) + menu.rebuild() + } + } + entries += + RetroMenuEntry.Action( + label = + when (phase) { + RetroNetplayPhase.SCANNING -> getString(R.string.retro_netplay_stop_scan) + RetroNetplayPhase.SCAN_RESULTS -> getString(R.string.retro_netplay_scan_again) + else -> getString(R.string.retro_netplay_scan_action) + }, + icon = RetroDrawerIcons.Search, + active = phase == RetroNetplayPhase.SCANNING || phase == RetroNetplayPhase.SCAN_RESULTS, + subtitle = + when (phase) { + RetroNetplayPhase.SCANNING -> + RetroNetplayLobby.statusText.ifBlank { + getString(R.string.retro_netplay_scanning) + } + RetroNetplayPhase.SCAN_RESULTS -> + RetroNetplayLobby.statusText.ifBlank { + getString(R.string.retro_netplay_scan_results) + } + else -> getString(R.string.retro_netplay_scan_hint) + }, + ) { + if (phase == RetroNetplayPhase.SCANNING) { + RetroNetplayLobby.stopScan() + menu.rebuild() + } else { + menu.close() + RetroNetplayLobby.scan(this, sysId) + } + } + if (phase == RetroNetplayPhase.SCAN_RESULTS) { + entries += + RetroMenuEntry.Action( + label = getString(R.string.retro_netplay_dismiss), + icon = RetroDrawerIcons.Exit, + ) { + RetroNetplayLobby.dismissScanResults() + menu.rebuild() + } + } + RetroNetplayLobby.discovered.forEach { room -> + entries += + RetroMenuEntry.Action( + label = "${room.gameName} · ${room.hostPlayerName}", + icon = RetroDrawerIcons.Play, + subtitle = "${room.hostAddress}:${room.port} · ${getString(R.string.retro_netplay_join_room)}", + ) { + joinDiscoveredRoom(room) + } + } + if (phase != RetroNetplayPhase.SCANNING) { + entries += + RetroMenuEntry.Action( + label = getString(R.string.retro_netplay_join_action), + icon = RetroDrawerIcons.Link, + subtitle = + if (savedHost.isNotBlank()) { + "$savedHost:$port" + } else { + getString(R.string.retro_gs_netplay_host_hint) + }, + ) { + promptJoinByAddress(sysId, port, name, savedHost) + } + } + } + } + return entries + } + + private fun promptJoinByAddress( + sysId: String, + port: Int, + playerName: String, + initialHost: String, + ) { + menu.renamePrompt = + RetroRenamePrompt( + title = getString(R.string.retro_gs_netplay_host), + initial = initialHost, + ) { entered -> + val host = entered?.trim().orEmpty() + if (host.isBlank()) return@RetroRenamePrompt + netplayLocalPort = 1 + RetroNetplayLobby.join( + host = host, + port = port, + playerName = playerName, + gameName = gameName, + systemId = sysId, + retroView = retroView, + ) + menu.close() + menu.rebuild() + } + } + + private fun buildControlsEntries(): List = + RetroControlsMenu.build( + RetroControlsMenu.Host( + context = this, + overlay = overlay, + menu = menu, + systemId = system?.id, + touchControls = { touchControlsSetting }, + onTouchControls = { value -> + touchControlsSetting = value + if (controllerConnected) manualTouchOverride = true + updateOverlayVisibility() + syncInGameOverlayPlacement() + persistExtra(RetroShortcuts.KEY_TOUCH_CONTROLS, if (value) "1" else "0") + }, + adaptiveSticks = { adaptiveSticksSetting }, + onAdaptiveSticks = { value -> + adaptiveSticksSetting = value + persistExtra(RetroShortcuts.KEY_ADAPTIVE_STICKS, if (value) "1" else "0") + }, + orientationLabel = { + if ((rootLayout?.height ?: 0) > (rootLayout?.width ?: 0)) { + getString(R.string.retro_lr_portrait) + } else { + getString(R.string.retro_lr_landscape) + } + }, + onCloseMenu = { menu.close() }, + showStickInversion = system?.id == RetroSystems.PSX.id || RetroCoreManager.usesDolphinCore(system), + ), + ) + + private fun setHudVisible(value: Boolean) { + hudVisible = value + if (value) { + showHud() + } else { + frameRating?.visibility = View.GONE + applyDisplayGeometry() + } + RetroDefaults.setHud(this, system?.id ?: "", value) + menu.rebuild() + } + + private fun buildHudEntries(): List { + val style = + HudStyle( + alpha = hudAlpha, + bgDecoupled = hudBgDecoupled, + bgAlpha = hudBgAlpha, + scale = hudScale, + frametimeNumeric = hudFrametimeNumeric, + dualBattery = hudDualBattery, + ) + return RetroHudSupport.buildHudEntries( + context = this, + hudVisible = hudVisible, + style = style, + elements = hudElements, + onMaster = { setHudVisible(it) }, + onStyle = { next -> + hudAlpha = next.alpha + hudBgDecoupled = next.bgDecoupled + hudBgAlpha = next.bgAlpha + hudScale = next.scale + hudFrametimeNumeric = next.frametimeNumeric + hudDualBattery = next.dualBattery + frameRating?.let { RetroHudSupport.applyStyle(it, next, hudElements) } + saveHudSettings() + }, + onElements = { next -> + hudElements = next + frameRating?.let { RetroHudSupport.applyStyle(it, style, next) } + saveHudSettings() + }, + onRebuild = { menu.rebuild() }, + ) + } + + private fun buildMainEntries(): List { + val entries = mutableListOf() + val hardcoreActive = achievementsSessionStarted && RetroAchievementsManager.isHardcoreActive() + entries += + RetroMenuEntry.Action(getString(R.string.retro_lr_save_state), RetroDrawerIcons.Save) { + savesLoadMode = false + menu.showPane(RetroPane.SAVES) + } + entries += + RetroMenuEntry.Action(getString(R.string.retro_lr_load_save_state), RetroDrawerIcons.Load) { + if (hardcoreActive) { + Toast.makeText(this, getString(R.string.retro_lr_loading_states_disabled_hardcore), Toast.LENGTH_SHORT).show() + } else { + savesLoadMode = true + menu.showPane(RetroPane.SAVES) + } + } + if (RetroAchievementsManager.isLoggedIn(this) && RetroAchievementsManager.consoleId(system?.id) != 0) { + entries += + RetroMenuEntry.Action(getString(R.string.retro_lr_achievements), RetroDrawerIcons.Achievements) { + menu.close() + openAchievementsScreen() + } + } + entries += + RetroMenuEntry.Action(getString(R.string.retro_lr_cheats), RetroDrawerIcons.Cheats, active = !cheatsAllowed()) { + if (!cheatsAllowed()) { + Toast.makeText(this, getString(R.string.retro_lr_cheats_disabled_hardcore), Toast.LENGTH_SHORT).show() + } else { + menu.close() + openCheatsScreen() + } + } + entries += + RetroMenuEntry.Action(getString(R.string.retro_lr_reset), RetroDrawerIcons.Reset) { + menu.close() + retroView.reset() + RetroAchievementsManager.onEmulatorReset() + } + entries += + RetroMenuEntry.Action(getString(R.string.retro_lr_fast_forward), RetroDrawerIcons.FastForward, active = fastForward) { + if (hardcoreActive) { + Toast.makeText(this, getString(R.string.retro_lr_fast_forward_disabled_hardcore), Toast.LENGTH_SHORT).show() + } else { + fastForward = !fastForward + retroView.frameSpeed = if (fastForward) 2 else 1 + menu.rebuild() + } + } + entries += + RetroMenuEntry.Action(getString(R.string.retro_lr_hud), RetroDrawerIcons.Hud, active = hudVisible) { + setHudVisible(!hudVisible) + } + if (diskCount > 1) { + entries += + RetroMenuEntry.Action(getString(R.string.retro_lr_disc, currentDisk + 1, diskCount), RetroDrawerIcons.Disc) { + val next = (currentDisk + 1) % diskCount + lifecycleScope.launch(Dispatchers.Default) { + runCatching { retroView.changeDisk(next) } + currentDisk = next + runOnUiThread { menu.rebuild() } + } + } + } + return entries + } + + private fun buildBottomEntries(): List = + listOf( + if (emulationPaused) { + RetroMenuEntry.Action(getString(R.string.retro_lr_resume), RetroDrawerIcons.Resume, active = true) { + resumeEmulation() + menu.close() + } + } else { + RetroMenuEntry.Action(getString(R.string.retro_lr_pause), RetroDrawerIcons.Pause) { + pauseEmulation() + menu.close() + } + }, + RetroMenuEntry.Action(getString(R.string.retro_lr_exit), RetroDrawerIcons.Exit, danger = true) { finish() }, + ) + + private fun requestSixtyHzDisplayMode(): Boolean { + val display = runCatching { windowManager.defaultDisplay }.getOrNull() ?: return false + val current = runCatching { display.mode }.getOrNull() ?: return false + val rate = display.refreshRate + val multiple = Math.round(rate / 60f) + if (multiple >= 1 && kotlin.math.abs(rate - multiple * 60f) < 2f) return false + val sixtyModes = display.supportedModes.filter { abs(it.refreshRate - 60f) < 1f } + val target = + sixtyModes.firstOrNull { + it.physicalWidth == current.physicalWidth && it.physicalHeight == current.physicalHeight + } ?: sixtyModes.firstOrNull() ?: return false + val attributes = window.attributes + attributes.preferredDisplayModeId = target.modeId + window.attributes = attributes + return true + } + + private fun openMenu() { + if (!retroReady) { + return + } + overlay?.releaseAll() + menu.open() + } + + private fun mapPhysicalKey(keyCode: Int): Int = + when (keyCode) { + KeyEvent.KEYCODE_BUTTON_A -> KeyEvent.KEYCODE_BUTTON_B + KeyEvent.KEYCODE_BUTTON_B -> KeyEvent.KEYCODE_BUTTON_A + KeyEvent.KEYCODE_BUTTON_X -> KeyEvent.KEYCODE_BUTTON_Y + KeyEvent.KEYCODE_BUTTON_Y -> KeyEvent.KEYCODE_BUTTON_X + else -> keyCode + } + + private fun isGamepadSource(event: KeyEvent): Boolean { + val source = event.device?.sources ?: return false + return source and InputDevice.SOURCE_GAMEPAD == InputDevice.SOURCE_GAMEPAD || + source and InputDevice.SOURCE_JOYSTICK == InputDevice.SOURCE_JOYSTICK + } + + private val forwardedKeys = + setOf( + KeyEvent.KEYCODE_BUTTON_A, + KeyEvent.KEYCODE_BUTTON_B, + KeyEvent.KEYCODE_BUTTON_X, + KeyEvent.KEYCODE_BUTTON_Y, + KeyEvent.KEYCODE_BUTTON_L1, + KeyEvent.KEYCODE_BUTTON_R1, + KeyEvent.KEYCODE_BUTTON_L2, + KeyEvent.KEYCODE_BUTTON_R2, + KeyEvent.KEYCODE_BUTTON_THUMBL, + KeyEvent.KEYCODE_BUTTON_THUMBR, + KeyEvent.KEYCODE_BUTTON_START, + KeyEvent.KEYCODE_BUTTON_SELECT, + KeyEvent.KEYCODE_DPAD_UP, + KeyEvent.KEYCODE_DPAD_DOWN, + KeyEvent.KEYCODE_DPAD_LEFT, + KeyEvent.KEYCODE_DPAD_RIGHT, + ) + + override fun dispatchKeyEvent(event: KeyEvent): Boolean { + val keyCode = event.keyCode + if (keyCode == KeyEvent.KEYCODE_BUTTON_MODE && isGamepadSource(event)) { + if (event.action == KeyEvent.ACTION_UP) { + if (menu.visible) menu.close() else if (retroReady) openMenu() + } + return true + } + if (menu.visible && isGamepadSource(event)) { + menu.handleKey(keyCode, event.action) + return true + } + if (retroReady && isGamepadSource(event)) { + if (keyCode in forwardedKeys) { + val mapped = mapPhysicalKey(keyCode) + val port = localNetplayPort() + retroView.sendKeyEvent(event.action, mapped, port) + if (RetroNetplayLobby.activeSession()?.isRunning == true) { + RetroNetplayLobby.sendLocalKey(mapped, event.action) + } + return true + } + } + return super.dispatchKeyEvent(event) + } + + override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean { + if (menu.visible && event.source and InputDevice.SOURCE_JOYSTICK == InputDevice.SOURCE_JOYSTICK) { + val x = event.getAxisValue(MotionEvent.AXIS_HAT_X).takeIf { abs(it) > 0.5f } ?: event.getAxisValue(MotionEvent.AXIS_X) + val y = event.getAxisValue(MotionEvent.AXIS_HAT_Y).takeIf { abs(it) > 0.5f } ?: event.getAxisValue(MotionEvent.AXIS_Y) + menu.handleAxis(x, y) + return true + } + if (retroReady && + event.action == MotionEvent.ACTION_MOVE && + event.source and InputDevice.SOURCE_JOYSTICK == InputDevice.SOURCE_JOYSTICK + ) { + val hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X) + val hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y) + val stickX = if (overlay?.invertLX == true) -event.getAxisValue(MotionEvent.AXIS_X) else event.getAxisValue(MotionEvent.AXIS_X) + val stickY = if (overlay?.invertLY == true) -event.getAxisValue(MotionEvent.AXIS_Y) else event.getAxisValue(MotionEvent.AXIS_Y) + val port = localNetplayPort() + val netActive = RetroNetplayLobby.activeSession()?.isRunning == true + if (stickIsAnalog) { + retroView.sendMotionEvent(GLRetroView.MOTION_SOURCE_DPAD, hatX, hatY, port) + retroView.sendMotionEvent(GLRetroView.MOTION_SOURCE_ANALOG_LEFT, stickX, stickY, port) + if (netActive) { + RetroNetplayLobby.sendLocalMotion(GLRetroView.MOTION_SOURCE_DPAD, hatX, hatY) + RetroNetplayLobby.sendLocalMotion(GLRetroView.MOTION_SOURCE_ANALOG_LEFT, stickX, stickY) + } + } else { + val deadzone = 0.45f + val dpadX = + when { + abs(hatX) > 0.5f -> hatX + stickX > deadzone -> 1f + stickX < -deadzone -> -1f + else -> 0f + } + val dpadY = + when { + abs(hatY) > 0.5f -> hatY + stickY > deadzone -> 1f + stickY < -deadzone -> -1f + else -> 0f + } + retroView.sendMotionEvent(GLRetroView.MOTION_SOURCE_DPAD, dpadX, dpadY, port) + retroView.sendMotionEvent(GLRetroView.MOTION_SOURCE_ANALOG_LEFT, stickX, stickY, port) + if (netActive) { + RetroNetplayLobby.sendLocalMotion(GLRetroView.MOTION_SOURCE_DPAD, dpadX, dpadY) + RetroNetplayLobby.sendLocalMotion(GLRetroView.MOTION_SOURCE_ANALOG_LEFT, stickX, stickY) + } + } + val rx = if (overlay?.invertRX == true) -event.getAxisValue(MotionEvent.AXIS_Z) else event.getAxisValue(MotionEvent.AXIS_Z) + val ry = if (overlay?.invertRY == true) -event.getAxisValue(MotionEvent.AXIS_RZ) else event.getAxisValue(MotionEvent.AXIS_RZ) + retroView.sendMotionEvent(GLRetroView.MOTION_SOURCE_ANALOG_RIGHT, rx, ry, port) + if (netActive) { + RetroNetplayLobby.sendLocalMotion(GLRetroView.MOTION_SOURCE_ANALOG_RIGHT, rx, ry) + } + return true + } + return super.dispatchGenericMotionEvent(event) + } + + override fun onButton( + keyCode: Int, + down: Boolean, + ) { + if (!retroReady || menu.visible) return + val action = if (down) KeyEvent.ACTION_DOWN else KeyEvent.ACTION_UP + val port = localNetplayPort() + retroView.sendKeyEvent(action, keyCode, port) + if (RetroNetplayLobby.activeSession()?.isRunning == true) { + RetroNetplayLobby.sendLocalKey(keyCode, action) + } + } + + override fun onDpad( + x: Float, + y: Float, + ) { + if (!retroReady || menu.visible) return + val port = localNetplayPort() + retroView.sendMotionEvent(GLRetroView.MOTION_SOURCE_DPAD, x, y, port) + if (RetroNetplayLobby.activeSession()?.isRunning == true) { + RetroNetplayLobby.sendLocalMotion(GLRetroView.MOTION_SOURCE_DPAD, x, y) + } + } + + override fun onStick( + x: Float, + y: Float, + ) { + if (!retroReady || menu.visible) return + val port = localNetplayPort() + retroView.sendMotionEvent(GLRetroView.MOTION_SOURCE_ANALOG_LEFT, x, y, port) + if (RetroNetplayLobby.activeSession()?.isRunning == true) { + RetroNetplayLobby.sendLocalMotion(GLRetroView.MOTION_SOURCE_ANALOG_LEFT, x, y) + } + } + + override fun onRightStick( + x: Float, + y: Float, + ) { + if (!retroReady || menu.visible) return + val port = localNetplayPort() + retroView.sendMotionEvent(GLRetroView.MOTION_SOURCE_ANALOG_RIGHT, x, y, port) + if (RetroNetplayLobby.activeSession()?.isRunning == true) { + RetroNetplayLobby.sendLocalMotion(GLRetroView.MOTION_SOURCE_ANALOG_RIGHT, x, y) + } + } + + override fun onMenu() { + runOnUiThread { openMenu() } + } + + private fun saveState(slot: Int) { + runCatching { + val bytes = retroView.serializeState() + check(RetroSaveStates.writeSlot(this, gameName, slot, bytes)) + }.onSuccess { + showInGameMessage(getString(R.string.retro_lr_saved_to_slot, slot)) + launchExitCloudBackup() + }.onFailure { + showInGameMessage(getString(R.string.retro_lr_could_not_save_state)) + } + } + + private fun showBiosRequiredDialog(system: RetroSystem) { + androidx.appcompat.app.AlertDialog.Builder(this) + .setTitle(getString(R.string.retro_lr_bios_required_title, system.shortName)) + .setMessage(getString(R.string.retro_lr_bios_required_message)) + .setCancelable(false) + .setPositiveButton(getString(R.string.retro_lr_import_bios)) { _, _ -> + runCatching { biosPicker.launch(arrayOf("*/*")) } + .onFailure { finish() } + } + .setNegativeButton(getString(R.string.retro_lr_cancel)) { _, _ -> finish() } + .show() + } + + private fun openAchievementsScreen() { + val sys = system ?: return + val rom = intent.getStringExtra(EXTRA_ROM_PATH) ?: return + startActivity( + android.content.Intent(this, RetroAchievementsActivity::class.java).apply { + putExtra(RetroAchievementsActivity.EXTRA_SYSTEM_ID, sys.id) + putExtra(RetroAchievementsActivity.EXTRA_GAME_NAME, gameName) + putExtra(RetroAchievementsActivity.EXTRA_ROM_PATH, rom) + putExtra(RetroAchievementsActivity.EXTRA_IN_SESSION, true) + }, + ) + } + + private fun loadState(slot: Int) { + if (achievementsSessionStarted && RetroAchievementsManager.isHardcoreActive()) { + showInGameMessage(getString(R.string.retro_lr_loading_states_disabled_hardcore)) + return + } + val bytes = RetroSaveStates.readSlot(this, gameName, slot) + if (bytes == null) { + showInGameMessage(getString(R.string.retro_lr_slot_empty, slot)) + return + } + runCatching { check(retroView.unserializeState(bytes)) } + .onSuccess { showInGameMessage(getString(R.string.retro_lr_loaded_slot, slot)) } + .onFailure { showInGameMessage(getString(R.string.retro_lr_could_not_load_state)) } + } + + private fun buildSaveSlotEntries(): List = + RetroSaveStates.listSlots(this, gameName).map { info -> + RetroMenuEntry.SaveSlot( + slot = info.slot, + title = info.customName ?: getString(R.string.retro_lr_slot_title, info.slot), + subtitle = RetroSaveStates.relativeTime(info.timestampMs), + filled = info.exists, + onClick = { + if (savesLoadMode) { + if (info.exists) { + menu.close() + loadState(info.slot) + } + } else { + saveState(info.slot) + menu.rebuild() + } + }, + onRename = { + menu.renamePrompt = + RetroRenamePrompt( + title = getString(R.string.retro_lr_rename_slot, info.slot), + initial = info.customName ?: "", + ) { newName -> + RetroSaveStates.renameSlot(this, gameName, info.slot, newName) + menu.rebuild() + } + }, + ) + } + + private fun persistSram() { + if (!retroReady) return + runCatching { + val sram = retroView.serializeSRAM() + if (sram.isNotEmpty()) { + RetroSaveStates.sramFile(this, gameName).writeBytes(sram) + } + } + } + + override fun onPause() { + persistSram() + accumulatePlaytime() + if (isFinishing) launchExitCloudBackup() + super.onPause() + } + + override fun onResume() { + super.onResume() + if (retroReady && surfaceReady) applyCheats() + if (emulationPaused && retroReady) { + window.decorView.post { + if (emulationPaused && retroReady) { + retroView.onPause() + LibretroDroid.pause() + } + } + } + } + + override fun onWindowFocusChanged(hasFocus: Boolean) { + super.onWindowFocusChanged(hasFocus) + if (hasFocus) hideSystemBars() + } + + private fun hideSystemBars() { + val controller = WindowInsetsControllerCompat(window, window.decorView) + controller.hide(WindowInsetsCompat.Type.systemBars()) + controller.systemBarsBehavior = + WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE + window.decorView.systemUiVisibility = + View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or + View.SYSTEM_UI_FLAG_FULLSCREEN or + View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or + View.SYSTEM_UI_FLAG_LAYOUT_STABLE or + View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or + View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + } +} diff --git a/app/src/main/feature/retro/RetroBiosImport.kt b/app/src/main/feature/retro/RetroBiosImport.kt new file mode 100644 index 000000000..730b753a2 --- /dev/null +++ b/app/src/main/feature/retro/RetroBiosImport.kt @@ -0,0 +1,95 @@ +package com.winlator.cmod.feature.retro + +import android.content.Context +import android.net.Uri +import java.io.File +import java.security.MessageDigest + +object RetroBiosImport { + private val KNOWN_BIOS: Map = + mapOf( + "8dd7d5296a650fac7319bce665a6a53c" to "scph5500.bin", + "490f666e1afb15b7362b406ed1cea246" to "scph5501.bin", + "32736f17079d0b2b7024407c39bd3050" to "scph5502.bin", + "924e392ed05558ffdb115408c263dccf" to "scph1001.bin", + "1e68c231d0896b7eadcad1d7d8e76129" to "scph7001.bin", + ) + + fun importFromUri( + context: Context, + uri: Uri, + ): Result = + runCatching { + val bytes = + context.contentResolver.openInputStream(uri)?.use { it.readBytes() } + ?: throw IllegalStateException("Could not read file") + val md5 = MessageDigest.getInstance("MD5").digest(bytes).joinToString("") { "%02x".format(it) } + val canonical = + KNOWN_BIOS[md5] + ?: throw IllegalArgumentException("Not a recognized PlayStation BIOS") + val dir = RetroCoreManager.systemDir(context) + val target = File(dir, canonical) + val tmp = File(dir, "$canonical.tmp") + tmp.writeBytes(bytes) + if (!tmp.renameTo(target)) { + target.writeBytes(bytes) + tmp.delete() + } + canonical + } + + fun ps2BiosDir(context: Context): File = + File(context.getExternalFilesDir(null) ?: context.filesDir, "bios").apply { mkdirs() } + + fun installedPs2Bios(context: Context): List = + ps2BiosDir(context).listFiles().orEmpty() + .filter { it.isFile && it.length() >= 3L * 1024 * 1024 } + .map { it.name } + .sorted() + + fun deletePs1Bios(context: Context): Int { + val dir = RetroCoreManager.systemDir(context) + var removed = 0 + RetroSystems.PSX.biosFiles.forEach { val f = File(dir, it); if (f.isFile && f.delete()) removed++ } + return removed + } + + fun deletePs2Bios(context: Context): Int { + var removed = 0 + ps2BiosDir(context).listFiles().orEmpty().forEach { if (it.isFile && it.delete()) removed++ } + context.getSharedPreferences("ARMSX2", Context.MODE_PRIVATE).edit().remove("bios").apply() + return removed + } + + fun importPs2FromUri( + context: Context, + uri: Uri, + ): Result = + runCatching { + val name = + context.contentResolver.query(uri, arrayOf(android.provider.OpenableColumns.DISPLAY_NAME), null, null, null)?.use { + if (it.moveToFirst()) it.getString(0) else null + } ?: "ps2-bios.bin" + val bytes = + context.contentResolver.openInputStream(uri)?.use { it.readBytes() } + ?: throw IllegalStateException("Could not read file") + if (bytes.size !in (3 * 1024 * 1024)..(8 * 1024 * 1024)) { + throw IllegalArgumentException("Not a PS2 BIOS — expected a single merged .bin dump (3–8MB), not a split ROM0/MEC/NVM set.") + } + val head = String(bytes, 0, minOf(bytes.size, 4096), Charsets.ISO_8859_1) + if (!head.contains("PS2", true) && !head.contains("Sony", true) && !head.contains("ROMDIR", true)) { + throw IllegalArgumentException("This file doesn't look like a PS2 BIOS dump.") + } + val safe = name.ifBlank { "ps2-bios.bin" }.let { if (it.endsWith(".bin", true)) it else "$it.bin" } + val target = File(ps2BiosDir(context), safe) + val tmp = File(ps2BiosDir(context), "$safe.tmp") + tmp.writeBytes(bytes) + if (!tmp.renameTo(target)) { + target.writeBytes(bytes) + tmp.delete() + } + context.getSharedPreferences("ARMSX2", Context.MODE_PRIVATE) + .edit().putString("bios", target.absolutePath).apply() + safe + } +} diff --git a/app/src/main/feature/retro/RetroBoxart.kt b/app/src/main/feature/retro/RetroBoxart.kt new file mode 100644 index 000000000..fe3283282 --- /dev/null +++ b/app/src/main/feature/retro/RetroBoxart.kt @@ -0,0 +1,357 @@ +package com.winlator.cmod.feature.retro + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.LinearGradient +import android.graphics.Paint +import android.graphics.Path +import android.graphics.RadialGradient +import android.graphics.RectF +import android.graphics.Shader +import java.io.File +import java.net.HttpURLConnection +import java.net.URL +import java.net.URLDecoder +import java.net.URLEncoder +import java.util.Locale + +object RetroBoxart { + private const val BASE = "https://thumbnails.libretro.com" + private const val OUT_W = 920 + private const val OUT_H = 430 + private const val INDEX_TTL_MS = 7L * 24 * 3600 * 1000 + + private val FOLDERS = + mapOf( + "nes" to "Nintendo - Nintendo Entertainment System", + "snes" to "Nintendo - Super Nintendo Entertainment System", + "gb" to "Nintendo - Game Boy", + "gbc" to "Nintendo - Game Boy Color", + "gba" to "Nintendo - Game Boy Advance", + "genesis" to "Sega - Mega Drive - Genesis", + "sms" to "Sega - Master System - Mark III", + "gg" to "Sega - Game Gear", + "n64" to "Nintendo - Nintendo 64", + "psx" to "Sony - PlayStation", + "ps2" to "Sony - PlayStation 2", + "gc" to "Nintendo - GameCube", + "wii" to "Nintendo - Wii", + ) + + private data class CaseStyle( + val body: Int, + val accent: Int, + val cartAspect: Float, + val isDisc: Boolean, + val labelPortrait: Boolean, + ) + + private val STYLES = + mapOf( + "nes" to CaseStyle(0xFF9A9AA2.toInt(), 0xFF3B3B42.toInt(), 0.80f, false, true), + "snes" to CaseStyle(0xFFB6B1AB.toInt(), 0xFF8A5BA5.toInt(), 1.45f, false, false), + "gb" to CaseStyle(0xFFB9B8C2.toInt(), 0xFF4A4A55.toInt(), 1.0f, false, true), + "gbc" to CaseStyle(0xFF6E5FD8.toInt(), 0xFF2F2A66.toInt(), 1.0f, false, true), + "gba" to CaseStyle(0xFF5F58C7.toInt(), 0xFF29255C.toInt(), 1.5f, false, false), + "genesis" to CaseStyle(0xFF232329.toInt(), 0xFFC9A24A.toInt(), 0.82f, false, true), + "sms" to CaseStyle(0xFF24242C.toInt(), 0xFFD03A3A.toInt(), 0.82f, false, true), + "gg" to CaseStyle(0xFF1C1C22.toInt(), 0xFF3E7BD6.toInt(), 0.95f, false, true), + "n64" to CaseStyle(0xFF515158.toInt(), 0xFFCF3B3B.toInt(), 1.28f, false, false), + "psx" to CaseStyle(0xFFE8E8EC.toInt(), 0xFF2F2F36.toInt(), 1.0f, true, false), + "ps2" to CaseStyle(0xFF1E2C6E.toInt(), 0xFF0E1436.toInt(), 0.74f, true, true), + "gc" to CaseStyle(0xFF4A4E57.toInt(), 0xFF6B3FA0.toInt(), 0.74f, true, true), + "wii" to CaseStyle(0xFFE8E8EC.toInt(), 0xFF1BA0D8.toInt(), 0.74f, true, true), + ) + + val artVersion = androidx.compose.runtime.mutableStateOf(0) + private val working = java.util.concurrent.atomic.AtomicBoolean(false) + + fun ensureArtworkAsync(context: Context) { + if (!working.compareAndSet(false, true)) return + val app = context.applicationContext + Thread { + try { + val retro = + runCatching { + com.winlator.cmod.runtime.container.ContainerManager(app) + .loadShortcuts() + .filter { RetroShortcuts.isRetroShortcut(it) } + }.getOrDefault(emptyList()) + retro.forEach { shortcut -> + if (com.winlator.cmod.feature.shortcuts.LibraryShortcutArtwork.findIconArtworkPath(shortcut) != null) return@forEach + val existing = shortcut.getExtra("customCoverArtPath") + if (existing.isNotBlank() && File(existing).isFile) return@forEach + val system = RetroShortcuts.systemForShortcut(shortcut) ?: return@forEach + val name = shortcut.getExtra("custom_name", shortcut.name) + val uuid = com.winlator.cmod.feature.shortcuts.LibraryShortcutArtwork.ensureShortcutUuid(shortcut) + val artFile = com.winlator.cmod.feature.shortcuts.LibraryShortcutArtwork.buildManagedCustomGameArtworkFile(app, uuid) + if (fetchAndCompose(app, system, name, artFile)) { + shortcut.putExtra("customCoverArtPath", artFile.absolutePath) + shortcut.saveData() + artVersion.value++ + } + } + } finally { + working.set(false) + } + }.start() + } + + fun caseArtEnabled(context: Context): Boolean = + androidx.preference.PreferenceManager + .getDefaultSharedPreferences(context) + .getBoolean("retro_case_art", true) + + fun setCaseArtEnabled(context: Context, enabled: Boolean) { + androidx.preference.PreferenceManager + .getDefaultSharedPreferences(context) + .edit().putBoolean("retro_case_art", enabled).apply() + } + + fun fetchAndCompose(context: Context, system: RetroSystem, gameName: String, outFile: File): Boolean = + runCatching { + val boxart = fetchBoxart(context, system, gameName) + val bmp = compose(context, system, gameName, boxart) + outFile.parentFile?.mkdirs() + outFile.outputStream().use { bmp.compress(Bitmap.CompressFormat.PNG, 95, it) } + bmp.recycle() + boxart?.recycle() + outFile.isFile + }.getOrDefault(false) + + fun composeCustom(context: Context, system: RetroSystem, gameName: String, source: Bitmap, outFile: File): Boolean = + runCatching { + val bmp = compose(context, system, gameName, source) + outFile.parentFile?.mkdirs() + outFile.outputStream().use { bmp.compress(Bitmap.CompressFormat.PNG, 95, it) } + bmp.recycle() + outFile.isFile + }.getOrDefault(false) + + private fun fetchBoxart(context: Context, system: RetroSystem, gameName: String): Bitmap? { + val folder = FOLDERS[system.id] ?: return null + val names = index(context, system.id, folder) ?: return null + val match = bestMatch(gameName, names) ?: return null + val url = "$BASE/${encodePath(folder)}/Named_Boxarts/${encodePath(match)}" + return download(url) + } + + private fun index(context: Context, sysId: String, folder: String): List? { + val cache = File(File(context.filesDir, "retro/boxart_index"), "$sysId.txt") + if (cache.isFile && System.currentTimeMillis() - cache.lastModified() < INDEX_TTL_MS) { + return cache.readLines().filter { it.isNotBlank() } + } + val html = + runCatching { + val conn = URL("$BASE/${encodePath(folder)}/Named_Boxarts/").openConnection() as HttpURLConnection + conn.connectTimeout = 12000 + conn.readTimeout = 30000 + conn.inputStream.bufferedReader().use { it.readText() } + }.getOrNull() ?: return if (cache.isFile) cache.readLines().filter { it.isNotBlank() } else null + val names = + Regex("href=\"([^\"?]+\\.png)\"").findAll(html) + .map { URLDecoder.decode(it.groupValues[1], "UTF-8") } + .filter { !it.startsWith("/") } + .toList() + if (names.isEmpty()) return null + cache.parentFile?.mkdirs() + cache.writeText(names.joinToString("\n")) + return names + } + + private fun normalize(name: String): String = + name.substringBeforeLast('.') + .replace(Regex("[\\(\\[][^\\)\\]]*[\\)\\]]"), " ") + .lowercase(Locale.US) + .replace(Regex("[^a-z0-9]+"), " ") + .trim() + + private fun bestMatch(gameName: String, names: List): String? { + val target = normalize(gameName) + if (target.isBlank()) return null + val byNorm = LinkedHashMap>() + names.forEach { byNorm.getOrPut(normalize(it)) { ArrayList() }.add(it) } + val exact = byNorm[target] + if (exact != null) return preferRegion(exact) + val targetTokens = target.split(' ').toSet() + var best: String? = null + var bestScore = 0f + byNorm.forEach { (norm, files) -> + val tokens = norm.split(' ').toSet() + val overlap = (targetTokens intersect tokens).size.toFloat() + if (overlap == 0f) return@forEach + val score = overlap * 2f / (targetTokens.size + tokens.size) + val boosted = if (norm.startsWith(target) || target.startsWith(norm)) score + 0.3f else score + if (boosted > bestScore) { + bestScore = boosted + best = preferRegion(files) + } + } + return if (bestScore >= 0.6f) best else null + } + + private fun preferRegion(files: List): String = + files.firstOrNull { it.contains("(USA", true) } + ?: files.firstOrNull { it.contains("(World", true) } + ?: files.firstOrNull { it.contains("(Europe", true) } + ?: files.first() + + private fun download(url: String): Bitmap? = + runCatching { + val conn = URL(url).openConnection() as HttpURLConnection + conn.connectTimeout = 12000 + conn.readTimeout = 30000 + conn.inputStream.use { BitmapFactory.decodeStream(it) } + }.getOrNull() + + private fun encodePath(segment: String): String = + URLEncoder.encode(segment, "UTF-8").replace("+", "%20") + + private fun compose(context: Context, system: RetroSystem, gameName: String, boxart: Bitmap?): Bitmap { + val style = STYLES[system.id] ?: STYLES.getValue("nes") + val out = Bitmap.createBitmap(OUT_W, OUT_H, Bitmap.Config.ARGB_8888) + val c = Canvas(out) + val p = Paint(Paint.ANTI_ALIAS_FLAG) + + p.shader = LinearGradient(0f, 0f, 0f, OUT_H.toFloat(), 0xFF16161E.toInt(), 0xFF0B0B10.toInt(), Shader.TileMode.CLAMP) + c.drawRect(0f, 0f, OUT_W.toFloat(), OUT_H.toFloat(), p) + p.shader = RadialGradient(OUT_W * 0.5f, OUT_H * 0.42f, OUT_W * 0.5f, 0x2AFFFFFF, 0x00000000, Shader.TileMode.CLAMP) + c.drawRect(0f, 0f, OUT_W.toFloat(), OUT_H.toFloat(), p) + p.shader = null + + if (!caseArtEnabled(context) && boxart != null) { + drawFitted(c, boxart, RectF(0f, 0f, OUT_W.toFloat(), OUT_H.toFloat()), 24f, 0.94f) + return out + } + + val caseH = OUT_H * 0.86f + val caseW = (caseH * style.cartAspect).coerceAtMost(OUT_W * 0.62f) + val cx = OUT_W * 0.5f + val top = (OUT_H - caseH) * 0.5f + val body = RectF(cx - caseW / 2f, top, cx + caseW / 2f, top + caseH) + val corner = if (style.isDisc) 14f else 22f + + p.color = 0x66000000 + c.drawRoundRect(RectF(body.left + 8f, body.top + 12f, body.right + 8f, body.bottom + 12f), corner, corner, p) + + p.shader = LinearGradient(body.left, body.top, body.left, body.bottom, lighten(style.body, 0.14f), darken(style.body, 0.18f), Shader.TileMode.CLAMP) + c.drawRoundRect(body, corner, corner, p) + p.shader = null + p.style = Paint.Style.STROKE + p.strokeWidth = 3f + p.color = darken(style.body, 0.4f) + c.drawRoundRect(body, corner, corner, p) + p.style = Paint.Style.FILL + + val label: RectF + if (style.isDisc) { + val spineW = body.width() * 0.085f + p.color = style.accent + c.drawRoundRect(RectF(body.left, body.top, body.left + spineW + corner, body.bottom), corner, corner, p) + c.drawRect(RectF(body.left + spineW, body.top, body.left + spineW + corner, body.bottom), p) + label = RectF(body.left + spineW + 10f, body.top + 10f, body.right - 10f, body.bottom - 10f) + p.color = 0x30FFFFFF + c.drawRect(RectF(body.left + spineW + 4f, body.top, body.left + spineW + 8f, body.bottom), p) + } else { + p.color = darken(style.body, 0.28f) + val grooveTop = body.top + body.height() * 0.055f + for (i in 0 until 3) { + val y = grooveTop + i * body.height() * 0.028f + c.drawRoundRect(RectF(body.left + body.width() * 0.12f, y, body.right - body.width() * 0.12f, y + body.height() * 0.012f), 4f, 4f, p) + } + val inset = body.width() * 0.10f + val labelTop = body.top + body.height() * 0.17f + val labelBottom = body.bottom - body.height() * 0.09f + label = RectF(body.left + inset, labelTop, body.right - inset, labelBottom) + p.color = darken(style.body, 0.35f) + c.drawRoundRect(RectF(label.left - 5f, label.top - 5f, label.right + 5f, label.bottom + 5f), 10f, 10f, p) + } + + if (boxart != null) { + drawFitted(c, boxart, label, 8f, 1f) + } else { + p.shader = LinearGradient(label.left, label.top, label.left, label.bottom, lighten(style.accent, 0.18f), darken(style.accent, 0.25f), Shader.TileMode.CLAMP) + c.drawRoundRect(label, 8f, 8f, p) + p.shader = null + drawTitle(c, gameName, system.shortName, label) + } + + p.shader = LinearGradient(body.left, body.top, body.left, body.top + body.height() * 0.20f, 0x33FFFFFF, 0x00FFFFFF, Shader.TileMode.CLAMP) + c.drawRoundRect(RectF(body.left, body.top, body.right, body.top + body.height() * 0.22f), corner, corner, p) + p.shader = null + return out + } + + private fun drawFitted(c: Canvas, bmp: Bitmap, area: RectF, radius: Float, maxFill: Float) { + val scale = minOf(area.width() * maxFill / bmp.width, area.height() * maxFill / bmp.height) + val w = bmp.width * scale + val h = bmp.height * scale + val dst = RectF(area.centerX() - w / 2f, area.centerY() - h / 2f, area.centerX() + w / 2f, area.centerY() + h / 2f) + val p = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG) + val path = Path().apply { addRoundRect(dst, radius, radius, Path.Direction.CW) } + c.save() + c.clipPath(path) + c.drawBitmap(bmp, null, dst, p) + c.restore() + } + + private fun drawTitle(c: Canvas, gameName: String, shortName: String, area: RectF) { + val p = Paint(Paint.ANTI_ALIAS_FLAG) + p.color = Color.WHITE + p.textAlign = Paint.Align.CENTER + p.isFakeBoldText = true + var size = area.height() * 0.16f + p.textSize = size + val words = gameName.trim().split(Regex("\\s+")) + var lines = wrap(words, p, area.width() * 0.88f) + while (lines.size > 3 && size > area.height() * 0.09f) { + size *= 0.88f + p.textSize = size + lines = wrap(words, p, area.width() * 0.88f) + } + if (lines.size > 3) lines = lines.take(3) + val lineH = p.textSize * 1.18f + var y = area.centerY() - (lines.size - 1) * lineH / 2f + p.textSize * 0.35f + lines.forEach { + c.drawText(it, area.centerX(), y, p) + y += lineH + } + p.isFakeBoldText = false + p.textSize = area.height() * 0.08f + p.color = 0xB3FFFFFF.toInt() + c.drawText(shortName.uppercase(Locale.US), area.centerX(), area.bottom - area.height() * 0.06f, p) + } + + private fun wrap(words: List, p: Paint, maxW: Float): List { + val lines = ArrayList() + var line = StringBuilder() + words.forEach { w -> + val candidate = if (line.isEmpty()) w else "$line $w" + if (p.measureText(candidate) <= maxW || line.isEmpty()) { + line = StringBuilder(candidate) + } else { + lines.add(line.toString()) + line = StringBuilder(w) + } + } + if (line.isNotEmpty()) lines.add(line.toString()) + return lines + } + + private fun mix(a: Int, b: Int, f: Float): Int { + val inv = 1f - f + return Color.argb( + 255, + (Color.red(a) * inv + Color.red(b) * f).toInt(), + (Color.green(a) * inv + Color.green(b) * f).toInt(), + (Color.blue(a) * inv + Color.blue(b) * f).toInt(), + ) + } + + private fun lighten(color: Int, f: Float) = mix(color, Color.WHITE, f) + + private fun darken(color: Int, f: Float) = mix(color, Color.BLACK, f) +} diff --git a/app/src/main/feature/retro/RetroBundle.kt b/app/src/main/feature/retro/RetroBundle.kt new file mode 100644 index 000000000..20eba52f4 --- /dev/null +++ b/app/src/main/feature/retro/RetroBundle.kt @@ -0,0 +1,179 @@ +package com.winlator.cmod.feature.retro + +import android.content.Context +import android.widget.Toast +import com.winlator.cmod.R +import com.winlator.cmod.shared.io.TarCompressorUtils +import java.io.File +import java.net.HttpURLConnection +import java.net.URL +import java.security.MessageDigest +import org.json.JSONObject + +object RetroBundle { + private const val BASE = "https://github.com/WinNative-Emu/Retro-Consoles/releases/latest/download" + private const val ARCHIVE = "retro-consoles.tzst" + private const val INFO = "bundle-info.json" + + fun root(context: Context): File = File(context.filesDir, "retro/bundle") + + fun coresDir(context: Context): File = File(root(context), "cores") + + fun dataDir(context: Context): File = File(root(context), "data") + + data class Version( + val tag: String, + val buildDate: String, + val sha256: String, + val size: Long, + ) { + val day: String get() = buildDate.substringBefore('T') + + fun toJson(): String = + JSONObject() + .put("tag", tag) + .put("buildDate", buildDate) + .put("sha256", sha256) + .put("size", size) + .toString() + + companion object { + fun parse(json: String): Version { + val o = JSONObject(json) + return Version( + tag = o.getString("tag"), + buildDate = o.getString("buildDate"), + sha256 = o.getString("sha256").lowercase(), + size = o.getLong("size"), + ) + } + } + } + + private fun marker(context: Context): File = File(root(context), ".installed") + + fun isInstalled(context: Context): Boolean = installed(context) != null + + fun requireInstalled(context: Context): Boolean { + if (isInstalled(context)) return true + Toast.makeText(context, context.getString(R.string.retro_bundle_required), Toast.LENGTH_LONG).show() + return false + } + + fun installed(context: Context): Version? = + runCatching { Version.parse(marker(context).readText()) }.getOrNull() + + fun published(): Result = runCatching { Version.parse(fetchText("$BASE/$INFO")) } + + sealed class Progress { + data class Downloading(val bytes: Long, val total: Long) : Progress() + + data object Verifying : Progress() + + data object Extracting : Progress() + } + + fun install( + context: Context, + version: Version, + onProgress: (Progress) -> Unit = {}, + ): Result = + runCatching { + val work = File(context.cacheDir, "retro-bundle").apply { deleteRecursively(); mkdirs() } + val archive = File(work, ARCHIVE) + + download("$BASE/$ARCHIVE", archive) { got, total -> + onProgress(Progress.Downloading(got, if (total > 0) total else version.size)) + } + + onProgress(Progress.Verifying) + val actual = sha256(archive) + if (!actual.equals(version.sha256, ignoreCase = true)) { + throw IllegalStateException("Bundle checksum mismatch: expected ${version.sha256}, got $actual") + } + + onProgress(Progress.Extracting) + val staging = File(work, "stage").apply { mkdirs() } + val ok = + TarCompressorUtils + .extractAsync(TarCompressorUtils.Type.ZSTD, archive, staging) + .get() + if (ok != true) throw IllegalStateException("Bundle extraction failed") + + val destination = root(context) + destination.deleteRecursively() + destination.parentFile?.mkdirs() + if (!staging.renameTo(destination)) { + staging.copyRecursively(destination, overwrite = true) + staging.deleteRecursively() + } + marker(context).writeText(version.toJson()) + work.deleteRecursively() + version + } + + fun uninstall(context: Context) { + root(context).deleteRecursively() + } + + private fun open(url: String): HttpURLConnection = + (URL(url).openConnection() as HttpURLConnection).apply { + connectTimeout = 15000 + readTimeout = 60000 + instanceFollowRedirects = true + } + + private fun fetchText(url: String): String = + open(url).let { c -> + try { + c.inputStream.bufferedReader().use { it.readText() } + } finally { + c.disconnect() + } + } + + private fun download( + url: String, + target: File, + onProgress: (Long, Long) -> Unit, + ) { + val connection = open(url) + try { + val total = connection.contentLengthLong + target.parentFile?.mkdirs() + connection.inputStream.use { input -> + target.outputStream().use { output -> + val buffer = ByteArray(1 shl 16) + var got = 0L + var lastReport = 0L + while (true) { + val read = input.read(buffer) + if (read < 0) break + output.write(buffer, 0, read) + got += read + if (got - lastReport >= 1L shl 20) { + lastReport = got + onProgress(got, total) + } + } + onProgress(got, total) + } + } + } finally { + connection.disconnect() + } + } + + private fun sha256(file: File): String { + val digest = MessageDigest.getInstance("SHA-256") + file.inputStream().use { input -> + val buffer = ByteArray(1 shl 16) + while (true) { + val read = input.read(buffer) + if (read < 0) break + digest.update(buffer, 0, read) + } + } + return digest.digest().joinToString("") { "%02x".format(it) } + } +} diff --git a/app/src/main/feature/retro/RetroCheats.kt b/app/src/main/feature/retro/RetroCheats.kt new file mode 100644 index 000000000..97e15e8e6 --- /dev/null +++ b/app/src/main/feature/retro/RetroCheats.kt @@ -0,0 +1,72 @@ +package com.winlator.cmod.feature.retro + +import android.content.Context +import androidx.preference.PreferenceManager +import org.json.JSONArray +import org.json.JSONObject + +data class RetroCheat( + val name: String, + val code: String, + val enabled: Boolean, +) + +object RetroCheats { + private fun prefs(context: Context) = PreferenceManager.getDefaultSharedPreferences(context) + + private fun safeName(gameName: String): String = gameName.replace(Regex("[^A-Za-z0-9._-]"), "_") + + private fun key(gameName: String) = "retro_cheats_${safeName(gameName)}" + + fun load( + context: Context, + gameName: String, + ): List { + val raw = prefs(context).getString(key(gameName), null) ?: return emptyList() + return runCatching { + val arr = JSONArray(raw) + (0 until arr.length()).map { i -> + val o = arr.getJSONObject(i) + RetroCheat( + name = o.optString("name"), + code = o.optString("code"), + enabled = o.optBoolean("enabled", false), + ) + } + }.getOrDefault(emptyList()) + } + + fun save( + context: Context, + gameName: String, + cheats: List, + ) { + val arr = JSONArray() + cheats.forEach { c -> + arr.put( + JSONObject() + .put("name", c.name) + .put("code", c.code) + .put("enabled", c.enabled), + ) + } + prefs(context).edit().putString(key(gameName), arr.toString()).apply() + } + + fun hasEnabled( + context: Context, + gameName: String, + ): Boolean = load(context, gameName).any { it.enabled } + + fun formatHint(systemId: String?): String = + when (systemId) { + RetroSystems.NES.id -> "Game Genie or raw codes (e.g. SXIOPO)" + RetroSystems.SNES.id -> "Game Genie or Pro Action Replay codes" + RetroSystems.GAMEBOY.id, RetroSystems.GAMEBOY_COLOR.id -> "Game Genie or GameShark codes" + RetroSystems.GBA.id -> "GameShark, Action Replay or Code Breaker codes" + RetroSystems.GENESIS.id, RetroSystems.MASTER_SYSTEM.id, RetroSystems.GAME_GEAR.id -> "Game Genie or raw codes" + RetroSystems.N64.id -> "GameShark codes (8-digit address + value)" + RetroSystems.PSX.id -> "GameShark codes (8-digit address + value)" + else -> "Cheat code" + } +} diff --git a/app/src/main/feature/retro/RetroCheatsActivity.kt b/app/src/main/feature/retro/RetroCheatsActivity.kt new file mode 100644 index 000000000..489de1ded --- /dev/null +++ b/app/src/main/feature/retro/RetroCheatsActivity.kt @@ -0,0 +1,359 @@ +package com.winlator.cmod.feature.retro + +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.systemBars +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Add +import androidx.compose.material.icons.outlined.Close +import androidx.compose.material.icons.outlined.Delete +import androidx.compose.material.icons.outlined.VideogameAsset +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.OutlinedTextFieldDefaults +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.SwitchDefaults +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.KeyboardCapitalization +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.winlator.cmod.R +import com.winlator.cmod.shared.ui.nav.LocalPaneNav +import com.winlator.cmod.shared.ui.nav.PaneNavRegistry +import com.winlator.cmod.shared.ui.nav.bindPaneNav +import com.winlator.cmod.shared.ui.nav.paneNavItem + +private val BgDark = Color(0xFF12121B) +private val SurfaceDark = Color(0xFF171722) +private val CardBorder = Color(0xFF2A2A3A) +private val Accent = Color(0xFF1A9FFF) +private val TextPrimary = Color(0xFFF0F4FF) +private val TextSecondary = Color(0xFF93A6BC) +private val Danger = Color(0xFFE07B6B) +private val ScrimColor = Color(0xFF000000) + +class RetroCheatsActivity : ComponentActivity() { + companion object { + const val EXTRA_SYSTEM_ID = "system_id" + const val EXTRA_GAME_NAME = "game_name" + } + + private val navRegistry = PaneNavRegistry() + private var restoreNav: (() -> Unit)? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + androidx.core.view.WindowCompat.setDecorFitsSystemWindows(window, false) + val controller = androidx.core.view.WindowInsetsControllerCompat(window, window.decorView) + controller.hide(androidx.core.view.WindowInsetsCompat.Type.systemBars()) + controller.systemBarsBehavior = + androidx.core.view.WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE + val systemId = intent.getStringExtra(EXTRA_SYSTEM_ID) + val gameName = intent.getStringExtra(EXTRA_GAME_NAME) ?: "Retro Game" + setContent { + com.winlator.cmod.shared.theme.WinNativeTheme { + CompositionLocalProvider(LocalPaneNav provides navRegistry) { + RetroCheatsScreen(systemId, gameName) { finish() } + } + } + } + } + + override fun onResume() { + super.onResume() + restoreNav = window.bindPaneNav(navRegistry, onDismiss = { finish() }) + } + + override fun onPause() { + restoreNav?.invoke() + restoreNav = null + super.onPause() + } +} + +@Composable +private fun RetroCheatsScreen( + systemId: String?, + gameName: String, + onClose: () -> Unit, +) { + val context = LocalContext.current + var cheats by remember { mutableStateOf(RetroCheats.load(context, gameName)) } + var editing by remember { mutableStateOf(false) } + var editIndex by remember { mutableStateOf(-1) } + var draftName by remember { mutableStateOf("") } + var draftCode by remember { mutableStateOf("") } + + fun persist(next: List) { + cheats = next + RetroCheats.save(context, gameName, next) + } + + BoxWithConstraints( + modifier = + Modifier + .fillMaxSize() + .background(ScrimColor.copy(alpha = 0.62f)) + .windowInsetsPadding(WindowInsets.systemBars), + contentAlignment = Alignment.Center, + ) { + val dialogWidth = (maxWidth - 32.dp).coerceAtMost(560.dp) + val dialogHeight = (maxHeight - 40.dp).coerceIn(340.dp, 680.dp) + Surface( + modifier = Modifier.widthIn(min = 320.dp, max = dialogWidth).fillMaxWidth().height(dialogHeight), + shape = RoundedCornerShape(16.dp), + color = BgDark, + border = BorderStroke(1.dp, CardBorder), + tonalElevation = 8.dp, + ) { + Column(Modifier.fillMaxSize()) { + Row( + modifier = Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp, top = 12.dp, bottom = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Box( + Modifier.size(38.dp).background(Accent.copy(alpha = 0.16f), RoundedCornerShape(10.dp)), + contentAlignment = Alignment.Center, + ) { + Icon(Icons.Outlined.VideogameAsset, contentDescription = null, tint = Accent, modifier = Modifier.size(22.dp)) + } + Column(Modifier.weight(1f)) { + Text(stringResource(R.string.retro_che_brand), color = TextSecondary, fontSize = 9.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.sp) + Text( + gameName, + style = MaterialTheme.typography.titleMedium, + color = TextPrimary, + fontWeight = FontWeight.Bold, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + IconButton(onClick = onClose, modifier = Modifier.size(40.dp).paneNavItem(onActivate = onClose)) { + Icon(Icons.Outlined.Close, contentDescription = "Close", tint = TextSecondary, modifier = Modifier.size(22.dp)) + } + } + Box(Modifier.fillMaxWidth().height(1.dp).background(CardBorder)) + + Column( + Modifier.fillMaxWidth().weight(1f).verticalScroll(rememberScrollState()).padding(16.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + if (editing) { + val fieldColors = + OutlinedTextFieldDefaults.colors( + focusedTextColor = TextPrimary, + unfocusedTextColor = TextPrimary, + cursorColor = Accent, + focusedBorderColor = Accent, + unfocusedBorderColor = CardBorder, + focusedLabelColor = Accent, + unfocusedLabelColor = TextSecondary, + focusedContainerColor = SurfaceDark, + unfocusedContainerColor = SurfaceDark, + ) + OutlinedTextField( + value = draftName, + onValueChange = { draftName = it }, + label = { Text(stringResource(R.string.retro_che_name)) }, + singleLine = true, + colors = fieldColors, + modifier = Modifier.fillMaxWidth(), + ) + OutlinedTextField( + value = draftCode, + onValueChange = { draftCode = it }, + label = { Text(stringResource(R.string.retro_che_code)) }, + colors = fieldColors, + keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Characters), + modifier = Modifier.fillMaxWidth(), + ) + Text( + RetroCheats.formatHint(systemId), + color = TextSecondary, + style = MaterialTheme.typography.labelSmall, + ) + Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) { + Button( + onClick = { editing = false }, + colors = ButtonDefaults.buttonColors(containerColor = SurfaceDark, contentColor = TextPrimary), + modifier = Modifier.weight(1f).paneNavItem(onActivate = { editing = false }), + ) { Text(stringResource(R.string.retro_che_cancel)) } + Button( + onClick = { + val name = draftName.ifBlank { context.getString(R.string.retro_che_default_name, cheats.size + 1) } + val code = draftCode.trim() + if (code.isNotEmpty()) { + val entry = RetroCheat(name, code, true) + val next = + if (editIndex >= 0 && editIndex < cheats.size) { + cheats.toMutableList().also { it[editIndex] = entry } + } else { + cheats + entry + } + persist(next) + } + editing = false + }, + colors = ButtonDefaults.buttonColors(containerColor = Accent, contentColor = Color.White), + modifier = + Modifier.weight(1f).paneNavItem(onActivate = { + val code = draftCode.trim() + if (code.isNotEmpty()) { + val entry = RetroCheat(draftName.ifBlank { context.getString(R.string.retro_che_default_name, cheats.size + 1) }, code, true) + val next = + if (editIndex >= 0 && editIndex < cheats.size) { + cheats.toMutableList().also { it[editIndex] = entry } + } else { + cheats + entry + } + persist(next) + } + editing = false + }), + ) { Text(stringResource(R.string.retro_che_save)) } + } + } else { + if (cheats.isEmpty()) { + Text( + stringResource(R.string.retro_che_empty), + color = TextSecondary, + style = MaterialTheme.typography.bodyMedium, + modifier = Modifier.padding(vertical = 8.dp), + ) + } + cheats.forEachIndexed { index, cheat -> + CheatRow( + cheat = cheat, + onToggle = { + persist(cheats.toMutableList().also { it[index] = cheat.copy(enabled = !cheat.enabled) }) + }, + onEdit = { + editIndex = index + draftName = cheat.name + draftCode = cheat.code + editing = true + }, + onDelete = { + persist(cheats.toMutableList().also { it.removeAt(index) }) + }, + ) + } + Button( + onClick = { + editIndex = -1 + draftName = "" + draftCode = "" + editing = true + }, + colors = ButtonDefaults.buttonColors(containerColor = Accent, contentColor = Color.White), + modifier = + Modifier.fillMaxWidth().padding(top = 4.dp).paneNavItem(isEntry = true, onActivate = { + editIndex = -1 + draftName = "" + draftCode = "" + editing = true + }), + ) { + Icon(Icons.Outlined.Add, contentDescription = null, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(8.dp)) + Text(stringResource(R.string.retro_che_add)) + } + } + } + } + } + } +} + +@Composable +private fun CheatRow( + cheat: RetroCheat, + onToggle: () -> Unit, + onEdit: () -> Unit, + onDelete: () -> Unit, +) { + Surface( + shape = RoundedCornerShape(12.dp), + color = SurfaceDark.copy(alpha = 0.5f), + border = BorderStroke(1.dp, CardBorder), + modifier = Modifier.fillMaxWidth().paneNavItem(cornerRadius = 12.dp, onActivate = onToggle, onSecondary = onDelete), + ) { + Row(Modifier.padding(horizontal = 12.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f)) { + Text( + cheat.name, + color = TextPrimary, + fontWeight = FontWeight.SemiBold, + style = MaterialTheme.typography.bodyMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text( + cheat.code, + color = TextSecondary, + style = MaterialTheme.typography.labelSmall, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + IconButton(onClick = onEdit, modifier = Modifier.size(36.dp)) { + Icon(Icons.Outlined.VideogameAsset, contentDescription = "Edit", tint = TextSecondary, modifier = Modifier.size(16.dp)) + } + IconButton(onClick = onDelete, modifier = Modifier.size(36.dp).paneNavItem(onActivate = onDelete)) { + Icon(Icons.Outlined.Delete, contentDescription = "Delete", tint = Danger, modifier = Modifier.size(18.dp)) + } + Switch( + checked = cheat.enabled, + onCheckedChange = { onToggle() }, + colors = + SwitchDefaults.colors( + checkedThumbColor = Color.White, + checkedTrackColor = Accent, + uncheckedTrackColor = SurfaceDark, + uncheckedBorderColor = CardBorder, + ), + ) + } + } +} diff --git a/app/src/main/feature/retro/RetroControlLayouts.kt b/app/src/main/feature/retro/RetroControlLayouts.kt new file mode 100644 index 000000000..b24209f46 --- /dev/null +++ b/app/src/main/feature/retro/RetroControlLayouts.kt @@ -0,0 +1,133 @@ +package com.winlator.cmod.feature.retro + +import android.content.Context +import androidx.preference.PreferenceManager +import org.json.JSONObject + +data class RetroControlOverride( + var x: Float, + var y: Float, + var scale: Float = 1f, + var visible: Boolean = true, +) + +data class RetroCustomColors( + var body: Int? = null, + var button: Int? = null, + var text: Int? = null, + var shadow: Int? = null, +) + +object RetroControlLayouts { + private fun layoutKey( + systemId: String, + portrait: Boolean, + ) = "retro_layout_v1_${systemId}_${if (portrait) "port" else "land"}" + + private fun colorsKey(systemId: String) = "retro_colors_v1_$systemId" + + fun load( + context: Context, + systemId: String?, + portrait: Boolean, + ): MutableMap { + val result = mutableMapOf() + if (systemId == null) return result + val json = + PreferenceManager + .getDefaultSharedPreferences(context) + .getString(layoutKey(systemId, portrait), null) ?: return result + runCatching { + val obj = JSONObject(json) + obj.keys().forEach { id -> + val c = obj.getJSONObject(id) + result[id] = + RetroControlOverride( + c.optDouble("x", 0.5).toFloat(), + c.optDouble("y", 0.5).toFloat(), + c.optDouble("s", 1.0).toFloat(), + c.optBoolean("v", true), + ) + } + } + return result + } + + fun save( + context: Context, + systemId: String?, + portrait: Boolean, + map: Map, + ) { + if (systemId == null) return + val prefs = PreferenceManager.getDefaultSharedPreferences(context) + if (map.isEmpty()) { + prefs.edit().remove(layoutKey(systemId, portrait)).apply() + return + } + val obj = JSONObject() + map.forEach { (id, o) -> + obj.put( + id, + JSONObject() + .put("x", o.x.toDouble()) + .put("y", o.y.toDouble()) + .put("s", o.scale.toDouble()) + .put("v", o.visible), + ) + } + prefs.edit().putString(layoutKey(systemId, portrait), obj.toString()).apply() + } + + fun reset( + context: Context, + systemId: String?, + portrait: Boolean, + ) { + if (systemId == null) return + PreferenceManager + .getDefaultSharedPreferences(context) + .edit() + .remove(layoutKey(systemId, portrait)) + .apply() + } + + fun loadColors( + context: Context, + systemId: String?, + ): RetroCustomColors { + val colors = RetroCustomColors() + if (systemId == null) return colors + val json = + PreferenceManager + .getDefaultSharedPreferences(context) + .getString(colorsKey(systemId), null) ?: return colors + runCatching { + val obj = JSONObject(json) + if (obj.has("body")) colors.body = obj.getInt("body") + if (obj.has("button")) colors.button = obj.getInt("button") + if (obj.has("text")) colors.text = obj.getInt("text") + if (obj.has("shadow")) colors.shadow = obj.getInt("shadow") + } + return colors + } + + fun saveColors( + context: Context, + systemId: String?, + colors: RetroCustomColors, + ) { + if (systemId == null) return + val prefs = PreferenceManager.getDefaultSharedPreferences(context) + if (colors.body == null && colors.button == null && colors.text == null && colors.shadow == null) { + prefs.edit().remove(colorsKey(systemId)).apply() + return + } + val obj = JSONObject() + colors.body?.let { obj.put("body", it) } + colors.button?.let { obj.put("button", it) } + colors.text?.let { obj.put("text", it) } + colors.shadow?.let { obj.put("shadow", it) } + prefs.edit().putString(colorsKey(systemId), obj.toString()).apply() + } +} diff --git a/app/src/main/feature/retro/RetroControlsMenu.kt b/app/src/main/feature/retro/RetroControlsMenu.kt new file mode 100644 index 000000000..697e15c55 --- /dev/null +++ b/app/src/main/feature/retro/RetroControlsMenu.kt @@ -0,0 +1,153 @@ +package com.winlator.cmod.feature.retro + +import android.content.Context +import android.widget.Toast +import com.winlator.cmod.R + +object RetroControlsMenu { + class Host( + val context: Context, + val overlay: RetroInputView?, + val menu: RetroMenuController, + val systemId: String?, + val touchControls: () -> Boolean, + val onTouchControls: (Boolean) -> Unit, + val adaptiveSticks: () -> Boolean, + val onAdaptiveSticks: (Boolean) -> Unit, + val orientationLabel: () -> String, + val onCloseMenu: () -> Unit, + val showStickInversion: Boolean = false, + ) + + fun l3r3PrefKey(systemId: String?) = "retro_show_l3r3_" + (systemId ?: "default") + + fun build(host: Host): List = + buildList { + val context = host.context + add( + RetroMenuEntry.Toggle( + context.getString(R.string.retro_lr_on_screen_controls), + checked = host.touchControls(), + ) { value -> + host.onTouchControls(value) + host.menu.rebuild() + }, + ) + if (host.showStickInversion) { + val invPrefs = androidx.preference.PreferenceManager.getDefaultSharedPreferences(context) + val sys = host.systemId ?: "default" + fun invToggle(label: String, key: String) = + RetroMenuEntry.Toggle(label, checked = invPrefs.getBoolean(key, false)) { value -> + invPrefs.edit().putBoolean(key, value).apply() + host.overlay?.loadStickInversion() + host.menu.rebuild() + } + add(invToggle(context.getString(R.string.retro_lr_left_stick_invert_x), "retro_inv_lx_$sys")) + add(invToggle(context.getString(R.string.retro_lr_left_stick_invert_y), "retro_inv_ly_$sys")) + add(invToggle(context.getString(R.string.retro_lr_right_stick_invert_x), "retro_inv_rx_$sys")) + add(invToggle(context.getString(R.string.retro_lr_right_stick_invert_y), "retro_inv_ry_$sys")) + } + add( + RetroMenuEntry.Toggle( + context.getString(R.string.retro_lr_adaptive_sticks), + checked = host.adaptiveSticks(), + ) { value -> + host.onAdaptiveSticks(value) + host.overlay?.adaptiveSticks = value + host.menu.rebuild() + }, + ) + if (host.overlay?.supportsStickButtons == true) { + val prefs = androidx.preference.PreferenceManager.getDefaultSharedPreferences(context) + val key = l3r3PrefKey(host.systemId) + add( + RetroMenuEntry.Toggle( + context.getString(R.string.retro_ps2_show_l3r3), + checked = prefs.getBoolean(key, true), + ) { value -> + prefs.edit().putBoolean(key, value).apply() + host.overlay.showL3R3 = value + host.menu.rebuild() + }, + ) + } + add( + RetroMenuEntry.Slider( + label = context.getString(R.string.retro_lr_haptic_feedback), + valueText = host.overlay?.hapticStrength?.let { "${(it * 100).toInt()}%" } ?: "0%", + value = host.overlay?.hapticStrength ?: 0f, + min = 0f, + max = 1f, + step = 0.05f, + ) { value -> + host.overlay?.hapticStrength = value + androidx.preference.PreferenceManager + .getDefaultSharedPreferences(context) + .edit() + .putFloat("retro_haptic_strength", value) + .apply() + host.menu.rebuild() + }, + ) + val orientationLabel = host.orientationLabel() + add( + RetroMenuEntry.Action( + context.getString(R.string.retro_lr_edit_layout, orientationLabel), + RetroDrawerIcons.EditLayout, + ) { + host.onCloseMenu() + host.overlay?.let { + it.visibility = android.view.View.VISIBLE + it.enterEdit() + } + }, + ) + add( + RetroMenuEntry.Action( + context.getString(R.string.retro_lr_reset_layout, orientationLabel), + RetroDrawerIcons.Reset, + ) { + host.overlay?.resetLayout() + Toast + .makeText(context, context.getString(R.string.retro_lr_layout_reset, orientationLabel), Toast.LENGTH_SHORT) + .show() + }, + ) + val colors = RetroControlLayouts.loadColors(context, host.systemId) + fun persistColors(mutate: (RetroCustomColors) -> Unit) { + mutate(colors) + RetroControlLayouts.saveColors(context, host.systemId, colors) + host.overlay?.setCustomColors(colors) + host.menu.rebuild() + } + add( + RetroMenuEntry.ColorPick(context.getString(R.string.retro_lr_button_color), colors.button) { value -> + persistColors { it.button = value } + }, + ) + add( + RetroMenuEntry.ColorPick(context.getString(R.string.retro_lr_letter_color), colors.text) { value -> + persistColors { it.text = value } + }, + ) + add( + RetroMenuEntry.ColorPick(context.getString(R.string.retro_lr_shadow_color), colors.shadow) { value -> + persistColors { it.shadow = value } + }, + ) + add( + RetroMenuEntry.ColorPick(context.getString(R.string.retro_lr_background_color), colors.body) { value -> + persistColors { it.body = value } + }, + ) + add( + RetroMenuEntry.Action(context.getString(R.string.retro_lr_reset_colors), RetroDrawerIcons.Reset) { + val fresh = RetroCustomColors() + RetroControlLayouts.saveColors(context, host.systemId, fresh) + host.overlay?.setCustomColors(fresh) + host.menu.rebuild() + Toast.makeText(context, context.getString(R.string.retro_lr_colors_reset), Toast.LENGTH_SHORT).show() + }, + ) + } +} diff --git a/app/src/main/feature/retro/RetroCoreCatalog.kt b/app/src/main/feature/retro/RetroCoreCatalog.kt new file mode 100644 index 000000000..bdb6d7978 --- /dev/null +++ b/app/src/main/feature/retro/RetroCoreCatalog.kt @@ -0,0 +1,3228 @@ +package com.winlator.cmod.feature.retro + +import com.winlator.cmod.R + +internal object RetroCoreCatalog { + val FCEUMM: List = listOf( + RetroCoreOption( + key = "fceumm_arkanoid_mode", + label = "Arkanoid Mode", + values = listOf("abs_mouse", "mouse", "stelladaptor", "touchscreen"), + valueLabels = listOf("Absolute mouse", "Mouse", "Stelladaptor", "Touchscreen"), + defaultValue = "mouse", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "fceumm_mouse_sensitivity", + label = "Mouse Sensitivity", + values = listOf("20", "30", "40", "50", "60", "70", "80", "90", "100", "110", "120", "130", "140", "150", "160", "170", "180", "190", "200"), + valueLabels = listOf("20", "30", "40", "50", "60", "70", "80", "90", "100", "110", "120", "130", "140", "150", "160", "170", "180", "190", "200"), + defaultValue = "100", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "fceumm_show_crosshair", + label = "Show Zapper Crosshair", + values = listOf("enabled", "disabled"), + valueLabels = listOf("enabled", "disabled"), + defaultValue = "enabled", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "fceumm_turbo_delay", + label = "Turbo Delay (in frames)", + values = listOf("1", "2", "3", "5", "10", "15", "30", "60"), + valueLabels = listOf("1", "2", "3", "5", "10", "15", "30", "60"), + defaultValue = "3", + category = RetroOptionCategory.CONTROLS, + advanced = false, + ), + RetroCoreOption( + key = "fceumm_turbo_enable", + label = "Turbo Enable", + values = listOf("None", "Player 1", "Player 2", "Both"), + valueLabels = listOf("None", "Player 1", "Player 2", "Both"), + defaultValue = "None", + category = RetroOptionCategory.CONTROLS, + advanced = false, + ), + RetroCoreOption( + key = "fceumm_up_down_allowed", + label = "Allow Opposing Directions", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "fceumm_zapper_mode", + label = "Zapper Mode", + values = listOf("clightgun", "stlightgun", "touchscreen", "mouse"), + valueLabels = listOf("Crosshair light gun", "Sequential Targets light gun", "Touchscreen", "Mouse"), + defaultValue = "clightgun", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "fceumm_zapper_sensor", + label = "Invert Zapper Sensor Signal", + values = listOf("enabled", "disabled"), + valueLabels = listOf("enabled", "disabled"), + defaultValue = "enabled", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "fceumm_zapper_tolerance", + label = "Zapper Tolerance", + values = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"), + valueLabels = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"), + defaultValue = "6", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "fceumm_zapper_trigger", + label = "Invert Zapper Trigger Signal", + values = listOf("enabled", "disabled"), + valueLabels = listOf("enabled", "disabled"), + defaultValue = "enabled", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "fceumm_aspect", + label = "Aspect Ratio", + values = listOf("8:7 PAR", "4:3", "PP"), + valueLabels = listOf("8:7 PAR", "4:3", "Pixel Perfect"), + defaultValue = "8:7 PAR", + category = RetroOptionCategory.DISPLAY, + advanced = false, + labelRes = R.string.retro_co_aspect_ratio, + ), + RetroCoreOption( + key = "fceumm_ntsc_filter", + label = "NTSC Filter", + values = listOf("disabled", "composite", "svideo", "rgb", "monochrome"), + valueLabels = listOf("disabled", "Composite", "S-Video", "RGB", "Monochrome"), + defaultValue = "disabled", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "fceumm_overscan_h_left", + label = "Crop Horizontal Left Overscan", + values = listOf("0", "4", "8", "12", "16"), + valueLabels = listOf("0", "4", "8", "12", "16"), + defaultValue = "0", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "fceumm_overscan_h_right", + label = "Crop Horizontal Right Overscan", + values = listOf("0", "4", "8", "12", "16"), + valueLabels = listOf("0", "4", "8", "12", "16"), + defaultValue = "0", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "fceumm_overscan_v_bottom", + label = "Crop Vertical Bottom Overscan", + values = listOf("0", "4", "8", "12", "16", "20", "24"), + valueLabels = listOf("0", "4", "8", "12", "16", "20", "24"), + defaultValue = "8", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "fceumm_overscan_v_top", + label = "Crop Vertical Top Overscan", + values = listOf("0", "4", "8", "12", "16", "20", "24"), + valueLabels = listOf("0", "4", "8", "12", "16", "20", "24"), + defaultValue = "8", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "fceumm_palette", + label = "Color Palette", + values = listOf("default", "asqrealc", "restored-wii-vc", "wii-vc", "rgb", "yuv-v3", "unsaturated-final", "sony-cxa2025as-us", "pal", "bmf-final2", "bmf-final3", "smooth-fbx", "composite-direct-fbx", "pvm-style-d93-fbx", "ntsc-hardware-fbx", "nes-classic-fbx-fs", "nescap", "wavebeam", "digital-prime-fbx", "magnum-fbx", "smooth-v2-fbx", "nes-classic-fbx", "royaltea", "mugicha", "raw", "custom"), + valueLabels = listOf("Default", "AspiringSquire's Real", "Restored Wii VC", "Wii Virtual Console", "Nintendo RGB PPU", "FBX's YUV-V3", "FBX's Unsaturated-Final", "Sony CXA2025AS US", "PAL", "BMF's Final 2", "BMF's Final 3", "FBX's Smooth", "FBX's Composite Direct", "FBX's PVM Style D93", "FBX's NTSC Hardware", "FBX's NES Classic (fixed)", "RGBSource's NESCAP", "nakedarthur's Wavebeam", "FBX's Digital Prime", "FBX's Magnum", "FBX's Smooth V2", "FBX's NES Classic", "Royaltea (PVM-2530)", "Mugicha", "Raw", "Custom"), + defaultValue = "default", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "fceumm_nospritelimit", + label = "No Sprite Limit", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + ), + RetroCoreOption( + key = "fceumm_overclocking", + label = "Overclock", + values = listOf("disabled", "2x-Postrender", "2x-VBlank"), + valueLabels = listOf("disabled", "2x-Postrender", "2x-VBlank"), + defaultValue = "disabled", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + ), + RetroCoreOption( + key = "fceumm_ramstate", + label = "RAM Power-On Fill (Restart Required)", + values = listOf("fill \$ff", "fill \$00", "random"), + valueLabels = listOf("\$FF", "\$00", "Random"), + defaultValue = "fill \$ff", + category = RetroOptionCategory.PERFORMANCE, + advanced = true, + ), + RetroCoreOption( + key = "fceumm_apu_1", + label = "Audio Channel 1 (Square 1)", + values = listOf("enabled", "disabled"), + valueLabels = listOf("enabled", "disabled"), + defaultValue = "enabled", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "fceumm_apu_2", + label = "Audio Channel 2 (Square 2)", + values = listOf("enabled", "disabled"), + valueLabels = listOf("enabled", "disabled"), + defaultValue = "enabled", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "fceumm_apu_3", + label = "Audio Channel 3 (Triangle)", + values = listOf("enabled", "disabled"), + valueLabels = listOf("enabled", "disabled"), + defaultValue = "enabled", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "fceumm_apu_4", + label = "Audio Channel 4 (Noise)", + values = listOf("enabled", "disabled"), + valueLabels = listOf("enabled", "disabled"), + defaultValue = "enabled", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "fceumm_apu_5", + label = "Audio Channel 5 (PCM)", + values = listOf("enabled", "disabled"), + valueLabels = listOf("enabled", "disabled"), + defaultValue = "enabled", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "fceumm_apu_fds", + label = "Channel Volume (FDS)", + values = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"), + valueLabels = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "fceumm_apu_mmc5", + label = "Channel Volume (MMC5)", + values = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"), + valueLabels = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "fceumm_apu_n163", + label = "Channel Volume (N163)", + values = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"), + valueLabels = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "fceumm_apu_s5b", + label = "Channel Volume (S5B)", + values = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"), + valueLabels = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "fceumm_apu_vrc6", + label = "Channel Volume (VRC6)", + values = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"), + valueLabels = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "fceumm_apu_vrc7", + label = "Channel Volume (VRC7)", + values = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"), + valueLabels = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "fceumm_reducedmcpopping", + label = "Reduce DMC Channel Popping", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "fceumm_removetrianglenoise", + label = "Reduce Triangle Channel Popping", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "fceumm_sndlowpass", + label = "Audio RF Filter", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.SOUND, + advanced = false, + ), + RetroCoreOption( + key = "fceumm_sndquality", + label = "Sound Quality", + values = listOf("Low", "High", "Very High"), + valueLabels = listOf("Low", "High", "Very High"), + defaultValue = "Low", + category = RetroOptionCategory.SOUND, + advanced = false, + ), + RetroCoreOption( + key = "fceumm_sndrate_hint", + label = "Sound Samplerate (Hint)", + values = listOf("Auto", "32KHz", "44KHz", "48KHz", "96KHz"), + valueLabels = listOf("Auto", "32KHz", "44KHz", "48KHz", "96KHz"), + defaultValue = "Auto", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "fceumm_sndstereodelay", + label = "Stereo Sound Effect", + values = listOf("disabled", "01_ms_delay", "02_ms_delay", "03_ms_delay", "04_ms_delay", "05_ms_delay", "06_ms_delay", "07_ms_delay", "08_ms_delay", "09_ms_delay", "10_ms_delay", "11_ms_delay", "12_ms_delay", "13_ms_delay", "14_ms_delay", "15_ms_delay", "16_ms_delay", "17_ms_delay", "18_ms_delay", "19_ms_delay", "20_ms_delay", "21_ms_delay", "22_ms_delay", "23_ms_delay", "24_ms_delay", "25_ms_delay", "26_ms_delay", "27_ms_delay", "28_ms_delay", "29_ms_delay", "30_ms_delay", "31_ms_delay", "32_ms_delay"), + valueLabels = listOf("disabled", "1ms Delay", "2ms Delay", "3ms Delay", "4ms Delay", "5ms Delay", "6ms Delay", "7ms Delay", "8ms Delay", "9ms Delay", "10ms Delay", "11ms Delay", "12ms Delay", "13ms Delay", "14ms Delay", "15ms Delay (Default)", "16ms Delay", "17ms Delay", "18ms Delay", "19ms Delay", "20ms Delay", "21ms Delay", "22ms Delay", "23ms Delay", "24ms Delay", "25ms Delay", "26ms Delay", "27ms Delay", "28ms Delay", "29ms Delay", "30ms Delay", "31ms Delay", "32ms Delay"), + defaultValue = "disabled", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "fceumm_sndvolume", + label = "Master Volume", + values = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"), + valueLabels = listOf("0%", "10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%", "90%", "100%"), + defaultValue = "7", + category = RetroOptionCategory.SOUND, + advanced = false, + ), + RetroCoreOption( + key = "fceumm_swapduty", + label = "Swap Audio Duty Cycles", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "fceumm_game_genie", + label = "Game Genie Add-On (Restart Required)", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.SYSTEM, + advanced = true, + ), + RetroCoreOption( + key = "fceumm_region", + label = "Region", + values = listOf("Auto", "NTSC", "PAL", "Dendy"), + valueLabels = listOf("Auto", "NTSC", "PAL", "Dendy"), + defaultValue = "Auto", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + ) + + val SNES9X: List = listOf( + RetroCoreOption( + key = "snes9x_justifier1_color", + label = "Justifier 1 Color", + values = listOf("Blue", "Blue (blend)", "Violet", "Violet (blend)", "Pink", "Pink (blend)", "Purple", "Purple (blend)", "Black", "Black (blend)", "25% Grey", "25% Grey (blend)", "50% Grey", "50% Grey (blend)", "75% Grey", "75% Grey (blend)", "White", "White (blend)", "Red", "Red (blend)", "Orange", "Orange (blend)", "Yellow", "Yellow (blend)", "Green", "Green (blend)", "Cyan", "Cyan (blend)", "Sky", "Sky (blend)"), + valueLabels = listOf("Blue", "Blue (blend)", "Violet", "Violet (blend)", "Pink", "Pink (blend)", "Purple", "Purple (blend)", "Black", "Black (blend)", "25% Grey", "25% Grey (blend)", "50% Grey", "50% Grey (blend)", "75% Grey", "75% Grey (blend)", "White", "White (blend)", "Red", "Red (blend)", "Orange", "Orange (blend)", "Yellow", "Yellow (blend)", "Green", "Green (blend)", "Cyan", "Cyan (blend)", "Sky", "Sky (blend)"), + defaultValue = "Blue", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_justifier1_crosshair", + label = "Justifier 1 Crosshair", + values = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"), + valueLabels = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"), + defaultValue = "4", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_justifier2_color", + label = "Justifier 2 Color", + values = listOf("Pink", "Pink (blend)", "Purple", "Purple (blend)", "Black", "Black (blend)", "25% Grey", "25% Grey (blend)", "50% Grey", "50% Grey (blend)", "75% Grey", "75% Grey (blend)", "White", "White (blend)", "Red", "Red (blend)", "Orange", "Orange (blend)", "Yellow", "Yellow (blend)", "Green", "Green (blend)", "Cyan", "Cyan (blend)", "Sky", "Sky (blend)", "Blue", "Blue (blend)", "Violet", "Violet (blend)"), + valueLabels = listOf("Pink", "Pink (blend)", "Purple", "Purple (blend)", "Black", "Black (blend)", "25% Grey", "25% Grey (blend)", "50% Grey", "50% Grey (blend)", "75% Grey", "75% Grey (blend)", "White", "White (blend)", "Red", "Red (blend)", "Orange", "Orange (blend)", "Yellow", "Yellow (blend)", "Green", "Green (blend)", "Cyan", "Cyan (blend)", "Sky", "Sky (blend)", "Blue", "Blue (blend)", "Violet", "Violet (blend)"), + defaultValue = "Pink", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_justifier2_crosshair", + label = "Justifier 2 Crosshair", + values = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"), + valueLabels = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"), + defaultValue = "4", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_lightgun_mode", + label = "Light Gun Mode", + values = listOf("Lightgun", "Touchscreen"), + valueLabels = listOf("Light Gun", "Touchscreen"), + defaultValue = "Lightgun", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_rifle_color", + label = "M.A.C.S. Rifle Color", + values = listOf("White", "White (blend)", "Red", "Red (blend)", "Orange", "Orange (blend)", "Yellow", "Yellow (blend)", "Green", "Green (blend)", "Cyan", "Cyan (blend)", "Sky", "Sky (blend)", "Blue", "Blue (blend)", "Violet", "Violet (blend)", "Pink", "Pink (blend)", "Purple", "Purple (blend)", "Black", "Black (blend)", "25% Grey", "25% Grey (blend)", "50% Grey", "50% Grey (blend)", "75% Grey", "75% Grey (blend)"), + valueLabels = listOf("White", "White (blend)", "Red", "Red (blend)", "Orange", "Orange (blend)", "Yellow", "Yellow (blend)", "Green", "Green (blend)", "Cyan", "Cyan (blend)", "Sky", "Sky (blend)", "Blue", "Blue (blend)", "Violet", "Violet (blend)", "Pink", "Pink (blend)", "Purple", "Purple (blend)", "Black", "Black (blend)", "25% Grey", "25% Grey (blend)", "50% Grey", "50% Grey (blend)", "75% Grey", "75% Grey (blend)"), + defaultValue = "White", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_rifle_crosshair", + label = "M.A.C.S. Rifle Crosshair", + values = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"), + valueLabels = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"), + defaultValue = "2", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_superscope_color", + label = "Super Scope Color", + values = listOf("White", "White (blend)", "Red", "Red (blend)", "Orange", "Orange (blend)", "Yellow", "Yellow (blend)", "Green", "Green (blend)", "Cyan", "Cyan (blend)", "Sky", "Sky (blend)", "Blue", "Blue (blend)", "Violet", "Violet (blend)", "Pink", "Pink (blend)", "Purple", "Purple (blend)", "Black", "Black (blend)", "25% Grey", "25% Grey (blend)", "50% Grey", "50% Grey (blend)", "75% Grey", "75% Grey (blend)"), + valueLabels = listOf("White", "White (blend)", "Red", "Red (blend)", "Orange", "Orange (blend)", "Yellow", "Yellow (blend)", "Green", "Green (blend)", "Cyan", "Cyan (blend)", "Sky", "Sky (blend)", "Blue", "Blue (blend)", "Violet", "Violet (blend)", "Pink", "Pink (blend)", "Purple", "Purple (blend)", "Black", "Black (blend)", "25% Grey", "25% Grey (blend)", "50% Grey", "50% Grey (blend)", "75% Grey", "75% Grey (blend)"), + defaultValue = "White", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_superscope_crosshair", + label = "Super Scope Crosshair", + values = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"), + valueLabels = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"), + defaultValue = "2", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_superscope_reverse_buttons", + label = "Super Scope Reverse Trigger Buttons", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_up_down_allowed", + label = "Allow Opposing Directions", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.CONTROLS, + advanced = false, + ), + RetroCoreOption( + key = "snes9x_aspect", + label = "Preferred Aspect Ratio", + values = listOf("4:3", "4:3 scaled", "uncorrected", "auto", "ntsc", "pal"), + valueLabels = listOf("4:3", "4:3 (Preserved)", "Uncorrected", "Auto", "NTSC", "PAL"), + defaultValue = "4:3", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "snes9x_hires_blend", + label = "Hi-Res Blending", + values = listOf("disabled", "merge", "blur"), + valueLabels = listOf("disabled", "Merge", "Blur"), + defaultValue = "disabled", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "snes9x_overscan", + label = "Crop Overscan", + values = listOf("enabled", "12_pixels", "16_pixels", "auto", "disabled"), + valueLabels = listOf("~8 Pixels", "12 Pixels", "16 Pixels", "Auto (~8 Pixels)", "disabled"), + defaultValue = "enabled", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "snes9x_block_invalid_vram_access", + label = "Block Invalid VRAM Access", + values = listOf("enabled", "disabled"), + valueLabels = listOf("enabled", "disabled"), + defaultValue = "enabled", + category = RetroOptionCategory.PERFORMANCE, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_echo_buffer_hack", + label = "Echo Buffer Hack (Unsafe, only enable for old addmusic hacks)", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.PERFORMANCE, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_overclock_cycles", + label = "Reduce Slowdown (Hack, Unsafe)", + values = listOf("disabled", "light", "compatible", "max"), + valueLabels = listOf("disabled", "Light", "Compatible", "Max"), + defaultValue = "disabled", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + ), + RetroCoreOption( + key = "snes9x_overclock_superfx", + label = "SuperFX Overclocking", + values = listOf("50%", "60%", "70%", "80%", "90%", "100%", "150%", "200%", "250%", "300%", "350%", "400%", "450%", "500%"), + valueLabels = listOf("50%", "60%", "70%", "80%", "90%", "100%", "150%", "200%", "250%", "300%", "350%", "400%", "450%", "500%"), + defaultValue = "100%", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + ), + RetroCoreOption( + key = "snes9x_randomize_memory", + label = "Randomize Memory (Unsafe)", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.PERFORMANCE, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_reduce_sprite_flicker", + label = "Reduce Flickering (Hack, Unsafe)", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + ), + RetroCoreOption( + key = "snes9x_audio_interpolation", + label = "Audio Interpolation", + values = listOf("gaussian", "cubic", "sinc", "none", "linear"), + valueLabels = listOf("Gaussian", "Cubic", "Sinc", "None", "Linear"), + defaultValue = "gaussian", + category = RetroOptionCategory.SOUND, + advanced = false, + ), + RetroCoreOption( + key = "snes9x_gfx_clip", + label = "Enable Graphic Clip Windows", + values = listOf("enabled", "disabled"), + valueLabels = listOf("enabled", "disabled"), + defaultValue = "enabled", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_gfx_transp", + label = "Enable Transparency Effects", + values = listOf("enabled", "disabled"), + valueLabels = listOf("enabled", "disabled"), + defaultValue = "enabled", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_layer_1", + label = "Show Layer 1", + values = listOf("enabled", "disabled"), + valueLabels = listOf("enabled", "disabled"), + defaultValue = "enabled", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_layer_2", + label = "Show Layer 2", + values = listOf("enabled", "disabled"), + valueLabels = listOf("enabled", "disabled"), + defaultValue = "enabled", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_layer_3", + label = "Show Layer 3", + values = listOf("enabled", "disabled"), + valueLabels = listOf("enabled", "disabled"), + defaultValue = "enabled", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_layer_4", + label = "Show Layer 4", + values = listOf("enabled", "disabled"), + valueLabels = listOf("enabled", "disabled"), + defaultValue = "enabled", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_layer_5", + label = "Show Sprite Layer", + values = listOf("enabled", "disabled"), + valueLabels = listOf("enabled", "disabled"), + defaultValue = "enabled", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_sndchan_volume_1", + label = "Volume % for Sound Channel 1", + values = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + valueLabels = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_sndchan_volume_2", + label = "Volume % for Sound Channel 2", + values = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + valueLabels = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_sndchan_volume_3", + label = "Volume % for Sound Channel 3", + values = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + valueLabels = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_sndchan_volume_4", + label = "Volume % for Sound Channel 4", + values = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + valueLabels = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_sndchan_volume_5", + label = "Volume % for Sound Channel 5", + values = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + valueLabels = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_sndchan_volume_6", + label = "Volume % for Sound Channel 6", + values = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + valueLabels = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_sndchan_volume_7", + label = "Volume % for Sound Channel 7", + values = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + valueLabels = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_sndchan_volume_8", + label = "Volume % for Sound Channel 8", + values = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + valueLabels = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "snes9x_blargg", + label = "Blargg NTSC Filter", + values = listOf("disabled", "monochrome", "rf", "composite", "s-video", "rgb"), + valueLabels = listOf("disabled", "Monochrome", "RF", "Composite", "S-Video", "RGB"), + defaultValue = "disabled", + category = RetroOptionCategory.SYSTEM, + advanced = false, + labelRes = R.string.retro_co_ntsc_filter, + ), + RetroCoreOption( + key = "snes9x_region", + label = "Console Region (Reload Core)", + values = listOf("auto", "ntsc", "pal"), + valueLabels = listOf("Auto", "NTSC", "PAL"), + defaultValue = "auto", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + ) + + val GAMBATTE: List = listOf( + RetroCoreOption( + key = "gambatte_gb_link_mode", + label = "Game Link Mode", + values = listOf("Not Connected", "Network Server", "Network Client"), + valueLabels = listOf("Not Connected", "Network Server", "Network Client"), + defaultValue = "Not Connected", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "gambatte_gb_link_network_port", + label = "Network Link Port", + values = listOf("56400", "56401", "56402", "56403", "56404", "56405", "56406", "56407", "56408", "56409", "56410", "56411", "56412", "56413", "56414", "56415", "56416", "56417", "56418", "56419", "56420"), + valueLabels = listOf("56400", "56401", "56402", "56403", "56404", "56405", "56406", "56407", "56408", "56409", "56410", "56411", "56412", "56413", "56414", "56415", "56416", "56417", "56418", "56419", "56420"), + defaultValue = "56400", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "gambatte_rumble_level", + label = "Controller Rumble Strength", + values = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"), + valueLabels = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"), + defaultValue = "10", + category = RetroOptionCategory.CONTROLS, + advanced = false, + ), + RetroCoreOption( + key = "gambatte_turbo_period", + label = "Turbo Button Period", + values = listOf("4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100", "101", "102", "103", "104", "105", "106", "107", "108", "109", "110", "111", "112", "113", "114", "115", "116", "117", "118", "119", "120"), + valueLabels = listOf("4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100", "101", "102", "103", "104", "105", "106", "107", "108", "109", "110", "111", "112", "113", "114", "115", "116", "117", "118", "119", "120"), + defaultValue = "4", + category = RetroOptionCategory.CONTROLS, + advanced = false, + ), + RetroCoreOption( + key = "gambatte_up_down_allowed", + label = "Allow Opposing Directions", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "gambatte_dark_filter_level", + label = "Dark Filter Level (%)", + values = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50"), + valueLabels = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50"), + defaultValue = "0", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "gambatte_gb_colorization", + label = "GB Colorization", + values = listOf("disabled", "auto", "GBC", "SGB", "internal", "custom"), + valueLabels = listOf("disabled", "Auto", "GBC", "SGB", "Internal", "Custom"), + defaultValue = "disabled", + category = RetroOptionCategory.DISPLAY, + advanced = false, + labelRes = R.string.retro_co_colorization, + ), + RetroCoreOption( + key = "gambatte_gb_internal_palette", + label = "Internal Palette", + values = listOf("GB - DMG", "GB - Pocket", "GB - Light", "GBC - Blue", "GBC - Brown", "GBC - Dark Blue", "GBC - Dark Brown", "GBC - Dark Green", "GBC - Grayscale", "GBC - Green", "GBC - Inverted", "GBC - Orange", "GBC - Pastel Mix", "GBC - Red", "GBC - Yellow", "SGB - 1A", "SGB - 1B", "SGB - 1C", "SGB - 1D", "SGB - 1E", "SGB - 1F", "SGB - 1G", "SGB - 1H", "SGB - 2A", "SGB - 2B", "SGB - 2C", "SGB - 2D", "SGB - 2E", "SGB - 2F", "SGB - 2G", "SGB - 2H", "SGB - 3A", "SGB - 3B", "SGB - 3C", "SGB - 3D", "SGB - 3E", "SGB - 3F", "SGB - 3G", "SGB - 3H", "SGB - 4A", "SGB - 4B", "SGB - 4C", "SGB - 4D", "SGB - 4E", "SGB - 4F", "SGB - 4G", "SGB - 4H", "Special 1", "Special 2", "Special 3", "Special 4 (TI-83 Legacy)", "TWB64 - Pack 1", "TWB64 - Pack 2", "TWB64 - Pack 3", "PixelShift - Pack 1"), + valueLabels = listOf("GB - DMG", "GB - Pocket", "GB - Light", "GBC - Blue", "GBC - Brown", "GBC - Dark Blue", "GBC - Dark Brown", "GBC - Dark Green", "GBC - Grayscale", "GBC - Green", "GBC - Inverted", "GBC - Orange", "GBC - Pastel Mix", "GBC - Red", "GBC - Yellow", "SGB - 1A", "SGB - 1B", "SGB - 1C", "SGB - 1D", "SGB - 1E", "SGB - 1F", "SGB - 1G", "SGB - 1H", "SGB - 2A", "SGB - 2B", "SGB - 2C", "SGB - 2D", "SGB - 2E", "SGB - 2F", "SGB - 2G", "SGB - 2H", "SGB - 3A", "SGB - 3B", "SGB - 3C", "SGB - 3D", "SGB - 3E", "SGB - 3F", "SGB - 3G", "SGB - 3H", "SGB - 4A", "SGB - 4B", "SGB - 4C", "SGB - 4D", "SGB - 4E", "SGB - 4F", "SGB - 4G", "SGB - 4H", "Special 1", "Special 2", "Special 3", "Special 4 (TI-83 Legacy)", "TWB64 - Pack 1", "TWB64 - Pack 2", "TWB64 - Pack 3", "PixelShift - Pack 1"), + defaultValue = "GB - DMG", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "gambatte_gb_palette_pixelshift_1", + label = "> PixelShift - Pack 1 Palette", + values = listOf("PixelShift 01 - Arctic Green", "PixelShift 02 - Arduboy", "PixelShift 03 - BGB 0.3 Emulator", "PixelShift 04 - Camouflage", "PixelShift 05 - Chocolate Bar", "PixelShift 06 - CMYK", "PixelShift 07 - Cotton Candy", "PixelShift 08 - Easy Greens", "PixelShift 09 - Gamate", "PixelShift 10 - Game Boy Light", "PixelShift 11 - Game Boy Pocket", "PixelShift 12 - Game Boy Pocket Alt", "PixelShift 13 - Game Pocket Computer", "PixelShift 14 - Game & Watch Ball", "PixelShift 15 - GB Backlight Blue", "PixelShift 16 - GB Backlight Faded", "PixelShift 17 - GB Backlight Orange", "PixelShift 18 - GB Backlight White", "PixelShift 19 - GB Backlight Yellow Dark", "PixelShift 20 - GB Bootleg", "PixelShift 21 - GB Hunter", "PixelShift 22 - GB Kiosk", "PixelShift 23 - GB Kiosk 2", "PixelShift 24 - GB New", "PixelShift 25 - GB Nuked", "PixelShift 26 - GB Old", "PixelShift 27 - GBP Bivert", "PixelShift 28 - GB Washed Yellow Backlight", "PixelShift 29 - Ghost", "PixelShift 30 - Glow In The Dark", "PixelShift 31 - Gold Bar", "PixelShift 32 - Grapefruit", "PixelShift 33 - Gray Green Mix", "PixelShift 34 - Missingno", "PixelShift 35 - MS-Dos", "PixelShift 36 - Newspaper", "PixelShift 37 - Pip-Boy", "PixelShift 38 - Pocket Girl", "PixelShift 39 - Silhouette", "PixelShift 40 - Sunburst", "PixelShift 41 - Technicolor", "PixelShift 42 - Tron", "PixelShift 43 - Vaporwave", "PixelShift 44 - Virtual Boy", "PixelShift 45 - Wish"), + valueLabels = listOf("PixelShift 01 - Arctic Green", "PixelShift 02 - Arduboy", "PixelShift 03 - BGB 0.3 Emulator", "PixelShift 04 - Camouflage", "PixelShift 05 - Chocolate Bar", "PixelShift 06 - CMYK", "PixelShift 07 - Cotton Candy", "PixelShift 08 - Easy Greens", "PixelShift 09 - Gamate", "PixelShift 10 - Game Boy Light", "PixelShift 11 - Game Boy Pocket", "PixelShift 12 - Game Boy Pocket Alt", "PixelShift 13 - Game Pocket Computer", "PixelShift 14 - Game & Watch Ball", "PixelShift 15 - GB Backlight Blue", "PixelShift 16 - GB Backlight Faded", "PixelShift 17 - GB Backlight Orange", "PixelShift 18 - GB Backlight White", "PixelShift 19 - GB Backlight Yellow Dark", "PixelShift 20 - GB Bootleg", "PixelShift 21 - GB Hunter", "PixelShift 22 - GB Kiosk", "PixelShift 23 - GB Kiosk 2", "PixelShift 24 - GB New", "PixelShift 25 - GB Nuked", "PixelShift 26 - GB Old", "PixelShift 27 - GBP Bivert", "PixelShift 28 - GB Washed Yellow Backlight", "PixelShift 29 - Ghost", "PixelShift 30 - Glow In The Dark", "PixelShift 31 - Gold Bar", "PixelShift 32 - Grapefruit", "PixelShift 33 - Gray Green Mix", "PixelShift 34 - Missingno", "PixelShift 35 - MS-Dos", "PixelShift 36 - Newspaper", "PixelShift 37 - Pip-Boy", "PixelShift 38 - Pocket Girl", "PixelShift 39 - Silhouette", "PixelShift 40 - Sunburst", "PixelShift 41 - Technicolor", "PixelShift 42 - Tron", "PixelShift 43 - Vaporwave", "PixelShift 44 - Virtual Boy", "PixelShift 45 - Wish"), + defaultValue = "PixelShift 01 - Arctic Green", + category = RetroOptionCategory.DISPLAY, + advanced = true, + ), + RetroCoreOption( + key = "gambatte_gb_palette_twb64_1", + label = "> TWB64 - Pack 1 Palette", + values = listOf("TWB64 001 - Aqours Blue", "TWB64 002 - Anime Expo Ver.", "TWB64 003 - SpongeBob Yellow", "TWB64 004 - Patrick Star Pink", "TWB64 005 - Neon Red", "TWB64 006 - Neon Blue", "TWB64 007 - Neon Yellow", "TWB64 008 - Neon Green", "TWB64 009 - Neon Pink", "TWB64 010 - Mario Red", "TWB64 011 - Nick Orange", "TWB64 012 - Virtual Vision", "TWB64 013 - Golden Wild", "TWB64 014 - DMG-099", "TWB64 015 - Classic Blurple", "TWB64 016 - 765 Production Ver.", "TWB64 017 - Superball Ivory", "TWB64 018 - Crunchyroll Orange", "TWB64 019 - Muse Pink", "TWB64 020 - School Idol Blue", "TWB64 021 - Gamate Ver.", "TWB64 022 - Greenscale Ver.", "TWB64 023 - Odyssey Gold", "TWB64 024 - Super Saiyan God", "TWB64 025 - Super Saiyan Blue", "TWB64 026 - ANIMAX BLUE", "TWB64 027 - BMO Ver.", "TWB64 028 - Game.com Ver.", "TWB64 029 - Sanrio Pink", "TWB64 030 - Timmy Turner Pink", "TWB64 031 - Fairly OddPalette", "TWB64 032 - Danny Phantom Silver", "TWB64 033 - Link's Awakening DX Ver.", "TWB64 034 - Travel Wood", "TWB64 035 - Pokemon Ver.", "TWB64 036 - Game Grump Orange", "TWB64 037 - Scooby-Doo Mystery Ver.", "TWB64 038 - Pokemon mini Ver.", "TWB64 039 - Supervision Ver.", "TWB64 040 - DMG Ver.", "TWB64 041 - Pocket Ver.", "TWB64 042 - Light Ver.", "TWB64 043 - All Might Hero Palette", "TWB64 044 - U.A. High School Uniform", "TWB64 045 - Pikachu Yellow", "TWB64 046 - Eevee Brown", "TWB64 047 - Microvision Ver.", "TWB64 048 - TI-83 Ver.", "TWB64 049 - Aegis Cherry", "TWB64 050 - Labo Fawn", "TWB64 051 - MILLION LIVE GOLD!", "TWB64 052 - Squidward Sea Foam Green", "TWB64 053 - VMU Ver.", "TWB64 054 - Game Master Ver.", "TWB64 055 - Android Green", "TWB64 056 - Amazon Vision", "TWB64 057 - Google Red", "TWB64 058 - Google Blue", "TWB64 059 - Google Yellow", "TWB64 060 - Google Green", "TWB64 061 - WonderSwan Ver.", "TWB64 062 - Neo Geo Pocket Ver.", "TWB64 063 - Dew Green", "TWB64 064 - Coca-Cola Vision", "TWB64 065 - GameKing Ver.", "TWB64 066 - Do The Dew Ver.", "TWB64 067 - Digivice Ver.", "TWB64 068 - Bikini Bottom Ver.", "TWB64 069 - Blossom Pink", "TWB64 070 - Bubbles Blue", "TWB64 071 - Buttercup Green", "TWB64 072 - NASCAR Ver.", "TWB64 073 - Lemon-Lime Green", "TWB64 074 - Mega Man V Ver.", "TWB64 075 - Tamagotchi Ver.", "TWB64 076 - Phantom Red", "TWB64 077 - Halloween Ver.", "TWB64 078 - Christmas Ver.", "TWB64 079 - Cardcaptor Pink", "TWB64 080 - Pretty Guardian Gold", "TWB64 081 - Camouflage Ver.", "TWB64 082 - Legendary Super Saiyan", "TWB64 083 - Super Saiyan Rose", "TWB64 084 - Super Saiyan", "TWB64 085 - Perfected Ultra Instinct", "TWB64 086 - Saint Snow Red", "TWB64 087 - Yellow Banana", "TWB64 088 - Green Banana", "TWB64 089 - Super Saiyan 3", "TWB64 090 - Super Saiyan Blue Evolved", "TWB64 091 - Pocket Tales Ver.", "TWB64 092 - Investigation Yellow", "TWB64 093 - S.E.E.S. Blue", "TWB64 094 - Ultra Instinct Sign", "TWB64 095 - Hokage Orange", "TWB64 096 - Straw Hat Red", "TWB64 097 - Sword Art Cyan", "TWB64 098 - Deku Alpha Emerald", "TWB64 099 - Blue Stripes Ver.", "TWB64 100 - Precure Marble Raspberry"), + valueLabels = listOf("TWB64 001 - Aqours Blue", "TWB64 002 - Anime Expo Ver.", "TWB64 003 - SpongeBob Yellow", "TWB64 004 - Patrick Star Pink", "TWB64 005 - Neon Red", "TWB64 006 - Neon Blue", "TWB64 007 - Neon Yellow", "TWB64 008 - Neon Green", "TWB64 009 - Neon Pink", "TWB64 010 - Mario Red", "TWB64 011 - Nick Orange", "TWB64 012 - Virtual Vision", "TWB64 013 - Golden Wild", "TWB64 014 - DMG-099", "TWB64 015 - Classic Blurple", "TWB64 016 - 765 Production Ver.", "TWB64 017 - Superball Ivory", "TWB64 018 - Crunchyroll Orange", "TWB64 019 - Muse Pink", "TWB64 020 - School Idol Blue", "TWB64 021 - Gamate Ver.", "TWB64 022 - Greenscale Ver.", "TWB64 023 - Odyssey Gold", "TWB64 024 - Super Saiyan God", "TWB64 025 - Super Saiyan Blue", "TWB64 026 - ANIMAX BLUE", "TWB64 027 - BMO Ver.", "TWB64 028 - Game.com Ver.", "TWB64 029 - Sanrio Pink", "TWB64 030 - Timmy Turner Pink", "TWB64 031 - Fairly OddPalette", "TWB64 032 - Danny Phantom Silver", "TWB64 033 - Link's Awakening DX Ver.", "TWB64 034 - Travel Wood", "TWB64 035 - Pokemon Ver.", "TWB64 036 - Game Grump Orange", "TWB64 037 - Scooby-Doo Mystery Ver.", "TWB64 038 - Pokemon mini Ver.", "TWB64 039 - Supervision Ver.", "TWB64 040 - DMG Ver.", "TWB64 041 - Pocket Ver.", "TWB64 042 - Light Ver.", "TWB64 043 - All Might Hero Palette", "TWB64 044 - U.A. High School Uniform", "TWB64 045 - Pikachu Yellow", "TWB64 046 - Eevee Brown", "TWB64 047 - Microvision Ver.", "TWB64 048 - TI-83 Ver.", "TWB64 049 - Aegis Cherry", "TWB64 050 - Labo Fawn", "TWB64 051 - MILLION LIVE GOLD!", "TWB64 052 - Squidward Sea Foam Green", "TWB64 053 - VMU Ver.", "TWB64 054 - Game Master Ver.", "TWB64 055 - Android Green", "TWB64 056 - Amazon Vision", "TWB64 057 - Google Red", "TWB64 058 - Google Blue", "TWB64 059 - Google Yellow", "TWB64 060 - Google Green", "TWB64 061 - WonderSwan Ver.", "TWB64 062 - Neo Geo Pocket Ver.", "TWB64 063 - Dew Green", "TWB64 064 - Coca-Cola Vision", "TWB64 065 - GameKing Ver.", "TWB64 066 - Do The Dew Ver.", "TWB64 067 - Digivice Ver.", "TWB64 068 - Bikini Bottom Ver.", "TWB64 069 - Blossom Pink", "TWB64 070 - Bubbles Blue", "TWB64 071 - Buttercup Green", "TWB64 072 - NASCAR Ver.", "TWB64 073 - Lemon-Lime Green", "TWB64 074 - Mega Man V Ver.", "TWB64 075 - Tamagotchi Ver.", "TWB64 076 - Phantom Red", "TWB64 077 - Halloween Ver.", "TWB64 078 - Christmas Ver.", "TWB64 079 - Cardcaptor Pink", "TWB64 080 - Pretty Guardian Gold", "TWB64 081 - Camouflage Ver.", "TWB64 082 - Legendary Super Saiyan", "TWB64 083 - Super Saiyan Rose", "TWB64 084 - Super Saiyan", "TWB64 085 - Perfected Ultra Instinct", "TWB64 086 - Saint Snow Red", "TWB64 087 - Yellow Banana", "TWB64 088 - Green Banana", "TWB64 089 - Super Saiyan 3", "TWB64 090 - Super Saiyan Blue Evolved", "TWB64 091 - Pocket Tales Ver.", "TWB64 092 - Investigation Yellow", "TWB64 093 - S.E.E.S. Blue", "TWB64 094 - Ultra Instinct Sign", "TWB64 095 - Hokage Orange", "TWB64 096 - Straw Hat Red", "TWB64 097 - Sword Art Cyan", "TWB64 098 - Deku Alpha Emerald", "TWB64 099 - Blue Stripes Ver.", "TWB64 100 - Precure Marble Raspberry"), + defaultValue = "TWB64 001 - Aqours Blue", + category = RetroOptionCategory.DISPLAY, + advanced = true, + ), + RetroCoreOption( + key = "gambatte_gb_palette_twb64_2", + label = "> TWB64 - Pack 2 Palette", + values = listOf("TWB64 101 - 765PRO Pink", "TWB64 102 - CINDERELLA Blue", "TWB64 103 - MILLION Yellow!", "TWB64 104 - SideM Green", "TWB64 105 - SHINY Sky Blue", "TWB64 106 - Angry Volcano Ver.", "TWB64 107 - NBA Vision", "TWB64 108 - NFL Vision", "TWB64 109 - MLB Vision", "TWB64 110 - Anime Digivice Ver.", "TWB64 111 - Aquatic Iro", "TWB64 112 - Tea Midori", "TWB64 113 - Sakura Pink", "TWB64 114 - Wisteria Murasaki", "TWB64 115 - Oni Aka", "TWB64 116 - Golden Kiiro", "TWB64 117 - Silver Shiro", "TWB64 118 - Fruity Orange", "TWB64 119 - AKB48 Pink", "TWB64 120 - Miku Blue", "TWB64 121 - Tri Digivice Ver.", "TWB64 122 - Survey Corps Uniform", "TWB64 123 - Island Green", "TWB64 124 - Nogizaka46 Purple", "TWB64 125 - Ninja Turtle Green", "TWB64 126 - Slime Blue", "TWB64 127 - Lime Midori", "TWB64 128 - Ghostly Aoi", "TWB64 129 - Retro Bogeda", "TWB64 130 - Royal Blue", "TWB64 131 - Neon Purple", "TWB64 132 - Neon Orange", "TWB64 133 - Moonlight Vision", "TWB64 134 - Rising Sun Red", "TWB64 135 - Burger King Color Combo", "TWB64 136 - Grand Zeno Coat", "TWB64 137 - Pac-Man Yellow", "TWB64 138 - Irish Green", "TWB64 139 - Goku Gi", "TWB64 140 - Dragon Ball Orange", "TWB64 141 - Christmas Gold", "TWB64 142 - Pepsi Vision", "TWB64 143 - Bubblun Green", "TWB64 144 - Bobblun Blue", "TWB64 145 - Baja Blast Storm", "TWB64 146 - Olympic Gold", "TWB64 147 - LisAni Orange!", "TWB64 148 - Liella Purple!", "TWB64 149 - Olympic Silver", "TWB64 150 - Olympic Bronze", "TWB64 151 - ANA Flight Blue", "TWB64 152 - Nijigasaki Orange", "TWB64 153 - Holoblue", "TWB64 154 - WWE White and Red", "TWB64 155 - Yoshi Egg Green", "TWB64 156 - Pokedex Red", "TWB64 157 - FamilyMart Vision", "TWB64 158 - Xbox Green", "TWB64 159 - Sonic Mega Blue", "TWB64 160 - Sprite Green", "TWB64 161 - Scarlett Green", "TWB64 162 - Glitchy Blue", "TWB64 163 - Classic LCD", "TWB64 164 - 3DS Virtual Console Ver.", "TWB64 165 - PocketStation Ver.", "TWB64 166 - Timeless Gold and Red", "TWB64 167 - Smurfy Blue", "TWB64 168 - Swampy Ogre Green", "TWB64 169 - Sailor Spinach Green", "TWB64 170 - Shenron Green", "TWB64 171 - Berserk Blood", "TWB64 172 - Super Star Pink", "TWB64 173 - Gamebuino Classic Ver.", "TWB64 174 - Barbie Pink", "TWB64 175 - YOASOBI AMARANTH", "TWB64 176 - Nokia 3310 Ver.", "TWB64 177 - Clover Green", "TWB64 178 - Goku GT Gi", "TWB64 179 - Famicom Disk Yellow", "TWB64 180 - Team Rocket Uniform", "TWB64 181 - SEIKO Timely Vision", "TWB64 182 - PASTEL109", "TWB64 183 - Doraemon Tricolor", "TWB64 184 - Fury Blue", "TWB64 185 - GOOD SMILE VISION", "TWB64 186 - Puyo Puyo Green", "TWB64 187 - Circle K Color Combo", "TWB64 188 - Pizza Hut Red", "TWB64 189 - Emerald Green", "TWB64 190 - Grand Ivory", "TWB64 191 - Demon's Gold", "TWB64 192 - SEGA Tokyo Blue", "TWB64 193 - Champion's Tunic", "TWB64 194 - DK Barrel Brown", "TWB64 195 - EVA-01", "TWB64 196 - Wild West Vision", "TWB64 197 - Optimus Prime Palette", "TWB64 198 - Niconico Sea Green", "TWB64 199 - Duracell Copper", "TWB64 200 - TOKYO SKYTREE CLOUDY BLUE"), + valueLabels = listOf("TWB64 101 - 765PRO Pink", "TWB64 102 - CINDERELLA Blue", "TWB64 103 - MILLION Yellow!", "TWB64 104 - SideM Green", "TWB64 105 - SHINY Sky Blue", "TWB64 106 - Angry Volcano Ver.", "TWB64 107 - NBA Vision", "TWB64 108 - NFL Vision", "TWB64 109 - MLB Vision", "TWB64 110 - Anime Digivice Ver.", "TWB64 111 - Aquatic Iro", "TWB64 112 - Tea Midori", "TWB64 113 - Sakura Pink", "TWB64 114 - Wisteria Murasaki", "TWB64 115 - Oni Aka", "TWB64 116 - Golden Kiiro", "TWB64 117 - Silver Shiro", "TWB64 118 - Fruity Orange", "TWB64 119 - AKB48 Pink", "TWB64 120 - Miku Blue", "TWB64 121 - Tri Digivice Ver.", "TWB64 122 - Survey Corps Uniform", "TWB64 123 - Island Green", "TWB64 124 - Nogizaka46 Purple", "TWB64 125 - Ninja Turtle Green", "TWB64 126 - Slime Blue", "TWB64 127 - Lime Midori", "TWB64 128 - Ghostly Aoi", "TWB64 129 - Retro Bogeda", "TWB64 130 - Royal Blue", "TWB64 131 - Neon Purple", "TWB64 132 - Neon Orange", "TWB64 133 - Moonlight Vision", "TWB64 134 - Rising Sun Red", "TWB64 135 - Burger King Color Combo", "TWB64 136 - Grand Zeno Coat", "TWB64 137 - Pac-Man Yellow", "TWB64 138 - Irish Green", "TWB64 139 - Goku Gi", "TWB64 140 - Dragon Ball Orange", "TWB64 141 - Christmas Gold", "TWB64 142 - Pepsi Vision", "TWB64 143 - Bubblun Green", "TWB64 144 - Bobblun Blue", "TWB64 145 - Baja Blast Storm", "TWB64 146 - Olympic Gold", "TWB64 147 - LisAni Orange!", "TWB64 148 - Liella Purple!", "TWB64 149 - Olympic Silver", "TWB64 150 - Olympic Bronze", "TWB64 151 - ANA Flight Blue", "TWB64 152 - Nijigasaki Orange", "TWB64 153 - Holoblue", "TWB64 154 - WWE White and Red", "TWB64 155 - Yoshi Egg Green", "TWB64 156 - Pokedex Red", "TWB64 157 - FamilyMart Vision", "TWB64 158 - Xbox Green", "TWB64 159 - Sonic Mega Blue", "TWB64 160 - Sprite Green", "TWB64 161 - Scarlett Green", "TWB64 162 - Glitchy Blue", "TWB64 163 - Classic LCD", "TWB64 164 - 3DS Virtual Console Ver.", "TWB64 165 - PocketStation Ver.", "TWB64 166 - Timeless Gold and Red", "TWB64 167 - Smurfy Blue", "TWB64 168 - Swampy Ogre Green", "TWB64 169 - Sailor Spinach Green", "TWB64 170 - Shenron Green", "TWB64 171 - Berserk Blood", "TWB64 172 - Super Star Pink", "TWB64 173 - Gamebuino Classic Ver.", "TWB64 174 - Barbie Pink", "TWB64 175 - YOASOBI AMARANTH", "TWB64 176 - Nokia 3310 Ver.", "TWB64 177 - Clover Green", "TWB64 178 - Goku GT Gi", "TWB64 179 - Famicom Disk Yellow", "TWB64 180 - Team Rocket Uniform", "TWB64 181 - SEIKO Timely Vision", "TWB64 182 - PASTEL109", "TWB64 183 - Doraemon Tricolor", "TWB64 184 - Fury Blue", "TWB64 185 - GOOD SMILE VISION", "TWB64 186 - Puyo Puyo Green", "TWB64 187 - Circle K Color Combo", "TWB64 188 - Pizza Hut Red", "TWB64 189 - Emerald Green", "TWB64 190 - Grand Ivory", "TWB64 191 - Demon's Gold", "TWB64 192 - SEGA Tokyo Blue", "TWB64 193 - Champion's Tunic", "TWB64 194 - DK Barrel Brown", "TWB64 195 - EVA-01", "TWB64 196 - Wild West Vision", "TWB64 197 - Optimus Prime Palette", "TWB64 198 - Niconico Sea Green", "TWB64 199 - Duracell Copper", "TWB64 200 - TOKYO SKYTREE CLOUDY BLUE"), + defaultValue = "TWB64 101 - 765PRO Pink", + category = RetroOptionCategory.DISPLAY, + advanced = true, + ), + RetroCoreOption( + key = "gambatte_gb_palette_twb64_3", + label = "> TWB64 - Pack 3 Palette", + values = listOf("TWB64 201 - DMG-GOLD", "TWB64 202 - LCD Clock Green", "TWB64 203 - Famicom Frenzy", "TWB64 204 - DK Arcade Blue", "TWB64 205 - Advanced Indigo", "TWB64 206 - Ultra Black", "TWB64 207 - Chaos Emerald Green", "TWB64 208 - Blue Bomber Vision", "TWB64 209 - Krispy Kreme Vision", "TWB64 210 - Steam Gray", "TWB64 211 - Dream Land GB Ver.", "TWB64 212 - Pokemon Pinball Ver.", "TWB64 213 - Poketch Ver.", "TWB64 214 - COLLECTION of SaGa Ver.", "TWB64 215 - Rocky-Valley Holiday", "TWB64 216 - Giga Kiwi DMG", "TWB64 217 - DMG Pea Green", "TWB64 218 - Timing Hero Ver.", "TWB64 219 - Invincible Yellow and Blue", "TWB64 220 - Grinchy Green", "TWB64 221 - Animate Vision", "TWB64 222 - School Idol Mix", "TWB64 223 - Green Awakening", "TWB64 224 - Goomba Brown", "TWB64 225 - WarioWare MicroBlue", "TWB64 226 - KonoSuba Sherbet", "TWB64 227 - Spooky Purple", "TWB64 228 - Treasure Gold", "TWB64 229 - Cherry Blossom Pink", "TWB64 230 - Golden Trophy", "TWB64 231 - Glacial Winter Blue", "TWB64 232 - Leprechaun Green", "TWB64 233 - SAITAMA SUPER BLUE", "TWB64 234 - SAITAMA SUPER GREEN", "TWB64 235 - Duolingo Green", "TWB64 236 - Super Mushroom Vision", "TWB64 237 - Ancient Hisuian Brown", "TWB64 238 - Sky Pop Ivory", "TWB64 239 - LAWSON BLUE", "TWB64 240 - Anime Expo Red", "TWB64 241 - Brilliant Diamond Blue", "TWB64 242 - Shining Pearl Pink", "TWB64 243 - Funimation Melon", "TWB64 244 - Teyvat Brown", "TWB64 245 - Chozo Blue", "TWB64 246 - Spotify Green", "TWB64 247 - Dr Pepper Red", "TWB64 248 - NHK Silver Gray", "TWB64 249 - Dunkin' Vision", "TWB64 250 - Deku Gamma Palette", "TWB64 251 - Universal Studios Blue", "TWB64 252 - Hogwarts Goldius", "TWB64 253 - Kentucky Fried Red", "TWB64 254 - Cheeto Orange", "TWB64 255 - Namco Idol Pink", "TWB64 256 - Domino's Pizza Vision", "TWB64 257 - Pac-Man Vision", "TWB64 258 - Bill's PC Screen", "TWB64 259 - Ebott Prolouge", "TWB64 260 - Fool's Gold and Silver", "TWB64 261 - UTA VISION", "TWB64 262 - Metallic Paldea Brass", "TWB64 263 - Classy Christmas", "TWB64 264 - Winter Christmas", "TWB64 265 - IDOL WORLD TRICOLOR!!!", "TWB64 266 - Inkling Tricolor", "TWB64 267 - 7-Eleven Color Combo", "TWB64 268 - PAC-PALETTE", "TWB64 269 - Vulnerable Blue", "TWB64 270 - Nightvision Green", "TWB64 271 - Bandai Namco Tricolor", "TWB64 272 - Gold, Silver, and Bronze", "TWB64 273 - Deku Vigilante Palette", "TWB64 274 - Super Famicom Supreme", "TWB64 275 - Absorbent and Yellow", "TWB64 276 - 765PRO TRICOLOR", "TWB64 277 - GameCube Glimmer", "TWB64 278 - 1st Vision Pastel", "TWB64 279 - Perfect Majin Emperor", "TWB64 280 - J-Pop Idol Sherbet", "TWB64 281 - Ryuuguu Sunset", "TWB64 282 - Tropical Starfall", "TWB64 283 - Colorful Horizons", "TWB64 284 - BLACKPINK BLINK PINK", "TWB64 285 - DMG-SWITCH", "TWB64 286 - POCKET SWITCH", "TWB64 287 - Sunny Passion Paradise", "TWB64 288 - Saiyan Beast Silver", "TWB64 289 - RADIANT SMILE RAMP", "TWB64 290 - A-RISE BLUE", "TWB64 291 - TROPICAL TWICE APRICOT", "TWB64 292 - Odyssey Boy", "TWB64 293 - Frog Coin Green", "TWB64 294 - Garfield Vision", "TWB64 295 - Bedrock Caveman Vision", "TWB64 296 - BANGTAN ARMY PURPLE", "TWB64 297 - LE SSERAFIM FEARLESS BLUE", "TWB64 298 - Baja Blast Beach", "TWB64 299 - 3DS Virtual Console Green", "TWB64 300 - Wonder Purple"), + valueLabels = listOf("TWB64 201 - DMG-GOLD", "TWB64 202 - LCD Clock Green", "TWB64 203 - Famicom Frenzy", "TWB64 204 - DK Arcade Blue", "TWB64 205 - Advanced Indigo", "TWB64 206 - Ultra Black", "TWB64 207 - Chaos Emerald Green", "TWB64 208 - Blue Bomber Vision", "TWB64 209 - Krispy Kreme Vision", "TWB64 210 - Steam Gray", "TWB64 211 - Dream Land GB Ver.", "TWB64 212 - Pokemon Pinball Ver.", "TWB64 213 - Poketch Ver.", "TWB64 214 - COLLECTION of SaGa Ver.", "TWB64 215 - Rocky-Valley Holiday", "TWB64 216 - Giga Kiwi DMG", "TWB64 217 - DMG Pea Green", "TWB64 218 - Timing Hero Ver.", "TWB64 219 - Invincible Yellow and Blue", "TWB64 220 - Grinchy Green", "TWB64 221 - Animate Vision", "TWB64 222 - School Idol Mix", "TWB64 223 - Green Awakening", "TWB64 224 - Goomba Brown", "TWB64 225 - WarioWare MicroBlue", "TWB64 226 - KonoSuba Sherbet", "TWB64 227 - Spooky Purple", "TWB64 228 - Treasure Gold", "TWB64 229 - Cherry Blossom Pink", "TWB64 230 - Golden Trophy", "TWB64 231 - Glacial Winter Blue", "TWB64 232 - Leprechaun Green", "TWB64 233 - SAITAMA SUPER BLUE", "TWB64 234 - SAITAMA SUPER GREEN", "TWB64 235 - Duolingo Green", "TWB64 236 - Super Mushroom Vision", "TWB64 237 - Ancient Hisuian Brown", "TWB64 238 - Sky Pop Ivory", "TWB64 239 - LAWSON BLUE", "TWB64 240 - Anime Expo Red", "TWB64 241 - Brilliant Diamond Blue", "TWB64 242 - Shining Pearl Pink", "TWB64 243 - Funimation Melon", "TWB64 244 - Teyvat Brown", "TWB64 245 - Chozo Blue", "TWB64 246 - Spotify Green", "TWB64 247 - Dr Pepper Red", "TWB64 248 - NHK Silver Gray", "TWB64 249 - Dunkin' Vision", "TWB64 250 - Deku Gamma Palette", "TWB64 251 - Universal Studios Blue", "TWB64 252 - Hogwarts Goldius", "TWB64 253 - Kentucky Fried Red", "TWB64 254 - Cheeto Orange", "TWB64 255 - Namco Idol Pink", "TWB64 256 - Domino's Pizza Vision", "TWB64 257 - Pac-Man Vision", "TWB64 258 - Bill's PC Screen", "TWB64 259 - Ebott Prolouge", "TWB64 260 - Fool's Gold and Silver", "TWB64 261 - UTA VISION", "TWB64 262 - Metallic Paldea Brass", "TWB64 263 - Classy Christmas", "TWB64 264 - Winter Christmas", "TWB64 265 - IDOL WORLD TRICOLOR!!!", "TWB64 266 - Inkling Tricolor", "TWB64 267 - 7-Eleven Color Combo", "TWB64 268 - PAC-PALETTE", "TWB64 269 - Vulnerable Blue", "TWB64 270 - Nightvision Green", "TWB64 271 - Bandai Namco Tricolor", "TWB64 272 - Gold, Silver, and Bronze", "TWB64 273 - Deku Vigilante Palette", "TWB64 274 - Super Famicom Supreme", "TWB64 275 - Absorbent and Yellow", "TWB64 276 - 765PRO TRICOLOR", "TWB64 277 - GameCube Glimmer", "TWB64 278 - 1st Vision Pastel", "TWB64 279 - Perfect Majin Emperor", "TWB64 280 - J-Pop Idol Sherbet", "TWB64 281 - Ryuuguu Sunset", "TWB64 282 - Tropical Starfall", "TWB64 283 - Colorful Horizons", "TWB64 284 - BLACKPINK BLINK PINK", "TWB64 285 - DMG-SWITCH", "TWB64 286 - POCKET SWITCH", "TWB64 287 - Sunny Passion Paradise", "TWB64 288 - Saiyan Beast Silver", "TWB64 289 - RADIANT SMILE RAMP", "TWB64 290 - A-RISE BLUE", "TWB64 291 - TROPICAL TWICE APRICOT", "TWB64 292 - Odyssey Boy", "TWB64 293 - Frog Coin Green", "TWB64 294 - Garfield Vision", "TWB64 295 - Bedrock Caveman Vision", "TWB64 296 - BANGTAN ARMY PURPLE", "TWB64 297 - LE SSERAFIM FEARLESS BLUE", "TWB64 298 - Baja Blast Beach", "TWB64 299 - 3DS Virtual Console Green", "TWB64 300 - Wonder Purple"), + defaultValue = "TWB64 201 - DMG-GOLD", + category = RetroOptionCategory.DISPLAY, + advanced = true, + ), + RetroCoreOption( + key = "gambatte_gbc_color_correction", + label = "Color Correction", + values = listOf("GBC only", "always", "disabled"), + valueLabels = listOf("GBC Only", "Always", "disabled"), + defaultValue = "GBC only", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "gambatte_gbc_color_correction_mode", + label = "Color Correction Mode", + values = listOf("accurate", "fast"), + valueLabels = listOf("Accurate", "Fast"), + defaultValue = "accurate", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "gambatte_audio_resampler", + label = "Audio Resampler", + values = listOf("sinc", "cc"), + valueLabels = listOf("Sinc", "Cosine"), + defaultValue = "cc", + category = RetroOptionCategory.SOUND, + advanced = false, + ), + RetroCoreOption( + key = "gambatte_gb_bootloader", + label = "Use Official Bootloader (Restart Required)", + values = listOf("enabled", "disabled"), + valueLabels = listOf("enabled", "disabled"), + defaultValue = "enabled", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + RetroCoreOption( + key = "gambatte_gb_hwmode", + label = "Emulated Hardware (Restart Required)", + values = listOf("Auto", "GB", "GBC", "GBA"), + valueLabels = listOf("Auto", "GB", "GBC", "GBA"), + defaultValue = "Auto", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + RetroCoreOption( + key = "gambatte_gbc_frontlight_position", + label = "Color Correction - Frontlight Position", + values = listOf("central", "above screen", "below screen"), + valueLabels = listOf("Central", "Above Screen", "Below Screen"), + defaultValue = "central", + category = RetroOptionCategory.SYSTEM, + advanced = true, + ), + RetroCoreOption( + key = "gambatte_mix_frames", + label = "Interframe Blending", + values = listOf("disabled", "mix", "lcd_ghosting", "lcd_ghosting_fast"), + valueLabels = listOf("disabled", "Simple", "LCD Ghosting (Accurate)", "LCD Ghosting (Fast)"), + defaultValue = "disabled", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + ) + + val MGBA: List = listOf( + RetroCoreOption( + key = "mgba_allow_opposing_directions", + label = "Allow Opposing Directional Input", + values = listOf("no", "yes"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "no", + category = RetroOptionCategory.CONTROLS, + advanced = false, + ), + RetroCoreOption( + key = "mgba_force_gbp", + label = "Game Boy Player Rumble (Restart)", + values = listOf("OFF", "ON"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "OFF", + category = RetroOptionCategory.CONTROLS, + advanced = false, + ), + RetroCoreOption( + key = "mgba_solar_sensor_level", + label = "Solar Sensor Level", + values = listOf("sensor", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"), + valueLabels = listOf("Use device sensor if available", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"), + defaultValue = "0", + category = RetroOptionCategory.CONTROLS, + advanced = false, + ), + RetroCoreOption( + key = "mgba_color_correction", + label = "Color Correction", + values = listOf("OFF", "GBA", "GBC", "Auto"), + valueLabels = listOf("disabled", "Game Boy Advance", "Game Boy Color", "Auto"), + defaultValue = "OFF", + category = RetroOptionCategory.DISPLAY, + advanced = false, + labelRes = R.string.retro_co_color_correction, + ), + RetroCoreOption( + key = "mgba_gb_colors", + label = "Default Game Boy Palette", + values = listOf("Grayscale"), + valueLabels = listOf("Grayscale"), + defaultValue = "Grayscale", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "mgba_gb_colors_preset", + label = "Hardware Preset Game Boy Palettes (Restart)", + values = listOf("0", "1", "2", "3"), + valueLabels = listOf("Default Game Boy preset", "Game Boy Color presets only", "Super Game Boy presets only", "Any available presets"), + defaultValue = "0", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "mgba_interframe_blending", + label = "Interframe Blending", + values = listOf("OFF", "mix", "mix_smart", "lcd_ghosting", "lcd_ghosting_fast"), + valueLabels = listOf("disabled", "Simple", "Smart", "LCD Ghosting (Accurate)", "LCD Ghosting (Fast)"), + defaultValue = "OFF", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "mgba_sgb_borders", + label = "Use Super Game Boy Borders (Restart)", + values = listOf("ON", "OFF"), + valueLabels = listOf("enabled", "disabled"), + defaultValue = "ON", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "mgba_frameskip", + label = "Frameskip", + values = listOf("disabled", "auto", "auto_threshold", "fixed_interval"), + valueLabels = listOf("disabled", "Auto", "Auto (Threshold)", "Fixed Interval"), + defaultValue = "disabled", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + ), + RetroCoreOption( + key = "mgba_frameskip_interval", + label = "Frameskip Interval", + values = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"), + valueLabels = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"), + defaultValue = "0", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + ), + RetroCoreOption( + key = "mgba_frameskip_threshold", + label = "Frameskip Threshold (%)", + values = listOf("15", "18", "21", "24", "27", "30", "33", "36", "39", "42", "45", "48", "51", "54", "57", "60"), + valueLabels = listOf("15", "18", "21", "24", "27", "30", "33", "36", "39", "42", "45", "48", "51", "54", "57", "60"), + defaultValue = "33", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + ), + RetroCoreOption( + key = "mgba_idle_optimization", + label = "Idle Loop Removal", + values = listOf("Remove Known", "Detect and Remove", "Don't Remove"), + valueLabels = listOf("Remove Known", "Detect and Remove", "Don't Remove"), + defaultValue = "Remove Known", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + ), + RetroCoreOption( + key = "mgba_audio_low_pass_filter", + label = "Audio Filter", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.SOUND, + advanced = false, + ), + RetroCoreOption( + key = "mgba_audio_low_pass_range", + label = "Audio Filter Level", + values = listOf("5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95"), + valueLabels = listOf("5%", "10%", "15%", "20%", "25%", "30%", "35%", "40%", "45%", "50%", "55%", "60%", "65%", "70%", "75%", "80%", "85%", "90%", "95%"), + defaultValue = "60", + category = RetroOptionCategory.SOUND, + advanced = false, + ), + RetroCoreOption( + key = "mgba_gb_model", + label = "Game Boy Model (Restart)", + values = listOf("Autodetect", "Game Boy", "Super Game Boy", "Game Boy Color", "Super Game Boy Color", "Game Boy Advance"), + valueLabels = listOf("Autodetect", "Game Boy", "Super Game Boy", "Game Boy Color", "Super Game Boy Color", "Game Boy Advance"), + defaultValue = "Autodetect", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + RetroCoreOption( + key = "mgba_skip_bios", + label = "Skip BIOS Intro (Restart)", + values = listOf("OFF", "ON"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "OFF", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + RetroCoreOption( + key = "mgba_use_bios", + label = "Use BIOS File if Found (Restart)", + values = listOf("ON", "OFF"), + valueLabels = listOf("enabled", "disabled"), + defaultValue = "ON", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + ) + + val GENESIS_PLUS_GX: List = listOf( + RetroCoreOption( + key = "genesis_plus_gx_gun_cursor", + label = "Show Light Gun Crosshair", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_gun_input", + label = "Light Gun Input", + values = listOf("lightgun", "touchscreen"), + valueLabels = listOf("Light Gun", "Touchscreen"), + defaultValue = "lightgun", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_invert_mouse", + label = "Invert Mouse Y-Axis", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_aspect_ratio", + label = "Core-Provided Aspect Ratio", + values = listOf("auto", "NTSC PAR", "PAL PAR", "4:3", "Uncorrected"), + valueLabels = listOf("Auto", "NTSC PAR", "PAL PAR", "4:3", "Uncorrected"), + defaultValue = "auto", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "genesis_plus_gx_blargg_ntsc_filter", + label = "Blargg NTSC Filter", + values = listOf("disabled", "monochrome", "composite", "svideo", "rgb"), + valueLabels = listOf("disabled", "Monochrome", "Composite", "S-Video", "RGB"), + defaultValue = "disabled", + category = RetroOptionCategory.DISPLAY, + advanced = false, + labelRes = R.string.retro_co_ntsc_filter, + ), + RetroCoreOption( + key = "genesis_plus_gx_frameskip", + label = "Frameskip", + values = listOf("disabled", "auto", "manual"), + valueLabels = listOf("disabled", "Auto", "Manual"), + defaultValue = "disabled", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "genesis_plus_gx_frameskip_threshold", + label = "Frameskip Threshold (%)", + values = listOf("15", "18", "21", "24", "27", "30", "33", "36", "39", "42", "45", "48", "51", "54", "57", "60"), + valueLabels = listOf("15", "18", "21", "24", "27", "30", "33", "36", "39", "42", "45", "48", "51", "54", "57", "60"), + defaultValue = "33", + category = RetroOptionCategory.DISPLAY, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_gg_extra", + label = "Game Gear Extended Screen", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "genesis_plus_gx_lcd_filter", + label = "LCD Ghosting Filter", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "genesis_plus_gx_left_border", + label = "Hide Master System Side Borders", + values = listOf("disabled", "left border", "left & right borders"), + valueLabels = listOf("disabled", "Left Border Only", "Left & Right Borders"), + defaultValue = "disabled", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "genesis_plus_gx_overscan", + label = "Borders", + values = listOf("disabled", "top/bottom", "left/right", "full"), + valueLabels = listOf("disabled", "Top/Bottom", "Left/Right", "Full"), + defaultValue = "disabled", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "genesis_plus_gx_render", + label = "Interlaced Mode 2 Output", + values = listOf("single field", "double field"), + valueLabels = listOf("Single Field", "Double Field"), + defaultValue = "single field", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "genesis_plus_gx_addr_error", + label = "68K Address Error", + values = listOf("enabled", "disabled"), + valueLabels = listOf("enabled", "disabled"), + defaultValue = "enabled", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + ), + RetroCoreOption( + key = "genesis_plus_gx_cd_latency", + label = "CD Access Time", + values = listOf("enabled", "disabled"), + valueLabels = listOf("enabled", "disabled"), + defaultValue = "enabled", + category = RetroOptionCategory.PERFORMANCE, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_cd_precache", + label = "CD Image Cache", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.PERFORMANCE, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_enhanced_vscroll", + label = "Enhanced per-tile vertical scroll", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + ), + RetroCoreOption( + key = "genesis_plus_gx_enhanced_vscroll_limit", + label = "Enhanced per-tile vertical scroll limit", + values = listOf("2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"), + valueLabels = listOf("2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"), + defaultValue = "8", + category = RetroOptionCategory.PERFORMANCE, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_force_dtack", + label = "System Lock-Ups", + values = listOf("enabled", "disabled"), + valueLabels = listOf("enabled", "disabled"), + defaultValue = "enabled", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + ), + RetroCoreOption( + key = "genesis_plus_gx_no_sprite_limit", + label = "Remove Per-Line Sprite Limit", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + labelRes = R.string.retro_co_remove_sprite_limit, + ), + RetroCoreOption( + key = "genesis_plus_gx_overclock", + label = "CPU Speed", + values = listOf("100", "125", "150", "175", "200", "225", "250", "275", "300", "325", "350", "375", "400", "425", "450", "475", "500"), + valueLabels = listOf("100%", "125%", "150%", "175%", "200%", "225%", "250%", "275%", "300%", "325%", "350%", "375%", "400%", "425%", "450%", "475%", "500%"), + defaultValue = "100%", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + ), + RetroCoreOption( + key = "genesis_plus_gx_audio_eq_high", + label = "EQ High", + values = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"), + valueLabels = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_audio_eq_low", + label = "EQ Low", + values = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"), + valueLabels = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_audio_eq_mid", + label = "EQ Mid", + values = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"), + valueLabels = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_audio_filter", + label = "Audio Filter", + values = listOf("disabled", "low-pass", "EQ"), + valueLabels = listOf("disabled", "Low-Pass", "EQ"), + defaultValue = "disabled", + category = RetroOptionCategory.SOUND, + advanced = false, + ), + RetroCoreOption( + key = "genesis_plus_gx_cdda_volume", + label = "CD-DA Volume", + values = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"), + valueLabels = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_fm_preamp", + label = "FM Preamp Level", + values = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100", "105", "110", "115", "120", "125", "130", "135", "140", "145", "150", "155", "160", "165", "170", "175", "180", "185", "190", "195", "200"), + valueLabels = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100", "105", "110", "115", "120", "125", "130", "135", "140", "145", "150", "155", "160", "165", "170", "175", "180", "185", "190", "195", "200"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = false, + ), + RetroCoreOption( + key = "genesis_plus_gx_lowpass_range", + label = "Low-Pass Filter %", + values = listOf("5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95"), + valueLabels = listOf("5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95"), + defaultValue = "60", + category = RetroOptionCategory.SOUND, + advanced = false, + ), + RetroCoreOption( + key = "genesis_plus_gx_md_channel_0_volume", + label = "Mega Drive/Genesis FM Channel 0 Volume %", + values = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + valueLabels = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_md_channel_1_volume", + label = "Mega Drive/Genesis FM Channel 1 Volume %", + values = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + valueLabels = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_md_channel_2_volume", + label = "Mega Drive/Genesis FM Channel 2 Volume %", + values = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + valueLabels = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_md_channel_3_volume", + label = "Mega Drive/Genesis FM Channel 3 Volume %", + values = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + valueLabels = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_md_channel_4_volume", + label = "Mega Drive/Genesis FM Channel 4 Volume %", + values = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + valueLabels = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_md_channel_5_volume", + label = "Mega Drive/Genesis FM Channel 5 Volume %", + values = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + valueLabels = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_pcm_volume", + label = "PCM Volume", + values = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"), + valueLabels = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_psg_channel_0_volume", + label = "PSG Tone Channel 0 Volume %", + values = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + valueLabels = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_psg_channel_1_volume", + label = "PSG Tone Channel 1 Volume %", + values = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + valueLabels = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_psg_channel_2_volume", + label = "PSG Tone Channel 2 Volume %", + values = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + valueLabels = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_psg_channel_3_volume", + label = "PSG Noise Channel 3 Volume %", + values = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + valueLabels = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_psg_preamp", + label = "PSG Preamp Level", + values = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100", "105", "110", "115", "120", "125", "130", "135", "140", "145", "150", "155", "160", "165", "170", "175", "180", "185", "190", "195", "200"), + valueLabels = listOf("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100", "105", "110", "115", "120", "125", "130", "135", "140", "145", "150", "155", "160", "165", "170", "175", "180", "185", "190", "195", "200"), + defaultValue = "150", + category = RetroOptionCategory.SOUND, + advanced = false, + ), + RetroCoreOption( + key = "genesis_plus_gx_sms_fm_channel_0_volume", + label = "Master System FM (YM2413) Channel 0 Volume %", + values = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + valueLabels = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_sms_fm_channel_1_volume", + label = "Master System FM (YM2413) Channel 1 Volume %", + values = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + valueLabels = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_sms_fm_channel_2_volume", + label = "Master System FM (YM2413) Channel 2 Volume %", + values = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + valueLabels = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_sms_fm_channel_3_volume", + label = "Master System FM (YM2413) Channel 3 Volume %", + values = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + valueLabels = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_sms_fm_channel_4_volume", + label = "Master System FM (YM2413) Channel 4 Volume %", + values = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + valueLabels = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_sms_fm_channel_5_volume", + label = "Master System FM (YM2413) Channel 5 Volume %", + values = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + valueLabels = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_sms_fm_channel_6_volume", + label = "Master System FM (YM2413) Channel 6 Volume %", + values = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + valueLabels = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_sms_fm_channel_7_volume", + label = "Master System FM (YM2413) Channel 7 Volume %", + values = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + valueLabels = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_sms_fm_channel_8_volume", + label = "Master System FM (YM2413) Channel 8 Volume %", + values = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + valueLabels = listOf("0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"), + defaultValue = "100", + category = RetroOptionCategory.SOUND, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_sound_output", + label = "Sound Output", + values = listOf("stereo", "mono"), + valueLabels = listOf("Stereo", "Mono"), + defaultValue = "stereo", + category = RetroOptionCategory.SOUND, + advanced = false, + ), + RetroCoreOption( + key = "genesis_plus_gx_ym2413", + label = "Master System FM (YM2413)", + values = listOf("auto", "disabled", "enabled"), + valueLabels = listOf("Auto", "disabled", "enabled"), + defaultValue = "auto", + category = RetroOptionCategory.SOUND, + advanced = false, + ), + RetroCoreOption( + key = "genesis_plus_gx_ym2413_core", + label = "Master System FM (YM2413) Core", + values = listOf("mame", "nuked"), + valueLabels = listOf("MAME", "Nuked"), + defaultValue = "mame", + category = RetroOptionCategory.SOUND, + advanced = false, + ), + RetroCoreOption( + key = "genesis_plus_gx_add_on", + label = "CD add-on (MD mode) (Requires Restart)", + values = listOf("auto", "sega/mega cd", "megasd", "none"), + valueLabels = listOf("Auto", "Sega/Mega CD", "MegaSD", "None"), + defaultValue = "auto", + category = RetroOptionCategory.SYSTEM, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_bios", + label = "System Boot ROM", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.SYSTEM, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_cart_bram", + label = "CD Backup Cart BRAM (Requires Restart)", + values = listOf("per cart", "per game"), + valueLabels = listOf("Per-Cart", "Per-Game"), + defaultValue = "per cart", + category = RetroOptionCategory.SYSTEM, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_cart_size", + label = "CD Backup Cart BRAM Size (Requires Restart)", + values = listOf("disabled", "128k", "256k", "512k", "1meg", "2meg", "4meg"), + valueLabels = listOf("Disabled", "128Kbit", "256Kbit", "512Kbit", "1Mbit", "2Mbit", "4Mbit"), + defaultValue = "4meg", + category = RetroOptionCategory.SYSTEM, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_lock_on", + label = "Cartridge Lock-On", + values = listOf("disabled", "game genie", "action replay (pro)", "sonic & knuckles"), + valueLabels = listOf("disabled", "Game Genie", "Action Replay (Pro)", "Sonic & Knuckles"), + defaultValue = "disabled", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + RetroCoreOption( + key = "genesis_plus_gx_region_detect", + label = "System Region", + values = listOf("auto", "ntsc-u", "pal", "ntsc-j"), + valueLabels = listOf("Auto", "NTSC-U", "PAL", "NTSC-J"), + defaultValue = "auto", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + RetroCoreOption( + key = "genesis_plus_gx_system_bram", + label = "CD System BRAM (Requires Restart)", + values = listOf("per bios", "per game"), + valueLabels = listOf("Per-BIOS", "Per-Game"), + defaultValue = "per bios", + category = RetroOptionCategory.SYSTEM, + advanced = true, + ), + RetroCoreOption( + key = "genesis_plus_gx_system_hw", + label = "System Hardware", + values = listOf("auto", "sg-1000", "sg-1000 II", "sg-1000 II + ram ext.", "mark-III", "master system", "master system II", "game gear", "mega drive / genesis"), + valueLabels = listOf("Auto", "SG-1000", "SG-1000 II", "SG-1000 II + RAM Ext.", "Mark III", "Master System", "Master System II", "Game Gear", "Mega Drive/Genesis"), + defaultValue = "auto", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + RetroCoreOption( + key = "genesis_plus_gx_vdp_mode", + label = "Force VDP Mode", + values = listOf("auto", "60hz", "50hz"), + valueLabels = listOf("Disabled", "NTSC (60Hz)", "PAL (50Hz)"), + defaultValue = "auto", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + RetroCoreOption( + key = "genesis_plus_gx_ym2612", + label = "Mega Drive/Genesis FM", + values = listOf("mame (ym2612)", "mame (asic ym3438)", "mame (enhanced ym3438)", "nuked (ym2612)", "nuked (ym3438)"), + valueLabels = listOf("MAME (YM2612)", "MAME (ASIC YM3438)", "MAME (Enhanced YM3438)", "Nuked (YM2612)", "Nuked (YM3438)"), + defaultValue = "mame (ym2612)", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + ) + + val BEETLE_PSX: List = listOf( + RetroCoreOption( + key = "beetle_psx_analog_calibration", + label = "Analog Self-Calibration", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_analog_toggle", + label = "DualShock Analog Mode Toggle", + values = listOf("disabled", "enabled", "enabled-analog"), + valueLabels = listOf("disabled", "enabled", "Default-Analog"), + defaultValue = "disabled", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_analog_toggle_combo", + label = "DualShock Analog Mode Combo", + values = listOf("l1+l2+r1+r2+start+select", "l1+r1+select", "l1+r1+start", "l1+r1+l3", "l1+r1+r3", "l2+r2+select", "l2+r2+start", "l2+r2+l3", "l2+r2+r3", "l3+r3"), + valueLabels = listOf("L1 + L2 + R1 + R2 + Start + Select", "L1 + R1 + Select", "L1 + R1 + Start", "L1 + R1 + L3", "L1 + R1 + R3", "L2 + R2 + Select", "L2 + R2 + Start", "L2 + R2 + L3", "L2 + R2 + R3", "L3 + R3"), + defaultValue = "l1+r1+select", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_analog_toggle_hold", + label = "DualShock Analog Mode Combo Hold Delay", + values = listOf("0", "1", "2", "3", "4", "5"), + valueLabels = listOf("0 Second Delay", "1 Second Delay", "2 Second Delay", "3 Second Delay", "4 Second Delay", "5 Second Delay"), + defaultValue = "1", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_crosshair_color_p1", + label = "Gun Crosshair Color: Port 1", + values = listOf("red", "blue", "green", "orange", "yellow", "cyan", "pink", "purple", "black", "white"), + valueLabels = listOf("Red", "Blue", "Green", "Orange", "Yellow", "Cyan", "Pink", "Purple", "Black", "White"), + defaultValue = "red", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_crosshair_color_p2", + label = "Gun Crosshair Color: Port 2", + values = listOf("blue", "red", "green", "orange", "yellow", "cyan", "pink", "purple", "black", "white"), + valueLabels = listOf("Blue", "Red", "Green", "Orange", "Yellow", "Cyan", "Pink", "Purple", "Black", "White"), + defaultValue = "blue", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_enable_multitap_port1", + label = "Multitap on Port 1", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_enable_multitap_port2", + label = "Multitap on Port 2", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_gun_cursor", + label = "Gun Cursor", + values = listOf("off", "cross", "dot"), + valueLabels = listOf("disabled", "Cross", "Dot"), + defaultValue = "cross", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_gun_input_mode", + label = "Gun Input Mode", + values = listOf("lightgun", "touchscreen"), + valueLabels = listOf("Light Gun", "Touchscreen"), + defaultValue = "lightgun", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_mouse_sensitivity", + label = "Mouse Sensitivity", + values = listOf("5%", "10%", "15%", "20%", "25%", "30%", "35%", "40%", "45%", "50%", "55%", "60%", "65%", "70%", "75%", "80%", "85%", "90%", "95%", "100%", "105%", "110%", "115%", "120%", "125%", "130%", "135%", "140%", "145%", "150%", "155%", "160%", "165%", "170%", "175%", "180%", "185%", "190%", "195%", "200%"), + valueLabels = listOf("5%", "10%", "15%", "20%", "25%", "30%", "35%", "40%", "45%", "50%", "55%", "60%", "65%", "70%", "75%", "80%", "85%", "90%", "95%", "100%", "105%", "110%", "115%", "120%", "125%", "130%", "135%", "140%", "145%", "150%", "155%", "160%", "165%", "170%", "175%", "180%", "185%", "190%", "195%", "200%"), + defaultValue = "100%", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_negcon_deadzone", + label = "neGcon Twist Deadzone", + values = listOf("0%", "5%", "10%", "15%", "20%", "25%", "30%"), + valueLabels = listOf("0%", "5%", "10%", "15%", "20%", "25%", "30%"), + defaultValue = "0%", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_negcon_response", + label = "neGcon Twist Response", + values = listOf("linear", "quadratic", "cubic"), + valueLabels = listOf("Linear", "Quadratic", "Cubic"), + defaultValue = "linear", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_adaptive_smoothing", + label = "Adaptive Smoothing", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "beetle_psx_aspect_ratio", + label = "Core Aspect Ratio", + values = listOf("corrected", "uncorrected", "4:3", "ntsc", "16:9"), + valueLabels = listOf("Corrected", "Uncorrected", "Force 4:3", "Force NTSC", "Force 16:9"), + defaultValue = "corrected", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "beetle_psx_core_timing_fps", + label = "Core-Reported FPS Timing", + values = listOf("auto_toggle", "force_progressive", "force_interlaced"), + valueLabels = listOf("Automatic Toggling", "Force Progressive Rate", "Force Interlaced Rate"), + defaultValue = "auto_toggle", + category = RetroOptionCategory.DISPLAY, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_crop_overscan", + label = "Crop Overscan", + values = listOf("disabled", "static", "smart"), + valueLabels = listOf("Disabled", "Horizontal", "Horizontal + Vertical"), + defaultValue = "smart", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "beetle_psx_deinterlacer", + label = "Deinterlace Method", + values = listOf("weave", "bob", "bob_offset", "fastmad", "off"), + valueLabels = listOf("Weave", "Bob", "Bob (Offset)", "FastMAD (Motion Adaptive)", "Off"), + defaultValue = "weave", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "beetle_psx_depth", + label = "Internal Color Depth", + values = listOf("16bpp(native)", "32bpp"), + valueLabels = listOf("16 bpp (Native)", "32 bpp"), + defaultValue = "16bpp(native)", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "beetle_psx_dither_mode", + label = "Dithering Pattern", + values = listOf("1x(native)", "internal resolution", "disabled"), + valueLabels = listOf("1x (Native)", "Internal Resolution", "disabled"), + defaultValue = "1x(native)", + category = RetroOptionCategory.DISPLAY, + advanced = false, + labelRes = R.string.retro_co_dithering, + ), + RetroCoreOption( + key = "beetle_psx_dump_textures", + label = "Dump Textures", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.DISPLAY, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_filter", + label = "Texture Filtering", + values = listOf("nearest", "SABR", "xBR", "bilinear", "3-point", "JINC2"), + valueLabels = listOf("Nearest", "SABR", "xBR", "Bilinear", "3-Point", "JINC2"), + defaultValue = "nearest", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "beetle_psx_filter_exclude_2d_polygon", + label = "Exclude 2D Polygons from Filtering", + values = listOf("disabled", "opaque", "all"), + valueLabels = listOf("disabled", "Opaque Only", "Opaque and Semi-Transparent"), + defaultValue = "disabled", + category = RetroOptionCategory.DISPLAY, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_filter_exclude_sprite", + label = "Exclude Sprites from Filtering", + values = listOf("disabled", "opaque", "all"), + valueLabels = listOf("disabled", "Opaque Only", "Opaque and Semi-Transparent"), + defaultValue = "disabled", + category = RetroOptionCategory.DISPLAY, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_frame_duping", + label = "Frame Duping", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "beetle_psx_image_crop", + label = "Additional Cropping", + values = listOf("disabled", "1px", "2px", "3px", "4px", "5px", "6px", "7px", "8px", "9px", "10px", "11px", "12px", "13px", "14px", "15px", "16px", "17px", "18px", "19px", "20px"), + valueLabels = listOf("0", "1px", "2px", "3px", "4px", "5px", "6px", "7px", "8px", "9px", "10px", "11px", "12px", "13px", "14px", "15px", "16px", "17px", "18px", "19px", "20px"), + defaultValue = "disabled", + category = RetroOptionCategory.DISPLAY, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_image_offset", + label = "Offset Cropped Image", + values = listOf("-12px", "-11px", "-10px", "-9px", "-8px", "-7px", "-6px", "-5px", "-4px", "-3px", "-2px", "-1px", "disabled", "+1px", "+2px", "+3px", "+4px", "+5px", "+6px", "+7px", "+8px", "+9px", "+10px", "+11px", "+12px"), + valueLabels = listOf("-12px", "-11px", "-10px", "-9px", "-8px", "-7px", "-6px", "-5px", "-4px", "-3px", "-2px", "-1px", "0", "+1px", "+2px", "+3px", "+4px", "+5px", "+6px", "+7px", "+8px", "+9px", "+10px", "+11px", "+12px"), + defaultValue = "disabled", + category = RetroOptionCategory.DISPLAY, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_image_offset_cycles", + label = "Horizontal Image Offset (GPU Cycles)", + values = listOf("-40", "-39", "-38", "-37", "-36", "-35", "-34", "-33", "-32", "-31", "-30", "-29", "-28", "-27", "-26", "-25", "-24", "-23", "-22", "-21", "-20", "-19", "-18", "-17", "-16", "-15", "-14", "-13", "-12", "-11", "-10", "-9", "-8", "-7", "-6", "-5", "-4", "-3", "-2", "-1", "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"), + valueLabels = listOf("-40", "-39", "-38", "-37", "-36", "-35", "-34", "-33", "-32", "-31", "-30", "-29", "-28", "-27", "-26", "-25", "-24", "-23", "-22", "-21", "-20", "-19", "-18", "-17", "-16", "-15", "-14", "-13", "-12", "-11", "-10", "-9", "-8", "-7", "-6", "-5", "-4", "-3", "-2", "-1", "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"), + defaultValue = "0", + category = RetroOptionCategory.DISPLAY, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_initial_scanline", + label = "Initial Scan Line - NTSC", + values = listOf("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"), + valueLabels = listOf("0 (Default)", "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"), + defaultValue = "0", + category = RetroOptionCategory.DISPLAY, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_initial_scanline_pal", + label = "Initial Scan Line - PAL", + values = listOf("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"), + valueLabels = listOf("0 (Default)", "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"), + defaultValue = "0", + category = RetroOptionCategory.DISPLAY, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_internal_resolution", + label = "Internal GPU Resolution", + values = listOf("1x(native)", "2x", "4x", "8x", "16x"), + valueLabels = listOf("1x (Native)", "2x", "4x", "8x", "16x"), + defaultValue = "1x(native)", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "beetle_psx_last_scanline", + label = "Last Scan Line - NTSC", + values = listOf("210", "211", "212", "213", "214", "215", "216", "217", "218", "219", "220", "221", "222", "223", "224", "225", "226", "227", "228", "229", "230", "231", "232", "233", "234", "235", "236", "237", "238", "239"), + valueLabels = listOf("210", "211", "212", "213", "214", "215", "216", "217", "218", "219", "220", "221", "222", "223", "224", "225", "226", "227", "228", "229", "230", "231", "232", "233", "234", "235", "236", "237", "238", "239 (Default)"), + defaultValue = "239", + category = RetroOptionCategory.DISPLAY, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_last_scanline_pal", + label = "Last Scan Line - PAL", + values = listOf("230", "231", "232", "233", "234", "235", "236", "237", "238", "239", "240", "241", "242", "243", "244", "245", "246", "247", "248", "249", "250", "251", "252", "253", "254", "255", "256", "257", "258", "259", "260", "261", "262", "263", "264", "265", "266", "267", "268", "269", "270", "271", "272", "273", "274", "275", "276", "277", "278", "279", "280", "281", "282", "283", "284", "285", "286", "287"), + valueLabels = listOf("230", "231", "232", "233", "234", "235", "236", "237", "238", "239", "240", "241", "242", "243", "244", "245", "246", "247", "248", "249", "250", "251", "252", "253", "254", "255", "256", "257", "258", "259", "260", "261", "262", "263", "264", "265", "266", "267", "268", "269", "270", "271", "272", "273", "274", "275", "276", "277", "278", "279", "280", "281", "282", "283", "284", "285", "286", "287 (Default)"), + defaultValue = "287", + category = RetroOptionCategory.DISPLAY, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_mdec_yuv", + label = "MDEC YUV Chroma Filter", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.DISPLAY, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_msaa", + label = "Multi-Sampled Anti Aliasing", + values = listOf("1x", "2x", "4x", "8x", "16x"), + valueLabels = listOf("1x", "2x", "4x", "8x", "16x"), + defaultValue = "1x", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "beetle_psx_pal_video_timing_override", + label = "PAL Video Timing Override", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.DISPLAY, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_renderer_software_fb", + label = "Software Framebuffer", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "enabled", + category = RetroOptionCategory.DISPLAY, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_replace_textures", + label = "Replace Textures", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.DISPLAY, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_scaled_uv_offset", + label = "Texture UV Offset", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "enabled", + category = RetroOptionCategory.DISPLAY, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_super_sampling", + label = "Supersampling (Downsample to Native Resolution)", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "beetle_psx_track_textures", + label = "Track Textures", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.DISPLAY, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_cpu_dynarec", + label = "CPU Dynarec", + values = listOf("disabled", "execute", "run_interpreter"), + valueLabels = listOf("Disabled (Beetle Interpreter)", "Max Performance", "Lightrec Interpreter"), + defaultValue = "disabled", + category = RetroOptionCategory.PERFORMANCE, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_dynarec_eventcycles", + label = "Dynarec DMA/GPU/MDEC/Timer Event Cycles", + values = listOf("128", "256", "384", "512", "640", "768", "896", "1024", "1152", "1280", "1408", "1536", "1664", "1792", "1920", "2048"), + valueLabels = listOf("128 (Default)", "256", "384", "512", "640", "768", "896", "1024", "1152", "1280", "1408", "1536", "1664", "1792", "1920", "2048"), + defaultValue = "128", + category = RetroOptionCategory.PERFORMANCE, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_dynarec_invalidate", + label = "Dynarec Code Invalidation", + values = listOf("full", "dma"), + valueLabels = listOf("Full", "DMA Only (Slightly Faster)"), + defaultValue = "full", + category = RetroOptionCategory.PERFORMANCE, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_dynarec_op_cycles", + label = "Dynarec Cycles Per Instruction", + values = listOf("2", "1"), + valueLabels = listOf("2 (Default)", "1 (Accurate, Fixes Parasite Eve 2 etc.)"), + defaultValue = "2", + category = RetroOptionCategory.PERFORMANCE, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_dynarec_spgp_opt", + label = "Dynarec SP GP Hit RAM Optimization", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.PERFORMANCE, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_dynarec_spu_samples", + label = "Dynarec SPU Samples", + values = listOf("1", "4", "16"), + valueLabels = listOf("1 (Default)", "4", "16"), + defaultValue = "1", + category = RetroOptionCategory.PERFORMANCE, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_line_render", + label = "Line-to-Quad Hack", + values = listOf("default", "aggressive", "disabled"), + valueLabels = listOf("Default", "Aggressive", "disabled"), + defaultValue = "default", + category = RetroOptionCategory.PERFORMANCE, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_pgxp_2d_tol", + label = "PGXP 2D Geometry Tolerance", + values = listOf("disabled", "0px", "1px", "2px", "3px", "4px", "5px", "6px", "7px", "8px"), + valueLabels = listOf("disabled", "0px", "1px", "2px", "3px", "4px", "5px", "6px", "7px", "8px"), + defaultValue = "disabled", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + ), + RetroCoreOption( + key = "beetle_psx_pgxp_mode", + label = "PGXP Operation Mode", + values = listOf("disabled", "memory only", "memory + CPU"), + valueLabels = listOf("disabled", "Memory Only", "Memory + CPU (Buggy)"), + defaultValue = "disabled", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + ), + RetroCoreOption( + key = "beetle_psx_pgxp_nclip", + label = "PGXP Primitive Culling", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + ), + RetroCoreOption( + key = "beetle_psx_pgxp_texture", + label = "PGXP Perspective Correct Texturing", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + ), + RetroCoreOption( + key = "beetle_psx_pgxp_vertex", + label = "PGXP Vertex Cache", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + ), + RetroCoreOption( + key = "beetle_psx_spu_silent_voice", + label = "SPU Silent Voice Optimization", + values = listOf("enabled", "disabled"), + valueLabels = listOf("enabled", "disabled"), + defaultValue = "enabled", + category = RetroOptionCategory.PERFORMANCE, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_widescreen_hack", + label = "Widescreen Mode Hack", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + labelRes = R.string.retro_co_widescreen_hack, + ), + RetroCoreOption( + key = "beetle_psx_widescreen_hack_aspect_ratio", + label = "Widescreen Mode Hack Aspect Ratio", + values = listOf("16:9", "16:10", "18:9", "19:9", "20:9", "21:9", "32:9"), + valueLabels = listOf("16:9", "16:10", "18:9", "19:9", "20:9", "21:9", "32:9"), + defaultValue = "16:9", + category = RetroOptionCategory.PERFORMANCE, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_cd_access_method", + label = "CD Access Method", + values = listOf("sync", "async", "precache"), + valueLabels = listOf("Synchronous", "Asynchronous", "Pre-Cache"), + defaultValue = "sync", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + RetroCoreOption( + key = "beetle_psx_cd_fastload", + label = "CD Loading Speed", + values = listOf("2x(native)", "4x", "6x", "8x", "10x", "12x", "14x"), + valueLabels = listOf("2x (Native)", "4x", "6x", "8x", "10x", "12x", "14x"), + defaultValue = "2x(native)", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + RetroCoreOption( + key = "beetle_psx_cpu_freq_scale", + label = "CPU Frequency Scaling (Overclock)", + values = listOf("50%", "60%", "70%", "80%", "90%", "100%", "110%", "120%", "130%", "140%", "150%", "160%", "170%", "180%", "190%", "200%", "210%", "220%", "230%", "240%", "250%", "260%", "270%", "280%", "290%", "300%", "310%", "320%", "330%", "340%", "350%", "360%", "370%", "380%", "390%", "400%", "410%", "420%", "430%", "440%", "450%", "460%", "470%", "480%", "490%", "500%", "510%", "520%", "530%", "540%", "550%", "560%", "570%", "580%", "590%", "600%", "610%", "620%", "630%", "640%", "650%", "660%", "670%", "680%", "690%", "700%", "710%", "720%", "730%", "740%", "750%"), + valueLabels = listOf("50%", "60%", "70%", "80%", "90%", "100% (Native)", "110%", "120%", "130%", "140%", "150%", "160%", "170%", "180%", "190%", "200%", "210%", "220%", "230%", "240%", "250%", "260%", "270%", "280%", "290%", "300%", "310%", "320%", "330%", "340%", "350%", "360%", "370%", "380%", "390%", "400%", "410%", "420%", "430%", "440%", "450%", "460%", "470%", "480%", "490%", "500%", "510%", "520%", "530%", "540%", "550%", "560%", "570%", "580%", "590%", "600%", "610%", "620%", "630%", "640%", "650%", "660%", "670%", "680%", "690%", "700%", "710%", "720%", "730%", "740%", "750%"), + defaultValue = "100%", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + RetroCoreOption( + key = "beetle_psx_display_internal_fps", + label = "Display Internal FPS", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.SYSTEM, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_display_osd", + label = "Display OSD Messages", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "enabled", + category = RetroOptionCategory.SYSTEM, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_display_vram", + label = "Display Full VRAM (Debug)", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.SYSTEM, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_enable_memcard1", + label = "Memory Card Slot 2", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + RetroCoreOption( + key = "beetle_psx_gpu_overclock", + label = "GPU Rasterizer Overclock", + values = listOf("1x(native)", "2x", "4x", "8x", "16x", "32x"), + valueLabels = listOf("1x (Native)", "2x", "4x", "8x", "16x", "32x"), + defaultValue = "1x(native)", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + RetroCoreOption( + key = "beetle_psx_gte_overclock", + label = "GTE Overclock", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + RetroCoreOption( + key = "beetle_psx_memcard_left_index", + label = "Memory Card Slot 1 Index", + values = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63"), + valueLabels = listOf("0 (Default)", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63"), + defaultValue = "0", + category = RetroOptionCategory.SYSTEM, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_memcard_right_index", + label = "Memory Card Slot 2 Index", + values = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63"), + valueLabels = listOf("0", "1 (Default)", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63"), + defaultValue = "1", + category = RetroOptionCategory.SYSTEM, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_override_bios", + label = "Override BIOS", + values = listOf("disabled", "psxonpsp", "ps1_rom", "openbios"), + valueLabels = listOf("disabled", "PSP PS1 BIOS", "PS3 PS1 BIOS", "OpenBIOS"), + defaultValue = "disabled", + category = RetroOptionCategory.SYSTEM, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_region", + label = "System Region", + values = listOf("auto", "ntsc-j", "ntsc-u", "pal"), + valueLabels = listOf("Auto", "NTSC-J (Japan)", "NTSC-U (North America)", "PAL (Europe)"), + defaultValue = "auto", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + RetroCoreOption( + key = "beetle_psx_shared_memory_cards", + label = "Shared Memory Cards", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.SYSTEM, + advanced = true, + ), + RetroCoreOption( + key = "beetle_psx_skip_bios", + label = "Skip BIOS", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + RetroCoreOption( + key = "beetle_psx_use_mednafen_memcard0_method", + label = "Memory Card Method", + values = listOf("libretro", "mednafen"), + valueLabels = listOf("Libretro", "Mednafen"), + defaultValue = "libretro", + category = RetroOptionCategory.SYSTEM, + advanced = true, + ), + ) + + val MUPEN64PLUS_NEXT: List = listOf( + RetroCoreOption( + key = "mupen64plus-alt-map", + label = "Independent C-button Controls", + values = listOf("False", "True"), + valueLabels = listOf("False", "True"), + defaultValue = "False", + category = RetroOptionCategory.CONTROLS, + advanced = false, + ), + RetroCoreOption( + key = "mupen64plus-astick-deadzone", + label = "Analog Deadzone (percent)", + values = listOf("0", "5", "10", "15", "20", "25", "30"), + valueLabels = listOf("0", "5", "10", "15", "20", "25", "30"), + defaultValue = "15", + category = RetroOptionCategory.CONTROLS, + advanced = false, + ), + RetroCoreOption( + key = "mupen64plus-astick-sensitivity", + label = "Analog Sensitivity (percent)", + values = listOf("50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100", "105", "110", "115", "120", "125", "130", "135", "140", "145", "150"), + valueLabels = listOf("50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100", "105", "110", "115", "120", "125", "130", "135", "140", "145", "150"), + defaultValue = "100", + category = RetroOptionCategory.CONTROLS, + advanced = false, + ), + RetroCoreOption( + key = "mupen64plus-d-cbutton", + label = "Down C Button", + values = listOf("C1", "C2", "C3", "C4"), + valueLabels = listOf("C1", "C2", "C3", "C4"), + defaultValue = "C3", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "mupen64plus-l-cbutton", + label = "Left C Button", + values = listOf("C1", "C2", "C3", "C4"), + valueLabels = listOf("C1", "C2", "C3", "C4"), + defaultValue = "C2", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "mupen64plus-pak1", + label = "Player 1 Pak", + values = listOf("none", "memory", "rumble", "transfer"), + valueLabels = listOf("none", "memory", "rumble", "transfer"), + defaultValue = "memory", + category = RetroOptionCategory.CONTROLS, + advanced = false, + ), + RetroCoreOption( + key = "mupen64plus-pak2", + label = "Player 2 Pak", + values = listOf("none", "memory", "rumble", "transfer"), + valueLabels = listOf("none", "memory", "rumble", "transfer"), + defaultValue = "none", + category = RetroOptionCategory.CONTROLS, + advanced = false, + ), + RetroCoreOption( + key = "mupen64plus-pak3", + label = "Player 3 Pak", + values = listOf("none", "memory", "rumble", "transfer"), + valueLabels = listOf("none", "memory", "rumble", "transfer"), + defaultValue = "none", + category = RetroOptionCategory.CONTROLS, + advanced = false, + ), + RetroCoreOption( + key = "mupen64plus-pak4", + label = "Player 4 Pak", + values = listOf("none", "memory", "rumble", "transfer"), + valueLabels = listOf("none", "memory", "rumble", "transfer"), + defaultValue = "none", + category = RetroOptionCategory.CONTROLS, + advanced = false, + ), + RetroCoreOption( + key = "mupen64plus-r-cbutton", + label = "Right C Button", + values = listOf("C1", "C2", "C3", "C4"), + valueLabels = listOf("C1", "C2", "C3", "C4"), + defaultValue = "C1", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "mupen64plus-u-cbutton", + label = "Up C Button", + values = listOf("C1", "C2", "C3", "C4"), + valueLabels = listOf("C1", "C2", "C3", "C4"), + defaultValue = "C4", + category = RetroOptionCategory.CONTROLS, + advanced = true, + ), + RetroCoreOption( + key = "mupen64plus-169screensize", + label = "Wide Resolution", + values = listOf("640x360", "960x540", "1280x720", "1706x720", "1366x768", "1920x810", "1920x1080", "2560x1080", "2560x1440", "3414x1440", "3840x2160", "4096x2160", "5120x2160", "7680x3240", "7680x4320", "10240x4320"), + valueLabels = listOf("640x360 (16:9)", "960x540 (16:9)", "1280x720 (16:9)", "1706x720 (64:27)", "1366x768 (16:9)", "1920x810 (64:27)", "1920x1080 (16:9)", "2560x1080 (64:27)", "2560x1440 (16:9)", "3414x1440 (64:27)", "3840x2160 (16:9)", "4096x2160 (17:9)", "5120x2160 (64:27)", "7680x3240 (64:27)", "7680x4320 (16:9)", "10240x4320 (64:27)"), + defaultValue = "960x540", + category = RetroOptionCategory.DISPLAY, + advanced = false, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-43screensize", + label = "4:3 Resolution", + values = listOf("320x240", "640x480", "960x720", "1280x960", "1440x1080", "1600x1200", "1920x1440", "2240x1680", "2560x1920", "2880x2160", "3200x2400", "3520x2640", "3840x2880"), + valueLabels = listOf("320x240", "640x480", "960x720", "1280x960", "1440x1080", "1600x1200", "1920x1440", "2240x1680", "2560x1920", "2880x2160", "3200x2400", "3520x2640", "3840x2880"), + defaultValue = "640x480", + category = RetroOptionCategory.DISPLAY, + advanced = false, + labelRes = R.string.retro_co_resolution, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-BackgroundMode", + label = "Background Mode", + values = listOf("Stripped", "OnePiece"), + valueLabels = listOf("Stripped", "OnePiece"), + defaultValue = "OnePiece", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-BilinearMode", + label = "Bilinear filtering mode", + values = listOf("3point", "standard"), + valueLabels = listOf("3point", "standard"), + defaultValue = "standard", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-CorrectTexrectCoords", + label = "Continuous texrect coords", + values = listOf("Off", "Auto", "Force"), + valueLabels = listOf("Off", "Auto", "Force"), + defaultValue = "Off", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-DitheringPattern", + label = "Dithering", + values = listOf("True", "False"), + valueLabels = listOf("Enabled", "Disabled"), + defaultValue = "False", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-DitheringQuantization", + label = "Dithering Quantization", + values = listOf("True", "False"), + valueLabels = listOf("Enabled", "Disabled"), + defaultValue = "False", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-EnableCopyAuxToRDRAM", + label = "Copy auxiliary buffers to RDRAM", + values = listOf("False", "True"), + valueLabels = listOf("False", "True"), + defaultValue = "False", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-EnableCopyColorFromRDRAM", + label = "Enable color buffer copy from RDRAM", + values = listOf("False", "True"), + valueLabels = listOf("False", "True"), + defaultValue = "False", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-EnableCopyColorToRDRAM", + label = "Color buffer to RDRAM", + values = listOf("Off", "Sync", "Async", "TripleBuffer"), + valueLabels = listOf("Off", "Sync", "DoubleBuffer", "TripleBuffer"), + defaultValue = "Async", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-EnableCopyDepthToRDRAM", + label = "Depth buffer to RDRAM", + values = listOf("Off", "Software", "FromMem"), + valueLabels = listOf("Off", "Software", "FromMem"), + defaultValue = "Software", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-EnableEnhancedHighResStorage", + label = "Use enhanced Hi-Res Storage", + values = listOf("False", "True"), + valueLabels = listOf("False", "True"), + defaultValue = "False", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-EnableEnhancedTextureStorage", + label = "Use enhanced Texture Storage", + values = listOf("False", "True"), + valueLabels = listOf("False", "True"), + defaultValue = "False", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-EnableFBEmulation", + label = "Framebuffer Emulation", + values = listOf("False", "True"), + valueLabels = listOf("False", "True"), + defaultValue = "True", + category = RetroOptionCategory.DISPLAY, + advanced = false, + labelRes = R.string.retro_co_framebuffer_emulation, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-EnableFragmentDepthWrite", + label = "GPU shader depth write", + values = listOf("False", "True"), + valueLabels = listOf("False", "True"), + defaultValue = "False", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-EnableHWLighting", + label = "Hardware per-pixel lighting", + values = listOf("False", "True"), + valueLabels = listOf("False", "True"), + defaultValue = "False", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-EnableHiResAltCRC", + label = "Use alternative method for High-Res Checksums", + values = listOf("False", "True"), + valueLabels = listOf("False", "True"), + defaultValue = "False", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-EnableInaccurateTextureCoordinates", + label = "Enable inaccurate texture coordinates", + values = listOf("False", "True"), + valueLabels = listOf("False", "True"), + defaultValue = "False", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-EnableLODEmulation", + label = "LOD Emulation", + values = listOf("False", "True"), + valueLabels = listOf("False", "True"), + defaultValue = "True", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-EnableLegacyBlending", + label = "Less accurate blending mode", + values = listOf("False", "True"), + valueLabels = listOf("False", "True"), + defaultValue = "True", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-EnableN64DepthCompare", + label = "N64 Depth Compare", + values = listOf("False", "True", "Compatible"), + valueLabels = listOf("Off", "Fast", "Compatible"), + defaultValue = "False", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-EnableNativeResFactor", + label = "Native Resolution Factor", + values = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8"), + valueLabels = listOf("Disabled", "1x", "2x", "3x", "4x", "5x", "6x", "7x", "8x"), + defaultValue = "0", + category = RetroOptionCategory.DISPLAY, + advanced = false, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-EnableNativeResTexrects", + label = "Native res. 2D texrects", + values = listOf("Disabled", "Unoptimized", "Optimized"), + valueLabels = listOf("Disabled", "Unoptimized", "Optimized"), + defaultValue = "Disabled", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-EnableOverscan", + label = "Overscan", + values = listOf("Disabled", "Enabled"), + valueLabels = listOf("Disabled", "Enabled"), + defaultValue = "Enabled", + category = RetroOptionCategory.DISPLAY, + advanced = false, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-EnableShadersStorage", + label = "Cache GPU Shaders", + values = listOf("False", "True"), + valueLabels = listOf("False", "True"), + defaultValue = "True", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-EnableTexCoordBounds", + label = "Enable native-res boundaries for texture coordinates", + values = listOf("False", "True"), + valueLabels = listOf("False", "True"), + defaultValue = "False", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-EnableTextureCache", + label = "Cache Textures", + values = listOf("False", "True"), + valueLabels = listOf("False", "True"), + defaultValue = "True", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-FXAA", + label = "FXAA", + values = listOf("0", "1"), + valueLabels = listOf("0", "1"), + defaultValue = "0", + category = RetroOptionCategory.DISPLAY, + advanced = false, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-GLideN64IniBehaviour", + label = "INI Behaviour", + values = listOf("late", "early", "disabled"), + valueLabels = listOf("Prioritize INI over Core Options", "Prioritize Core Options over INI", "Disable INI"), + defaultValue = "late", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-HybridFilter", + label = "Hybrid Filter", + values = listOf("True", "False"), + valueLabels = listOf("Enabled", "Disabled"), + defaultValue = "True", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-MaxHiResTxVramLimit", + label = "Max High-Res VRAM Limit", + values = listOf("0", "500", "1000", "1500", "2000", "2500", "3000", "3500", "4000"), + valueLabels = listOf("0", "500", "1000", "1500", "2000", "2500", "3000", "3500", "4000"), + defaultValue = "0", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-MaxTxCacheSize", + label = "Max texture cache size", + values = listOf("1500", "4000", "8000"), + valueLabels = listOf("1500", "4000", "8000"), + defaultValue = "1500", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-MultiSampling", + label = "MSAA level", + values = listOf("0", "2", "4", "8", "16"), + valueLabels = listOf("0", "2", "4", "8", "16"), + defaultValue = "0", + category = RetroOptionCategory.DISPLAY, + advanced = false, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-OverscanBottom", + label = "Overscan Offset (Bottom)", + values = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50"), + valueLabels = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50"), + defaultValue = "0", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-OverscanLeft", + label = "Overscan Offset (Left)", + values = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50"), + valueLabels = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50"), + defaultValue = "0", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-OverscanRight", + label = "Overscan Offset (Right)", + values = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50"), + valueLabels = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50"), + defaultValue = "0", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-OverscanTop", + label = "Overscan Offset (Top)", + values = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50"), + valueLabels = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50"), + defaultValue = "0", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-RDRAMImageDitheringMode", + label = "Image Dithering Mode", + values = listOf("False", "Bayer", "MagicSquare", "BlueNoise"), + valueLabels = listOf("Disabled", "Bayer", "Magic Square", "Blue Noise"), + defaultValue = "False", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-ThreadedRenderer", + label = "Threaded Renderer", + values = listOf("True", "False"), + valueLabels = listOf("Enabled", "Disabled"), + defaultValue = "False", + category = RetroOptionCategory.DISPLAY, + advanced = false, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-angrylion-multithread", + label = "Multi-threading", + values = listOf("all threads", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "75"), + valueLabels = listOf("all threads", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "75"), + defaultValue = "all threads", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "angrylion", + ), + RetroCoreOption( + key = "mupen64plus-angrylion-overscan", + label = "Hide overscan", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "angrylion", + ), + RetroCoreOption( + key = "mupen64plus-angrylion-sync", + label = "Thread sync level", + values = listOf("Low", "Medium", "High"), + valueLabels = listOf("Low", "Medium", "High"), + defaultValue = "Low", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "angrylion", + ), + RetroCoreOption( + key = "mupen64plus-angrylion-vioverlay", + label = "VI Overlay", + values = listOf("Filtered", "AA+Blur", "AA+Dedither", "AA only", "Unfiltered", "Depth", "Coverage"), + valueLabels = listOf("Filtered", "AA+Blur", "AA+Dedither", "AA only", "Unfiltered", "Depth", "Coverage"), + defaultValue = "Filtered", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "angrylion", + ), + RetroCoreOption( + key = "mupen64plus-aspect", + label = "Aspect Ratio", + values = listOf("4:3", "16:9", "16:9 adjusted"), + valueLabels = listOf("Original (4:3)", "Wide (Stretched)", "Wide (Adjusted)"), + defaultValue = "4:3", + category = RetroOptionCategory.DISPLAY, + advanced = false, + labelRes = R.string.retro_co_aspect_ratio, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-parallel-rdp-deinterlace-method", + label = "(ParaLLEl-RDP) Deinterlacing method", + values = listOf("Bob", "Weave"), + valueLabels = listOf("Bob", "Weave"), + defaultValue = "Bob", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "parallel", + ), + RetroCoreOption( + key = "mupen64plus-parallel-rdp-dither-filter", + label = "(ParaLLEl-RDP) VI dither filter", + values = listOf("True", "False"), + valueLabels = listOf("Enabled", "Disabled"), + defaultValue = "True", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "parallel", + ), + RetroCoreOption( + key = "mupen64plus-parallel-rdp-divot-filter", + label = "(ParaLLEl-RDP) VI Divot filter", + values = listOf("True", "False"), + valueLabels = listOf("Enabled", "Disabled"), + defaultValue = "True", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "parallel", + ), + RetroCoreOption( + key = "mupen64plus-parallel-rdp-downscaling", + label = "(ParaLLEl-RDP) Downsampling factor", + values = listOf("disable", "1/2", "1/4", "1/8"), + valueLabels = listOf("disable", "1/2", "1/4", "1/8"), + defaultValue = "disable", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "parallel", + ), + RetroCoreOption( + key = "mupen64plus-parallel-rdp-gamma-dither", + label = "(ParaLLEl-RDP) VI Gamma dither", + values = listOf("True", "False"), + valueLabels = listOf("Enabled", "Disabled"), + defaultValue = "True", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "parallel", + ), + RetroCoreOption( + key = "mupen64plus-parallel-rdp-native-tex-rect", + label = "(ParaLLEl-RDP) Native resolution TEX_RECT", + values = listOf("True", "False"), + valueLabels = listOf("Enabled", "Disabled"), + defaultValue = "True", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "parallel", + ), + RetroCoreOption( + key = "mupen64plus-parallel-rdp-native-texture-lod", + label = "(ParaLLEl-RDP) Native texture LOD", + values = listOf("False", "True"), + valueLabels = listOf("Disabled", "Enabled"), + defaultValue = "False", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "parallel", + ), + RetroCoreOption( + key = "mupen64plus-parallel-rdp-overscan", + label = "(ParaLLEl-RDP) Crop overscan", + values = listOf("0", "2", "4", "6", "8", "10", "12", "14", "16", "18", "20", "22", "24", "26", "28", "30", "32", "34", "36", "38", "40", "42", "44", "46", "48", "50", "52", "54", "56", "58", "60", "62", "64"), + valueLabels = listOf("0", "2", "4", "6", "8", "10", "12", "14", "16", "18", "20", "22", "24", "26", "28", "30", "32", "34", "36", "38", "40", "42", "44", "46", "48", "50", "52", "54", "56", "58", "60", "62", "64"), + defaultValue = "0", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "parallel", + ), + RetroCoreOption( + key = "mupen64plus-parallel-rdp-super-sampled-read-back", + label = "(ParaLLEl-RDP) SSAA framebuffer effects (restart)", + values = listOf("False", "True"), + valueLabels = listOf("Disabled", "Enabled"), + defaultValue = "False", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "parallel", + ), + RetroCoreOption( + key = "mupen64plus-parallel-rdp-super-sampled-read-back-dither", + label = "(ParaLLEl-RDP) Dither SSAA framebuffer effects (restart)", + values = listOf("True", "False"), + valueLabels = listOf("Enabled", "Disabled"), + defaultValue = "True", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "parallel", + ), + RetroCoreOption( + key = "mupen64plus-parallel-rdp-synchronous", + label = "(ParaLLEl-RDP) Synchronous RDP", + values = listOf("True", "False"), + valueLabels = listOf("Enabled", "Disabled"), + defaultValue = "True", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "parallel", + ), + RetroCoreOption( + key = "mupen64plus-parallel-rdp-upscaling", + label = "(ParaLLEl-RDP) Upscaling factor (restart)", + values = listOf("1x", "2x", "4x", "8x"), + valueLabels = listOf("1x", "2x", "4x", "8x"), + defaultValue = "1x", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "parallel", + ), + RetroCoreOption( + key = "mupen64plus-parallel-rdp-vi-aa", + label = "(ParaLLEl-RDP) VI anti-aliasing", + values = listOf("True", "False"), + valueLabels = listOf("Enabled", "Disabled"), + defaultValue = "True", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "parallel", + ), + RetroCoreOption( + key = "mupen64plus-parallel-rdp-vi-bilinear", + label = "(ParaLLEl-RDP) VI bilinear", + values = listOf("True", "False"), + valueLabels = listOf("Enabled", "Disabled"), + defaultValue = "True", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "parallel", + ), + RetroCoreOption( + key = "mupen64plus-rdp-plugin", + label = "RDP Plugin", + values = listOf("angrylion", "parallel", "gliden64"), + valueLabels = listOf("Angrylion", "ParaLLEl-RDP", "GLideN64"), + defaultValue = "gliden64", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "mupen64plus-txCacheCompression", + label = "Use High-Res Texture Cache Compression", + values = listOf("False", "True"), + valueLabels = listOf("False", "True"), + defaultValue = "True", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-txEnhancementMode", + label = "Texture Enhancement", + values = listOf("None", "As Is", "X2", "X2SAI", "HQ2X", "HQ2XS", "LQ2X", "LQ2XS", "HQ4X", "2xBRZ", "3xBRZ", "4xBRZ", "5xBRZ", "6xBRZ"), + valueLabels = listOf("None", "As Is", "X2", "X2SAI", "HQ2X", "HQ2XS", "LQ2X", "LQ2XS", "HQ4X", "2xBRZ", "3xBRZ", "4xBRZ", "5xBRZ", "6xBRZ"), + defaultValue = "None", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-txFilterIgnoreBG", + label = "Don't filter background textures", + values = listOf("False", "True"), + valueLabels = listOf("False", "True"), + defaultValue = "True", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-txFilterMode", + label = "Texture filter", + values = listOf("None", "Smooth filtering 1", "Smooth filtering 2", "Smooth filtering 3", "Smooth filtering 4", "Sharp filtering 1", "Sharp filtering 2"), + valueLabels = listOf("None", "Smooth filtering 1", "Smooth filtering 2", "Smooth filtering 3", "Smooth filtering 4", "Sharp filtering 1", "Sharp filtering 2"), + defaultValue = "None", + category = RetroOptionCategory.DISPLAY, + advanced = false, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-txHiresEnable", + label = "Use High-Res textures", + values = listOf("False", "True"), + valueLabels = listOf("False", "True"), + defaultValue = "False", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-txHiresFullAlphaChannel", + label = "Use High-Res Full Alpha Channel", + values = listOf("False", "True"), + valueLabels = listOf("False", "True"), + defaultValue = "False", + category = RetroOptionCategory.DISPLAY, + advanced = true, + visibleWhen = "mupen64plus-rdp-plugin" to "gliden64", + ), + RetroCoreOption( + key = "mupen64plus-CountPerOp", + label = "Count Per Op", + values = listOf("0", "1", "2", "3", "4", "5"), + valueLabels = listOf("0", "1", "2", "3", "4", "5"), + defaultValue = "0", + category = RetroOptionCategory.PERFORMANCE, + advanced = true, + ), + RetroCoreOption( + key = "mupen64plus-CountPerOpDenomPot", + label = "Count Per Op Divider (Overclock)", + values = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"), + valueLabels = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"), + defaultValue = "0", + category = RetroOptionCategory.PERFORMANCE, + advanced = true, + ), + RetroCoreOption( + key = "mupen64plus-FrameDuping", + label = "Frame Duplication", + values = listOf("False", "True"), + valueLabels = listOf("False", "True"), + defaultValue = "True", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + ), + RetroCoreOption( + key = "mupen64plus-Framerate", + label = "Framerate", + values = listOf("Original", "Fullspeed"), + valueLabels = listOf("Original", "Fullspeed"), + defaultValue = "Original", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + ), + RetroCoreOption( + key = "mupen64plus-IgnoreTLBExceptions", + label = "Ignore emulated TLB Exceptions", + values = listOf("False", "OnlyNotEnabled", "AlwaysIgnoreTLB"), + valueLabels = listOf("Don't Ignore", "Ignore TLB Exceptions if not using TLB", "Always Ignore TLB Exceptions"), + defaultValue = "False", + category = RetroOptionCategory.PERFORMANCE, + advanced = true, + ), + RetroCoreOption( + key = "mupen64plus-cpucore", + label = "CPU Core", + values = listOf("pure_interpreter", "cached_interpreter", "dynamic_recompiler"), + valueLabels = listOf("Pure Interpreter", "Cached Interpreter", "Dynarec"), + defaultValue = "dynamic_recompiler", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + ), + RetroCoreOption( + key = "mupen64plus-rsp-plugin", + label = "RSP Plugin", + values = listOf("cxd4", "parallel", "hle"), + valueLabels = listOf("CXD4", "ParaLLEl", "HLE"), + defaultValue = "hle", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + ), + RetroCoreOption( + key = "mupen64plus-virefresh", + label = "VI Refresh (Overclock)", + values = listOf("Auto", "1500", "2200"), + valueLabels = listOf("Auto", "1500", "2200"), + defaultValue = "Auto", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + ), + RetroCoreOption( + key = "mupen64plus-ForceDisableExtraMem", + label = "Disable Expansion Pak", + values = listOf("False", "True"), + valueLabels = listOf("False", "True"), + defaultValue = "False", + category = RetroOptionCategory.SYSTEM, + advanced = true, + ), + ) + + val GPSP: List = listOf( + RetroCoreOption( + key = "gpsp_rumble", + label = "Rumble support", + values = listOf("auto", "enabled", "disabled"), + valueLabels = listOf("auto", "enabled", "disabled"), + defaultValue = "auto", + category = RetroOptionCategory.CONTROLS, + advanced = false, + ), + RetroCoreOption( + key = "gpsp_turbo_period", + label = "Turbo Button Period", + values = listOf("4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100", "101", "102", "103", "104", "105", "106", "107", "108", "109", "110", "111", "112", "113", "114", "115", "116", "117", "118", "119", "120"), + valueLabels = listOf("4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100", "101", "102", "103", "104", "105", "106", "107", "108", "109", "110", "111", "112", "113", "114", "115", "116", "117", "118", "119", "120"), + defaultValue = "4", + category = RetroOptionCategory.CONTROLS, + advanced = false, + ), + RetroCoreOption( + key = "gpsp_color_correction", + label = "Color Correction", + values = listOf("enabled", "disabled"), + valueLabels = listOf("enabled", "disabled"), + defaultValue = "disabled", + category = RetroOptionCategory.DISPLAY, + advanced = false, + ), + RetroCoreOption( + key = "gpsp_frameskip", + label = "Frameskip", + values = listOf("disabled", "auto", "auto_threshold", "fixed_interval"), + valueLabels = listOf("disabled", "Auto", "Auto (Threshold)", "Fixed Interval"), + defaultValue = "disabled", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + ), + RetroCoreOption( + key = "gpsp_frameskip_interval", + label = "Frameskip Interval", + values = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"), + valueLabels = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"), + defaultValue = "1", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + ), + RetroCoreOption( + key = "gpsp_frameskip_threshold", + label = "Frameskip Threshold (%)", + values = listOf("15", "18", "21", "24", "27", "30", "33", "36", "39", "42", "45", "48", "51", "54", "57", "60"), + valueLabels = listOf("15", "18", "21", "24", "27", "30", "33", "36", "39", "42", "45", "48", "51", "54", "57", "60"), + defaultValue = "33", + category = RetroOptionCategory.PERFORMANCE, + advanced = false, + ), + RetroCoreOption( + key = "gpsp_bios", + label = "BIOS", + values = listOf("auto", "builtin", "official"), + valueLabels = listOf("Auto select", "Builtin BIOS", "Original BIOS"), + defaultValue = "auto", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + RetroCoreOption( + key = "gpsp_boot_mode", + label = "Boot mode", + values = listOf("game", "bios"), + valueLabels = listOf("Boot to game", "Boot to BIOS"), + defaultValue = "game", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + RetroCoreOption( + key = "gpsp_drc", + label = "Dynamic Recompiler", + values = listOf("enabled", "disabled"), + valueLabels = listOf("enabled", "disabled"), + defaultValue = "enabled", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + RetroCoreOption( + key = "gpsp_frame_mixing", + label = "Interframe Blending", + values = listOf("enabled", "disabled"), + valueLabels = listOf("enabled", "disabled"), + defaultValue = "disabled", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + RetroCoreOption( + key = "gpsp_rtc", + label = "RTC support", + values = listOf("auto", "enabled", "disabled"), + valueLabels = listOf("auto", "enabled", "disabled"), + defaultValue = "auto", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + RetroCoreOption( + key = "gpsp_serial", + label = "Link Cable Connectivity", + values = listOf("auto", "disabled", "rfu", "mul_poke", "mul_aw1", "mul_aw2"), + valueLabels = listOf("Automatic", "Disabled", "GBA Wireless Adapter", "Link Cable - Pokemon Gen3 mode", "Link Cable - Advance Wars 1 mode", "Link Cable - Advance Wars 2 mode"), + defaultValue = "auto", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + RetroCoreOption( + key = "gpsp_sound_rate", + label = "Sound Output Rate (Hz)", + values = listOf("65536", "32768"), + valueLabels = listOf("65536", "32768"), + defaultValue = "65536", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + RetroCoreOption( + key = "gpsp_sprlim", + label = "No Sprite Limit", + values = listOf("disabled", "enabled"), + valueLabels = listOf("disabled", "enabled"), + defaultValue = "disabled", + category = RetroOptionCategory.SYSTEM, + advanced = false, + ), + ) + +} diff --git a/app/src/main/feature/retro/RetroCoreManager.kt b/app/src/main/feature/retro/RetroCoreManager.kt new file mode 100644 index 000000000..0480d6b84 --- /dev/null +++ b/app/src/main/feature/retro/RetroCoreManager.kt @@ -0,0 +1,174 @@ +package com.winlator.cmod.feature.retro + +import android.content.Context +import java.io.File + +object RetroCoreManager { + private fun resolveCore( + context: Context, + fileName: String, + ): File = + if (fileName == RetroSystems.DOLPHIN_LIBRETRO_CORE) { + File(context.applicationInfo.nativeLibraryDir, fileName) + } else { + File(RetroBundle.coresDir(context), fileName) + } + + fun coreFile( + context: Context, + system: RetroSystem, + ): File = resolveCore(context, system.coreFileName) + + fun multiplayerCoreFile( + context: Context, + system: RetroSystem, + ): File = + if (system.id == RetroSystems.GBA.id) { + resolveCore(context, RetroSystems.GBA_MULTIPLAYER_CORE) + } else { + coreFile(context, system) + } + + fun isCoreAvailable( + context: Context, + system: RetroSystem, + ): Boolean = coreFile(context, system).isFile + + fun isMultiplayerCoreAvailable( + context: Context, + system: RetroSystem, + ): Boolean = multiplayerCoreFile(context, system).isFile + + fun systemDir(context: Context): File = File(context.filesDir, "retro/system").also { it.mkdirs() } + + fun savesDir(context: Context): File = File(context.filesDir, "retro/saves").also { it.mkdirs() } + + fun statesDir(context: Context): File = File(context.filesDir, "retro/states").also { it.mkdirs() } + + fun stateFile( + context: Context, + gameName: String, + slot: Int, + ): File { + val safe = gameName.replace(Regex("[^A-Za-z0-9._-]"), "_") + val suffix = if (slot <= 0) "state" else "state$slot" + return File(statesDir(context), "$safe.$suffix") + } + + fun ensureGlideN64Ini(context: Context) { + val target = File(File(systemDir(context), "Mupen64plus").also { it.mkdirs() }, "GLideN64.custom.ini") + runCatching { + context.assets.open("retro/GLideN64.custom.ini").use { input -> + val bytes = input.readBytes() + if (!target.isFile || target.length() != bytes.size.toLong()) { + target.writeBytes(bytes) + } + } + } + } + + fun ensureDolphinSys(context: Context) { + val marker = File(systemDir(context), "dolphin-emu/.wn_sys_ready") + if (marker.isFile) return + val destRoot = File(systemDir(context), "dolphin-emu").also { it.mkdirs() } + runCatching { + val fromBundle = File(RetroBundle.dataDir(context), "dolphin-emu") + if (!fromBundle.isDirectory) return + fromBundle.copyRecursively(destRoot, overwrite = true) + marker.parentFile?.mkdirs() + marker.writeText("1") + } + } + + fun ensureDolphinUser(context: Context) { + val userRoot = File(savesDir(context), "User") + val gcRoot = File(userRoot, "GC").also { it.mkdirs() } + for (region in listOf("USA", "EUR", "JAP")) { + File(gcRoot, "$region/Card A").mkdirs() + File(gcRoot, "$region/Card B").mkdirs() + } + File(userRoot, "Config").mkdirs() + File(userRoot, "Wii").mkdirs() + File(userRoot, "GBA/Saves").mkdirs() + ensureDolphinIni(File(userRoot, "Config/Dolphin.ini")) + } + + private fun ensureDolphinIni(ini: File) { + runCatching { + val existing = if (ini.isFile) ini.readText() else "" + val desired = + mapOf( + "SlotA" to "8", + "SlotB" to "255", + "MemcardAPath" to "", + "MemcardBPath" to "", + "GCIFolderAPath" to "", + "GCIFolderBPath" to "", + "MemoryCardSize" to "-1", + "CPUThread" to "False", + "Fastmem" to "False", + "FastmemArena" to "False", + ) + val merged = mergeIniSection(existing, "Core", desired) + if (merged != existing) { + ini.parentFile?.mkdirs() + ini.writeText(merged) + } + } + } + + private fun mergeIniSection( + source: String, + section: String, + keys: Map, + ): String { + if (keys.isEmpty()) return source + val lines = source.replace("\r\n", "\n").split('\n').toMutableList() + val header = "[$section]" + var sectionStart = lines.indexOfFirst { it.trim().equals(header, ignoreCase = true) } + if (sectionStart < 0) { + val builder = StringBuilder(source.trimEnd()) + if (builder.isNotEmpty()) builder.append("\n\n") + builder.append(header).append('\n') + for ((k, v) in keys) builder.append(k).append(" = ").append(v).append('\n') + return builder.toString() + } + var sectionEnd = lines.size + for (i in (sectionStart + 1) until lines.size) { + val t = lines[i].trim() + if (t.startsWith("[") && t.endsWith("]")) { + sectionEnd = i + break + } + } + val remaining = keys.toMutableMap() + for (i in (sectionStart + 1) until sectionEnd) { + val raw = lines[i] + val trimmed = raw.trim() + if (trimmed.isEmpty() || trimmed.startsWith("#") || trimmed.startsWith(";")) continue + val eq = trimmed.indexOf('=') + if (eq <= 0) continue + val key = trimmed.substring(0, eq).trim() + val wanted = remaining.remove(key) ?: continue + lines[i] = "$key = $wanted" + } + if (remaining.isNotEmpty()) { + val insertAt = sectionEnd + val block = remaining.map { (k, v) -> "$k = $v" } + lines.addAll(insertAt, block) + } + return lines.joinToString("\n").let { if (it.endsWith("\n")) it else "$it\n" } + } + + fun usesDolphinCore(system: RetroSystem?): Boolean = + system?.id == RetroSystems.GAMECUBE.id || system?.id == RetroSystems.WII.id + + fun missingBios( + context: Context, + system: RetroSystem, + ): Boolean { + if (!system.needsBios) return false + val dir = systemDir(context) + return system.biosFiles.none { File(dir, it).isFile } + } +} diff --git a/app/src/main/feature/retro/RetroCoreOptions.kt b/app/src/main/feature/retro/RetroCoreOptions.kt new file mode 100644 index 000000000..75c5fd69a --- /dev/null +++ b/app/src/main/feature/retro/RetroCoreOptions.kt @@ -0,0 +1,284 @@ +package com.winlator.cmod.feature.retro + +import android.content.Context +import com.winlator.cmod.R + +enum class RetroOptionCategory { + DISPLAY, + SOUND, + PERFORMANCE, + CONTROLS, + SYSTEM, +} + +data class RetroCoreOption( + val key: String, + val label: String, + val values: List, + val valueLabels: List, + val defaultValue: String, + val category: RetroOptionCategory = RetroOptionCategory.SYSTEM, + val advanced: Boolean = false, + @androidx.annotation.StringRes val labelRes: Int? = null, + val visibleWhen: Pair? = null, +) { + fun labelText(context: Context): String = labelRes?.let { context.getString(it) } ?: label + + fun isApplicable(current: (String) -> String?): Boolean { + val (key, value) = visibleWhen ?: return true + return (current(key) ?: return true) == value + } +} + +object RetroCoreOptions { + private val DOLPHIN_COMMON_OPTIONS = + listOf( + RetroCoreOption( + key = "dolphin_renderer", + label = "Renderer", + values = listOf("Hardware", "Software"), + valueLabels = listOf("Hardware", "Software"), + defaultValue = "Hardware", + category = RetroOptionCategory.DISPLAY, + labelRes = R.string.retro_co_renderer, + ), + RetroCoreOption( + key = "dolphin_efb_scale", + label = "Internal Resolution", + values = listOf("1", "2", "3", "4", "5", "6"), + valueLabels = listOf("1x", "2x", "3x", "4x", "5x", "6x"), + defaultValue = "1", + category = RetroOptionCategory.DISPLAY, + labelRes = R.string.retro_co_internal_resolution, + ), + ) + + private fun dolphinAspectOption(defaultValue: String) = + RetroCoreOption( + key = "dolphin_aspect_ratio", + label = "Aspect Ratio", + values = listOf("0", "1", "2", "3"), + valueLabels = listOf("Auto", "16:9", "4:3", "Stretch"), + defaultValue = defaultValue, + category = RetroOptionCategory.DISPLAY, + labelRes = R.string.retro_co_aspect_ratio, + ) + + private val DOLPHIN_CPU_OPTIONS = + listOf( + RetroCoreOption( + key = "dolphin_cpu_core", + label = "CPU Core", + values = listOf("4", "5", "0"), + valueLabels = listOf("JIT", "Cached Interpreter", "Interpreter"), + defaultValue = "4", + category = RetroOptionCategory.PERFORMANCE, + labelRes = R.string.retro_co_cpu_core, + ), + RetroCoreOption( + key = "dolphin_main_cpu_thread", + label = "Dual Core", + values = listOf("disabled", "enabled"), + valueLabels = listOf("Off", "On"), + defaultValue = "disabled", + category = RetroOptionCategory.PERFORMANCE, + labelRes = R.string.retro_co_dual_core, + ), + ) + + private val DOLPHIN_CHEATS_OPTION = + RetroCoreOption( + key = "dolphin_cheats_enabled", + label = "Internal Cheats", + values = listOf("disabled", "enabled"), + valueLabels = listOf("Off", "On"), + defaultValue = "disabled", + category = RetroOptionCategory.SYSTEM, + labelRes = R.string.retro_co_internal_cheats, + ) + + private val DOLPHIN_VI_SKIP_OPTION = + RetroCoreOption( + key = "dolphin_vi_skip", + label = "VBI Skip", + values = listOf("enabled", "disabled"), + valueLabels = listOf("On", "Off"), + defaultValue = "enabled", + category = RetroOptionCategory.PERFORMANCE, + labelRes = R.string.retro_co_vbi_skip, + ) + + private val GAMECUBE_OPTIONS = + DOLPHIN_COMMON_OPTIONS + + dolphinAspectOption("2") + + listOf( + RetroCoreOption( + key = "dolphin_widescreen_hack", + label = "Widescreen Hack", + values = listOf("disabled", "enabled"), + valueLabels = listOf("Off", "On (16:9)"), + defaultValue = "disabled", + category = RetroOptionCategory.DISPLAY, + labelRes = R.string.retro_co_widescreen_hack, + ), + ) + + DOLPHIN_CPU_OPTIONS + + listOf( + RetroCoreOption( + key = "dolphin_skip_gc_bios", + label = "Skip GameCube BIOS", + values = listOf("enabled", "disabled"), + valueLabels = listOf("On", "Off"), + defaultValue = "enabled", + category = RetroOptionCategory.SYSTEM, + labelRes = R.string.retro_co_skip_gc_bios, + ), + DOLPHIN_VI_SKIP_OPTION, + DOLPHIN_CHEATS_OPTION, + ) + + private val WII_OPTIONS = + DOLPHIN_COMMON_OPTIONS + + dolphinAspectOption("1") + + listOf( + RetroCoreOption( + key = "dolphin_widescreen", + label = "Widescreen", + values = listOf("enabled", "disabled"), + valueLabels = listOf("On", "Off"), + defaultValue = "enabled", + category = RetroOptionCategory.DISPLAY, + labelRes = R.string.retro_co_widescreen, + ), + ) + + DOLPHIN_CPU_OPTIONS + + listOf( + RetroCoreOption( + key = "dolphin_sensor_bar_position", + label = "Sensor Bar Position", + values = listOf("0", "1"), + valueLabels = listOf("Bottom", "Top"), + defaultValue = "0", + category = RetroOptionCategory.CONTROLS, + labelRes = R.string.retro_co_sensor_bar, + ), + DOLPHIN_VI_SKIP_OPTION, + DOLPHIN_CHEATS_OPTION, + ) + + fun sanitizeDolphinVariables(vars: MutableMap) { + when (vars["dolphin_cpu_core"]?.trim()) { + "JITARM64", "JIT", "JIT64" -> vars["dolphin_cpu_core"] = "4" + "Cached Interpreter", "CachedInterpreter" -> vars["dolphin_cpu_core"] = "5" + "Interpreter" -> vars["dolphin_cpu_core"] = "0" + } + vars["dolphin_efb_scale"]?.let { raw -> + val t = raw.trim() + if (t.length == 1 && t[0].isDigit()) return@let + val digit = + Regex("""^x?(\d+)""", RegexOption.IGNORE_CASE).find(t)?.groupValues?.getOrNull(1) + if (digit != null) vars["dolphin_efb_scale"] = digit + } + DOLPHIN_PERF_DEFAULTS.forEach { (k, v) -> + if (vars[k].isNullOrBlank()) vars[k] = v + } + if (vars["dolphin_skip_dupe_frames"] == "enabled") { + vars["dolphin_skip_dupe_frames"] = "disabled" + } + } + + private val DOLPHIN_PERF_DEFAULTS: Map = + mapOf( + "dolphin_renderer" to "Hardware", + "dolphin_efb_scale" to "1", + "dolphin_cpu_core" to "4", + "dolphin_main_cpu_thread" to "disabled", + "dolphin_dsp_hle" to "enabled", + "dolphin_fast_disc_speed" to "enabled", + "dolphin_vi_skip" to "disabled", + "dolphin_skip_dupe_frames" to "disabled", + "dolphin_cheats_enabled" to "disabled", + ) + + fun defaultVariables(system: RetroSystem?): Map = + when (system?.id) { + RetroSystems.N64.id -> + mapOf( + "mupen64plus-43screensize" to "640x480", + "mupen64plus-EnableFBEmulation" to "True", + "mupen64plus-aspect" to "4:3", + ) + RetroSystems.PSX.id -> + mapOf( + "beetle_psx_skip_bios" to "enabled", + ) + RetroSystems.GAMECUBE.id -> + DOLPHIN_PERF_DEFAULTS + + mapOf( + "dolphin_widescreen" to "disabled", + "dolphin_widescreen_hack" to "disabled", + "dolphin_aspect_ratio" to "2", + "dolphin_skip_gc_bios" to "enabled", + ) + RetroSystems.WII.id -> + DOLPHIN_PERF_DEFAULTS + + mapOf( + "dolphin_widescreen" to "enabled", + "dolphin_aspect_ratio" to "1", + "dolphin_sensor_bar_position" to "0", + ) + else -> emptyMap() + } + + fun forSystem(system: RetroSystem?): List = + when (system?.id) { + RetroSystems.NES.id -> RetroCoreCatalog.FCEUMM + RetroSystems.SNES.id -> RetroCoreCatalog.SNES9X + RetroSystems.GAMEBOY.id, RetroSystems.GAMEBOY_COLOR.id -> RetroCoreCatalog.GAMBATTE + RetroSystems.GBA.id -> RetroCoreCatalog.MGBA + RetroSystems.GENESIS.id -> forGenesisFamily(RetroSystems.GENESIS.id) + RetroSystems.MASTER_SYSTEM.id -> forGenesisFamily(RetroSystems.MASTER_SYSTEM.id) + RetroSystems.GAME_GEAR.id -> forGenesisFamily(RetroSystems.GAME_GEAR.id) + RetroSystems.N64.id -> RetroCoreCatalog.MUPEN64PLUS_NEXT + RetroSystems.PSX.id -> RetroCoreCatalog.BEETLE_PSX + RetroSystems.GAMECUBE.id -> GAMECUBE_OPTIONS + RetroSystems.WII.id -> WII_OPTIONS + else -> emptyList() + } + + private fun forGenesisFamily(systemId: String): List { + val promote = + when (systemId) { + RetroSystems.MASTER_SYSTEM.id -> + setOf( + "genesis_plus_gx_ym2413", + "genesis_plus_gx_ym2413_core", + "genesis_plus_gx_left_border", + ) + RetroSystems.GAME_GEAR.id -> + setOf( + "genesis_plus_gx_gg_extra", + "genesis_plus_gx_lcd_filter", + ) + else -> emptySet() + } + val demote = + when (systemId) { + RetroSystems.GENESIS.id -> + setOf( + "genesis_plus_gx_ym2413", + "genesis_plus_gx_ym2413_core", + "genesis_plus_gx_left_border", + "genesis_plus_gx_gg_extra", + ) + else -> emptySet() + } + return RetroCoreCatalog.GENESIS_PLUS_GX.map { option -> + when (option.key) { + in promote -> option.copy(advanced = false) + in demote -> option.copy(advanced = true) + else -> option + } + } + } +} diff --git a/app/src/main/feature/retro/RetroCreditsScreen.kt b/app/src/main/feature/retro/RetroCreditsScreen.kt new file mode 100644 index 000000000..d9ab0aeeb --- /dev/null +++ b/app/src/main/feature/retro/RetroCreditsScreen.kt @@ -0,0 +1,130 @@ +package com.winlator.cmod.feature.retro + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.navigationBars +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.winlator.cmod.R +import com.winlator.cmod.feature.settings.SettingsNavBridge +import com.winlator.cmod.shared.ui.focus.rememberSettingsContentNav +import com.winlator.cmod.shared.ui.nav.LocalPaneNav +import com.winlator.cmod.shared.ui.nav.paneNavItem + +private val CreditsBg = Color(0xFF101018) +private val CreditsText = Color(0xFFF0F4FF) +private val CreditsSub = Color(0xFF93A6BC) + +@Composable +fun RetroCreditsScreen(bridge: SettingsNavBridge? = null) { + val context = LocalContext.current + val contentNav = rememberSettingsContentNav(bridge) + + fun open(url: String) { + runCatching { + context.startActivity( + android.content.Intent( + android.content.Intent.ACTION_VIEW, + android.net.Uri.parse(url), + ), + ) + } + } + + CompositionLocalProvider(LocalPaneNav provides contentNav) { + Column( + modifier = + Modifier + .fillMaxSize() + .background(CreditsBg) + .verticalScroll(rememberScrollState()) + .windowInsetsPadding(WindowInsets.navigationBars) + .padding(16.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text( + stringResource(R.string.retro_scr_credits_licenses), + color = CreditsSub, + fontSize = 11.sp, + fontWeight = FontWeight.Bold, + letterSpacing = 1.sp, + modifier = Modifier.padding(top = 4.dp), + ) + Text( + stringResource(R.string.retro_scr_credits_desc), + color = CreditsSub, + style = MaterialTheme.typography.labelMedium, + ) + RetroSettingGroup { + RETRO_CREDITS.forEach { credit -> + Row( + modifier = + Modifier + .fillMaxWidth() + .clickable { open(credit.url) } + .paneNavItem( + cornerRadius = 8.dp, + onActivate = { open(credit.url) }, + highlightColor = Color(0xFF4FC3F7), + tapToSelect = true, + ) + .padding(vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text(credit.name, color = CreditsText, style = MaterialTheme.typography.bodyMedium) + Text(credit.detail, color = CreditsSub, fontSize = 11.sp) + } + Text(credit.license, color = CreditsSub, fontSize = 11.sp) + } + } + } + } + } +} + +internal data class RetroCredit( + val name: String, + val detail: String, + val license: String, + val url: String, +) + +internal val RETRO_CREDITS = + listOf( + RetroCredit("ARMSX2", "PlayStation 2", "GPL-3.0", "https://github.com/ARMSX2/ARMSX2"), + RetroCredit("Beetle PSX", "PlayStation", "GPL-2.0", "https://github.com/libretro/beetle-psx-libretro"), + RetroCredit("Dolphin", "GameCube / Wii", "GPL-2.0", "https://github.com/dolphin-emu/dolphin"), + RetroCredit("FCEUmm", "NES", "GPL-2.0", "https://github.com/libretro/libretro-fceumm"), + RetroCredit("Gambatte", "Game Boy / Color", "GPL-2.0", "https://github.com/libretro/gambatte-libretro"), + RetroCredit("Genesis Plus GX", "Genesis / SMS / GG", "GPX", "https://github.com/libretro/Genesis-Plus-GX"), + RetroCredit("LibretroDroid", "libretro frontend", "GPL-3.0", "https://github.com/Swordfish90/LibretroDroid"), + RetroCredit("mGBA", "Game Boy Advance", "MPL-2.0", "https://github.com/libretro/mgba"), + RetroCredit("ParaLLEl N64", "Nintendo 64", "GPL-2.0", "https://github.com/libretro/parallel-n64"), + RetroCredit("PCSX2", "PS2 upstream of ARMSX2", "GPL-3.0", "https://github.com/pcsx2/pcsx2"), + RetroCredit("rcheevos", "RetroAchievements", "MIT", "https://github.com/RetroAchievements/rcheevos"), + RetroCredit("Snapdragon GSR", "Upscaling", "BSD-3", "https://github.com/quic/snapdragon-gsr"), + RetroCredit("Snes9x", "SNES", "Snes9x", "https://github.com/libretro/snes9x"), + RetroCredit("SwanStation", "PlayStation", "GPL-3.0", "https://github.com/libretro/swanstation"), + RetroCredit("Winlator", "Windows-on-Android base", "GPL-3.0", "https://github.com/brunodev85/winlator"), + ) diff --git a/app/src/main/feature/retro/RetroDefaults.kt b/app/src/main/feature/retro/RetroDefaults.kt new file mode 100644 index 000000000..2fc1863d9 --- /dev/null +++ b/app/src/main/feature/retro/RetroDefaults.kt @@ -0,0 +1,165 @@ +package com.winlator.cmod.feature.retro + +import android.content.Context +import androidx.preference.PreferenceManager + +object RetroDefaults { + private fun prefs(context: Context) = PreferenceManager.getDefaultSharedPreferences(context) + + private fun key( + setting: String, + systemId: String, + ) = "retro_def_${setting}_$systemId" + + private fun varKey( + systemId: String, + optionKey: String, + ) = "retro_def_var_${systemId}_$optionKey" + + fun romsDir(context: Context): String? = + prefs(context).getString("retro_roms_dir", null)?.takeIf { it.isNotBlank() } + + fun setRomsDir(context: Context, value: String?) = + prefs(context).edit().putString("retro_roms_dir", value).apply() + + fun shader(context: Context, systemId: String): String = + prefs(context).getString(key("shader", systemId), "default") ?: "default" + + fun setShader(context: Context, systemId: String, value: String) = + prefs(context).edit().putString(key("shader", systemId), value).apply() + + fun sgsr(context: Context, systemId: String): Boolean = + prefs(context).getBoolean(key("sgsr", systemId), false) + + fun setSgsr(context: Context, systemId: String, value: Boolean) = + prefs(context).edit().putBoolean(key("sgsr", systemId), value).apply() + + fun upscale(context: Context, systemId: String): String = + prefs(context).getString(key("upscale", systemId), "native") ?: "native" + + fun setUpscale(context: Context, systemId: String, value: String) = + prefs(context).edit().putString(key("upscale", systemId), value).apply() + + fun audio(context: Context, systemId: String): Boolean = + prefs(context).getBoolean(key("audio", systemId), true) + + fun setAudio(context: Context, systemId: String, value: Boolean) = + prefs(context).edit().putBoolean(key("audio", systemId), value).apply() + + fun touchControls(context: Context, systemId: String): Boolean = + prefs(context).getBoolean(key("touch", systemId), true) + + fun setTouchControls(context: Context, systemId: String, value: Boolean) = + prefs(context).edit().putBoolean(key("touch", systemId), value).apply() + + fun adaptiveSticks(context: Context, systemId: String): Boolean = + prefs(context).getBoolean(key("adaptive", systemId), false) + + fun setAdaptiveSticks(context: Context, systemId: String, value: Boolean) = + prefs(context).edit().putBoolean(key("adaptive", systemId), value).apply() + + fun hud(context: Context, systemId: String): Boolean = + prefs(context).getBoolean("retro_def_hud_global", false) + + fun setHud(context: Context, systemId: String, value: Boolean) = + prefs(context).edit().putBoolean("retro_def_hud_global", value).apply() + + fun netplayEnabled(context: Context, systemId: String): Boolean = + prefs(context).getBoolean(key("netplay", systemId), false) + + fun setNetplayEnabled(context: Context, systemId: String, value: Boolean) = + prefs(context).edit().putBoolean(key("netplay", systemId), value).apply() + + fun clearNetplayArm( + context: Context, + systemId: String, + ) { + prefs(context) + .edit() + .putBoolean(key("netplay", systemId), false) + .putString(key("netplay_mode", systemId), "off") + .putBoolean(key("netplay_host_mode", systemId), false) + .apply() + } + + fun netplayHost(context: Context, systemId: String): String = + prefs(context).getString(key("netplay_host", systemId), "") ?: "" + + fun setNetplayHost(context: Context, systemId: String, value: String) = + prefs(context).edit().putString(key("netplay_host", systemId), value).apply() + + fun netplayPort(context: Context, systemId: String): Int { + val fallback = + when { + RetroOnlineSupport.supportsGameLink(systemId) -> RetroGameLink.DEFAULT_PORT + RetroOnlineSupport.supportsDolphinNetplay(systemId) -> 2626 + else -> 55435 + } + return prefs(context).getInt(key("netplay_port", systemId), fallback) + } + + fun setNetplayPort(context: Context, systemId: String, value: Int) = + prefs(context).edit().putInt(key("netplay_port", systemId), value.coerceIn(1, 65535)).apply() + + fun netplayHostMode(context: Context, systemId: String): Boolean = + prefs(context).getBoolean(key("netplay_host_mode", systemId), true) + + fun setNetplayHostMode(context: Context, systemId: String, value: Boolean) = + prefs(context).edit().putBoolean(key("netplay_host_mode", systemId), value).apply() + + fun netplayTraversal(context: Context, systemId: String): Boolean = + prefs(context).getBoolean(key("netplay_traversal", systemId), false) + + fun setNetplayTraversal(context: Context, systemId: String, value: Boolean) = + prefs(context).edit().putBoolean(key("netplay_traversal", systemId), value).apply() + + fun netplayHostCode(context: Context, systemId: String): String = + prefs(context).getString(key("netplay_host_code", systemId), "") ?: "" + + fun setNetplayHostCode(context: Context, systemId: String, value: String) = + prefs(context).edit().putString(key("netplay_host_code", systemId), value.trim()).apply() + + fun netplayPlayerName(context: Context): String = + prefs(context).getString("retro_netplay_player_name", "") ?: "" + + fun setNetplayPlayerName(context: Context, value: String) = + prefs(context).edit().putString("retro_netplay_player_name", value.trim().take(24)).apply() + + fun netplayLaunchMode(context: Context, systemId: String): String { + val raw = prefs(context).getString(key("netplay_mode", systemId), null) + return when (raw?.lowercase()) { + "join" -> "join" + "host" -> "host" + "off", "manual", null -> "off" + else -> "off" + } + } + + fun setNetplayLaunchMode(context: Context, systemId: String, value: String) { + val mode = + when (value.lowercase()) { + "join" -> "join" + "host" -> "host" + else -> "off" + } + prefs(context) + .edit() + .putString(key("netplay_mode", systemId), mode) + .putBoolean(key("netplay_host_mode", systemId), mode == "host") + .apply() + } + + fun coreOption( + context: Context, + systemId: String, + optionKey: String, + fallback: String, + ): String = prefs(context).getString(varKey(systemId, optionKey), fallback) ?: fallback + + fun setCoreOption( + context: Context, + systemId: String, + optionKey: String, + value: String, + ) = prefs(context).edit().putString(varKey(systemId, optionKey), value).apply() +} diff --git a/app/src/main/feature/retro/RetroDefaultsScreen.kt b/app/src/main/feature/retro/RetroDefaultsScreen.kt new file mode 100644 index 000000000..6ef09a30c --- /dev/null +++ b/app/src/main/feature/retro/RetroDefaultsScreen.kt @@ -0,0 +1,1010 @@ +package com.winlator.cmod.feature.retro + +import android.widget.Toast +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.navigationBars +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Button +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.ui.draw.clip +import androidx.compose.ui.unit.sp +import androidx.compose.runtime.CompositionLocalProvider +import com.winlator.cmod.R +import com.winlator.cmod.feature.settings.SettingsNavBridge +import com.winlator.cmod.shared.ui.focus.rememberSettingsContentNav +import com.winlator.cmod.shared.ui.nav.LocalPaneNav +import com.winlator.cmod.shared.ui.nav.paneNavItem +import java.io.File +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +private val PageBg = Color(0xFF101018) +private val PageText = Color(0xFFF0F4FF) +private val PageSub = Color(0xFF93A6BC) + +private val SHADER_KEYS = listOf("default", "crt", "lcd", "sharp") +private val UPSCALE_KEYS = listOf("2x", "4x", "native") + +@Composable +fun RetroDefaultsScreen(bridge: SettingsNavBridge? = null) { + val context = LocalContext.current + val scope = androidx.compose.runtime.rememberCoroutineScope() + var expandedConsole by remember { mutableStateOf(null) } + var refresh by remember { mutableIntStateOf(0) } + var confirmHardcore by remember { mutableStateOf(false) } + val contentNav = rememberSettingsContentNav(bridge) + + if (confirmHardcore) { + RetroHardcoreConfirmDialog( + onConfirm = { + confirmHardcore = false + RetroAchievementsManager.setHardcorePreferred(context, true) + refresh++ + }, + onDismiss = { confirmHardcore = false }, + ) + } + + val biosPicker = + rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> + if (uri != null) { + scope.launch { + val result = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { + RetroBiosImport.importFromUri(context, uri) + } + result + .onSuccess { Toast.makeText(context, context.getString(R.string.retro_scr_bios_imported, it), Toast.LENGTH_SHORT).show() } + .onFailure { Toast.makeText(context, it.message ?: context.getString(R.string.retro_scr_invalid_bios_file), Toast.LENGTH_LONG).show() } + refresh++ + } + } + } + + val ps2BiosPicker = + rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> + if (uri != null) { + scope.launch { + val result = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { + RetroBiosImport.importPs2FromUri(context, uri) + } + result + .onSuccess { Toast.makeText(context, context.getString(R.string.retro_scr_ps2_bios_imported, it), Toast.LENGTH_SHORT).show() } + .onFailure { Toast.makeText(context, it.message ?: context.getString(R.string.retro_scr_invalid_ps2_bios_file), Toast.LENGTH_LONG).show() } + refresh++ + } + } + } + + @Suppress("UNUSED_EXPRESSION") refresh + + CompositionLocalProvider(LocalPaneNav provides contentNav) { + Column( + modifier = + Modifier + .fillMaxSize() + .background(PageBg) + .verticalScroll(rememberScrollState()) + .windowInsetsPadding(WindowInsets.navigationBars) + .padding(16.dp), + verticalArrangement = Arrangement.spacedBy(14.dp), + ) { + Text( + stringResource(R.string.retro_scr_retro_defaults), + color = PageSub, + fontSize = 11.sp, + fontWeight = FontWeight.Bold, + letterSpacing = 1.sp, + ) + Text( + stringResource(R.string.retro_scr_retro_defaults_desc), + color = PageSub, + style = MaterialTheme.typography.bodySmall, + ) + + RetroConsoleBundleGroup(refreshKey = refresh, onChanged = { refresh++ }) + + RetroSettingGroup { + RetroGroupTitle(stringResource(R.string.retro_scr_retroachievements)) + RetroInfoRow( + stringResource(R.string.retro_scr_account), + if (RetroAchievementsManager.isLoggedIn(context)) { + RetroAchievementsManager.displayName(context) ?: stringResource(R.string.retro_scr_signed_in) + } else { + stringResource(R.string.retro_scr_not_signed_in_hint) + }, + ) + RetroSettingSwitch( + stringResource(R.string.retro_scr_achievements_enabled), + RetroAchievementsManager.isEnabled(context), + ) { + RetroAchievementsManager.setEnabled(context, it) + refresh++ + } + if (RetroAchievementsManager.HARDCORE_SUPPORTED) { + RetroSettingSwitch( + stringResource(R.string.retro_scr_hardcore_default), + RetroAchievementsManager.isHardcorePreferred(context), + ) { + if (it) { + confirmHardcore = true + } else { + RetroAchievementsManager.setHardcorePreferred(context, false) + refresh++ + } + } + } + if (RetroAchievementsManager.isLoggedIn(context)) { + OutlinedButton( + onClick = { + RetroAchievementsManager.logout(context) + refresh++ + }, + modifier = + Modifier + .fillMaxWidth() + .padding(top = 4.dp) + .paneNavItem( + cornerRadius = 8.dp, + onActivate = { + RetroAchievementsManager.logout(context) + refresh++ + }, + highlightColor = Color(0xFF4FC3F7), + tapToSelect = true, + ), + ) { + Text(stringResource(R.string.retro_scr_sign_out)) + } + } + } + + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(10.dp), + verticalAlignment = Alignment.Top, + ) { + Box(Modifier.weight(1f)) { + RetroSettingGroup { + RetroGroupTitle(stringResource(R.string.retro_scr_playstation_bios)) + val dir = RetroCoreManager.systemDir(context) + val installed = RetroSystems.PSX.biosFiles.filter { File(dir, it).isFile } + RetroInfoRow( + stringResource(R.string.retro_scr_installed), + if (installed.isEmpty()) { + stringResource(R.string.retro_scr_none_ps1_bios) + } else { + installed.joinToString(", ") + }, + ) + Button( + onClick = { runCatching { biosPicker.launch(arrayOf("*/*")) } }, + modifier = + Modifier + .fillMaxWidth() + .padding(top = 4.dp) + .paneNavItem( + cornerRadius = 8.dp, + onActivate = { runCatching { biosPicker.launch(arrayOf("*/*")) } }, + highlightColor = Color(0xFF4FC3F7), + tapToSelect = true, + ), + ) { + Text(stringResource(R.string.retro_scr_import_ps1_bios)) + } + if (installed.isNotEmpty()) { + OutlinedButton( + onClick = { + val n = RetroBiosImport.deletePs1Bios(context) + Toast.makeText( + context, + if (n > 0) { + context.getString(R.string.retro_scr_ps1_bios_removed) + } else { + context.getString(R.string.retro_scr_no_bios_to_remove) + }, + Toast.LENGTH_SHORT, + ).show() + refresh++ + }, + modifier = + Modifier + .fillMaxWidth() + .padding(top = 4.dp) + .paneNavItem( + cornerRadius = 8.dp, + onActivate = { + val n = RetroBiosImport.deletePs1Bios(context) + Toast.makeText( + context, + if (n > 0) { + context.getString(R.string.retro_scr_ps1_bios_removed) + } else { + context.getString(R.string.retro_scr_no_bios_to_remove) + }, + Toast.LENGTH_SHORT, + ).show() + refresh++ + }, + highlightColor = Color(0xFF4FC3F7), + tapToSelect = true, + ), + ) { + Text(stringResource(R.string.retro_scr_remove_ps1_bios)) + } + } + } + } + Box(Modifier.weight(1f)) { + RetroSettingGroup { + RetroGroupTitle(stringResource(R.string.retro_scr_playstation_2_bios)) + val ps2Installed = RetroBiosImport.installedPs2Bios(context) + RetroInfoRow( + stringResource(R.string.retro_scr_installed), + if (ps2Installed.isEmpty()) { + stringResource(R.string.retro_scr_none_ps2_bios) + } else { + ps2Installed.joinToString(", ") + }, + ) + Button( + onClick = { runCatching { ps2BiosPicker.launch(arrayOf("*/*")) } }, + modifier = + Modifier + .fillMaxWidth() + .padding(top = 4.dp) + .paneNavItem( + cornerRadius = 8.dp, + onActivate = { runCatching { ps2BiosPicker.launch(arrayOf("*/*")) } }, + highlightColor = Color(0xFF4FC3F7), + tapToSelect = true, + ), + ) { + Text(stringResource(R.string.retro_scr_import_ps2_bios)) + } + if (ps2Installed.isNotEmpty()) { + OutlinedButton( + onClick = { + val n = RetroBiosImport.deletePs2Bios(context) + Toast.makeText( + context, + if (n > 0) { + context.getString(R.string.retro_scr_ps2_bios_removed) + } else { + context.getString(R.string.retro_scr_no_bios_to_remove) + }, + Toast.LENGTH_SHORT, + ).show() + refresh++ + }, + modifier = + Modifier + .fillMaxWidth() + .padding(top = 4.dp) + .paneNavItem( + cornerRadius = 8.dp, + onActivate = { + val n = RetroBiosImport.deletePs2Bios(context) + Toast.makeText( + context, + if (n > 0) { + context.getString(R.string.retro_scr_ps2_bios_removed) + } else { + context.getString(R.string.retro_scr_no_bios_to_remove) + }, + Toast.LENGTH_SHORT, + ).show() + refresh++ + }, + highlightColor = Color(0xFF4FC3F7), + tapToSelect = true, + ), + ) { + Text(stringResource(R.string.retro_scr_remove_ps2_bios)) + } + } + } + } + } + + RetroSettingGroup { + RetroGroupTitle(stringResource(R.string.retro_scr_library_artwork)) + RetroSettingSwitch( + stringResource(R.string.retro_scr_retro_case_art), + RetroBoxart.caseArtEnabled(context), + ) { RetroBoxart.setCaseArtEnabled(context, it); refresh++ } + RetroInfoRow( + stringResource(R.string.retro_scr_box_art), + stringResource(R.string.retro_scr_box_art_desc), + ) + } + + RetroSettingGroup { + RetroGroupTitle(stringResource(R.string.retro_scr_roms_folder)) + val romsDir = RetroDefaults.romsDir(context) + RetroInfoRow( + stringResource(R.string.retro_scr_folder), + romsDir ?: stringResource(R.string.retro_scr_roms_not_set), + ) + RetroInfoRow( + stringResource(R.string.retro_scr_auto_import), + stringResource(R.string.retro_scr_auto_import_desc), + ) + val pickRomsFolder = { + val activity = context as? android.app.Activity + if (activity != null) { + com.winlator.cmod.shared.android.DirectoryPickerDialog.show( + activity = activity, + initialPath = romsDir + ?: android.os.Environment.getExternalStoragePublicDirectory( + android.os.Environment.DIRECTORY_DOWNLOADS, + ).absolutePath, + title = context.getString(R.string.retro_scr_select_roms_folder_title), + ) { path -> + RetroDefaults.setRomsDir(context, path) + Thread { + val result = RetroRomScanner.scan(context, File(path)) + activity.runOnUiThread { + Toast.makeText(context, scanMessage(context, result), Toast.LENGTH_SHORT).show() + refresh++ + } + }.start() + } + } + } + Button( + onClick = { pickRomsFolder() }, + modifier = + Modifier + .fillMaxWidth() + .padding(top = 4.dp) + .paneNavItem( + cornerRadius = 8.dp, + onActivate = { pickRomsFolder() }, + highlightColor = Color(0xFF4FC3F7), + tapToSelect = true, + ), + ) { + Text(if (romsDir == null) stringResource(R.string.retro_scr_select_roms_folder_button) else stringResource(R.string.retro_scr_change_roms_folder_button)) + } + if (romsDir != null) { + val scanNow = { + val activity = context as? android.app.Activity + Thread { + val result = RetroRomScanner.scanConfiguredFolder(context) + activity?.runOnUiThread { + Toast.makeText(context, scanMessage(context, result), Toast.LENGTH_SHORT).show() + refresh++ + } + }.start() + } + OutlinedButton( + onClick = { scanNow() }, + modifier = + Modifier + .fillMaxWidth() + .padding(top = 4.dp) + .paneNavItem( + cornerRadius = 8.dp, + onActivate = { scanNow() }, + highlightColor = Color(0xFF4FC3F7), + tapToSelect = true, + ), + ) { + Text(stringResource(R.string.retro_scr_scan_now)) + } + } + } + + RetroLibretroHudSection() + + Text( + stringResource(R.string.retro_scr_console_defaults), + color = PageSub, + fontSize = 11.sp, + fontWeight = FontWeight.Bold, + letterSpacing = 1.sp, + modifier = Modifier.padding(top = 4.dp), + ) + Text( + stringResource(R.string.retro_scr_console_defaults_desc), + color = PageSub, + style = MaterialTheme.typography.labelMedium, + ) + + RetroSystems.ALL.sortedBy { it.displayName }.forEach { console -> + val sys = console.id + val expanded = expandedConsole == sys + RetroSettingGroup { + Row( + modifier = + Modifier + .fillMaxWidth() + .clickable { expandedConsole = if (expanded) null else sys } + .paneNavItem( + cornerRadius = 8.dp, + onActivate = { expandedConsole = if (expanded) null else sys }, + highlightColor = Color(0xFF4FC3F7), + tapToSelect = true, + ) + .padding(vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + console.displayName, + color = PageText, + fontWeight = FontWeight.SemiBold, + modifier = Modifier.weight(1f), + style = MaterialTheme.typography.bodyLarge, + ) + Text( + if (expanded) "▲" else "▼", + color = PageSub, + ) + } + if (expanded && console.isExternal) { + val ps2Prefs = context.getSharedPreferences("ARMSX2", android.content.Context.MODE_PRIVATE) + val rendererKeys = listOf("vulkan", "opengl", "software") + val rendererLabels = listOf( + stringResource(R.string.retro_ps2_renderer_vulkan), + stringResource(R.string.retro_ps2_renderer_opengl), + stringResource(R.string.retro_ps2_renderer_software), + ) + RetroSettingDropdown( + label = stringResource(R.string.retro_scr_renderer), + entries = rendererLabels, + selectedIndex = rendererKeys.indexOf(ps2Prefs.getString("wn.ps2.renderer", "vulkan")).coerceAtLeast(0), + onSelected = { ps2Prefs.edit().putString("wn.ps2.renderer", rendererKeys[it]).apply(); refresh++ }, + ) + val ps2Drivers = remember { com.armsx2.CustomDriver.listInstalled(context) } + val driverIds = listOf("") + ps2Drivers.map { it.id } + val driverLabels = listOf(stringResource(R.string.retro_gpu_driver_system)) + ps2Drivers.map { it.name } + val curDriver = (ps2Prefs.getString("wn.ps2.driver", "") ?: "").let { if (it.equals("system", true)) "" else it } + RetroSettingDropdown( + label = stringResource(R.string.retro_gpu_driver), + entries = driverLabels, + selectedIndex = driverIds.indexOf(curDriver).coerceAtLeast(0), + onSelected = { ps2Prefs.edit().putString("wn.ps2.driver", driverIds[it]).apply(); refresh++ }, + ) + if (ps2Drivers.isEmpty()) { + Text( + stringResource(R.string.retro_gpu_driver_hint), + color = PageSub, + fontSize = 11.sp, + modifier = Modifier.padding(top = 2.dp), + ) + } + com.winlator.cmod.feature.retro.Ps2TurnipFlags(ps2Prefs, refresh) { refresh++ } + val ps2Scales = listOf(1f, 1.5f, 2f, 3f, 4f) + val ps2ScaleLabels = listOf( + stringResource(R.string.retro_gs_scale_1x_native), + stringResource(R.string.retro_gs_scale_1_5x), + stringResource(R.string.retro_gs_scale_2x), + stringResource(R.string.retro_gs_scale_3x), + stringResource(R.string.retro_gs_scale_4x), + ) + val curScale = ps2Prefs.getFloat("wn.ps2.upscale", 1f) + RetroSettingDropdown( + label = stringResource(R.string.retro_scr_upscale_resolution), + entries = ps2ScaleLabels, + selectedIndex = ps2Scales.indexOfFirst { kotlin.math.abs(it - curScale) < 0.01f }.coerceAtLeast(0), + onSelected = { ps2Prefs.edit().putFloat("wn.ps2.upscale", ps2Scales[it]).apply(); refresh++ }, + ) + RetroSettingDropdown( + label = stringResource(R.string.retro_scr_aspect_ratio), + entries = listOf( + stringResource(R.string.retro_scr_aspect_stretch), + stringResource(R.string.retro_scr_aspect_auto_standard), + stringResource(R.string.retro_scr_aspect_4_3), + stringResource(R.string.retro_scr_aspect_16_9), + ), + selectedIndex = ps2Prefs.getInt("wn.ps2.aspect", 1).coerceIn(0, 3), + onSelected = { ps2Prefs.edit().putInt("wn.ps2.aspect", it).apply(); refresh++ }, + ) + RetroSettingDropdown( + label = stringResource(R.string.retro_gs_fmv_aspect_ratio), + entries = listOf( + stringResource(R.string.retro_gs_off), + stringResource(R.string.retro_gs_aspect_auto_standard), + stringResource(R.string.retro_gs_aspect_4_3), + stringResource(R.string.retro_gs_aspect_16_9), + ), + selectedIndex = ps2Prefs.getInt("wn.ps2.fmvaspect", 0).coerceIn(0, 3), + onSelected = { ps2Prefs.edit().putInt("wn.ps2.fmvaspect", it).apply(); refresh++ }, + ) + RetroSettingDropdown( + label = stringResource(R.string.retro_gs_deinterlace_mode), + entries = listOf( + stringResource(R.string.retro_gs_deint_auto), + stringResource(R.string.retro_gs_deint_off), + stringResource(R.string.retro_gs_deint_weave_tff), + stringResource(R.string.retro_gs_deint_weave_bff), + stringResource(R.string.retro_gs_deint_bob_tff), + stringResource(R.string.retro_gs_deint_bob_bff), + stringResource(R.string.retro_gs_deint_blend_tff), + stringResource(R.string.retro_gs_deint_blend_bff), + stringResource(R.string.retro_gs_deint_adaptive_tff), + stringResource(R.string.retro_gs_deint_adaptive_bff), + ), + selectedIndex = ps2Prefs.getInt("wn.ps2.deinterlace", 0).coerceIn(0, 9), + onSelected = { ps2Prefs.edit().putInt("wn.ps2.deinterlace", it).apply(); refresh++ }, + ) + RetroSettingDropdown( + label = stringResource(R.string.retro_scr_display_filter), + entries = listOf( + stringResource(R.string.retro_scr_filter_nearest), + stringResource(R.string.retro_scr_filter_bilinear_smooth), + stringResource(R.string.retro_scr_filter_bilinear_sharp), + ), + selectedIndex = ps2Prefs.getInt("wn.ps2.displayfilter", 1).coerceIn(0, 2), + onSelected = { ps2Prefs.edit().putInt("wn.ps2.displayfilter", it).apply(); refresh++ }, + ) + RetroSettingDropdown( + label = stringResource(R.string.retro_scr_texture_filter), + entries = listOf( + stringResource(R.string.retro_scr_filter_nearest), + stringResource(R.string.retro_scr_filter_bilinear_forced), + stringResource(R.string.retro_scr_filter_bilinear_ps2), + stringResource(R.string.retro_scr_filter_bilinear_sprites), + ), + selectedIndex = ps2Prefs.getInt("wn.ps2.filter", 2).coerceIn(0, 3), + onSelected = { ps2Prefs.edit().putInt("wn.ps2.filter", it).apply(); refresh++ }, + ) + RetroSettingSwitch(stringResource(R.string.retro_scr_mipmapping), ps2Prefs.getBoolean("wn.ps2.mipmap", true)) { + ps2Prefs.edit().putBoolean("wn.ps2.mipmap", it).apply(); refresh++ + } + RetroSettingDropdown( + label = stringResource(R.string.retro_scr_blending_accuracy), + entries = listOf( + stringResource(R.string.retro_scr_blend_minimum), + stringResource(R.string.retro_scr_blend_basic), + stringResource(R.string.retro_scr_blend_medium), + stringResource(R.string.retro_scr_blend_high), + stringResource(R.string.retro_scr_blend_full), + stringResource(R.string.retro_scr_blend_maximum), + ), + selectedIndex = ps2Prefs.getInt("wn.ps2.blend", 1).coerceIn(0, 5), + onSelected = { ps2Prefs.edit().putInt("wn.ps2.blend", it).apply(); refresh++ }, + ) + RetroSettingSwitch(stringResource(R.string.retro_gs_anti_blur), ps2Prefs.getBoolean("wn.ps2.antiblur", true)) { + ps2Prefs.edit().putBoolean("wn.ps2.antiblur", it).apply(); refresh++ + } + RetroSettingDropdown( + label = stringResource(R.string.retro_scr_crt_tv_shader), + entries = listOf( + stringResource(R.string.retro_scr_shader_off), + stringResource(R.string.retro_scr_shader_scanline), + stringResource(R.string.retro_scr_shader_diagonal), + stringResource(R.string.retro_scr_shader_triangular), + stringResource(R.string.retro_scr_shader_wave), + stringResource(R.string.retro_scr_shader_lottes), + stringResource(R.string.retro_scr_shader_4xrgss), + stringResource(R.string.retro_scr_shader_nxagss), + ), + selectedIndex = ps2Prefs.getInt("wn.ps2.tvshader", 0).coerceIn(0, 7), + onSelected = { ps2Prefs.edit().putInt("wn.ps2.tvshader", it).apply(); refresh++ }, + ) + RetroSettingDropdown( + label = stringResource(R.string.retro_scr_frame_skip), + entries = listOf( + stringResource(R.string.retro_scr_skip_off), + stringResource(R.string.retro_scr_skip_1), + stringResource(R.string.retro_scr_skip_2), + stringResource(R.string.retro_scr_skip_3), + ), + selectedIndex = ps2Prefs.getInt("wn.ps2.frameskip", 0).coerceIn(0, 3), + onSelected = { ps2Prefs.edit().putInt("wn.ps2.frameskip", it).apply(); refresh++ }, + ) + RetroSettingSwitch(stringResource(R.string.retro_gs_widescreen_patches), ps2Prefs.getBoolean("wn.ps2.widescreen", false)) { + ps2Prefs.edit().putBoolean("wn.ps2.widescreen", it).apply(); refresh++ + } + RetroSettingSwitch(stringResource(R.string.retro_gs_no_interlace_patches), ps2Prefs.getBoolean("wn.ps2.nointerlace", false)) { + ps2Prefs.edit().putBoolean("wn.ps2.nointerlace", it).apply(); refresh++ + } + val eeRates = listOf(-3, -2, -1, 0, 1, 2, 3) + RetroSettingDropdown( + label = stringResource(R.string.retro_scr_ee_cycle_rate), + entries = listOf( + stringResource(R.string.retro_scr_ee_rate_50), + stringResource(R.string.retro_scr_ee_rate_60), + stringResource(R.string.retro_scr_ee_rate_75), + stringResource(R.string.retro_scr_ee_rate_100_default), + stringResource(R.string.retro_scr_ee_rate_130), + stringResource(R.string.retro_scr_ee_rate_180), + stringResource(R.string.retro_scr_ee_rate_300), + ), + selectedIndex = eeRates.indexOf(ps2Prefs.getInt("wn.ps2.eeRate", 0).coerceIn(-3, 3)).coerceAtLeast(0), + onSelected = { ps2Prefs.edit().putInt("wn.ps2.eeRate", eeRates[it]).apply(); refresh++ }, + ) + RetroSettingDropdown( + label = stringResource(R.string.retro_scr_ee_cycle_skip), + entries = listOf( + stringResource(R.string.retro_scr_skip_off), + stringResource(R.string.retro_scr_skip_num_1), + stringResource(R.string.retro_scr_skip_num_2), + stringResource(R.string.retro_scr_skip_num_3), + ), + selectedIndex = ps2Prefs.getInt("wn.ps2.eeSkip", 0).coerceIn(0, 3), + onSelected = { ps2Prefs.edit().putInt("wn.ps2.eeSkip", it).apply(); refresh++ }, + ) + RetroSettingSwitch(stringResource(R.string.retro_scr_mtvu), ps2Prefs.getBoolean("wn.ps2.mtvu", true)) { + ps2Prefs.edit().putBoolean("wn.ps2.mtvu", it).apply(); refresh++ + } + RetroSettingSwitch(stringResource(R.string.retro_scr_instant_vu1), ps2Prefs.getBoolean("wn.ps2.instantVu1", true)) { + ps2Prefs.edit().putBoolean("wn.ps2.instantVu1", it).apply(); refresh++ + } + RetroSettingSwitch(stringResource(R.string.retro_gs_vu_flag_hack), ps2Prefs.getBoolean("wn.ps2.vuFlagHack", true)) { + ps2Prefs.edit().putBoolean("wn.ps2.vuFlagHack", it).apply(); refresh++ + } + RetroSettingSwitch(stringResource(R.string.retro_gs_intc_spin), ps2Prefs.getBoolean("wn.ps2.intc", true)) { + ps2Prefs.edit().putBoolean("wn.ps2.intc", it).apply(); refresh++ + } + RetroSettingSwitch(stringResource(R.string.retro_gs_wait_loop), ps2Prefs.getBoolean("wn.ps2.waitloop", true)) { + ps2Prefs.edit().putBoolean("wn.ps2.waitloop", it).apply(); refresh++ + } + RetroSettingSwitch(stringResource(R.string.retro_scr_fast_cdvd), ps2Prefs.getBoolean("wn.ps2.fastCdvd", false)) { + ps2Prefs.edit().putBoolean("wn.ps2.fastCdvd", it).apply(); refresh++ + } + RetroSettingSwitch(stringResource(R.string.retro_gs_fast_boot), ps2Prefs.getBoolean("wn.ps2.fastboot", true)) { + ps2Prefs.edit().putBoolean("wn.ps2.fastboot", it).apply(); refresh++ + } + RetroSettingSwitch( + stringResource(R.string.retro_scr_touch_controls), + RetroDefaults.touchControls(context, sys), + ) { RetroDefaults.setTouchControls(context, sys, it); refresh++ } + RetroSettingSwitch( + stringResource(R.string.retro_gs_adaptive_sticks), + RetroDefaults.adaptiveSticks(context, sys), + subtitle = stringResource(R.string.retro_gs_adaptive_sticks_subtitle), + ) { RetroDefaults.setAdaptiveSticks(context, sys, it); refresh++ } + RetroSettingSwitch( + stringResource(R.string.retro_ps2_show_l3r3), + ps2Prefs.getBoolean("wn.ps2.showl3r3", true), + subtitle = stringResource(R.string.retro_ps2_show_l3r3_subtitle), + ) { ps2Prefs.edit().putBoolean("wn.ps2.showl3r3", it).apply(); refresh++ } + RetroSettingSwitch( + stringResource(R.string.retro_scr_sound), + !ps2Prefs.getBoolean("wn.ps2.muted", false), + ) { ps2Prefs.edit().putBoolean("wn.ps2.muted", !it).apply(); refresh++ } + RetroSettingSwitch( + stringResource(R.string.retro_scr_swap_stereo), + ps2Prefs.getBoolean("wn.ps2.swap", false), + ) { ps2Prefs.edit().putBoolean("wn.ps2.swap", it).apply(); refresh++ } + RetroSettingSwitch( + stringResource(R.string.retro_gs_time_stretch), + ps2Prefs.getBoolean("wn.ps2.timestretch", true), + ) { ps2Prefs.edit().putBoolean("wn.ps2.timestretch", it).apply(); refresh++ } + val bufferValues = listOf(40, 50, 60, 80, 100, 120, 160, 200) + RetroSettingDropdown( + label = stringResource(R.string.retro_gs_audio_buffer), + entries = bufferValues.map { context.getString(R.string.retro_gs_ms, it) }, + selectedIndex = bufferValues.indexOf(ps2Prefs.getInt("wn.ps2.audiobuffer", 50)).coerceAtLeast(0), + onSelected = { ps2Prefs.edit().putInt("wn.ps2.audiobuffer", bufferValues[it]).apply(); refresh++ }, + ) + val latencyValues = listOf(10, 15, 20, 30, 40, 60, 80, 100) + RetroSettingDropdown( + label = stringResource(R.string.retro_gs_audio_latency), + entries = latencyValues.map { context.getString(R.string.retro_gs_ms, it) }, + selectedIndex = latencyValues.indexOf(ps2Prefs.getInt("wn.ps2.audiolatency", 20)).coerceAtLeast(0), + onSelected = { ps2Prefs.edit().putInt("wn.ps2.audiolatency", latencyValues[it]).apply(); refresh++ }, + ) + RetroSettingSwitch( + stringResource(R.string.retro_scr_performance_hud), + RetroHudSupport.resolvePs2HudEnabled(context), + ) { + RetroHudSupport.setPs2HudEnabled(context, it) + RetroDefaults.setHud(context, sys, it) + refresh++ + } + RetroSettingSwitch( + stringResource(R.string.retro_scr_enable_online_dev9), + ps2Prefs.getBoolean("wn.ps2.net.enable", true), + ) { ps2Prefs.edit().putBoolean("wn.ps2.net.enable", it).apply(); refresh++ } + if (ps2Prefs.getBoolean("wn.ps2.net.enable", true)) { + val devices = listOf("Auto", "Wi-Fi") + RetroSettingDropdown( + label = stringResource(R.string.retro_scr_ethernet_device), + entries = listOf( + stringResource(R.string.retro_scr_net_auto), + stringResource(R.string.retro_scr_net_wifi), + ), + selectedIndex = devices.indexOf(ps2Prefs.getString("wn.ps2.net.ethdevice", "Auto")).coerceAtLeast(0), + onSelected = { ps2Prefs.edit().putString("wn.ps2.net.ethdevice", devices[it]).apply(); refresh++ }, + ) + val dnsModes = listOf("Manual", "Auto", "Internal") + RetroSettingDropdown( + label = stringResource(R.string.retro_scr_dns_mode), + entries = listOf( + stringResource(R.string.retro_scr_dns_manual), + stringResource(R.string.retro_scr_net_auto), + stringResource(R.string.retro_scr_dns_internal), + ), + selectedIndex = dnsModes.indexOf(ps2Prefs.getString("wn.ps2.net.dnsmode", "Manual")).coerceAtLeast(0), + onSelected = { ps2Prefs.edit().putString("wn.ps2.net.dnsmode", dnsModes[it]).apply(); refresh++ }, + ) + RetroSettingTextField(stringResource(R.string.retro_scr_primary_dns), ps2Prefs.getString("wn.ps2.net.dns1", PS2_DEFAULT_DNS).orEmpty(), PS2_DEFAULT_DNS) { ps2Prefs.edit().putString("wn.ps2.net.dns1", it).apply(); refresh++ } + RetroSettingTextField(stringResource(R.string.retro_scr_secondary_dns), ps2Prefs.getString("wn.ps2.net.dns2", "").orEmpty(), stringResource(R.string.retro_scr_optional)) { ps2Prefs.edit().putString("wn.ps2.net.dns2", it).apply(); refresh++ } + RetroSettingSwitch(stringResource(R.string.retro_gs_dnas_bypass), ps2Prefs.getBoolean(com.winlator.cmod.feature.retro.Ps2DnasBypass.PREF, true), subtitle = stringResource(R.string.retro_gs_dnas_bypass_subtitle)) { ps2Prefs.edit().putBoolean(com.winlator.cmod.feature.retro.Ps2DnasBypass.PREF, it).apply(); refresh++ } + RetroSettingSwitch(stringResource(R.string.retro_scr_auto_ip_dhcp), ps2Prefs.getBoolean("wn.ps2.net.dhcp", true)) { ps2Prefs.edit().putBoolean("wn.ps2.net.dhcp", it).apply(); refresh++ } + } + } + if (expanded && !console.isExternal) { + if (RetroCoreManager.usesDolphinCore(console)) { + val prefs = androidx.preference.PreferenceManager.getDefaultSharedPreferences(context) + val gcDrivers = remember { com.armsx2.CustomDriver.listInstalled(context) } + val gcDriverIds = remember(gcDrivers) { listOf("") + gcDrivers.map { it.id } } + val gcDriverLabels = listOf(stringResource(R.string.retro_gpu_driver_system)) + gcDrivers.map { it.name } + val curGcDriver = (prefs.getString(DolphinEmbedLaunch.DRIVER_PREF, "") ?: "").let { if (it.equals("system", true)) "" else it } + RetroSettingDropdown( + label = stringResource(R.string.retro_gpu_driver), + entries = gcDriverLabels, + selectedIndex = gcDriverIds.indexOf(curGcDriver).coerceAtLeast(0), + onSelected = { prefs.edit().putString(DolphinEmbedLaunch.DRIVER_PREF, gcDriverIds[it]).apply(); refresh++ }, + ) + } + val embeddedDolphin = + RetroCoreManager.usesDolphinCore(console) && + RetroShortcuts.embeddedDolphinEnabled(context) + if (!embeddedDolphin) { + RetroSettingDropdown( + label = stringResource(R.string.retro_scr_shader), + entries = listOf( + stringResource(R.string.retro_scr_shader_default), + stringResource(R.string.retro_scr_shader_crt), + stringResource(R.string.retro_scr_shader_lcd), + stringResource(R.string.retro_scr_shader_sharp), + ), + selectedIndex = SHADER_KEYS.indexOf(RetroDefaults.shader(context, sys)).coerceAtLeast(0), + onSelected = { RetroDefaults.setShader(context, sys, SHADER_KEYS[it]); refresh++ }, + ) + RetroSettingSwitch( + stringResource(R.string.retro_scr_sgsr_upscaling), + RetroDefaults.sgsr(context, sys), + ) { RetroDefaults.setSgsr(context, sys, it); refresh++ } + RetroSettingDropdown( + label = stringResource(R.string.retro_scr_upscale_resolution), + entries = listOf("2x", "4x", stringResource(R.string.retro_scr_upscale_native)), + selectedIndex = UPSCALE_KEYS.indexOf(RetroDefaults.upscale(context, sys)).coerceAtLeast(0), + onSelected = { RetroDefaults.setUpscale(context, sys, UPSCALE_KEYS[it]); refresh++ }, + ) + } + val consoleOptions = RetroCoreOptions.forSystem(console) + (consoleOptions.filterNot { it.advanced } + consoleOptions.filter { it.advanced }) + .forEach { option -> + val current = RetroDefaults.coreOption(context, sys, option.key, option.defaultValue) + RetroSettingDropdown( + label = option.labelText(context), + entries = option.valueLabels, + selectedIndex = option.values.indexOf(current).coerceAtLeast(0), + onSelected = { RetroDefaults.setCoreOption(context, sys, option.key, option.values[it]); refresh++ }, + ) + } + + RetroSettingSwitch( + stringResource(R.string.retro_scr_touch_controls), + RetroDefaults.touchControls(context, sys), + ) { RetroDefaults.setTouchControls(context, sys, it); refresh++ } + RetroSettingSwitch( + stringResource(R.string.retro_gs_adaptive_sticks), + RetroDefaults.adaptiveSticks(context, sys), + subtitle = stringResource(R.string.retro_gs_adaptive_sticks_subtitle), + ) { RetroDefaults.setAdaptiveSticks(context, sys, it); refresh++ } + RetroSettingSwitch( + stringResource(R.string.retro_scr_sound), + RetroDefaults.audio(context, sys), + ) { RetroDefaults.setAudio(context, sys, it); refresh++ } + if (RetroOnlineSupport.supportsMultiplayerUi(sys)) { + RetroNetplaySettingsSection( + systemId = sys, + version = refresh, + onChanged = { refresh++ }, + ) + } else if (RetroOnlineSupport.supportsDolphinNetplay(sys)) { + DolphinNetplaySettingsSection( + systemId = sys, + version = refresh, + onChanged = { refresh++ }, + ) + } + } + } + } + } + } +} + +private fun scanMessage(context: android.content.Context, result: RetroRomScanner.Result): String { + val parts = buildList { + if (result.added > 0) add(context.getString(R.string.retro_scan_added, result.added)) + if (result.removed > 0) add(context.getString(R.string.retro_scan_removed, result.removed)) + } + return if (parts.isEmpty()) { + context.getString(R.string.retro_scan_up_to_date) + } else { + context.getString(R.string.retro_scan_roms, parts.joinToString(", ")) + } +} + +@Composable +fun RetroHardcoreConfirmDialog( + onConfirm: () -> Unit, + onDismiss: () -> Unit, +) { + val accent = Color(0xFF1A9FFF) + com.winlator.cmod.shared.ui.dialog.WinNativeDialogShell( + onDismiss = onDismiss, + title = stringResource(R.string.retro_scr_enable_hardcore_title), + ) { + Text( + stringResource(R.string.retro_scr_enable_hardcore_body), + color = com.winlator.cmod.shared.theme.WinNativeTextSecondary, + fontSize = 14.sp, + lineHeight = 20.sp, + ) + Spacer(Modifier.height(16.dp)) + Box(Modifier.fillMaxWidth().height(1.dp).background(com.winlator.cmod.shared.theme.WinNativeOutline)) + Spacer(Modifier.height(16.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.End)) { + com.winlator.cmod.shared.ui.dialog.WinNativeDialogButton( + label = stringResource(R.string.retro_scr_cancel), + textColor = com.winlator.cmod.shared.theme.WinNativeTextPrimary, + onClick = onDismiss, + ) + com.winlator.cmod.shared.ui.dialog.WinNativeDialogButton( + label = stringResource(R.string.retro_scr_enable), + textColor = accent, + backgroundColor = accent.copy(alpha = 0.12f), + borderColor = accent.copy(alpha = 0.3f), + onClick = onConfirm, + ) + } + } +} + +@Composable +private fun RetroConsoleBundleGroup( + refreshKey: Int, + onChanged: () -> Unit, +) { + val context = LocalContext.current + val scope = androidx.compose.runtime.rememberCoroutineScope() + var busy by remember { mutableStateOf(false) } + var checking by remember { mutableStateOf(false) } + var step by remember { mutableStateOf(null) } + var downloaded by remember { mutableStateOf(0L to 0L) } + var checkFailed by remember { mutableStateOf(false) } + var installError by remember { mutableStateOf(null) } + var progress by remember { mutableStateOf(0f) } + var published by remember { mutableStateOf(null) } + val installed = remember(refreshKey, busy) { RetroBundle.installed(context) } + val updatable = published != null && published!!.sha256 != installed?.sha256 + + val verifyingText = stringResource(R.string.retro_scr_consoles_verifying) + val installingText = stringResource(R.string.retro_scr_consoles_installing) + + suspend fun check(): RetroBundle.Version? { + checking = true + val result = withContext(Dispatchers.IO) { RetroBundle.published() } + checking = false + published = result.getOrNull() ?: published + checkFailed = result.isFailure + return result.getOrNull() + } + + suspend fun install(version: RetroBundle.Version) { + busy = true + progress = 0f + step = null + downloaded = 0L to 0L + installError = null + val result = + withContext(Dispatchers.IO) { + RetroBundle.install(context, version) { p -> + when (p) { + is RetroBundle.Progress.Downloading -> { + downloaded = p.bytes to p.total + if (p.total > 0) progress = p.bytes.toFloat() / p.total + } + RetroBundle.Progress.Verifying -> step = verifyingText + RetroBundle.Progress.Extracting -> step = installingText + } + } + } + busy = false + step = null + installError = result.exceptionOrNull()?.let { it.message ?: it.toString() } + onChanged() + } + + androidx.compose.runtime.LaunchedEffect(Unit) { check() } + + RetroSettingGroup { + RetroGroupTitle(stringResource(R.string.retro_scr_consoles_group)) + RetroInfoRow( + stringResource(R.string.retro_scr_consoles_state), + when { + busy && step != null -> step!! + busy && downloaded.second > 0 -> + stringResource( + R.string.retro_scr_consoles_downloading, + downloaded.first / (1024 * 1024), + downloaded.second / (1024 * 1024), + ) + busy -> stringResource(R.string.retro_scr_consoles_working) + installError != null -> installError!! + checking -> stringResource(R.string.retro_scr_consoles_checking) + installed == null -> stringResource(R.string.retro_scr_consoles_missing) + updatable -> + stringResource( + R.string.retro_scr_consoles_update_available, + published!!.day, + published!!.size / (1024 * 1024), + ) + checkFailed -> stringResource(R.string.retro_scr_consoles_installed_no_check, installed.day) + else -> stringResource(R.string.retro_scr_consoles_installed, installed.day) + }, + ) + if (busy && progress > 0f) { + LinearProgressIndicator( + progress = { progress }, + modifier = Modifier.fillMaxWidth().padding(top = 6.dp), + ) + } + OutlinedButton( + enabled = !busy && !checking, + onClick = { + scope.launch { + if (installed == null || updatable) { + (published ?: check())?.let { install(it) } + } else { + check() + } + } + }, + modifier = Modifier.fillMaxWidth().padding(top = 4.dp), + ) { + Text( + stringResource( + when { + installed == null -> R.string.retro_scr_consoles_download + updatable -> R.string.retro_scr_consoles_update + else -> R.string.retro_scr_consoles_check + }, + ), + ) + } + } +} diff --git a/app/src/main/feature/retro/RetroDrawerMenu.kt b/app/src/main/feature/retro/RetroDrawerMenu.kt new file mode 100644 index 000000000..446203f59 --- /dev/null +++ b/app/src/main/feature/retro/RetroDrawerMenu.kt @@ -0,0 +1,1796 @@ +package com.winlator.cmod.feature.retro + +import android.view.KeyEvent +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.core.LinearEasing +import androidx.compose.animation.core.Spring +import androidx.compose.animation.core.animateDpAsState +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.spring +import androidx.compose.animation.core.tween +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsPressedAsState +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.defaultMinSize +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.outlined.ExitToApp +import androidx.compose.material.icons.automirrored.outlined.VolumeUp +import androidx.compose.material.icons.outlined.Album +import androidx.compose.material.icons.outlined.Bolt +import androidx.compose.material.icons.outlined.Apps +import androidx.compose.material.icons.outlined.Download +import androidx.compose.material.icons.outlined.Edit +import androidx.compose.material.icons.outlined.EmojiEvents +import androidx.compose.material.icons.outlined.FastForward +import androidx.compose.material.icons.outlined.Monitor +import androidx.compose.material.icons.outlined.Pause +import androidx.compose.material.icons.outlined.PlayArrow +import androidx.compose.material.icons.outlined.Wifi +import androidx.compose.material.icons.outlined.RestartAlt +import androidx.compose.material.icons.outlined.Save +import androidx.compose.material.icons.outlined.Speed +import androidx.compose.material.icons.outlined.SportsEsports +import androidx.compose.material.icons.outlined.Add +import androidx.compose.material.icons.outlined.Group +import androidx.compose.material.icons.outlined.Link +import androidx.compose.material.icons.outlined.Search +import androidx.compose.material.icons.outlined.Tune +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.Icon +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Slider +import androidx.compose.material3.SliderDefaults +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.layout.boundsInParent +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.winlator.cmod.R +import com.winlator.cmod.shared.theme.SessionDrawerStyle +import com.winlator.cmod.shared.theme.WinNativeOutline +import com.winlator.cmod.shared.theme.WinNativeSurface +import com.winlator.cmod.shared.ui.outlinedSwitchColors +import com.winlator.cmod.shared.ui.widget.chasingBorder + +private const val DrawerGradientLift = SessionDrawerStyle.GradientLift + +private val DrawerAccent = SessionDrawerStyle.Accent +private val DrawerActiveAccent = SessionDrawerStyle.ActiveAccent +private val DrawerFocusFill = SessionDrawerStyle.FocusFill +private val DrawerTextPrimary = SessionDrawerStyle.TextPrimary +private val DrawerTextSecondary = SessionDrawerStyle.TextSecondary +private val RetroSheetColor = SessionDrawerStyle.Background +private val TopRailSurfaceColor = SessionDrawerStyle.TopRailSurface +private val PaneSurfacePressed = SessionDrawerStyle.PaneSurfacePressed +private val PaneInnerResting = SessionDrawerStyle.PaneInnerResting +private val PaneInnerPressed = SessionDrawerStyle.PaneInnerPressed +private val TileExitResting = SessionDrawerStyle.TileExitResting +private val TileExitPressed = SessionDrawerStyle.TileExitPressed +private val RestingCardBorder = SessionDrawerStyle.RestingCardBorder +private val ActiveCardBorder = SessionDrawerStyle.ActiveCardBorder +private val GlassExitTint = SessionDrawerStyle.GlassExitTint +private val DividerColor = SessionDrawerStyle.Divider + +private val DrawerWidth = SessionDrawerStyle.Width +private val DrawerStartPadding = SessionDrawerStyle.StartPadding +private val DrawerVerticalPadding = SessionDrawerStyle.VerticalPadding + +enum class RetroPane { DISPLAY, SOUND, CONTROLS, HUD, SAVES, PERFORMANCE, MEMCARDS, NETWORK, SYSTEM } + +class RetroRenamePrompt( + val title: String, + val initial: String, + val onConfirm: (String?) -> Unit, +) + +class RetroConflictPrompt( + val message: String, + val options: List, + val onKeepLocal: () -> Unit, + val onPick: (Int) -> Unit, +) + +data class RetroTabSpec( + val pane: RetroPane?, + val icon: ImageVector, + val label: String, +) + +sealed class RetroMenuEntry { + class Action( + val label: String, + val icon: ImageVector, + val active: Boolean = false, + val danger: Boolean = false, + val subtitle: String? = null, + val onClick: () -> Unit, + ) : RetroMenuEntry() + + class Toggle( + val label: String, + val subtitle: String? = null, + val checked: Boolean, + val onChange: (Boolean) -> Unit, + ) : RetroMenuEntry() + + class Choice( + val label: String, + val values: List, + val selectedIndex: Int, + val visible: Boolean = true, + val onSelected: (Int) -> Unit, + ) : RetroMenuEntry() + + class Radio( + val label: String, + val selected: Boolean, + val onSelect: () -> Unit, + ) : RetroMenuEntry() + + class Slider( + val label: String, + val valueText: String, + val value: Float, + val min: Float, + val max: Float, + val step: Float, + val onChange: (Float) -> Unit, + ) : RetroMenuEntry() + + class Chips( + val label: String, + val items: List, + val states: List, + val onToggle: (Int) -> Unit, + ) : RetroMenuEntry() + + class ColorPick( + val label: String, + val color: Int?, + val onPick: (Int?) -> Unit, + ) : RetroMenuEntry() + + class SaveSlot( + val slot: Int, + val title: String, + val subtitle: String, + val filled: Boolean, + val onClick: () -> Unit, + val onRename: () -> Unit, + ) : RetroMenuEntry() + + class TextInput( + val label: String, + val value: String, + val placeholder: String = "", + val onOpen: () -> Unit, + ) : RetroMenuEntry() +} + +val RetroColorPalette: List = + listOf( + 0xFFFFFFFF, 0xFFB0B4BC, 0xFF6B7280, 0xFF2A2A30, 0xFF000000, + 0xFFE53935, 0xFFFF7043, 0xFFFFB300, 0xFFFFF176, 0xFF7CB342, + 0xFF2F9E44, 0xFF26A69A, 0xFF29B6F6, 0xFF2E63C9, 0xFF5E35B1, + 0xFF8E24AA, 0xFFD81B60, 0xFF8D6E63, + ).map { it.toInt() } + +class RetroMenuController { + var visible by mutableStateOf(false) + private set + var pane by mutableStateOf(null) + private set + var region by mutableIntStateOf(1) + var railIndex by mutableIntStateOf(0) + var contentIndex by mutableIntStateOf(0) + var chipIndex by mutableIntStateOf(0) + var bottomIndex by mutableIntStateOf(0) + var controllerActive by mutableStateOf(false) + var tabs by mutableStateOf>(emptyList()) + var entries by mutableStateOf>(emptyList()) + private set + var bottomEntries by mutableStateOf>(emptyList()) + private set + var entriesProvider: ((RetroPane?) -> List)? = null + var bottomProvider: (() -> List)? = null + var renamePrompt by mutableStateOf(null) + var conflictPrompt by mutableStateOf(null) + + val gridColumns: Int + get() = if (pane == null) 3 else 1 + + fun open() { + pane = null + railIndex = 0 + region = 1 + contentIndex = 0 + bottomIndex = 0 + controllerActive = false + rebuild() + visible = true + } + + fun close() { + visible = false + } + + fun showPane(target: RetroPane?) { + pane = target + rebuild() + region = 1 + contentIndex = 0 + railIndex = tabs.indexOfFirst { it.pane == target }.coerceAtLeast(0) + } + + fun rebuild() { + entries = entriesProvider?.invoke(pane) ?: emptyList() + bottomEntries = bottomProvider?.invoke() ?: emptyList() + if (contentIndex >= entries.size) contentIndex = (entries.size - 1).coerceAtLeast(0) + if (bottomIndex >= bottomEntries.size) bottomIndex = (bottomEntries.size - 1).coerceAtLeast(0) + } + + private fun activate(direction: Int) { + when (val entry = entries.getOrNull(contentIndex)) { + is RetroMenuEntry.Action -> if (direction == 0) entry.onClick() + is RetroMenuEntry.Toggle -> entry.onChange(!entry.checked) + is RetroMenuEntry.Choice -> { + val size = entry.values.size + if (size > 0) { + val step = if (direction < 0) -1 else 1 + entry.onSelected((entry.selectedIndex + step + size) % size) + } + } + is RetroMenuEntry.Radio -> if (direction == 0) entry.onSelect() + is RetroMenuEntry.Slider -> + if (direction != 0) { + entry.onChange((entry.value + direction * entry.step).coerceIn(entry.min, entry.max)) + } + is RetroMenuEntry.Chips -> + if (direction == 0) { + entry.onToggle(chipIndex.coerceIn(0, entry.items.size - 1)) + } else { + chipIndex = (chipIndex + direction + entry.items.size) % entry.items.size + } + is RetroMenuEntry.ColorPick -> { + val step = if (direction < 0) -1 else 1 + val palette = RetroColorPalette + val current = entry.color?.let { palette.indexOf(it) } ?: -1 + val span = palette.size + 1 + val next = ((current + 1 + step + span) % span) - 1 + entry.onPick(if (next < 0) null else palette[next]) + } + is RetroMenuEntry.SaveSlot -> if (direction == 0) entry.onClick() + is RetroMenuEntry.TextInput -> if (direction == 0) entry.onOpen() + else -> {} + } + } + + private fun moveContent(delta: Int) { + if (entries.isEmpty()) return + val next = contentIndex + delta + when { + next < 0 -> region = 0 + next >= entries.size && pane == null -> region = 2 + next in entries.indices -> contentIndex = next + } + } + + private var axisLatched = false + + fun handleAxis(x: Float, y: Float): Boolean { + if (!visible) return false + val dz = 0.5f + val dir = + when { + y < -dz -> KeyEvent.KEYCODE_DPAD_UP + y > dz -> KeyEvent.KEYCODE_DPAD_DOWN + x < -dz -> KeyEvent.KEYCODE_DPAD_LEFT + x > dz -> KeyEvent.KEYCODE_DPAD_RIGHT + else -> 0 + } + if (dir == 0) { + axisLatched = false + return true + } + if (axisLatched) return true + axisLatched = true + handleKey(dir, KeyEvent.ACTION_DOWN) + handleKey(dir, KeyEvent.ACTION_UP) + return true + } + + fun handleKey( + keyCode: Int, + action: Int, + ): Boolean { + if (!visible) return false + val navKeys = + setOf( + KeyEvent.KEYCODE_DPAD_UP, + KeyEvent.KEYCODE_DPAD_DOWN, + KeyEvent.KEYCODE_DPAD_LEFT, + KeyEvent.KEYCODE_DPAD_RIGHT, + KeyEvent.KEYCODE_DPAD_CENTER, + KeyEvent.KEYCODE_BUTTON_A, + KeyEvent.KEYCODE_BUTTON_B, + KeyEvent.KEYCODE_BACK, + KeyEvent.KEYCODE_BUTTON_MODE, + KeyEvent.KEYCODE_BUTTON_START, + ) + if (keyCode !in navKeys) return true + if (action == KeyEvent.ACTION_DOWN) { + controllerActive = true + when (keyCode) { + KeyEvent.KEYCODE_DPAD_UP -> + when (region) { + 1 -> moveContent(-gridColumns) + 2 -> region = 1 + } + KeyEvent.KEYCODE_DPAD_DOWN -> + when (region) { + 0 -> if (entries.isNotEmpty()) region = 1 + 1 -> moveContent(gridColumns) + } + KeyEvent.KEYCODE_DPAD_LEFT -> + when (region) { + 0 -> railIndex = (railIndex - 1 + tabs.size) % tabs.size + 1 -> if (gridColumns > 1) moveContent(-1) else activate(-1) + 2 -> if (bottomEntries.isNotEmpty()) { + bottomIndex = (bottomIndex - 1 + bottomEntries.size) % bottomEntries.size + } + } + KeyEvent.KEYCODE_DPAD_RIGHT -> + when (region) { + 0 -> railIndex = (railIndex + 1) % tabs.size + 1 -> if (gridColumns > 1) moveContent(1) else activate(1) + 2 -> if (bottomEntries.isNotEmpty()) { + bottomIndex = (bottomIndex + 1) % bottomEntries.size + } + } + KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_BUTTON_A -> + when (region) { + 0 -> tabs.getOrNull(railIndex)?.let { showPane(it.pane) } + 1 -> activate(0) + 2 -> bottomEntries.getOrNull(bottomIndex)?.onClick?.invoke() + } + } + } else if (action == KeyEvent.ACTION_UP) { + when (keyCode) { + KeyEvent.KEYCODE_BUTTON_B, KeyEvent.KEYCODE_BACK, + -> if (pane != null) showPane(null) else close() + } + } + return true + } +} + +@Composable +fun RetroDrawerMenu(controller: RetroMenuController) { + val density = LocalDensity.current + BoxWithConstraints(Modifier.fillMaxSize()) { + val portrait = maxHeight > maxWidth + val sheetHeight = + if (portrait) { + minOf(maxWidth, maxHeight - DrawerVerticalPadding * 2) + } else { + maxHeight - DrawerVerticalPadding * 2 + } + val paneScale = + (sheetHeight.value / SessionDrawerStyle.PaneScaleReferenceHeightDp) + .coerceIn(SessionDrawerStyle.PaneScaleMin, 1f) + if (controller.visible) { + Box( + Modifier + .fillMaxSize() + .clickable( + interactionSource = remember { MutableInteractionSource() }, + indication = null, + ) { controller.close() }, + ) + } + + val closedOffset = -(DrawerWidth + DrawerStartPadding + 8.dp) + val sheetOffset by animateDpAsState( + targetValue = if (controller.visible) 0.dp else closedOffset, + animationSpec = tween(durationMillis = 200, easing = LinearEasing), + label = "retroDrawerOffset", + ) + if (sheetOffset > closedOffset) { + Box( + Modifier + .padding(start = DrawerStartPadding, top = DrawerVerticalPadding, bottom = DrawerVerticalPadding) + .height(sheetHeight) + .width(DrawerWidth) + .offset { androidx.compose.ui.unit.IntOffset(with(density) { sheetOffset.roundToPx() }, 0) } + .clip(RoundedCornerShape(20.dp)) + .background(RetroSheetColor) + .clickable( + interactionSource = remember { MutableInteractionSource() }, + indication = null, + ) {}, + ) { + Column(Modifier.fillMaxSize()) { + RetroTopRail(controller, paneScale) + ThinDivider() + Box(Modifier.weight(1f).fillMaxWidth()) { + if (controller.pane == null) { + RetroActionGrid(controller, paneScale) + } else { + RetroPaneList(controller, paneScale) + } + } + if (controller.pane == null && controller.bottomEntries.isNotEmpty()) { + Column { + ThinDivider() + RetroBottomActions(controller, paneScale) + } + } + } + } + } + controller.renamePrompt?.let { prompt -> + RetroRenameDialog(prompt) { controller.renamePrompt = null } + } + controller.conflictPrompt?.let { prompt -> + RetroConflictDialog(prompt) + } + } +} + +private data class RailTileBounds( + val offsetX: Float, + val width: Float, + val height: Float, +) + +@Composable +private fun RetroTopRail( + controller: RetroMenuController, + paneScale: Float, +) { + val density = LocalDensity.current + val tileBounds = remember { mutableStateMapOf() } + val railScroll = rememberScrollState() + + val selectedIndex = + if (controller.controllerActive && controller.region == 0) { + controller.railIndex + } else { + controller.tabs.indexOfFirst { it.pane == controller.pane }.coerceAtLeast(0) + } + val selectedBounds = tileBounds[selectedIndex] + + val indicatorX = selectedBounds?.let { with(density) { it.offsetX.toDp() } } ?: 0.dp + val indicatorWidth = selectedBounds?.let { with(density) { it.width.toDp() } } ?: 0.dp + val indicatorTileHeight = selectedBounds?.let { with(density) { it.height.toDp() } } ?: 0.dp + val indicatorAlpha = if (selectedBounds != null) 1f else 0f + + Box( + modifier = + Modifier + .fillMaxWidth() + .background(TopRailSurfaceColor) + .padding( + start = (10f * paneScale).dp, + end = (10f * paneScale).dp, + top = (5f * paneScale).dp, + bottom = (2f * paneScale).dp, + ), + ) { + if (selectedBounds != null) { + Box( + modifier = + Modifier + .offset( + x = indicatorX - with(density) { railScroll.value.toDp() } + (6f * paneScale).dp, + y = indicatorTileHeight - (2f * paneScale).dp, + ) + .width((indicatorWidth - (12f * paneScale).dp).coerceAtLeast(0.dp)) + .height((2f * paneScale).dp) + .graphicsLayer { alpha = indicatorAlpha } + .clip(RoundedCornerShape(1.dp)) + .background(DrawerAccent), + ) + } + Row( + modifier = Modifier.horizontalScroll(railScroll), + horizontalArrangement = Arrangement.spacedBy((10f * paneScale).dp), + verticalAlignment = Alignment.CenterVertically, + ) { + controller.tabs.forEachIndexed { index, tab -> + RetroRailTile( + icon = tab.icon, + label = tab.label, + selected = + if (controller.controllerActive && controller.region == 0) { + controller.railIndex == index + } else { + controller.pane == tab.pane + }, + highlighted = controller.controllerActive && controller.region == 0 && controller.railIndex == index, + paneScale = paneScale, + onBoundsChanged = { tileBounds[index] = it }, + onClick = { + controller.railIndex = index + controller.showPane(tab.pane) + }, + ) + } + } + } +} + +@Composable +private fun RetroRailTile( + icon: ImageVector, + label: String, + selected: Boolean, + highlighted: Boolean, + paneScale: Float, + onBoundsChanged: (RailTileBounds) -> Unit, + onClick: () -> Unit, +) { + val interactionSource = remember { MutableInteractionSource() } + val pressed = interactionSource.collectIsPressedAsState().value + val scale by animateFloatAsState( + targetValue = if (pressed) 0.94f else 1f, + animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy, stiffness = Spring.StiffnessMedium), + label = "retroTileScale", + ) + val bgColor by animateColorAsState( + targetValue = + when { + highlighted -> DrawerFocusFill + pressed && !selected -> PaneSurfacePressed + else -> Color.Transparent + }, + animationSpec = tween(120), + label = "retroTileBg", + ) + val tint by animateColorAsState( + targetValue = if (selected) DrawerAccent else DrawerTextPrimary, + animationSpec = tween(120), + label = "retroTileTint", + ) + val cornerRadius = (12f * paneScale).dp + val shape = RoundedCornerShape(cornerRadius) + Column( + modifier = + Modifier + .defaultMinSize(minWidth = (60f * paneScale).dp) + .onGloballyPositioned { coords -> + val bounds = coords.boundsInParent() + onBoundsChanged(RailTileBounds(bounds.left, bounds.width, bounds.height)) + } + .graphicsLayer { + scaleX = scale + scaleY = scale + } + .clip(shape) + .background(bgColor) + .then( + if (highlighted) { + Modifier.chasingBorder(cornerRadius = cornerRadius, borderWidth = 1.5.dp, animationDurationMs = 8200) + } else { + Modifier + }, + ) + .clickable(interactionSource = interactionSource, indication = null, onClick = onClick) + .padding( + start = (10f * paneScale).dp, + end = (10f * paneScale).dp, + top = (10f * paneScale).dp, + bottom = (7f * paneScale).dp, + ), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center, + ) { + Icon(imageVector = icon, contentDescription = label, tint = tint, modifier = Modifier.size((22f * paneScale).dp)) + Spacer(Modifier.height((2f * paneScale).dp)) + Text( + text = label, + color = DrawerTextPrimary, + fontSize = (12f * paneScale).sp, + fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Medium, + letterSpacing = 0.2.sp, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } +} + +@Composable +private fun RetroActionGrid( + controller: RetroMenuController, + paneScale: Float, +) { + val actions = controller.entries + val spacing = (8f * paneScale).dp + Column( + modifier = + Modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(horizontal = (10f * paneScale).dp, vertical = (10f * paneScale).dp), + verticalArrangement = Arrangement.spacedBy(spacing), + ) { + actions.chunked(controller.gridColumns).forEachIndexed { rowIndex, row -> + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(spacing), + ) { + row.forEachIndexed { colIndex, entry -> + val flatIndex = rowIndex * controller.gridColumns + colIndex + if (entry is RetroMenuEntry.Action) { + RetroActionCard( + entry = entry, + highlighted = + controller.controllerActive && + controller.region == 1 && + controller.contentIndex == flatIndex, + paneScale = paneScale, + modifier = Modifier.weight(1f).aspectRatio(1f), + onClick = { + controller.contentIndex = flatIndex + entry.onClick() + }, + ) + } + } + repeat(controller.gridColumns - row.size) { + Spacer(Modifier.weight(1f)) + } + } + } + } +} + +@Composable +private fun RetroActionCard( + entry: RetroMenuEntry.Action, + highlighted: Boolean, + paneScale: Float, + modifier: Modifier = Modifier, + onClick: () -> Unit, +) { + val interactionSource = remember { MutableInteractionSource() } + val pressed = interactionSource.collectIsPressedAsState().value + val scale by animateFloatAsState( + targetValue = if (pressed) 0.96f else 1f, + animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy, stiffness = Spring.StiffnessMedium), + label = "retroCardScale", + ) + val bgColor by animateColorAsState( + targetValue = + when { + highlighted -> DrawerFocusFill + pressed -> PaneInnerPressed + else -> PaneInnerResting + }, + animationSpec = tween(120), + label = "retroCardBg", + ) + val borderColor by animateColorAsState( + targetValue = if (entry.active) ActiveCardBorder else RestingCardBorder, + animationSpec = tween(120), + label = "retroCardBorder", + ) + val tint = + when { + entry.danger -> GlassExitTint + entry.active -> DrawerActiveAccent + else -> DrawerTextPrimary + } + val cornerRadius = (12f * paneScale).dp + val shape = RoundedCornerShape(cornerRadius) + val topColor = + Color( + red = (bgColor.red + (1f - bgColor.red) * DrawerGradientLift).coerceIn(0f, 1f), + green = (bgColor.green + (1f - bgColor.green) * DrawerGradientLift).coerceIn(0f, 1f), + blue = (bgColor.blue + (1f - bgColor.blue) * DrawerGradientLift).coerceIn(0f, 1f), + alpha = bgColor.alpha, + ) + val shell = + modifier + .graphicsLayer { + scaleX = scale + scaleY = scale + } + .clip(shape) + .background(Brush.verticalGradient(listOf(topColor, bgColor))) + .border(1.dp, borderColor, shape) + .then( + if (highlighted) { + Modifier.chasingBorder(cornerRadius = cornerRadius, borderWidth = 1.5.dp, animationDurationMs = 8200) + } else { + Modifier + }, + ) + .clickable(interactionSource = interactionSource, indication = null, onClick = onClick) + if (entry.subtitle != null) { + Row( + modifier = + shell + .defaultMinSize(minHeight = (72f * paneScale).dp) + .padding(horizontal = (12f * paneScale).dp, vertical = (10f * paneScale).dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon( + imageVector = entry.icon, + contentDescription = entry.label, + tint = tint, + modifier = Modifier.size((22f * paneScale).dp), + ) + Spacer(Modifier.width((10f * paneScale).dp)) + Column(Modifier.weight(1f, fill = true)) { + Text( + text = entry.label, + color = DrawerTextPrimary, + fontSize = (13f * paneScale).sp, + fontWeight = if (entry.active) FontWeight.SemiBold else FontWeight.Medium, + maxLines = 3, + softWrap = true, + overflow = TextOverflow.Clip, + lineHeight = (16f * paneScale).sp, + ) + Spacer(Modifier.height(2.dp)) + Text( + text = entry.subtitle, + color = DrawerTextSecondary, + fontSize = (11f * paneScale).sp, + maxLines = 3, + softWrap = true, + overflow = TextOverflow.Clip, + lineHeight = (14f * paneScale).sp, + ) + } + } + } else { + Column( + modifier = shell, + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center, + ) { + Icon( + imageVector = entry.icon, + contentDescription = entry.label, + tint = tint, + modifier = Modifier.size((24f * paneScale).dp), + ) + Spacer(Modifier.height((4f * paneScale).dp)) + Text( + text = entry.label, + color = DrawerTextPrimary, + fontSize = (12f * paneScale).sp, + fontWeight = if (entry.active) FontWeight.SemiBold else FontWeight.Medium, + letterSpacing = 0.2.sp, + textAlign = TextAlign.Center, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } +} + +@Composable +private fun RetroPaneList( + controller: RetroMenuController, + paneScale: Float, +) { + val columns = controller.gridColumns.coerceAtLeast(1) + Column( + modifier = + Modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(horizontal = (10f * paneScale).dp, vertical = (10f * paneScale).dp), + verticalArrangement = Arrangement.spacedBy((8f * paneScale).dp), + ) { + controller.entries.chunked(columns).forEachIndexed { rowIndex, rowEntries -> + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy((8f * paneScale).dp), + ) { + rowEntries.forEachIndexed { colIndex, entry -> + val index = rowIndex * columns + colIndex + val highlighted = + controller.controllerActive && + controller.region == 1 && + controller.contentIndex == index + Box(Modifier.weight(1f)) { + when (entry) { + is RetroMenuEntry.Toggle -> + RetroBooleanRow( + entry = entry, + highlighted = highlighted, + paneScale = paneScale, + onClick = { + controller.contentIndex = index + entry.onChange(!entry.checked) + }, + ) + is RetroMenuEntry.Choice -> + if (entry.visible) { + RetroChoiceRow( + entry = entry, + highlighted = highlighted, + paneScale = paneScale, + onFocus = { controller.contentIndex = index }, + ) + } + is RetroMenuEntry.Radio -> + RetroRadioRow( + entry = entry, + highlighted = highlighted, + paneScale = paneScale, + onClick = { + controller.contentIndex = index + entry.onSelect() + }, + ) + is RetroMenuEntry.Action -> + RetroActionCard( + entry = entry, + highlighted = highlighted, + paneScale = paneScale, + modifier = + Modifier + .fillMaxWidth() + .defaultMinSize( + minHeight = + if (entry.subtitle != null) { + (68f * paneScale).dp + } else { + (56f * paneScale).dp + }, + ), + onClick = { + controller.contentIndex = index + entry.onClick() + }, + ) + is RetroMenuEntry.Slider -> + RetroSliderRow( + entry = entry, + highlighted = highlighted, + paneScale = paneScale, + onClick = { controller.contentIndex = index }, + ) + is RetroMenuEntry.Chips -> + RetroChipsGroup( + entry = entry, + highlighted = highlighted, + chipFocus = if (highlighted) controller.chipIndex else -1, + paneScale = paneScale, + onChipClick = { chip -> + controller.contentIndex = index + controller.chipIndex = chip + entry.onToggle(chip) + }, + ) + is RetroMenuEntry.ColorPick -> + RetroColorRow( + entry = entry, + highlighted = highlighted, + paneScale = paneScale, + onFocus = { controller.contentIndex = index }, + ) + is RetroMenuEntry.SaveSlot -> + RetroSaveSlotRow( + entry = entry, + highlighted = highlighted, + paneScale = paneScale, + onClick = { + controller.contentIndex = index + entry.onClick() + }, + ) + is RetroMenuEntry.TextInput -> + RetroTextInputRow( + entry = entry, + highlighted = highlighted, + paneScale = paneScale, + onClick = { + controller.contentIndex = index + entry.onOpen() + }, + ) + } + } + } + repeat(columns - rowEntries.size) { + Spacer(Modifier.weight(1f)) + } + } + } + } +} + +@Composable +private fun RetroRowShell( + highlighted: Boolean, + activeBorder: Boolean, + paneScale: Float, + onClick: () -> Unit, + content: @Composable androidx.compose.foundation.layout.RowScope.() -> Unit, +) { + val interactionSource = remember { MutableInteractionSource() } + val pressed = interactionSource.collectIsPressedAsState().value + val bgColor by animateColorAsState( + targetValue = + when { + highlighted -> DrawerFocusFill + pressed -> PaneInnerPressed + else -> PaneInnerResting + }, + animationSpec = tween(140), + label = "retroRowBg", + ) + val borderColor by animateColorAsState( + targetValue = if (activeBorder) ActiveCardBorder else RestingCardBorder, + animationSpec = tween(140), + label = "retroRowBorder", + ) + val cornerRadius = (14f * paneScale).dp + val shape = RoundedCornerShape(cornerRadius) + Row( + modifier = + Modifier + .fillMaxWidth() + .clip(shape) + .background(bgColor) + .border(1.dp, borderColor, shape) + .then( + if (highlighted) { + Modifier.chasingBorder(cornerRadius = cornerRadius, borderWidth = 1.5.dp, animationDurationMs = 8200) + } else { + Modifier + }, + ) + .clickable(interactionSource = interactionSource, indication = null, onClick = onClick) + .padding(horizontal = (12f * paneScale).dp, vertical = (8f * paneScale).dp), + verticalAlignment = Alignment.CenterVertically, + ) { + content() + } +} + +@Composable +private fun RetroBooleanRow( + entry: RetroMenuEntry.Toggle, + highlighted: Boolean, + paneScale: Float, + onClick: () -> Unit, +) { + RetroRowShell(highlighted = highlighted, activeBorder = entry.checked, paneScale = paneScale, onClick = onClick) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = entry.label, + color = DrawerTextPrimary, + fontSize = (14f * paneScale).sp, + fontWeight = FontWeight.Medium, + ) + Spacer(Modifier.height(2.dp)) + Text( + text = entry.subtitle ?: if (entry.checked) stringResource(R.string.retro_scr_enabled) else stringResource(R.string.retro_scr_disabled), + color = DrawerTextSecondary, + fontSize = (12f * paneScale).sp, + ) + } + Switch( + checked = entry.checked, + onCheckedChange = entry.onChange, + colors = outlinedSwitchColors(DrawerAccent, DrawerTextSecondary), + ) + } +} + +@Composable +private fun RetroTextInputRow( + entry: RetroMenuEntry.TextInput, + highlighted: Boolean, + paneScale: Float, + onClick: () -> Unit, +) { + RetroRowShell(highlighted = highlighted, activeBorder = entry.value.isNotBlank(), paneScale = paneScale, onClick = onClick) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = entry.label, + color = DrawerTextPrimary, + fontSize = (14f * paneScale).sp, + fontWeight = FontWeight.Medium, + ) + Spacer(Modifier.height(2.dp)) + Text( + text = entry.value.ifBlank { entry.placeholder }, + color = if (entry.value.isBlank()) DrawerTextSecondary else DrawerActiveAccent, + fontSize = (12f * paneScale).sp, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } +} + +@Composable +private fun RetroChoiceRow( + entry: RetroMenuEntry.Choice, + highlighted: Boolean, + paneScale: Float, + onFocus: () -> Unit, +) { + var expanded by remember { mutableStateOf(false) } + Box { + RetroRowShell( + highlighted = highlighted, + activeBorder = false, + paneScale = paneScale, + onClick = { + onFocus() + expanded = true + }, + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = entry.label, + color = DrawerTextPrimary, + fontSize = (14f * paneScale).sp, + fontWeight = FontWeight.Medium, + ) + Spacer(Modifier.height(2.dp)) + Text( + text = entry.values.getOrNull(entry.selectedIndex) ?: "", + color = DrawerActiveAccent, + fontSize = (12f * paneScale).sp, + fontWeight = FontWeight.SemiBold, + ) + } + Text( + text = "▾", + color = DrawerTextSecondary, + fontSize = (16f * paneScale).sp, + ) + } + DropdownMenu( + expanded = expanded, + onDismissRequest = { expanded = false }, + containerColor = WinNativeSurface, + ) { + entry.values.forEachIndexed { index, value -> + DropdownMenuItem( + text = { + Text( + text = value, + color = if (index == entry.selectedIndex) DrawerActiveAccent else DrawerTextPrimary, + fontSize = (13f * paneScale).sp, + fontWeight = if (index == entry.selectedIndex) FontWeight.SemiBold else FontWeight.Medium, + ) + }, + onClick = { + expanded = false + entry.onSelected(index) + }, + ) + } + } + } +} + +@Composable +private fun RetroRadioRow( + entry: RetroMenuEntry.Radio, + highlighted: Boolean, + paneScale: Float, + onClick: () -> Unit, +) { + RetroRowShell(highlighted = highlighted, activeBorder = entry.selected, paneScale = paneScale, onClick = onClick) { + Text( + text = entry.label, + color = if (entry.selected) DrawerActiveAccent else DrawerTextPrimary, + fontSize = (14f * paneScale).sp, + fontWeight = if (entry.selected) FontWeight.SemiBold else FontWeight.Medium, + modifier = Modifier.weight(1f), + ) + if (entry.selected) { + Text( + text = "✓", + color = DrawerActiveAccent, + fontSize = (14f * paneScale).sp, + fontWeight = FontWeight.SemiBold, + ) + } + } +} + +@Composable +private fun RetroChipsGroup( + entry: RetroMenuEntry.Chips, + highlighted: Boolean, + chipFocus: Int, + paneScale: Float, + onChipClick: (Int) -> Unit, +) { + Column(verticalArrangement = Arrangement.spacedBy((8f * paneScale).dp)) { + Text( + text = entry.label, + color = DrawerTextSecondary, + fontSize = (11f * paneScale).sp, + fontWeight = FontWeight.SemiBold, + letterSpacing = 0.8.sp, + ) + FlowRow( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy((8f * paneScale).dp), + verticalArrangement = Arrangement.spacedBy((8f * paneScale).dp), + ) { + entry.items.forEachIndexed { index, item -> + RetroHudChip( + label = item, + checked = entry.states.getOrElse(index) { false }, + focused = highlighted && chipFocus == index, + paneScale = paneScale, + onClick = { onChipClick(index) }, + ) + } + } + } +} + +@Composable +private fun RetroHudChip( + label: String, + checked: Boolean, + focused: Boolean, + paneScale: Float, + onClick: () -> Unit, +) { + val interactionSource = remember { MutableInteractionSource() } + val pressed = interactionSource.collectIsPressedAsState().value + val bgColor by animateColorAsState( + targetValue = + when { + focused -> DrawerFocusFill + pressed -> PaneInnerPressed + else -> PaneInnerResting + }, + animationSpec = tween(140), + label = "retroChipBg", + ) + val borderColor by animateColorAsState( + targetValue = if (checked) DrawerAccent else RestingCardBorder, + animationSpec = tween(140), + label = "retroChipBorder", + ) + val cornerRadius = (12f * paneScale).dp + val shape = RoundedCornerShape(cornerRadius) + Row( + modifier = + Modifier + .clip(shape) + .background(bgColor) + .border(1.dp, borderColor, shape) + .then( + if (focused) { + Modifier.chasingBorder(cornerRadius = cornerRadius, borderWidth = 1.5.dp, animationDurationMs = 8200) + } else { + Modifier + }, + ) + .clickable(interactionSource = interactionSource, indication = null, onClick = onClick) + .padding(horizontal = (10f * paneScale).dp, vertical = (9f * paneScale).dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Box( + modifier = + Modifier + .size((10f * paneScale).dp) + .clip(androidx.compose.foundation.shape.CircleShape) + .background(if (checked) DrawerAccent else Color(0x14FFFFFF)), + ) + Spacer(Modifier.width((8f * paneScale).dp)) + Text( + text = label, + color = DrawerTextPrimary, + fontSize = (13f * paneScale).sp, + fontWeight = if (checked) FontWeight.SemiBold else FontWeight.Medium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } +} + +@Composable +private fun RetroSaveSlotRow( + entry: RetroMenuEntry.SaveSlot, + highlighted: Boolean, + paneScale: Float, + onClick: () -> Unit, +) { + RetroRowShell( + highlighted = highlighted, + activeBorder = entry.filled, + paneScale = paneScale, + onClick = onClick, + ) { + Box( + modifier = + Modifier + .size((28f * paneScale).dp) + .clip(androidx.compose.foundation.shape.CircleShape) + .background(if (entry.filled) DrawerAccent.copy(alpha = 0.24f) else Color(0x14FFFFFF)), + ) { + Text( + text = entry.slot.toString(), + color = if (entry.filled) DrawerActiveAccent else DrawerTextSecondary, + fontSize = (12f * paneScale).sp, + fontWeight = FontWeight.SemiBold, + modifier = Modifier.align(Alignment.Center), + ) + } + Spacer(Modifier.width((10f * paneScale).dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = entry.title, + color = DrawerTextPrimary, + fontSize = (13f * paneScale).sp, + fontWeight = FontWeight.Medium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Spacer(Modifier.height(2.dp)) + Text( + text = entry.subtitle, + color = if (entry.filled) DrawerActiveAccent else DrawerTextSecondary, + fontSize = (11f * paneScale).sp, + ) + } + if (entry.filled) { + Icon( + imageVector = Icons.Outlined.Edit, + contentDescription = stringResource(R.string.retro_scr_rename), + tint = DrawerTextSecondary, + modifier = + Modifier + .size((18f * paneScale).dp) + .clickable( + interactionSource = remember { MutableInteractionSource() }, + indication = null, + ) { entry.onRename() }, + ) + } + } +} + +@Composable +internal fun RetroRenameDialog( + prompt: RetroRenamePrompt, + onDismiss: () -> Unit, +) { + var text by remember(prompt) { mutableStateOf(prompt.initial) } + Box( + modifier = + Modifier + .fillMaxSize() + .background(Color(0x99000000)) + .clickable( + interactionSource = remember { MutableInteractionSource() }, + indication = null, + ) { onDismiss() }, + contentAlignment = Alignment.Center, + ) { + Column( + modifier = + Modifier + .width(320.dp) + .clip(RoundedCornerShape(16.dp)) + .background(WinNativeSurface) + .border(1.dp, WinNativeOutline, RoundedCornerShape(16.dp)) + .clickable( + interactionSource = remember { MutableInteractionSource() }, + indication = null, + ) {} + .padding(16.dp), + ) { + Text( + text = prompt.title, + color = DrawerTextPrimary, + fontSize = 15.sp, + fontWeight = FontWeight.SemiBold, + ) + Spacer(Modifier.height(10.dp)) + OutlinedTextField( + value = text, + onValueChange = { if (it.length <= 48) text = it }, + singleLine = true, + textStyle = androidx.compose.ui.text.TextStyle(color = DrawerTextPrimary, fontSize = 14.sp), + modifier = Modifier.fillMaxWidth(), + ) + Spacer(Modifier.height(12.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Spacer(Modifier.weight(1f)) + Text( + text = stringResource(R.string.retro_scr_cancel), + color = DrawerTextSecondary, + fontSize = 13.sp, + fontWeight = FontWeight.SemiBold, + modifier = + Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { onDismiss() } + .padding(horizontal = 12.dp, vertical = 8.dp), + ) + Text( + text = stringResource(R.string.retro_scr_save), + color = DrawerActiveAccent, + fontSize = 13.sp, + fontWeight = FontWeight.SemiBold, + modifier = + Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { + prompt.onConfirm(text.trim().ifEmpty { null }) + onDismiss() + } + .padding(horizontal = 12.dp, vertical = 8.dp), + ) + } + } + } +} + +@Composable +internal fun RetroConflictDialog(prompt: RetroConflictPrompt) { + Box( + modifier = + Modifier + .fillMaxSize() + .background(Color(0xCC000000)) + .clickable( + interactionSource = remember { MutableInteractionSource() }, + indication = null, + ) {}, + contentAlignment = Alignment.Center, + ) { + Column( + modifier = + Modifier + .width(340.dp) + .clip(RoundedCornerShape(16.dp)) + .background(WinNativeSurface) + .border(1.dp, WinNativeOutline, RoundedCornerShape(16.dp)) + .padding(16.dp), + ) { + Text( + text = stringResource(R.string.retro_scr_cloud_save_conflict), + color = DrawerTextPrimary, + fontSize = 15.sp, + fontWeight = FontWeight.SemiBold, + ) + Spacer(Modifier.height(6.dp)) + Text( + text = prompt.message, + color = DrawerTextSecondary, + fontSize = 12.sp, + ) + Spacer(Modifier.height(12.dp)) + Column( + modifier = Modifier.verticalScroll(rememberScrollState()).weight(1f, fill = false), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + prompt.options.forEachIndexed { index, label -> + Row( + modifier = + Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(10.dp)) + .background(PaneInnerResting) + .border(1.dp, RestingCardBorder, RoundedCornerShape(10.dp)) + .clickable { prompt.onPick(index) } + .padding(horizontal = 12.dp, vertical = 10.dp), + ) { + Text( + text = label, + color = DrawerTextPrimary, + fontSize = 13.sp, + fontWeight = FontWeight.Medium, + ) + } + } + } + Spacer(Modifier.height(12.dp)) + Row( + modifier = + Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(10.dp)) + .background(DrawerFocusFill) + .border(1.dp, DrawerAccent, RoundedCornerShape(10.dp)) + .clickable { prompt.onKeepLocal() } + .padding(horizontal = 12.dp, vertical = 10.dp), + horizontalArrangement = Arrangement.Center, + ) { + Text( + text = stringResource(R.string.retro_scr_keep_local_save), + color = DrawerActiveAccent, + fontSize = 13.sp, + fontWeight = FontWeight.SemiBold, + ) + } + } + } +} + +@Composable +private fun RetroColorRow( + entry: RetroMenuEntry.ColorPick, + highlighted: Boolean, + paneScale: Float, + onFocus: () -> Unit, +) { + var expanded by remember { mutableStateOf(false) } + Column { + RetroRowShell( + highlighted = highlighted, + activeBorder = entry.color != null, + paneScale = paneScale, + onClick = { + onFocus() + expanded = !expanded + }, + ) { + Text( + text = entry.label, + color = DrawerTextPrimary, + fontSize = (14f * paneScale).sp, + fontWeight = FontWeight.Medium, + modifier = Modifier.weight(1f), + ) + Box( + modifier = + Modifier + .size((20f * paneScale).dp) + .clip(androidx.compose.foundation.shape.CircleShape) + .background(entry.color?.let { Color(it) } ?: Color(0x14FFFFFF)) + .border( + 1.dp, + if (entry.color != null) DrawerAccent else RestingCardBorder, + androidx.compose.foundation.shape.CircleShape, + ), + ) { + if (entry.color == null) { + Text( + text = stringResource(R.string.retro_scr_auto_color_abbrev), + color = DrawerTextSecondary, + fontSize = (10f * paneScale).sp, + fontWeight = FontWeight.SemiBold, + modifier = Modifier.align(Alignment.Center), + ) + } + } + Spacer(Modifier.width((8f * paneScale).dp)) + Text( + text = if (expanded) "▴" else "▾", + color = DrawerTextSecondary, + fontSize = (16f * paneScale).sp, + ) + } + AnimatedVisibility(visible = expanded) { + FlowRow( + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = (6f * paneScale).dp, vertical = (8f * paneScale).dp), + horizontalArrangement = Arrangement.spacedBy((7f * paneScale).dp), + verticalArrangement = Arrangement.spacedBy((7f * paneScale).dp), + ) { + RetroColorSwatch( + color = null, + selected = entry.color == null, + paneScale = paneScale, + ) { + entry.onPick(null) + } + RetroColorPalette.forEach { swatch -> + RetroColorSwatch( + color = swatch, + selected = entry.color == swatch, + paneScale = paneScale, + ) { + entry.onPick(swatch) + } + } + } + } + } +} + +@Composable +private fun RetroColorSwatch( + color: Int?, + selected: Boolean, + paneScale: Float, + onClick: () -> Unit, +) { + val shape = androidx.compose.foundation.shape.CircleShape + Box( + modifier = + Modifier + .size((26f * paneScale).dp) + .clip(shape) + .background(color?.let { Color(it) } ?: Color(0x14FFFFFF)) + .border( + if (selected) 2.dp else 1.dp, + if (selected) DrawerActiveAccent else RestingCardBorder, + shape, + ) + .clickable( + interactionSource = remember { MutableInteractionSource() }, + indication = null, + onClick = onClick, + ), + ) { + if (color == null) { + Text( + text = stringResource(R.string.retro_scr_auto_color_abbrev), + color = DrawerTextSecondary, + fontSize = (11f * paneScale).sp, + fontWeight = FontWeight.SemiBold, + modifier = Modifier.align(Alignment.Center), + ) + } + } +} + +@Composable +private fun RetroSliderRow( + entry: RetroMenuEntry.Slider, + highlighted: Boolean, + paneScale: Float, + onClick: () -> Unit, +) { + RetroRowShell(highlighted = highlighted, activeBorder = false, paneScale = paneScale, onClick = onClick) { + Column(modifier = Modifier.weight(1f)) { + Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Text( + text = entry.label, + color = DrawerTextPrimary, + fontSize = (14f * paneScale).sp, + fontWeight = FontWeight.Medium, + modifier = Modifier.weight(1f), + ) + Text( + text = entry.valueText, + color = DrawerActiveAccent, + fontSize = (12f * paneScale).sp, + fontWeight = FontWeight.SemiBold, + ) + } + val stepCount = (((entry.max - entry.min) / entry.step).toInt() - 1).coerceAtLeast(0) + Slider( + value = entry.value, + onValueChange = { raw -> + val snapped = + (kotlin.math.round((raw - entry.min) / entry.step) * entry.step + entry.min) + .coerceIn(entry.min, entry.max) + if (snapped != entry.value) entry.onChange(snapped) + }, + valueRange = entry.min..entry.max, + steps = stepCount, + colors = + SliderDefaults.colors( + thumbColor = DrawerAccent, + activeTrackColor = DrawerAccent, + inactiveTrackColor = WinNativeOutline.copy(alpha = 0.5f), + activeTickColor = Color.Transparent, + inactiveTickColor = Color.Transparent, + ), + modifier = Modifier.fillMaxWidth().height((26f * paneScale).dp), + ) + } + } +} + +@Composable +private fun RetroBottomActions( + controller: RetroMenuController, + paneScale: Float, +) { + Row( + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = (10f * paneScale).dp, vertical = (8f * paneScale).dp), + horizontalArrangement = Arrangement.spacedBy((8f * paneScale).dp), + verticalAlignment = Alignment.CenterVertically, + ) { + controller.bottomEntries.forEachIndexed { index, entry -> + RetroBottomActionButton( + entry = entry, + highlighted = + controller.controllerActive && + controller.region == 2 && + controller.bottomIndex == index, + paneScale = paneScale, + modifier = Modifier.weight(1f), + onClick = { + controller.bottomIndex = index + entry.onClick() + }, + ) + } + } +} + +@Composable +private fun RetroBottomActionButton( + entry: RetroMenuEntry.Action, + highlighted: Boolean, + paneScale: Float, + modifier: Modifier = Modifier, + onClick: () -> Unit, +) { + val interactionSource = remember { MutableInteractionSource() } + val pressed = interactionSource.collectIsPressedAsState().value + val bgColor by animateColorAsState( + targetValue = + when { + highlighted -> DrawerFocusFill + entry.danger && pressed -> TileExitPressed + entry.danger -> TileExitResting + pressed -> PaneSurfacePressed + else -> PaneInnerResting + }, + animationSpec = tween(120), + label = "retroBottomBg", + ) + val borderColor = + when { + entry.danger -> GlassExitTint.copy(alpha = 0.34f) + entry.active -> ActiveCardBorder + else -> RestingCardBorder + } + val tint = + when { + entry.danger -> GlassExitTint + entry.active -> DrawerActiveAccent + else -> DrawerTextPrimary + } + val cornerRadius = (14f * paneScale).dp + val shape = RoundedCornerShape(cornerRadius) + Row( + modifier = + modifier + .clip(shape) + .background(bgColor) + .border(1.dp, borderColor, shape) + .then( + if (highlighted) { + Modifier.chasingBorder(cornerRadius = cornerRadius, borderWidth = 1.5.dp, animationDurationMs = 8200) + } else { + Modifier + }, + ) + .clickable(interactionSource = interactionSource, indication = null, onClick = onClick) + .padding(horizontal = (12f * paneScale).dp, vertical = (10f * paneScale).dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.Center, + ) { + Icon( + imageVector = entry.icon, + contentDescription = entry.label, + tint = tint, + modifier = Modifier.size((18f * paneScale).dp), + ) + Spacer(Modifier.width((8f * paneScale).dp)) + Text( + text = entry.label, + color = tint, + fontSize = (13f * paneScale).sp, + fontWeight = FontWeight.SemiBold, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } +} + +@Composable +private fun ThinDivider() { + Box( + modifier = + Modifier + .fillMaxWidth() + .height(1.dp) + .background(DividerColor), + ) +} + +object RetroDrawerTabs { + fun build( + context: android.content.Context, + includePerformance: Boolean = false, + includeNetplay: Boolean = false, + includeSystem: Boolean = false, + ): List { + val tabs = mutableListOf() + tabs += RetroTabSpec(null, Icons.Outlined.Apps, context.getString(R.string.retro_tab_menu)) + tabs += RetroTabSpec(RetroPane.DISPLAY, Icons.Outlined.Monitor, context.getString(R.string.retro_tab_display)) + if (includePerformance) { + tabs += RetroTabSpec(RetroPane.PERFORMANCE, Icons.Outlined.Bolt, context.getString(R.string.retro_ps2_tab_performance)) + } + tabs += RetroTabSpec(RetroPane.HUD, Icons.Outlined.Speed, context.getString(R.string.retro_tab_hud)) + tabs += RetroTabSpec(RetroPane.SOUND, Icons.AutoMirrored.Outlined.VolumeUp, context.getString(R.string.retro_tab_sound)) + tabs += RetroTabSpec(RetroPane.CONTROLS, Icons.Outlined.SportsEsports, context.getString(R.string.retro_tab_controls)) + if (includeSystem) { + tabs += RetroTabSpec(RetroPane.SYSTEM, Icons.Outlined.Tune, context.getString(R.string.retro_tab_system)) + } + if (includeNetplay) { + tabs += RetroTabSpec(RetroPane.NETWORK, Icons.Outlined.Wifi, context.getString(R.string.retro_tab_netplay)) + } + return tabs + } +} + +object RetroDrawerIcons { + val EditLayout = Icons.Outlined.Tune + val Resume = Icons.Outlined.PlayArrow + val Pause = Icons.Outlined.Pause + val Save = Icons.Outlined.Save + val Load = Icons.Outlined.Download + val Reset = Icons.Outlined.RestartAlt + val FastForward = Icons.Outlined.FastForward + val Disc = Icons.Outlined.Album + val Hud = Icons.Outlined.Speed + val Achievements = Icons.Outlined.EmojiEvents + val Cheats = Icons.Outlined.Bolt + val Add = Icons.Outlined.Add + val Play = Icons.Outlined.PlayArrow + val Group = Icons.Outlined.Group + val Link = Icons.Outlined.Link + val Search = Icons.Outlined.Search + val Exit = Icons.AutoMirrored.Outlined.ExitToApp +} diff --git a/app/src/main/feature/retro/RetroGameLink.kt b/app/src/main/feature/retro/RetroGameLink.kt new file mode 100644 index 000000000..d32074f12 --- /dev/null +++ b/app/src/main/feature/retro/RetroGameLink.kt @@ -0,0 +1,142 @@ +package com.winlator.cmod.feature.retro + +import com.swordfish.libretrodroid.GLRetroView +import com.swordfish.libretrodroid.Variable + +object RetroGameLink { + const val DEFAULT_PORT = 56400 + + const val MODE_KEY = "gambatte_gb_link_mode" + const val PORT_KEY = "gambatte_gb_link_network_port" + private const val IP_KEY_PREFIX = "gambatte_gb_link_network_server_ip_" + + const val MODE_OFF = "Not Connected" + const val MODE_SERVER = "Network Server" + const val MODE_CLIENT = "Network Client" + + fun isSupported(systemId: String?): Boolean = + systemId == RetroSystems.GAMEBOY.id || + systemId == RetroSystems.GAMEBOY_COLOR.id || + systemId == RetroSystems.GBA.id + + const val GPSP_SERIAL_KEY = "gpsp_serial" + const val GPSP_SERIAL_RFU = "rfu" + const val GBA_NETPACKET_PORT = 55437 + + fun clampPort(port: Int): Int = + when { + port in 56400..56420 -> port + else -> DEFAULT_PORT + } + + fun ipv4ToDigits(ip: String): List { + val parts = + ip.trim() + .split('.') + .mapNotNull { it.toIntOrNull()?.coerceIn(0, 255) } + if (parts.size != 4) return List(12) { "0" } + return parts.flatMap { octet -> + val s = "%03d".format(octet) + listOf(s[0].toString(), s[1].toString(), s[2].toString()) + } + } + + fun digitsToIpv4(digits: List): String { + if (digits.size < 12) return "0.0.0.0" + fun octet(a: Int) = + ((digits.getOrNull(a)?.toIntOrNull() ?: 0) * 100 + + (digits.getOrNull(a + 1)?.toIntOrNull() ?: 0) * 10 + + (digits.getOrNull(a + 2)?.toIntOrNull() ?: 0)) + .coerceIn(0, 255) + return "${octet(0)}.${octet(3)}.${octet(6)}.${octet(9)}" + } + + fun buildHostVariables(port: Int): List { + val p = clampPort(port) + return listOf( + Variable(MODE_KEY, MODE_SERVER), + Variable(PORT_KEY, p.toString()), + ) + } + + fun buildClientVariables( + hostIp: String, + port: Int, + ): List { + val p = clampPort(port) + val digits = ipv4ToDigits(hostIp) + val vars = mutableListOf( + Variable(MODE_KEY, MODE_CLIENT), + Variable(PORT_KEY, p.toString()), + ) + digits.forEachIndexed { i, d -> + vars += Variable("$IP_KEY_PREFIX${i + 1}", d) + } + return vars + } + + fun buildDisconnectVariables(): List = + listOf(Variable(MODE_KEY, MODE_OFF)) + + fun applyToCore( + retroView: GLRetroView, + variables: List, + ) { + if (variables.isEmpty()) return + runCatching { + retroView.updateVariables(*variables.toTypedArray()) + } + } + + fun startHost( + retroView: GLRetroView?, + port: Int, + ) { + val vars = buildHostVariables(port) + if (retroView != null) applyToCore(retroView, vars) + } + + fun startClient( + retroView: GLRetroView?, + hostIp: String, + port: Int, + ) { + val vars = buildClientVariables(hostIp, port) + if (retroView != null) applyToCore(retroView, vars) + } + + fun stop(retroView: GLRetroView?) { + runCatching { retroView?.netpacketStop() } + if (retroView != null) { + runCatching { applyToCore(retroView, buildDisconnectVariables()) } + runCatching { + retroView.updateVariables(Variable(GPSP_SERIAL_KEY, "disabled")) + } + } + } + + fun startGbaHost( + retroView: GLRetroView, + port: Int = GBA_NETPACKET_PORT, + ): Boolean { + applyToCore( + retroView, + listOf(Variable(GPSP_SERIAL_KEY, GPSP_SERIAL_RFU)), + ) + if (!retroView.netpacketHasCore()) return false + return retroView.netpacketStartHost(port) + } + + fun startGbaClient( + retroView: GLRetroView, + hostIp: String, + port: Int = GBA_NETPACKET_PORT, + ): Boolean { + applyToCore( + retroView, + listOf(Variable(GPSP_SERIAL_KEY, GPSP_SERIAL_RFU)), + ) + if (!retroView.netpacketHasCore()) return false + return retroView.netpacketStartClient(hostIp, port) + } +} diff --git a/app/src/main/feature/retro/RetroGameSettings.kt b/app/src/main/feature/retro/RetroGameSettings.kt new file mode 100644 index 000000000..fb0990817 --- /dev/null +++ b/app/src/main/feature/retro/RetroGameSettings.kt @@ -0,0 +1,1979 @@ +package com.winlator.cmod.feature.retro + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.outlined.VolumeUp +import androidx.compose.material.icons.outlined.Edit +import androidx.compose.material.icons.outlined.KeyboardArrowDown +import androidx.compose.material.icons.outlined.Memory +import androidx.compose.material.icons.outlined.Bolt +import androidx.compose.material.icons.outlined.Code +import androidx.compose.material.icons.outlined.Monitor +import androidx.compose.material.icons.outlined.Public +import androidx.compose.material.icons.outlined.Speed +import androidx.compose.material.icons.outlined.SportsEsports +import androidx.compose.material.icons.outlined.Tune +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.Icon +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.compose.ui.window.PopupProperties +import com.winlator.cmod.R +import com.winlator.cmod.shared.theme.GameSettingsStyle +import com.winlator.cmod.shared.ui.settings.SharedGroupTitle +import com.winlator.cmod.shared.ui.settings.SharedInfoRow +import com.winlator.cmod.shared.ui.settings.SharedSettingGroup +import com.winlator.cmod.shared.ui.settings.SharedSettingSwitch +import com.winlator.cmod.feature.library.GameSettingsNav +import com.winlator.cmod.feature.shortcuts.LibraryShortcutArtwork +import com.winlator.cmod.runtime.container.Shortcut +import java.io.File +import com.winlator.cmod.shared.ui.nav.LocalPaneNav +import com.winlator.cmod.shared.ui.nav.PaneNavRegistry +import com.winlator.cmod.shared.ui.nav.paneHighlight +import com.winlator.cmod.shared.ui.nav.paneNavItem +import com.winlator.cmod.shared.ui.outlinedSwitchColors +import com.winlator.cmod.shared.ui.widget.chasingBorder + +private val BgDeep = GameSettingsStyle.BgDeep +private val SidebarBg = GameSettingsStyle.SidebarBg +private val ContentBg = GameSettingsStyle.ContentBg +private val CardSurface = GameSettingsStyle.CardSurface +private val CardBorder = GameSettingsStyle.CardBorder +private val InputSurface = GameSettingsStyle.InputSurface +private val InputBorder = GameSettingsStyle.InputBorder +private val AccentBlue = GameSettingsStyle.AccentBlue +private val TextPrimary = GameSettingsStyle.TextPrimary +private val TextSecondary = GameSettingsStyle.TextSecondary +private val TextDim = GameSettingsStyle.TextDim +private val DividerColor = GameSettingsStyle.Divider +private val NavHighlight = GameSettingsStyle.NavHighlight +private val DangerRed = GameSettingsStyle.DangerRed + +private val LabelSize = 11.sp +private val ValueSize = 12.sp +private val GroupCorner = 12.dp +private val GroupPadding = 12.dp +private val FieldCorner = 8.dp +private val ItemGap = 10.dp +private val TightGap = 4.dp + +private val SHADER_KEYS = listOf("default", "crt", "lcd", "sharp") +private val UPSCALE_KEYS = listOf("2x", "4x", "native") + +class RetroSettingsState( + val shortcut: Shortcut, + private val context: android.content.Context? = null, +) { + val system: RetroSystem? = RetroShortcuts.systemForShortcut(shortcut) + val coreOptions: List = RetroCoreOptions.forSystem(system) + val name: String = shortcut.getExtra("custom_name", shortcut.name) + val romPath: String = shortcut.getExtra(RetroShortcuts.KEY_ROM) + + private val sysId: String? = system?.id + + var shader by mutableStateOf( + shortcut.getExtra(RetroShortcuts.KEY_SHADER) + .ifEmpty { if (context != null && sysId != null) RetroDefaults.shader(context, sysId) else "default" } + .lowercase().let { if (it in SHADER_KEYS) it else "default" }, + ) + var sgsr by mutableStateOf( + when { + shortcut.getExtra(RetroShortcuts.KEY_SGSR).isNotEmpty() -> shortcut.getExtra(RetroShortcuts.KEY_SGSR) == "1" + shortcut.getExtra(RetroShortcuts.KEY_SHADER, "default").lowercase() == "sgsr" -> true + context != null && sysId != null -> RetroDefaults.sgsr(context, sysId) + else -> false + }, + ) + var upscale by mutableStateOf( + shortcut.getExtra(RetroShortcuts.KEY_UPSCALE) + .ifEmpty { if (context != null && sysId != null) RetroDefaults.upscale(context, sysId) else "native" } + .lowercase().let { if (it in UPSCALE_KEYS) it else "native" }, + ) + var touchControls by mutableStateOf( + shortcut.getExtra(RetroShortcuts.KEY_TOUCH_CONTROLS) + .ifEmpty { if (context != null && sysId != null) (if (RetroDefaults.touchControls(context, sysId)) "1" else "0") else "1" } != "0", + ) + var adaptiveSticks by mutableStateOf( + shortcut.getExtra(RetroShortcuts.KEY_ADAPTIVE_STICKS) + .ifEmpty { if (context != null && sysId != null) (if (RetroDefaults.adaptiveSticks(context, sysId)) "1" else "0") else "0" } == "1", + ) + var hddImage by mutableStateOf(shortcut.getExtra(RetroShortcuts.KEY_HDD_IMAGE)) + var hddEnable by mutableStateOf(shortcut.getExtra(RetroShortcuts.KEY_HDD_ENABLE) == "1") + var audio by mutableStateOf( + shortcut.getExtra(RetroShortcuts.KEY_AUDIO) + .ifEmpty { if (context != null && sysId != null) (if (RetroDefaults.audio(context, sysId)) "1" else "0") else "1" } != "0", + ) + + val optionValues = + mutableStateMapOf().apply { + coreOptions.forEach { option -> + put( + option.key, + shortcut.getExtra(RetroShortcuts.VAR_PREFIX + option.key).ifEmpty { + if (context != null && sysId != null) { + RetroDefaults.coreOption(context, sysId, option.key, option.defaultValue) + } else { + option.defaultValue + } + }, + ) + } + } + val artworkSelected = mutableStateMapOf() + var currentSection by mutableIntStateOf(0) + var biosRefresh by mutableIntStateOf(0) + + var hddRefresh by mutableIntStateOf(0) + var hddImporting by mutableStateOf(false) + var requestImportHdd: (() -> Unit)? = null + + val gameSerial: String? by lazy { + if (context != null && system?.id == RetroSystems.PS2.id) Ps2IsoSerial.serialOf(File(romPath)) else null + } + var cheatsRefresh by mutableIntStateOf(0) + var pendingImportIsPatch = false + var requestImportCheatFile: ((isPatch: Boolean) -> Unit)? = null + + init { + syncArtwork() + } + + fun syncArtwork() { + LibraryShortcutArtwork.LibraryArtworkSlot.entries.forEach { slot -> + val path = shortcut.getExtra(slot.extraKey) + artworkSelected[slot] = path.isNotBlank() && File(path).isFile + } + } + + fun save() { + shortcut.putExtra(RetroShortcuts.KEY_SHADER, shader) + shortcut.putExtra(RetroShortcuts.KEY_SGSR, if (sgsr) "1" else "0") + shortcut.putExtra(RetroShortcuts.KEY_UPSCALE, upscale) + shortcut.putExtra(RetroShortcuts.KEY_TOUCH_CONTROLS, if (touchControls) "1" else "0") + shortcut.putExtra(RetroShortcuts.KEY_ADAPTIVE_STICKS, if (adaptiveSticks) "1" else "0") + shortcut.putExtra(RetroShortcuts.KEY_HDD_IMAGE, hddImage) + shortcut.putExtra(RetroShortcuts.KEY_HDD_ENABLE, if (hddEnable) "1" else "0") + shortcut.putExtra(RetroShortcuts.KEY_AUDIO, if (audio) "1" else "0") + coreOptions.forEach { option -> + val consoleDefault = + if (context != null && sysId != null) { + RetroDefaults.coreOption(context, sysId, option.key, option.defaultValue) + } else { + option.defaultValue + } + val chosen = optionValues[option.key] ?: consoleDefault + shortcut.putExtra( + RetroShortcuts.VAR_PREFIX + option.key, + if (chosen == consoleDefault) null else chosen, + ) + } + shortcut.saveData() + } +} + +private enum class RetroSectionId { + GENERAL, + GRAPHICS, + PERFORMANCE, + HUD, + INPUT, + AUDIO, + ONLINE, + CHEATS, +} + +private data class RetroSection( + val id: RetroSectionId, + val icon: ImageVector, + val labelRes: Int, +) + +private fun buildRetroSections(state: RetroSettingsState): List { + val sections = mutableListOf() + val systemId = state.system?.id + sections += RetroSection(RetroSectionId.GENERAL, Icons.Outlined.Tune, R.string.retro_gs_section_general) + sections += RetroSection(RetroSectionId.GRAPHICS, Icons.Outlined.Monitor, R.string.retro_gs_section_graphics) + if (state.system?.isExternal == true) { + sections += RetroSection(RetroSectionId.PERFORMANCE, Icons.Outlined.Bolt, R.string.retro_gs_section_performance) + } + sections += RetroSection(RetroSectionId.HUD, Icons.Outlined.Speed, R.string.retro_gs_section_hud) + sections += RetroSection(RetroSectionId.INPUT, Icons.Outlined.SportsEsports, R.string.retro_gs_section_input) + sections += RetroSection(RetroSectionId.AUDIO, Icons.AutoMirrored.Outlined.VolumeUp, R.string.retro_gs_section_audio) + if (RetroOnlineSupport.supportsDev9(systemId) || + RetroOnlineSupport.supportsMultiplayerUi(systemId) || + RetroOnlineSupport.supportsDolphinNetplay(systemId) + ) { + sections += RetroSection(RetroSectionId.ONLINE, Icons.Outlined.Public, R.string.retro_gs_section_online) + } + if (state.system?.isExternal == true) { + sections += RetroSection(RetroSectionId.CHEATS, Icons.Outlined.Code, R.string.retro_gs_group_cheats) + } + return sections +} + +@Composable +fun RetroGameSettingsContent( + state: RetroSettingsState, + nav: GameSettingsNav? = null, + onPickArtwork: ((LibraryShortcutArtwork.LibraryArtworkSlot) -> Unit)? = null, + onRemoveArtwork: ((LibraryShortcutArtwork.LibraryArtworkSlot) -> Unit)? = null, + onImportBios: (() -> Unit)? = null, + onSave: () -> Unit, + onCancel: () -> Unit, +) { + val sections = remember(state) { buildRetroSections(state) } + val selectedIdx = state.currentSection + + if (nav != null) { + SideEffect { + nav.sidebarCount = sections.size + nav.onSelectSection = { state.currentSection = it } + nav.onSave = onSave + nav.onCancel = onCancel + } + } + + Box( + modifier = + Modifier + .fillMaxSize() + .clip(RoundedCornerShape(16.dp)) + .background(BgDeep), + ) { + Row(modifier = Modifier.fillMaxSize()) { + RetroSidebar( + title = state.name, + subtitle = state.system?.displayName ?: "", + sections = sections, + currentIndex = selectedIdx, + onSectionSelected = { state.currentSection = it }, + onSave = onSave, + onCancel = onCancel, + nav = nav, + modifier = Modifier.width(220.dp).fillMaxHeight(), + ) + Box(Modifier.width(1.dp).fillMaxHeight().background(DividerColor)) + Box( + modifier = + Modifier + .weight(1f) + .fillMaxHeight() + .background(ContentBg), + ) { + RetroSectionContent( + sectionIndex = selectedIdx, + state = state, + nav = nav, + onPickArtwork = onPickArtwork, + onRemoveArtwork = onRemoveArtwork, + onImportBios = onImportBios, + ) + } + } + } +} + +@Composable +private fun RetroSectionContent( + sectionIndex: Int, + state: RetroSettingsState, + nav: GameSettingsNav? = null, + onPickArtwork: ((LibraryShortcutArtwork.LibraryArtworkSlot) -> Unit)? = null, + onRemoveArtwork: ((LibraryShortcutArtwork.LibraryArtworkSlot) -> Unit)? = null, + onImportBios: (() -> Unit)? = null, +) { + run { + val idx = sectionIndex + val contentNav = remember(nav) { nav?.let { PaneNavRegistry(initialSignal = it.contentSignal) } } + val isCurrent = true + if (nav != null && contentNav != null) { + contentNav.controllerActive = nav.active && nav.inContent && isCurrent + contentNav.onEdgeLeft = { nav.exitToSidebar() } + if (isCurrent) { + nav.onContentBack = { + if (contentNav.overlay != null) { + contentNav.overlayClose?.invoke() + true + } else { + false + } + } + } + LaunchedEffect(nav.contentSignal) { + if (isCurrent) contentNav.processNav(nav.contentSignal, nav.contentDir) + } + LaunchedEffect(nav.contentResetSignal) { + if (isCurrent) contentNav.reset() + } + } + val sections = remember(state) { buildRetroSections(state) } + val sectionBody: @Composable () -> Unit = { + Column( + modifier = + Modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(horizontal = 20.dp, vertical = 14.dp), + ) { + when (sections.getOrNull(idx)?.id) { + RetroSectionId.GENERAL -> RetroGeneralSection(state, onPickArtwork, onRemoveArtwork, onImportBios) + RetroSectionId.GRAPHICS -> RetroGraphicsSection(state) + RetroSectionId.PERFORMANCE -> RetroPs2PerformanceSection() + RetroSectionId.HUD -> + if (state.system?.isExternal == true) RetroPs2HudSection() else RetroLibretroHudSection() + RetroSectionId.INPUT -> RetroInputSection(state) + RetroSectionId.AUDIO -> RetroAudioSection(state) + RetroSectionId.ONLINE -> { + when { + RetroOnlineSupport.supportsDev9(state.system?.id) -> + RetroPs2OnlineSection(state) + RetroOnlineSupport.supportsDolphinNetplay(state.system?.id) -> + RetroDolphinNetplaySection(state) + else -> RetroNetplaySection(state) + } + } + RetroSectionId.CHEATS -> RetroPs2CheatsSection(state) + null -> Unit + } + Spacer(Modifier.height(12.dp)) + } + } + if (contentNav != null) { + CompositionLocalProvider(LocalPaneNav provides contentNav) { sectionBody() } + } else { + sectionBody() + } + } +} + +@Composable +private fun RetroSidebar( + title: String, + subtitle: String, + sections: List, + currentIndex: Int, + onSectionSelected: (Int) -> Unit, + onSave: () -> Unit, + onCancel: () -> Unit, + nav: GameSettingsNav? = null, + modifier: Modifier = Modifier, +) { + val cancelHighlighted = nav != null && nav.active && !nav.inContent && nav.onActionRow && nav.actionCol == 0 + val saveHighlighted = nav != null && nav.active && !nav.inContent && nav.onActionRow && nav.actionCol == 1 + Column( + modifier = + modifier + .background(SidebarBg) + .padding(top = 14.dp, bottom = 12.dp), + ) { + Text( + text = title, + color = TextPrimary, + fontSize = LabelSize, + fontWeight = FontWeight.SemiBold, + letterSpacing = 0.2.sp, + lineHeight = 15.sp, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp) + .padding(bottom = 2.dp), + ) + if (subtitle.isNotBlank()) { + Text( + text = subtitle, + color = TextSecondary, + fontSize = 10.sp, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp) + .padding(bottom = 10.dp), + ) + } + Box( + modifier = + Modifier + .padding(horizontal = 12.dp) + .fillMaxWidth() + .height(1.dp) + .background(DividerColor), + ) + Spacer(Modifier.height(8.dp)) + + Column( + modifier = + Modifier + .weight(1f) + .verticalScroll(rememberScrollState()) + .padding(bottom = 8.dp), + verticalArrangement = Arrangement.spacedBy(1.dp), + ) { + sections.forEachIndexed { index, section -> + RetroSidebarItem( + icon = section.icon, + label = stringResource(section.labelRes), + isSelected = currentIndex == index, + navHighlighted = + nav != null && nav.active && !nav.inContent && !nav.onActionRow && + nav.sidebarIndex == index, + onClick = { + if (nav != null) nav.tapSection(index) else onSectionSelected(index) + }, + ) + } + } + + Box( + modifier = + Modifier + .padding(horizontal = 12.dp) + .fillMaxWidth() + .height(1.dp) + .background(DividerColor), + ) + Spacer(Modifier.height(8.dp)) + + Row( + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp), + horizontalArrangement = Arrangement.spacedBy(6.dp), + ) { + Box( + modifier = + Modifier + .weight(1f) + .height(30.dp) + .clip(RoundedCornerShape(8.dp)) + .border(1.dp, CardBorder, RoundedCornerShape(8.dp)) + .background(CardSurface) + .paneHighlight(cancelHighlighted, cornerRadius = 8.dp, highlightColor = NavHighlight) + .clickable { + nav?.tapAction(0) + onCancel() + }, + contentAlignment = Alignment.Center, + ) { + Text(stringResource(R.string.retro_gs_cancel), color = TextSecondary, fontSize = LabelSize, fontWeight = FontWeight.Medium) + } + Box( + modifier = + Modifier + .weight(1f) + .height(30.dp) + .clip(RoundedCornerShape(8.dp)) + .border(1.dp, AccentBlue.copy(alpha = 0.5f), RoundedCornerShape(8.dp)) + .background(AccentBlue.copy(alpha = 0.1f)) + .paneHighlight(saveHighlighted, cornerRadius = 8.dp, highlightColor = NavHighlight) + .clickable { + nav?.tapAction(1) + onSave() + }, + contentAlignment = Alignment.Center, + ) { + Text(stringResource(R.string.retro_gs_save), color = AccentBlue, fontSize = LabelSize, fontWeight = FontWeight.Medium) + } + } + } +} + +@Composable +private fun RetroSidebarItem( + icon: ImageVector, + label: String, + isSelected: Boolean, + navHighlighted: Boolean = false, + onClick: () -> Unit, +) { + Box( + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 8.dp) + .clip(RoundedCornerShape(8.dp)) + .chasingBorder(isFocused = isSelected, cornerRadius = 8.dp, borderWidth = 2.dp) + .paneHighlight(navHighlighted, cornerRadius = 8.dp, highlightColor = NavHighlight) + .clickable( + interactionSource = remember { MutableInteractionSource() }, + indication = null, + onClick = onClick, + ) + .padding(horizontal = 12.dp, vertical = 8.dp), + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + Icon( + icon, + contentDescription = null, + tint = if (isSelected) AccentBlue else TextDim, + modifier = Modifier.size(18.dp), + ) + Spacer(Modifier.width(10.dp)) + Text( + label, + color = if (isSelected) TextPrimary else TextSecondary, + fontSize = ValueSize, + fontWeight = if (isSelected) FontWeight.SemiBold else FontWeight.Normal, + maxLines = 1, + ) + } + } +} + +@Composable +internal fun RetroSettingGroup(content: @Composable () -> Unit) { + SharedSettingGroup(content) +} + +@Composable +internal fun RetroGroupTitle(text: String) { + SharedGroupTitle(text) +} + +@Composable +internal fun RetroInfoRow( + label: String, + value: String, + singleLineValue: Boolean = false, +) { + SharedInfoRow(label, value, singleLineValue = singleLineValue) +} + +@Composable +internal fun RetroSettingDropdown( + label: String, + entries: List, + selectedIndex: Int, + onSelected: (Int) -> Unit, +) { + var expanded by remember { mutableStateOf(false) } + val selectedText = entries.getOrElse(selectedIndex) { "" } + val parentNav = LocalPaneNav.current + val optionRegistry = remember { PaneNavRegistry() } + LaunchedEffect(expanded) { + if (expanded) { + optionRegistry.reset() + optionRegistry.controllerActive = true + parentNav?.overlay = optionRegistry + parentNav?.overlayClose = { expanded = false } + } else if (parentNav?.overlay === optionRegistry) { + parentNav.overlay = null + parentNav.overlayClose = null + } + } + + Column(modifier = Modifier.fillMaxWidth().padding(bottom = ItemGap)) { + Text( + label, + color = TextSecondary, + fontSize = LabelSize, + fontWeight = FontWeight.Medium, + letterSpacing = 0.3.sp, + modifier = Modifier.padding(bottom = TightGap), + ) + Box { + Row( + modifier = + Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(FieldCorner)) + .background(InputSurface) + .border(1.dp, InputBorder, RoundedCornerShape(FieldCorner)) + .paneNavItem( + cornerRadius = FieldCorner, + onActivate = { expanded = true }, + highlightColor = NavHighlight, + ) + .clickable { expanded = true } + .padding(horizontal = 12.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + selectedText, + color = TextPrimary, + fontSize = ValueSize, + modifier = Modifier.weight(1f), + maxLines = 1, + ) + Icon( + Icons.Outlined.KeyboardArrowDown, + contentDescription = null, + tint = TextDim, + modifier = Modifier.size(18.dp), + ) + } + DropdownMenu( + expanded = expanded, + onDismissRequest = { expanded = false }, + shape = RoundedCornerShape(8.dp), + containerColor = CardSurface, + properties = PopupProperties(focusable = false), + ) { + CompositionLocalProvider(LocalPaneNav provides optionRegistry) { + entries.forEachIndexed { index, entry -> + DropdownMenuItem( + text = { + Text( + entry, + color = if (index == selectedIndex) AccentBlue else TextPrimary, + fontSize = ValueSize, + fontWeight = if (index == selectedIndex) FontWeight.Medium else FontWeight.Normal, + ) + }, + onClick = { + onSelected(index) + expanded = false + }, + modifier = + ( + if (index == selectedIndex) { + Modifier.background(AccentBlue.copy(alpha = 0.06f)) + } else { + Modifier + } + ).paneNavItem( + cornerRadius = 6.dp, + onActivate = { + onSelected(index) + expanded = false + }, + isEntry = index == selectedIndex, + highlightColor = NavHighlight, + ), + ) + } + } + } + } + } +} + +@Composable +internal fun RetroSettingSwitch( + label: String, + checked: Boolean, + subtitle: String? = null, + onCheckedChange: (Boolean) -> Unit, +) { + SharedSettingSwitch(label, checked, subtitle, onCheckedChange) +} + +@Composable +internal fun RetroSettingTextField( + label: String, + value: String, + placeholder: String, + onChange: (String) -> Unit, +) { + var editing by remember { mutableStateOf(false) } + var draft by remember(value) { mutableStateOf(value) } + if (editing) { + androidx.compose.material3.AlertDialog( + onDismissRequest = { editing = false }, + title = { Text(label) }, + text = { + androidx.compose.material3.OutlinedTextField( + value = draft, + onValueChange = { draft = it }, + singleLine = true, + placeholder = { Text(placeholder) }, + ) + }, + confirmButton = { + androidx.compose.material3.TextButton(onClick = { + onChange(draft.trim()) + editing = false + }) { Text(stringResource(R.string.retro_gs_save)) } + }, + dismissButton = { + androidx.compose.material3.TextButton(onClick = { editing = false }) { Text(stringResource(R.string.retro_gs_cancel)) } + }, + ) + } + Column( + modifier = + Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(8.dp)) + .clickable( + interactionSource = remember { MutableInteractionSource() }, + indication = null, + ) { draft = value; editing = true } + .paneNavItem( + cornerRadius = 8.dp, + onActivate = { draft = value; editing = true }, + highlightColor = NavHighlight, + tapToSelect = true, + ) + .padding(vertical = TightGap + 2.dp), + ) { + Text( + label, + color = TextSecondary, + fontSize = LabelSize, + fontWeight = FontWeight.Medium, + maxLines = 2, + softWrap = true, + overflow = androidx.compose.ui.text.style.TextOverflow.Clip, + ) + Spacer(Modifier.height(2.dp)) + Text( + value.ifBlank { placeholder }, + color = if (value.isBlank()) TextSecondary else AccentBlue, + fontSize = ValueSize, + fontWeight = FontWeight.Medium, + maxLines = 3, + softWrap = true, + overflow = androidx.compose.ui.text.style.TextOverflow.Clip, + ) + } +} + +private fun coreDisplayName(system: RetroSystem?): String = + when { + system == null -> "" + system.id == RetroSystems.PS2.id -> "ARMSX2" + RetroCoreManager.usesDolphinCore(system) -> "Dolphin" + else -> system.coreFileName + } + +@Composable +private fun RetroConsoleEditPen(onClick: () -> Unit) { + val green = Color(0xFF3FB950) + Box( + modifier = + Modifier + .clip(RoundedCornerShape(9.dp)) + .background(green.copy(alpha = 0.12f)) + .border(1.dp, green.copy(alpha = 0.55f), RoundedCornerShape(9.dp)) + .clickable { onClick() } + .padding(horizontal = 10.dp, vertical = 6.dp), + contentAlignment = Alignment.Center, + ) { + Icon( + Icons.Outlined.Edit, + contentDescription = stringResource(R.string.retro_gs_change_console), + tint = green, + modifier = Modifier.size(16.dp), + ) + } +} + +@Composable +private fun RetroConsolePickerDialog( + current: RetroSystem?, + onDismiss: () -> Unit, + onPick: (RetroSystem) -> Unit, +) { + androidx.compose.material3.AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.retro_gs_identify_as)) }, + text = { + Column(Modifier.verticalScroll(rememberScrollState())) { + RetroSystems.ALL.sortedBy { it.displayName }.forEach { sys -> + val selected = sys.id == current?.id + Text( + sys.displayName, + color = if (selected) GameSettingsStyle.AccentBlue else GameSettingsStyle.TextPrimary, + fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal, + modifier = + Modifier + .fillMaxWidth() + .clickable { onPick(sys) } + .padding(vertical = 12.dp), + ) + } + } + }, + confirmButton = {}, + dismissButton = { + androidx.compose.material3.TextButton(onClick = onDismiss) { + Text(stringResource(R.string.retro_gs_cancel)) + } + }, + ) +} + +@Composable +private fun RetroGeneralSection( + state: RetroSettingsState, + onPickArtwork: ((LibraryShortcutArtwork.LibraryArtworkSlot) -> Unit)? = null, + onRemoveArtwork: ((LibraryShortcutArtwork.LibraryArtworkSlot) -> Unit)? = null, + onImportBios: (() -> Unit)? = null, +) { + val ctx = androidx.compose.ui.platform.LocalContext.current + var currentSystem by remember { mutableStateOf(state.system) } + var showConsolePicker by remember { mutableStateOf(false) } + SharedSettingGroup { + SharedGroupTitle(stringResource(R.string.retro_gs_group_game)) + SharedInfoRow(stringResource(R.string.retro_gs_label_name), state.name) + Row(verticalAlignment = Alignment.CenterVertically) { + Box(Modifier.weight(1f)) { + SharedInfoRow(stringResource(R.string.retro_gs_label_system), currentSystem?.displayName ?: "") + } + RetroConsoleEditPen { showConsolePicker = true } + } + SharedInfoRow( + stringResource(R.string.retro_gs_label_emulator_core), + coreDisplayName(currentSystem), + singleLineValue = true, + ) + SharedInfoRow( + stringResource(R.string.retro_gs_label_rom_path), + state.romPath, + singleLineValue = true, + ) + if (currentSystem?.isExternal == true) { + val ps2Prefs = remember(ctx) { ctx.getSharedPreferences("ARMSX2", android.content.Context.MODE_PRIVATE) } + var version by remember { androidx.compose.runtime.mutableIntStateOf(0) } + @Suppress("UNUSED_EXPRESSION") version + SharedSettingSwitch(stringResource(R.string.retro_gs_fast_boot), ps2Prefs.getBoolean("wn.ps2.fastboot", true)) { + ps2Prefs.edit().putBoolean("wn.ps2.fastboot", it).apply(); version++ + } + } + } + if (showConsolePicker) { + RetroConsolePickerDialog( + current = currentSystem, + onDismiss = { showConsolePicker = false }, + ) { picked -> + showConsolePicker = false + if (picked.id != currentSystem?.id) { + currentSystem = picked + kotlin.concurrent.thread { + runCatching { + state.shortcut.putExtra(RetroShortcuts.KEY_SYSTEM, picked.id) + state.shortcut.saveData() + } + } + android.widget.Toast.makeText( + ctx, + ctx.getString(R.string.retro_gs_console_changed, picked.displayName), + android.widget.Toast.LENGTH_SHORT, + ).show() + } + } + } + val biosSystem = currentSystem + if (biosSystem?.needsBios == true && onImportBios != null) { + val context = ctx + Spacer(Modifier.height(ItemGap)) + RetroSettingGroup { + RetroGroupTitle(stringResource(R.string.retro_gs_group_bios, biosSystem.shortName.uppercase())) + state.biosRefresh + val dir = RetroCoreManager.systemDir(context) + val installed = biosSystem.biosFiles.filter { java.io.File(dir, it).isFile } + RetroInfoRow( + stringResource(R.string.retro_gs_label_installed), + if (installed.isEmpty()) stringResource(R.string.retro_gs_bios_none, biosSystem.shortName) else installed.joinToString(", "), + ) + androidx.compose.material3.Button( + onClick = { onImportBios() }, + modifier = Modifier.fillMaxWidth().padding(top = ItemGap), + ) { + androidx.compose.material3.Text(stringResource(R.string.retro_gs_import_bios)) + } + if (installed.isNotEmpty()) { + androidx.compose.material3.OutlinedButton( + onClick = { + installed.forEach { java.io.File(dir, it).delete() } + state.biosRefresh++ + }, + modifier = Modifier.fillMaxWidth().padding(top = ItemGap), + ) { + androidx.compose.material3.Text(stringResource(R.string.retro_gs_remove_bios)) + } + } + } + } + if (onPickArtwork != null && onRemoveArtwork != null) { + Spacer(Modifier.height(ItemGap)) + RetroSettingGroup { + RetroGroupTitle(stringResource(R.string.retro_gs_group_library_artwork)) + Row(horizontalArrangement = Arrangement.spacedBy(ItemGap)) { + Box(Modifier.weight(1f)) { + RetroArtworkRow( + title = stringResource(R.string.retro_gs_artwork_game_card), + selected = state.artworkSelected[LibraryShortcutArtwork.LibraryArtworkSlot.GAME_CARD] == true, + onPick = { onPickArtwork(LibraryShortcutArtwork.LibraryArtworkSlot.GAME_CARD) }, + onRemove = { onRemoveArtwork(LibraryShortcutArtwork.LibraryArtworkSlot.GAME_CARD) }, + ) + } + Box(Modifier.weight(1f)) { + RetroArtworkRow( + title = stringResource(R.string.retro_gs_artwork_grid), + selected = state.artworkSelected[LibraryShortcutArtwork.LibraryArtworkSlot.GRID] == true, + onPick = { onPickArtwork(LibraryShortcutArtwork.LibraryArtworkSlot.GRID) }, + onRemove = { onRemoveArtwork(LibraryShortcutArtwork.LibraryArtworkSlot.GRID) }, + ) + } + } + Spacer(Modifier.height(ItemGap)) + Row(horizontalArrangement = Arrangement.spacedBy(ItemGap)) { + Box(Modifier.weight(1f)) { + RetroArtworkRow( + title = stringResource(R.string.retro_gs_artwork_carousel), + selected = state.artworkSelected[LibraryShortcutArtwork.LibraryArtworkSlot.CAROUSEL] == true, + onPick = { onPickArtwork(LibraryShortcutArtwork.LibraryArtworkSlot.CAROUSEL) }, + onRemove = { onRemoveArtwork(LibraryShortcutArtwork.LibraryArtworkSlot.CAROUSEL) }, + ) + } + Box(Modifier.weight(1f)) { + RetroArtworkRow( + title = stringResource(R.string.retro_gs_artwork_list), + selected = state.artworkSelected[LibraryShortcutArtwork.LibraryArtworkSlot.LIST] == true, + onPick = { onPickArtwork(LibraryShortcutArtwork.LibraryArtworkSlot.LIST) }, + onRemove = { onRemoveArtwork(LibraryShortcutArtwork.LibraryArtworkSlot.LIST) }, + ) + } + } + } + } +} + +@Composable +private fun RetroArtworkRow( + title: String, + selected: Boolean, + onPick: () -> Unit, + onRemove: () -> Unit, +) { + Box( + modifier = + Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(GroupCorner)) + .background(InputSurface) + .border(1.dp, InputBorder, RoundedCornerShape(GroupCorner)) + .padding(horizontal = 10.dp, vertical = 8.dp), + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = title, + color = TextPrimary, + fontSize = ValueSize, + fontWeight = FontWeight.SemiBold, + ) + if (selected) { + Spacer(Modifier.height(2.dp)) + Text( + text = stringResource(R.string.retro_gs_artwork_custom_set), + color = TextSecondary, + fontSize = LabelSize, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + Row( + horizontalArrangement = Arrangement.spacedBy(6.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + if (!selected) { + RetroArtworkActionButton(stringResource(R.string.retro_gs_artwork_set_image), AccentBlue, onPick) + } else { + RetroArtworkActionButton(stringResource(R.string.retro_gs_artwork_remove), DangerRed, onRemove) + } + } + } + } +} + +@Composable +private fun RetroArtworkActionButton( + text: String, + tint: Color, + onClick: () -> Unit, +) { + Box( + modifier = + Modifier + .clip(RoundedCornerShape(9.dp)) + .background(tint.copy(alpha = 0.08f)) + .border(1.dp, tint.copy(alpha = 0.2f), RoundedCornerShape(9.dp)) + .paneNavItem(cornerRadius = 9.dp, onActivate = { onClick() }, highlightColor = NavHighlight) + .clickable { onClick() } + .padding(horizontal = 10.dp, vertical = 6.dp), + ) { + Text( + text = text, + color = tint, + fontSize = LabelSize, + fontWeight = FontWeight.Medium, + ) + } +} + +@Composable +private fun RetroGraphicsSection(state: RetroSettingsState) { + if (state.system?.isExternal == true) { + RetroPs2GraphicsSection() + return + } + val shaderLabels = listOf( + stringResource(R.string.retro_gs_shader_default), + stringResource(R.string.retro_gs_shader_crt), + stringResource(R.string.retro_gs_shader_lcd), + stringResource(R.string.retro_gs_shader_sharp), + ) + val upscaleLabels = listOf( + stringResource(R.string.retro_gs_upscale_2x), + stringResource(R.string.retro_gs_upscale_4x), + stringResource(R.string.retro_gs_upscale_native), + ) + val embeddedDolphinContext = androidx.compose.ui.platform.LocalContext.current + val embeddedDolphin = + RetroCoreManager.usesDolphinCore(state.system) && + RetroShortcuts.embeddedDolphinEnabled(embeddedDolphinContext) + RetroSettingGroup { + RetroGroupTitle(stringResource(R.string.retro_gs_group_video)) + if (embeddedDolphin) { + DolphinGpuDriverDropdown() + } + if (!embeddedDolphin) { + RetroSettingDropdown( + label = stringResource(R.string.retro_gs_video_filter), + entries = shaderLabels, + selectedIndex = SHADER_KEYS.indexOf(state.shader).coerceAtLeast(0), + onSelected = { state.shader = SHADER_KEYS[it] }, + ) + RetroSettingSwitch( + label = stringResource(R.string.retro_gs_sgsr), + checked = state.sgsr, + onCheckedChange = { state.sgsr = it }, + ) + if (state.sgsr) { + RetroSettingDropdown( + label = stringResource(R.string.retro_gs_sgsr_upscale), + entries = upscaleLabels, + selectedIndex = UPSCALE_KEYS.indexOf(state.upscale).coerceAtLeast(0), + onSelected = { state.upscale = UPSCALE_KEYS[it] }, + ) + } + } + } + if (state.coreOptions.isNotEmpty()) { + Spacer(Modifier.height(12.dp)) + RetroSettingGroup { + RetroGroupTitle((state.system?.shortName ?: stringResource(R.string.retro_gs_group_core)).uppercase()) + val ctx = androidx.compose.ui.platform.LocalContext.current + val ordered = + state.coreOptions.filterNot { it.advanced } + state.coreOptions.filter { it.advanced } + ordered.forEach { option -> + val current = state.optionValues[option.key] ?: option.defaultValue + RetroSettingDropdown( + label = option.labelText(ctx), + entries = option.valueLabels, + selectedIndex = option.values.indexOf(current).coerceAtLeast(0), + onSelected = { state.optionValues[option.key] = option.values[it] }, + ) + } + } + } +} + +@Composable +private fun DolphinGpuDriverDropdown() { + val context = androidx.compose.ui.platform.LocalContext.current + val prefs = remember(context) { androidx.preference.PreferenceManager.getDefaultSharedPreferences(context) } + var driverVersion by remember { mutableIntStateOf(0) } + @Suppress("UNUSED_EXPRESSION") driverVersion + val gcDrivers = remember { com.armsx2.CustomDriver.listInstalled(context) } + val gcDriverIds = remember(gcDrivers) { listOf("") + gcDrivers.map { it.id } } + val gcDriverLabels = listOf(stringResource(R.string.retro_gpu_driver_system)) + gcDrivers.map { it.name } + val curGcDriver = (prefs.getString(DolphinEmbedLaunch.DRIVER_PREF, "") ?: "").let { if (it.equals("system", true)) "" else it } + RetroSettingDropdown( + label = stringResource(R.string.retro_gpu_driver), + entries = gcDriverLabels, + selectedIndex = gcDriverIds.indexOf(curGcDriver).coerceAtLeast(0), + onSelected = { + prefs.edit().putString(DolphinEmbedLaunch.DRIVER_PREF, gcDriverIds[it]).apply() + driverVersion++ + }, + ) +} + +@Composable +internal fun RetroLibretroHudSection() { + val context = androidx.compose.ui.platform.LocalContext.current + var version by remember { androidx.compose.runtime.mutableIntStateOf(0) } + @Suppress("UNUSED_EXPRESSION") version + val hudOn = RetroDefaults.hud(context, "") + val elements = remember(version) { RetroHudSupport.loadGlobalHudElements(context) } + RetroSettingGroup { + RetroGroupTitle(stringResource(R.string.retro_gs_group_performance_hud)) + RetroSettingSwitch(stringResource(R.string.retro_lr_performance_hud), hudOn) { + RetroDefaults.setHud(context, "", it) + version++ + } + if (hudOn) { + RetroHudElementButtons(elements) { index, on -> + val next = elements.copyOf() + next[index] = on + RetroHudSupport.saveGlobalHudElements(context, next) + version++ + } + } + } +} + +@Composable +private fun RetroHudElementButtons( + elements: BooleanArray, + onToggle: (index: Int, on: Boolean) -> Unit, +) { + RetroHudSupport.ELEMENT_ORDER.toList().chunked(3).forEach { rowIndices -> + Row( + Modifier.fillMaxWidth().padding(top = 6.dp), + horizontalArrangement = Arrangement.spacedBy(6.dp), + ) { + rowIndices.forEach { index -> + val on = elements[index] + HudToggleButton( + label = stringResource(RetroHudSupport.ELEMENT_LABEL_RES[index]), + on = on, + modifier = Modifier.weight(1f), + ) { onToggle(index, !on) } + } + repeat(3 - rowIndices.size) { Spacer(Modifier.weight(1f)) } + } + } +} + +@Composable +private fun HudToggleButton( + label: String, + on: Boolean, + modifier: Modifier = Modifier, + onClick: () -> Unit, +) { + OutlinedButton( + onClick = onClick, + modifier = modifier.height(40.dp), + shape = RoundedCornerShape(8.dp), + contentPadding = PaddingValues(horizontal = 6.dp, vertical = 4.dp), + border = + BorderStroke( + 1.dp, + if (on) GameSettingsStyle.AccentBlue else GameSettingsStyle.CardBorder, + ), + colors = + ButtonDefaults.outlinedButtonColors( + containerColor = + if (on) GameSettingsStyle.AccentBlue.copy(alpha = 0.15f) else Color.Transparent, + contentColor = + if (on) GameSettingsStyle.AccentBlue else GameSettingsStyle.TextSecondary, + ), + ) { + Text( + label, + fontSize = 11.sp, + fontWeight = FontWeight.Medium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } +} + +internal val PS2_TURNIP_FLAGS: List> = listOf( + "sysmem" to "Force system-memory rendering", + "gmem" to "Force GMEM (tiled GPU memory) rendering", + "flushall" to "Flush all caches every draw", + "nolrz" to "Disable low-resolution Z (LRZ)", + "nolrzfc" to "Disable LRZ fast-clear", + "noubwc" to "Disable bandwidth compression (UBWC)", + "noconform" to "Skip non-conformant fast paths", + "syncdraw" to "Synchronise every draw", + "forcebin" to "Force binning (tiled) mode", +) + +@Composable +internal fun Ps2TurnipFlags(prefs: android.content.SharedPreferences, refreshKey: Int, bump: () -> Unit) { + Text( + stringResource(R.string.retro_ps2_turnip_flags), + color = TextSecondary, + fontSize = LabelSize, + fontWeight = FontWeight.SemiBold, + modifier = Modifier.padding(top = ItemGap, bottom = TightGap), + ) + val usingTurnip = remember(refreshKey) { + val driver = (prefs.getString("wn.ps2.driver", "") ?: "").trim() + driver.isNotEmpty() && !driver.equals("system", ignoreCase = true) + } + if (!usingTurnip) { + Text( + stringResource(R.string.retro_ps2_turnip_flags_note), + color = TextDim, + fontSize = LabelSize, + modifier = Modifier.padding(bottom = TightGap), + ) + } + val active = remember(refreshKey) { + (prefs.getString("wn.ps2.turnipflags", "") ?: "") + .split(",").map { it.trim() }.filter { it.isNotEmpty() }.toSet() + } + PS2_TURNIP_FLAGS.forEach { (flag, hint) -> + RetroSettingSwitch(flag, flag in active, subtitle = hint) { on -> + val next = if (on) active + flag else active - flag + prefs.edit().putString("wn.ps2.turnipflags", next.joinToString(",")).apply() + bump() + } + } +} + +@Composable +private fun RetroPs2GraphicsSection() { + val context = androidx.compose.ui.platform.LocalContext.current + val prefs = remember(context) { context.getSharedPreferences("ARMSX2", android.content.Context.MODE_PRIVATE) } + var version by remember { androidx.compose.runtime.mutableIntStateOf(0) } + + @Suppress("UNUSED_EXPRESSION") version + + fun putInt(key: String, value: Int) { prefs.edit().putInt(key, value).apply(); version++ } + fun putBool(key: String, value: Boolean) { prefs.edit().putBoolean(key, value).apply(); version++ } + fun putStr(key: String, value: String) { prefs.edit().putString(key, value).apply(); version++ } + fun putFloat(key: String, value: Float) { prefs.edit().putFloat(key, value).apply(); version++ } + + RetroSettingGroup { + RetroGroupTitle(stringResource(R.string.retro_gs_group_video)) + val rendererKeys = listOf("vulkan", "opengl", "software") + RetroSettingDropdown( + stringResource(R.string.retro_gs_renderer), + listOf( + stringResource(R.string.retro_gs_renderer_vulkan), + stringResource(R.string.retro_gs_renderer_opengl), + stringResource(R.string.retro_gs_renderer_software), + ), + rendererKeys.indexOf(prefs.getString("wn.ps2.renderer", "vulkan")).coerceAtLeast(0), + ) { putStr("wn.ps2.renderer", rendererKeys[it]) } + val ps2Drivers = remember { com.armsx2.CustomDriver.listInstalled(context) } + val driverIds = remember(ps2Drivers) { listOf("") + ps2Drivers.map { it.id } } + val driverLabels = listOf(stringResource(R.string.retro_gpu_driver_system)) + ps2Drivers.map { it.name } + val curDriver = (prefs.getString("wn.ps2.driver", "") ?: "").let { if (it.equals("system", true)) "" else it } + RetroSettingDropdown( + stringResource(R.string.retro_gpu_driver), + driverLabels, + driverIds.indexOf(curDriver).coerceAtLeast(0), + ) { putStr("wn.ps2.driver", driverIds[it]) } + if (ps2Drivers.isEmpty()) { + Text( + stringResource(R.string.retro_gpu_driver_hint), + color = TextDim, + fontSize = LabelSize, + modifier = Modifier.padding(top = TightGap), + ) + } + Ps2TurnipFlags(prefs, version) { version++ } + val scales = listOf(1f, 1.5f, 2f, 3f, 4f) + RetroSettingDropdown( + stringResource(R.string.retro_gs_resolution_scale), + listOf( + stringResource(R.string.retro_gs_scale_1x_native), + stringResource(R.string.retro_gs_scale_1_5x), + stringResource(R.string.retro_gs_scale_2x), + stringResource(R.string.retro_gs_scale_3x), + stringResource(R.string.retro_gs_scale_4x), + ), + scales.indexOfFirst { kotlin.math.abs(it - prefs.getFloat("wn.ps2.upscale", 1f)) < 0.01f }.coerceAtLeast(0), + ) { putFloat("wn.ps2.upscale", scales[it]) } + RetroSettingDropdown( + stringResource(R.string.retro_gs_aspect_ratio), + listOf( + stringResource(R.string.retro_gs_aspect_stretch), + stringResource(R.string.retro_gs_aspect_auto_standard), + stringResource(R.string.retro_gs_aspect_4_3), + stringResource(R.string.retro_gs_aspect_16_9), + ), + prefs.getInt("wn.ps2.aspect", 1).coerceIn(0, 3), + ) { putInt("wn.ps2.aspect", it) } + RetroSettingDropdown( + stringResource(R.string.retro_gs_fmv_aspect_ratio), + listOf( + stringResource(R.string.retro_gs_off), + stringResource(R.string.retro_gs_aspect_auto_standard), + stringResource(R.string.retro_gs_aspect_4_3), + stringResource(R.string.retro_gs_aspect_16_9), + ), + prefs.getInt("wn.ps2.fmvaspect", 0).coerceIn(0, 3), + ) { putInt("wn.ps2.fmvaspect", it) } + RetroSettingDropdown( + stringResource(R.string.retro_gs_deinterlace_mode), + listOf( + stringResource(R.string.retro_gs_deint_auto), + stringResource(R.string.retro_gs_deint_off), + stringResource(R.string.retro_gs_deint_weave_tff), + stringResource(R.string.retro_gs_deint_weave_bff), + stringResource(R.string.retro_gs_deint_bob_tff), + stringResource(R.string.retro_gs_deint_bob_bff), + stringResource(R.string.retro_gs_deint_blend_tff), + stringResource(R.string.retro_gs_deint_blend_bff), + stringResource(R.string.retro_gs_deint_adaptive_tff), + stringResource(R.string.retro_gs_deint_adaptive_bff), + ), + prefs.getInt("wn.ps2.deinterlace", 0).coerceIn(0, 9), + ) { putInt("wn.ps2.deinterlace", it) } + RetroSettingDropdown( + stringResource(R.string.retro_gs_display_filter), + listOf( + stringResource(R.string.retro_gs_filter_nearest), + stringResource(R.string.retro_gs_filter_bilinear_smooth), + stringResource(R.string.retro_gs_filter_bilinear_sharp), + ), + prefs.getInt("wn.ps2.displayfilter", 1).coerceIn(0, 2), + ) { putInt("wn.ps2.displayfilter", it) } + RetroSettingDropdown( + stringResource(R.string.retro_gs_texture_filter), + listOf( + stringResource(R.string.retro_gs_filter_nearest), + stringResource(R.string.retro_gs_filter_bilinear_forced), + stringResource(R.string.retro_gs_filter_bilinear_ps2), + stringResource(R.string.retro_gs_filter_bilinear_sprites), + ), + prefs.getInt("wn.ps2.filter", 2).coerceIn(0, 3), + ) { putInt("wn.ps2.filter", it) } + RetroSettingSwitch(stringResource(R.string.retro_gs_mipmapping), prefs.getBoolean("wn.ps2.mipmap", true)) { putBool("wn.ps2.mipmap", it) } + RetroSettingDropdown( + stringResource(R.string.retro_gs_blending_accuracy), + listOf( + stringResource(R.string.retro_gs_blend_minimum), + stringResource(R.string.retro_gs_blend_basic), + stringResource(R.string.retro_gs_blend_medium), + stringResource(R.string.retro_gs_blend_high), + stringResource(R.string.retro_gs_blend_full), + stringResource(R.string.retro_gs_blend_maximum), + ), + prefs.getInt("wn.ps2.blend", 1).coerceIn(0, 5), + ) { putInt("wn.ps2.blend", it) } + RetroSettingSwitch(stringResource(R.string.retro_gs_anti_blur), prefs.getBoolean("wn.ps2.antiblur", true)) { putBool("wn.ps2.antiblur", it) } + RetroSettingDropdown( + stringResource(R.string.retro_gs_crt_tv_shader), + listOf( + stringResource(R.string.retro_gs_off), + stringResource(R.string.retro_gs_tvshader_scanline), + stringResource(R.string.retro_gs_tvshader_diagonal), + stringResource(R.string.retro_gs_tvshader_triangular), + stringResource(R.string.retro_gs_tvshader_wave), + stringResource(R.string.retro_gs_tvshader_lottes), + stringResource(R.string.retro_gs_tvshader_4xrgss), + stringResource(R.string.retro_gs_tvshader_nxagss), + ), + prefs.getInt("wn.ps2.tvshader", 0).coerceIn(0, 7), + ) { putInt("wn.ps2.tvshader", it) } + RetroSettingDropdown( + stringResource(R.string.retro_gs_frame_skip), + listOf( + stringResource(R.string.retro_gs_off), + stringResource(R.string.retro_gs_frameskip_1), + stringResource(R.string.retro_gs_frameskip_2), + stringResource(R.string.retro_gs_frameskip_3), + ), + prefs.getInt("wn.ps2.frameskip", 0).coerceIn(0, 3), + ) { putInt("wn.ps2.frameskip", it) } + RetroSettingSwitch(stringResource(R.string.retro_gs_widescreen_patches), prefs.getBoolean("wn.ps2.widescreen", false)) { putBool("wn.ps2.widescreen", it) } + RetroSettingSwitch(stringResource(R.string.retro_gs_no_interlace_patches), prefs.getBoolean("wn.ps2.nointerlace", false)) { putBool("wn.ps2.nointerlace", it) } + } +} + +@Composable +private fun RetroPs2PerformanceSection() { + val context = androidx.compose.ui.platform.LocalContext.current + val prefs = remember(context) { context.getSharedPreferences("ARMSX2", android.content.Context.MODE_PRIVATE) } + var version by remember { androidx.compose.runtime.mutableIntStateOf(0) } + + @Suppress("UNUSED_EXPRESSION") version + + fun putInt(key: String, value: Int) { prefs.edit().putInt(key, value).apply(); version++ } + fun putBool(key: String, value: Boolean) { prefs.edit().putBoolean(key, value).apply(); version++ } + + RetroSettingGroup { + RetroGroupTitle(stringResource(R.string.retro_gs_group_performance)) + val rateValues = listOf(-3, -2, -1, 0, 1, 2, 3) + RetroSettingDropdown( + stringResource(R.string.retro_gs_ee_cycle_rate), + listOf( + stringResource(R.string.retro_gs_rate_50), + stringResource(R.string.retro_gs_rate_60), + stringResource(R.string.retro_gs_rate_75), + stringResource(R.string.retro_gs_rate_100_default), + stringResource(R.string.retro_gs_rate_130), + stringResource(R.string.retro_gs_rate_180), + stringResource(R.string.retro_gs_rate_300), + ), + rateValues.indexOf(prefs.getInt("wn.ps2.eeRate", 0).coerceIn(-3, 3)).coerceAtLeast(0), + ) { putInt("wn.ps2.eeRate", rateValues[it]) } + RetroSettingDropdown( + stringResource(R.string.retro_gs_ee_cycle_skip), + listOf( + stringResource(R.string.retro_gs_off), + stringResource(R.string.retro_gs_num_1), + stringResource(R.string.retro_gs_num_2), + stringResource(R.string.retro_gs_num_3), + ), + prefs.getInt("wn.ps2.eeSkip", 0).coerceIn(0, 3), + ) { putInt("wn.ps2.eeSkip", it) } + RetroSettingSwitch(stringResource(R.string.retro_gs_mtvu), prefs.getBoolean("wn.ps2.mtvu", true)) { putBool("wn.ps2.mtvu", it) } + RetroSettingSwitch(stringResource(R.string.retro_gs_instant_vu1), prefs.getBoolean("wn.ps2.instantVu1", true)) { putBool("wn.ps2.instantVu1", it) } + RetroSettingSwitch(stringResource(R.string.retro_gs_vu_flag_hack), prefs.getBoolean("wn.ps2.vuFlagHack", true)) { putBool("wn.ps2.vuFlagHack", it) } + RetroSettingSwitch(stringResource(R.string.retro_gs_intc_spin), prefs.getBoolean("wn.ps2.intc", true)) { putBool("wn.ps2.intc", it) } + RetroSettingSwitch(stringResource(R.string.retro_gs_wait_loop), prefs.getBoolean("wn.ps2.waitloop", true)) { putBool("wn.ps2.waitloop", it) } + RetroSettingSwitch(stringResource(R.string.retro_gs_fast_cdvd), prefs.getBoolean("wn.ps2.fastCdvd", false)) { putBool("wn.ps2.fastCdvd", it) } + } +} + +@Composable +private fun RetroPs2HudSection() { + val context = androidx.compose.ui.platform.LocalContext.current + var version by remember { androidx.compose.runtime.mutableIntStateOf(0) } + + @Suppress("UNUSED_EXPRESSION") version + + val hudOn = RetroHudSupport.resolvePs2HudEnabled(context) + val elements = remember(version) { RetroHudSupport.loadPs2Elements(context) } + + RetroSettingGroup { + RetroGroupTitle(stringResource(R.string.retro_gs_group_performance_hud)) + RetroSettingSwitch(stringResource(R.string.retro_lr_performance_hud), hudOn) { + RetroHudSupport.setPs2HudEnabled(context, it) + version++ + } + if (hudOn) { + RetroHudElementButtons(elements) { index, on -> + val next = elements.copyOf() + next[index] = on + RetroHudSupport.savePs2Elements(context, next) + version++ + } + } + } +} + +@Composable +private fun RetroNetplaySection(state: RetroSettingsState) { + val systemId = state.system?.id ?: return + var version by remember { androidx.compose.runtime.mutableIntStateOf(0) } + RetroNetplaySettingsSection( + systemId = systemId, + version = version, + onChanged = { version++ }, + ) +} + +@Composable +private fun RetroDolphinNetplaySection(state: RetroSettingsState) { + val systemId = state.system?.id ?: return + var version by remember { androidx.compose.runtime.mutableIntStateOf(0) } + DolphinNetplaySettingsSection( + systemId = systemId, + version = version, + onChanged = { version++ }, + ) +} + +@Composable +private fun RetroPs2OnlineSection(state: RetroSettingsState) { + val context = androidx.compose.ui.platform.LocalContext.current + val prefs = remember(context) { context.getSharedPreferences("ARMSX2", android.content.Context.MODE_PRIVATE) } + var version by remember { androidx.compose.runtime.mutableIntStateOf(0) } + + @Suppress("UNUSED_EXPRESSION") version + + fun putBool(key: String, value: Boolean) { prefs.edit().putBoolean(key, value).apply(); version++ } + fun putStr(key: String, value: String) { prefs.edit().putString(key, value).apply(); version++ } + + RetroSettingGroup { + RetroGroupTitle(stringResource(R.string.retro_gs_group_online_dev9)) + val onlineEnabled = prefs.getBoolean("wn.ps2.net.enable", true) + RetroSettingSwitch(stringResource(R.string.retro_gs_enable_online), onlineEnabled) { putBool("wn.ps2.net.enable", it) } + val hddImages = remember(version, state.hddRefresh) { RetroHddImport.installed(context).map { it.name } } + val hddOptions = listOf(stringResource(R.string.retro_scr_none)) + hddImages + val hddSelected = (hddImages.indexOf(state.hddImage) + 1).coerceAtLeast(0) + RetroSettingDropdown(stringResource(R.string.retro_gs_hdd_image), hddOptions, hddSelected) { idx -> + state.hddImage = if (idx <= 0) "" else hddImages[idx - 1] + version++ + } + remember(state.hddImage, state.hddRefresh) { RetroHddImport.imageFile(context, state.hddImage) }?.let { f -> + Text( + stringResource(R.string.retro_gs_hdd_image_size, humanSize(f.length())), + color = TextDim, + fontSize = LabelSize, + modifier = Modifier.padding(top = TightGap), + ) + } + Row( + modifier = Modifier.fillMaxWidth().padding(top = ItemGap), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + androidx.compose.material3.OutlinedButton( + onClick = { if (!state.hddImporting) state.requestImportHdd?.invoke() }, + enabled = !state.hddImporting, + contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 14.dp, vertical = 6.dp), + ) { + Text( + if (state.hddImporting) stringResource(R.string.retro_scr_importing) else stringResource(R.string.retro_scr_import_hdd_image), + fontSize = ValueSize, + ) + } + if (state.hddImage.isNotBlank()) { + androidx.compose.material3.OutlinedButton( + onClick = { + val name = state.hddImage + RetroHddImport.delete(context, name) + state.hddImage = "" + state.hddRefresh++ + version++ + }, + contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 14.dp, vertical = 6.dp), + colors = androidx.compose.material3.ButtonDefaults.outlinedButtonColors(contentColor = DangerRed), + ) { Text(stringResource(R.string.retro_gs_hdd_remove_short), fontSize = ValueSize) } + } + } + RetroSettingSwitch(stringResource(R.string.retro_ps2_hdd), state.hddEnable) { state.hddEnable = it; version++ } + Text( + stringResource(R.string.retro_ps2_hdd_desc), + color = TextDim, + fontSize = LabelSize, + modifier = Modifier.padding(top = TightGap), + ) + if (onlineEnabled) { + val deviceKeys = listOf("Auto", "Wi-Fi") + val deviceLabels = listOf( + stringResource(R.string.retro_gs_net_auto), + stringResource(R.string.retro_gs_net_wifi), + ) + RetroSettingDropdown( + stringResource(R.string.retro_gs_ethernet_device), deviceLabels, + deviceKeys.indexOf(prefs.getString("wn.ps2.net.ethdevice", "Auto")).coerceAtLeast(0), + ) { putStr("wn.ps2.net.ethdevice", deviceKeys[it]) } + val dnsModeKeys = listOf("Manual", "Auto", "Internal") + val dnsModeLabels = listOf( + stringResource(R.string.retro_gs_dns_manual), + stringResource(R.string.retro_gs_net_auto), + stringResource(R.string.retro_gs_dns_internal), + ) + RetroSettingDropdown( + stringResource(R.string.retro_gs_dns_mode), dnsModeLabels, + dnsModeKeys.indexOf(prefs.getString("wn.ps2.net.dnsmode", "Manual")).coerceAtLeast(0), + ) { putStr("wn.ps2.net.dnsmode", dnsModeKeys[it]) } + RetroSettingTextField(stringResource(R.string.retro_gs_primary_dns), prefs.getString("wn.ps2.net.dns1", PS2_DEFAULT_DNS).orEmpty(), PS2_DEFAULT_DNS) { putStr("wn.ps2.net.dns1", it) } + RetroSettingTextField(stringResource(R.string.retro_gs_secondary_dns), prefs.getString("wn.ps2.net.dns2", "").orEmpty(), stringResource(R.string.retro_gs_dns_optional)) { putStr("wn.ps2.net.dns2", it) } + RetroSettingSwitch(stringResource(R.string.retro_gs_dnas_bypass), prefs.getBoolean(Ps2DnasBypass.PREF, true), subtitle = stringResource(R.string.retro_gs_dnas_bypass_subtitle)) { putBool(Ps2DnasBypass.PREF, it) } + RetroSettingSwitch(stringResource(R.string.retro_gs_auto_ip_dhcp), prefs.getBoolean("wn.ps2.net.dhcp", true)) { putBool("wn.ps2.net.dhcp", it) } + } + } +} + +@Composable +private fun RetroPs2CheatsSection(state: RetroSettingsState) { + val context = androidx.compose.ui.platform.LocalContext.current + val serial = remember(state) { state.gameSerial } + + if (serial == null) { + RetroSettingGroup { + RetroGroupTitle(stringResource(R.string.retro_gs_group_cheats)) + Text( + stringResource(R.string.retro_gs_cheats_detect_hint), + color = TextSecondary, + fontSize = ValueSize, + modifier = Modifier.padding(vertical = TightGap), + ) + } + return + } + + var loading by remember { mutableStateOf(true) } + var cheats by remember { mutableStateOf>(emptyList()) } + var patches by remember { mutableStateOf>(emptyList()) } + var selCheats by remember { mutableStateOf>(emptySet()) } + var selPatches by remember { mutableStateOf>(emptySet()) } + var repoCheatNames by remember { mutableStateOf>(emptySet()) } + var repoPatchNames by remember { mutableStateOf>(emptySet()) } + var dnasEntries by remember { mutableStateOf>(emptyList()) } + var dnasGlobalOn by remember { mutableStateOf(true) } + var dnasDisabled by remember { mutableStateOf>(emptySet()) } + + LaunchedEffect(serial, state.cheatsRefresh) { + val stagedC = Ps2CheatStaging.read(context, serial, false) + val stagedP = Ps2CheatStaging.read(context, serial, true) + cheats = stagedC + patches = stagedP + selCheats = stagedC.map { it.name }.toSet() + selPatches = stagedP.map { it.name }.toSet() + dnasEntries = Ps2DnasBypass.bypassEntries(context, serial).filter { it.auto } + dnasGlobalOn = context.getSharedPreferences("ARMSX2", android.content.Context.MODE_PRIVATE).getBoolean(Ps2DnasBypass.PREF, true) + dnasDisabled = Ps2DnasBypass.ensureSingleDnasEnabled(context, serial, dnasEntries.map { it.name }.toSet()) + loading = false + val repo = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { + runCatching { com.armsx2.PatchRepo.fetchForSerial(serial) }.getOrNull() + } + if (repo != null) { + val repoCheats = repo.entries.filter { it.source != "patches" } + val repoPatches = repo.entries.filter { it.source == "patches" } + repoCheatNames = repoCheats.map { it.name }.toSet() + repoPatchNames = repoPatches.map { it.name }.toSet() + cheats = repoCheats + stagedC.filter { s -> repoCheats.none { it.name == s.name } } + patches = repoPatches + stagedP.filter { s -> repoPatches.none { it.name == s.name } } + } + } + + fun toggleDnas(name: String, currentlyOn: Boolean) { + if (currentlyOn) { + dnasDisabled = dnasDisabled + name + } else { + if (!dnasGlobalOn) { Ps2DnasBypass.setEnabled(context, true); dnasGlobalOn = true } + val all = dnasEntries.map { it.name }.toSet() + dnasDisabled = all - name + } + Ps2DnasBypass.setDisabledNames(context, serial, dnasDisabled) + } + + fun persist() { + Ps2CheatStaging.write(context, serial, false, serial, cheats.filter { it.name in selCheats }) + Ps2CheatStaging.write(context, serial, true, serial, patches.filter { it.name in selPatches }) + } + + var showAdd by remember { mutableStateOf(false) } + var newName by remember { mutableStateOf("") } + var newCodes by remember { mutableStateOf("") } + var newIsPatch by remember { mutableStateOf(false) } + + RetroSettingGroup { + RetroGroupTitle(stringResource(R.string.retro_gs_group_cheats)) + Text( + stringResource(R.string.retro_gs_cheats_apply_note), + color = TextDim, + fontSize = LabelSize, + modifier = Modifier.padding(bottom = TightGap), + ) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(bottom = ItemGap)) { + androidx.compose.material3.OutlinedButton( + onClick = { newName = ""; newCodes = ""; newIsPatch = false; showAdd = true }, + contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 14.dp, vertical = 6.dp), + ) { Text(stringResource(R.string.retro_scr_add), fontSize = ValueSize) } + androidx.compose.material3.OutlinedButton( + onClick = { state.requestImportCheatFile?.invoke(true) }, + contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 14.dp, vertical = 6.dp), + ) { Text(stringResource(R.string.retro_scr_import_from_file), fontSize = ValueSize) } + } + when { + loading -> Text(stringResource(R.string.retro_scr_loading), color = TextSecondary, fontSize = ValueSize) + cheats.isEmpty() && patches.isEmpty() && dnasEntries.isEmpty() -> + Text(stringResource(R.string.retro_scr_no_cheats_or_patches), color = TextSecondary, fontSize = ValueSize) + else -> Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + if (dnasEntries.isNotEmpty()) { + Ps2SectionHeader(stringResource(R.string.retro_gs_dnas_group)) + dnasEntries.forEach { e -> + val on = dnasGlobalOn && e.name !in dnasDisabled + Ps2CheatRow( + com.armsx2.PatchRepo.Entry(e.name, stringResource(R.string.retro_gs_dnas_entry_desc), e.body, "dnas"), + on, isPatch = true, + onToggle = { toggleDnas(e.name, on) }, + ) + } + } + if (cheats.isNotEmpty()) { + Ps2SectionHeader(stringResource(R.string.retro_scr_cheats_section)) + cheats.forEach { entry -> + val isCustom = entry.name !in repoCheatNames + Ps2CheatRow( + entry, entry.name in selCheats, isPatch = false, + onToggle = { + selCheats = if (entry.name in selCheats) selCheats - entry.name else selCheats + entry.name + persist() + }, + onDelete = if (isCustom) { + { + cheats = cheats.filterNot { it.name == entry.name } + selCheats = selCheats - entry.name + persist() + } + } else null, + ) + } + } + if (patches.isNotEmpty()) { + Ps2SectionHeader(stringResource(R.string.retro_scr_patches_section)) + patches.forEach { entry -> + val isCustom = entry.name !in repoPatchNames + Ps2CheatRow( + entry, entry.name in selPatches, isPatch = true, + onToggle = { + selPatches = if (entry.name in selPatches) selPatches - entry.name else selPatches + entry.name + persist() + }, + onDelete = if (isCustom) { + { + patches = patches.filterNot { it.name == entry.name } + selPatches = selPatches - entry.name + persist() + } + } else null, + ) + } + } + } + } + } + + if (showAdd) { + androidx.compose.material3.AlertDialog( + onDismissRequest = { showAdd = false }, + title = { Text(stringResource(R.string.retro_scr_add_cheat)) }, + text = { + Column { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) { + androidx.compose.material3.OutlinedButton( + onClick = { newIsPatch = false }, modifier = Modifier.weight(1f), + colors = if (!newIsPatch) + androidx.compose.material3.ButtonDefaults.buttonColors() + else androidx.compose.material3.ButtonDefaults.outlinedButtonColors(), + ) { Text(stringResource(R.string.retro_scr_target_cheat)) } + androidx.compose.material3.OutlinedButton( + onClick = { newIsPatch = true }, modifier = Modifier.weight(1f), + colors = if (newIsPatch) + androidx.compose.material3.ButtonDefaults.buttonColors() + else androidx.compose.material3.ButtonDefaults.outlinedButtonColors(), + ) { Text(stringResource(R.string.retro_scr_target_patch)) } + } + Spacer(Modifier.height(8.dp)) + androidx.compose.material3.OutlinedTextField( + value = newName, onValueChange = { newName = it }, + label = { Text(stringResource(R.string.retro_scr_cheat_name)) }, + singleLine = true, modifier = Modifier.fillMaxWidth(), + ) + Spacer(Modifier.height(8.dp)) + androidx.compose.material3.OutlinedTextField( + value = newCodes, onValueChange = { newCodes = it }, + label = { Text(stringResource(R.string.retro_scr_cheat_codes)) }, + placeholder = { Text("2021A268 00000000") }, + modifier = Modifier.fillMaxWidth(), minLines = 3, + ) + } + }, + confirmButton = { + androidx.compose.material3.TextButton(onClick = { + val entry = buildCustomPnachEntry(context, newName, newCodes, if (newIsPatch) "patches" else "custom") + if (entry != null) { + if (newIsPatch) { + patches = patches.filterNot { it.name == entry.name } + entry + selPatches = selPatches + entry.name + } else { + cheats = cheats.filterNot { it.name == entry.name } + entry + selCheats = selCheats + entry.name + } + persist() + showAdd = false + } + }) { Text(stringResource(R.string.retro_scr_add)) } + }, + dismissButton = { + androidx.compose.material3.TextButton(onClick = { showAdd = false }) { Text(stringResource(R.string.retro_scr_cancel)) } + }, + ) + } +} + +@Composable +private fun RetroInputSection(state: RetroSettingsState) { + val context = androidx.compose.ui.platform.LocalContext.current + val prefs = + remember(context) { + androidx.preference.PreferenceManager.getDefaultSharedPreferences(context) + } + var haptic by remember { mutableStateOf(prefs.getFloat("retro_haptic_strength", 0.4f)) } + val ps2 = state.system?.isExternal == true + val ps2Prefs = if (ps2) remember(context) { context.getSharedPreferences("ARMSX2", android.content.Context.MODE_PRIVATE) } else null + var ps2Ver by remember { androidx.compose.runtime.mutableIntStateOf(0) } + @Suppress("UNUSED_EXPRESSION") ps2Ver + RetroSettingGroup { + RetroGroupTitle(stringResource(R.string.retro_gs_group_input)) + if (ps2 && ps2Prefs != null) { + RetroSettingSwitch( + label = stringResource(R.string.retro_gs_on_screen_controls), + checked = ps2Prefs.getBoolean("wn.ps2.touchcontrols", true), + onCheckedChange = { ps2Prefs.edit().putBoolean("wn.ps2.touchcontrols", it).apply(); ps2Ver++ }, + ) + RetroSettingSwitch( + label = stringResource(R.string.retro_gs_adaptive_sticks), + checked = ps2Prefs.getBoolean("wn.ps2.adaptivesticks", false), + subtitle = stringResource(R.string.retro_gs_adaptive_sticks_subtitle), + onCheckedChange = { ps2Prefs.edit().putBoolean("wn.ps2.adaptivesticks", it).apply(); ps2Ver++ }, + ) + RetroSettingSwitch( + label = stringResource(R.string.retro_ps2_show_l3r3), + checked = ps2Prefs.getBoolean("wn.ps2.showl3r3", true), + subtitle = stringResource(R.string.retro_ps2_show_l3r3_subtitle), + onCheckedChange = { ps2Prefs.edit().putBoolean("wn.ps2.showl3r3", it).apply(); ps2Ver++ }, + ) + } else { + RetroSettingSwitch( + label = stringResource(R.string.retro_gs_on_screen_controls), + checked = state.touchControls, + onCheckedChange = { state.touchControls = it }, + ) + RetroSettingSwitch( + label = stringResource(R.string.retro_gs_adaptive_sticks), + checked = state.adaptiveSticks, + subtitle = stringResource(R.string.retro_gs_adaptive_sticks_subtitle), + onCheckedChange = { state.adaptiveSticks = it }, + ) + val sysId = state.system?.id + if (sysId == RetroSystems.PSX.id || RetroCoreManager.usesDolphinCore(state.system)) { + var invVer by remember { androidx.compose.runtime.mutableIntStateOf(0) } + @Suppress("UNUSED_EXPRESSION") invVer + listOf( + R.string.retro_lr_left_stick_invert_x to "retro_inv_lx_$sysId", + R.string.retro_lr_left_stick_invert_y to "retro_inv_ly_$sysId", + R.string.retro_lr_right_stick_invert_x to "retro_inv_rx_$sysId", + R.string.retro_lr_right_stick_invert_y to "retro_inv_ry_$sysId", + ).forEach { (labelRes, key) -> + RetroSettingSwitch( + label = stringResource(labelRes), + checked = prefs.getBoolean(key, false), + onCheckedChange = { prefs.edit().putBoolean(key, it).apply(); invVer++ }, + ) + } + } + } + Row( + modifier = Modifier.fillMaxWidth().padding(vertical = TightGap), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + stringResource(R.string.retro_gs_haptic_feedback), + color = TextPrimary, + fontSize = ValueSize, + modifier = Modifier.weight(1f), + ) + Text( + "${(haptic * 100).toInt()}%", + color = TextSecondary, + fontSize = ValueSize, + ) + } + androidx.compose.material3.Slider( + value = haptic, + onValueChange = { value -> + haptic = value + prefs.edit().putFloat("retro_haptic_strength", value).apply() + }, + valueRange = 0f..1f, + modifier = Modifier.fillMaxWidth().height(26.dp), + ) + } +} + +@Composable +private fun RetroAudioSection(state: RetroSettingsState) { + if (state.system?.isExternal == true) { + val context = androidx.compose.ui.platform.LocalContext.current + val prefs = remember(context) { context.getSharedPreferences("ARMSX2", android.content.Context.MODE_PRIVATE) } + var version by remember { androidx.compose.runtime.mutableIntStateOf(0) } + @Suppress("UNUSED_EXPRESSION") version + var vol by remember { mutableStateOf(prefs.getInt("wn.ps2.volume", 100)) } + RetroSettingGroup { + RetroGroupTitle(stringResource(R.string.retro_gs_group_audio)) + Row( + modifier = Modifier.fillMaxWidth().padding(vertical = TightGap), + verticalAlignment = Alignment.CenterVertically, + ) { + Text(stringResource(R.string.retro_gs_volume), color = TextPrimary, fontSize = ValueSize, modifier = Modifier.weight(1f)) + Text("$vol%", color = TextSecondary, fontSize = ValueSize) + } + androidx.compose.material3.Slider( + value = vol.toFloat(), + onValueChange = { vol = it.toInt() }, + onValueChangeFinished = { prefs.edit().putInt("wn.ps2.volume", vol).apply() }, + valueRange = 0f..200f, + modifier = Modifier.fillMaxWidth().height(26.dp), + ) + RetroSettingSwitch(stringResource(R.string.retro_gs_mute), prefs.getBoolean("wn.ps2.muted", false)) { + prefs.edit().putBoolean("wn.ps2.muted", it).apply(); version++ + } + RetroSettingSwitch(stringResource(R.string.retro_gs_time_stretch), prefs.getBoolean("wn.ps2.timestretch", true)) { + prefs.edit().putBoolean("wn.ps2.timestretch", it).apply(); version++ + } + val bufferValues = listOf(40, 50, 60, 80, 100, 120, 160, 200) + RetroSettingDropdown( + stringResource(R.string.retro_gs_audio_buffer), + bufferValues.map { context.getString(R.string.retro_gs_ms, it) }, + bufferValues.indexOf(prefs.getInt("wn.ps2.audiobuffer", 50)).coerceAtLeast(0), + ) { + prefs.edit().putInt("wn.ps2.audiobuffer", bufferValues[it]).apply(); version++ + } + val latencyValues = listOf(10, 15, 20, 30, 40, 60, 80, 100) + RetroSettingDropdown( + stringResource(R.string.retro_gs_audio_latency), + latencyValues.map { context.getString(R.string.retro_gs_ms, it) }, + latencyValues.indexOf(prefs.getInt("wn.ps2.audiolatency", 20)).coerceAtLeast(0), + ) { + prefs.edit().putInt("wn.ps2.audiolatency", latencyValues[it]).apply(); version++ + } + RetroSettingSwitch(stringResource(R.string.retro_gs_swap_stereo), prefs.getBoolean("wn.ps2.swap", false)) { + prefs.edit().putBoolean("wn.ps2.swap", it).apply(); version++ + } + } + return + } + RetroSettingGroup { + RetroGroupTitle(stringResource(R.string.retro_gs_group_audio)) + RetroSettingSwitch( + label = stringResource(R.string.retro_gs_sound), + checked = state.audio, + onCheckedChange = { state.audio = it }, + ) + } +} diff --git a/app/src/main/feature/retro/RetroHddImport.kt b/app/src/main/feature/retro/RetroHddImport.kt new file mode 100644 index 000000000..227df33dd --- /dev/null +++ b/app/src/main/feature/retro/RetroHddImport.kt @@ -0,0 +1,64 @@ +package com.winlator.cmod.feature.retro + +import android.content.Context +import android.net.Uri +import java.io.File +import java.util.zip.ZipInputStream + +object RetroHddImport { + const val BLANK_IMAGE = "DEV9hdd.raw" + + fun hddDir(context: Context): File = + File(context.getExternalFilesDir(null) ?: context.filesDir, "hdd").apply { mkdirs() } + + fun installed(context: Context): List = + hddDir(context).listFiles().orEmpty() + .filter { it.isFile && it.extension.equals("raw", true) && it.name != BLANK_IMAGE } + .sortedBy { it.name.lowercase() } + + fun imageFile(context: Context, name: String?): File? { + if (name.isNullOrBlank()) return null + val f = File(hddDir(context), name) + return f.takeIf { it.isFile } + } + + fun delete(context: Context, name: String): Boolean = + File(hddDir(context), name).let { it.isFile && it.delete() } + + private fun displayName(context: Context, uri: Uri): String? = + runCatching { + context.contentResolver.query(uri, arrayOf(android.provider.OpenableColumns.DISPLAY_NAME), null, null, null)?.use { + if (it.moveToFirst()) it.getString(0) else null + } + }.getOrNull() + + fun importFromUri(context: Context, uri: Uri): Result = + runCatching { + val name = displayName(context, uri) ?: "hdd.raw" + val dir = hddDir(context) + if (name.endsWith(".zip", ignoreCase = true)) { + var extracted: String? = null + context.contentResolver.openInputStream(uri)?.use { input -> + ZipInputStream(input.buffered()).use { zin -> + var entry = zin.nextEntry + while (entry != null && extracted == null) { + val entryName = entry.name.substringAfterLast('/') + if (!entry.isDirectory && entryName.endsWith(".raw", ignoreCase = true)) { + File(dir, entryName).outputStream().buffered().use { out -> zin.copyTo(out, 1 shl 20) } + extracted = entryName + } + zin.closeEntry() + entry = zin.nextEntry + } + } + } ?: throw IllegalStateException("Could not read file") + extracted ?: throw IllegalArgumentException("No .raw HDD image found inside the ZIP") + } else { + val outName = if (name.endsWith(".raw", ignoreCase = true)) name else "$name.raw" + context.contentResolver.openInputStream(uri)?.use { input -> + File(dir, outName).outputStream().buffered().use { out -> input.copyTo(out, 1 shl 20) } + } ?: throw IllegalStateException("Could not read file") + outName + } + } +} diff --git a/app/src/main/feature/retro/RetroHudSupport.kt b/app/src/main/feature/retro/RetroHudSupport.kt new file mode 100644 index 000000000..3f844eddd --- /dev/null +++ b/app/src/main/feature/retro/RetroHudSupport.kt @@ -0,0 +1,459 @@ +package com.winlator.cmod.feature.retro + +import android.content.Context +import android.os.Handler +import android.os.Looper +import android.os.SystemClock +import android.view.View +import android.view.ViewGroup +import android.widget.FrameLayout +import androidx.preference.PreferenceManager +import com.winlator.cmod.R +import com.winlator.cmod.runtime.display.ui.FrameRating +import java.util.HashMap + +object RetroHudSupport { + const val HUD_ELEVATION = 2500f + + val ELEMENT_LABEL_RES = + intArrayOf( + R.string.retro_lr_hud_fps, + R.string.retro_lr_hud_console, + R.string.retro_lr_hud_gpu, + R.string.retro_lr_hud_cpu, + R.string.retro_lr_hud_ram, + R.string.retro_lr_hud_battery, + R.string.retro_lr_hud_temp, + R.string.retro_lr_hud_graph, + R.string.retro_lr_hud_cpu_temp, + ) + + val ELEMENT_ORDER = intArrayOf(1, 2, 3, 8, 4, 5, 6, 0, 7) + + const val PS2_HUD_PREF = "wn.ps2.hud" + private const val PS2_ELEMENTS_PREF = "wn.ps2.hud.elements" + private const val PS2_ALPHA_PREF = "wn.ps2.hud.alpha" + private const val PS2_BG_DECOUPLED_PREF = "wn.ps2.hud.bg_decoupled" + private const val PS2_BG_ALPHA_PREF = "wn.ps2.hud.bg_alpha" + private const val PS2_SCALE_PREF = "wn.ps2.hud.scale" + + fun defaultElements(): BooleanArray = booleanArrayOf(true, true, true, true, true, true, true, true, false) + + fun ps2Prefs(context: Context) = + context.getSharedPreferences("ARMSX2", Context.MODE_PRIVATE) + + fun resolvePs2HudEnabled(context: Context): Boolean { + val prefs = ps2Prefs(context) + if (prefs.contains(PS2_HUD_PREF)) { + return prefs.getBoolean(PS2_HUD_PREF, false) + } + val legacy = + listOf("fps", "speed", "res", "cpu", "gpu", "frametimes", "gsstats", "inputs", "hwinfo", "version") + .any { prefs.getBoolean("wn.osd.$it", false) } + if (legacy) { + prefs.edit().putBoolean(PS2_HUD_PREF, true).apply() + return true + } + return RetroDefaults.hud(context, RetroSystems.PS2.id) + } + + fun setPs2HudEnabled(context: Context, enabled: Boolean) { + ps2Prefs(context).edit().putBoolean(PS2_HUD_PREF, enabled).apply() + } + + fun loadPs2Elements(context: Context): BooleanArray { + val prefs = ps2Prefs(context) + val raw = prefs.getString(PS2_ELEMENTS_PREF, null) + if (!raw.isNullOrBlank()) { + val parts = raw.split(',') + val out = defaultElements() + for (i in out.indices) { + if (i < parts.size) out[i] = parts[i] == "1" || parts[i].equals("true", true) + } + return out + } + if (listOf("fps", "cpu", "gpu", "frametimes").any { prefs.contains("wn.osd.$it") }) { + val out = defaultElements() + out[0] = prefs.getBoolean("wn.osd.fps", true) + out[2] = prefs.getBoolean("wn.osd.gpu", true) + out[3] = prefs.getBoolean("wn.osd.cpu", true) + out[7] = prefs.getBoolean("wn.osd.frametimes", true) + savePs2Elements(context, out) + return out + } + return defaultElements() + } + + fun savePs2Elements(context: Context, elements: BooleanArray) { + val raw = elements.joinToString(",") { if (it) "1" else "0" } + ps2Prefs(context).edit().putString(PS2_ELEMENTS_PREF, raw).apply() + } + + fun loadPs2HudStyle(context: Context): HudStyle { + val prefs = ps2Prefs(context) + val pm = PreferenceManager.getDefaultSharedPreferences(context) + val alpha = prefs.getFloat(PS2_ALPHA_PREF, pm.getFloat(FrameRating.PREF_HUD_ALPHA, 1f)) + val scale = prefs.getFloat(PS2_SCALE_PREF, pm.getFloat(FrameRating.PREF_HUD_SCALE, 1f)) + val bgDecoupled = prefs.getBoolean(PS2_BG_DECOUPLED_PREF, false) + val bgAlpha = + prefs.getFloat( + PS2_BG_ALPHA_PREF, + (alpha * FrameRating.BACKDROP_BASE_ALPHA).coerceIn(0.1f, 1f), + ) + val frametimeNumeric = pm.getBoolean(FrameRating.PREF_HUD_FRAMETIME_NUMERIC, false) + val dualBattery = pm.getBoolean(FrameRating.PREF_HUD_DUAL_SERIES_BATTERY, false) + return HudStyle(alpha, bgDecoupled, bgAlpha, scale, frametimeNumeric, dualBattery) + } + + fun savePs2HudStyle(context: Context, style: HudStyle) { + ps2Prefs(context) + .edit() + .putFloat(PS2_ALPHA_PREF, style.alpha) + .putBoolean(PS2_BG_DECOUPLED_PREF, style.bgDecoupled) + .putFloat(PS2_BG_ALPHA_PREF, style.bgAlpha) + .putFloat(PS2_SCALE_PREF, style.scale) + .apply() + PreferenceManager + .getDefaultSharedPreferences(context) + .edit() + .putBoolean(FrameRating.PREF_HUD_FRAMETIME_NUMERIC, style.frametimeNumeric) + .putBoolean(FrameRating.PREF_HUD_DUAL_SERIES_BATTERY, style.dualBattery) + .apply() + } + + fun applyStyle( + rating: FrameRating, + style: HudStyle, + elements: BooleanArray, + ) { + rating.setHudAlpha(style.alpha) + rating.setBackgroundAlphaDecoupled(style.bgDecoupled) + rating.setHudBackgroundAlpha(style.bgAlpha) + rating.setHudScale(style.scale) + rating.setFrametimeNumericMode(style.frametimeNumeric) + rating.setDualSeriesBattery(style.dualBattery) + elements.forEachIndexed { index, enabled -> rating.toggleElement(index, enabled) } + } + + fun loadGlobalHudElements(context: Context): BooleanArray { + val prefs = androidx.preference.PreferenceManager.getDefaultSharedPreferences(context) + val csv = prefs.getString("retro_hud_elements", null) ?: return defaultElements() + val parts = csv.split(',') + val defaults = defaultElements() + return BooleanArray(defaults.size) { i -> parts.getOrNull(i)?.toBoolean() ?: defaults[i] } + } + + fun saveGlobalHudElements(context: Context, elements: BooleanArray) { + androidx.preference.PreferenceManager + .getDefaultSharedPreferences(context) + .edit() + .putString("retro_hud_elements", elements.joinToString(",")) + .apply() + } + + fun loadGlobalHudStyle(context: Context): HudStyle { + val prefs = androidx.preference.PreferenceManager.getDefaultSharedPreferences(context) + return HudStyle( + alpha = prefs.getFloat("retro_hud_alpha", 1f), + bgDecoupled = prefs.getBoolean("retro_hud_bg_decoupled", false), + bgAlpha = prefs.getFloat("retro_hud_bg_alpha", FrameRating.BACKDROP_BASE_ALPHA), + scale = prefs.getFloat("retro_hud_scale", 1f), + frametimeNumeric = prefs.getBoolean(FrameRating.PREF_HUD_FRAMETIME_NUMERIC, false), + dualBattery = prefs.getBoolean(FrameRating.PREF_HUD_DUAL_SERIES_BATTERY, false), + ) + } + + fun saveGlobalHudStyle(context: Context, style: HudStyle) { + androidx.preference.PreferenceManager + .getDefaultSharedPreferences(context) + .edit() + .putFloat("retro_hud_alpha", style.alpha) + .putBoolean("retro_hud_bg_decoupled", style.bgDecoupled) + .putFloat("retro_hud_bg_alpha", style.bgAlpha) + .putFloat("retro_hud_scale", style.scale) + .putBoolean(FrameRating.PREF_HUD_FRAMETIME_NUMERIC, style.frametimeNumeric) + .putBoolean(FrameRating.PREF_HUD_DUAL_SERIES_BATTERY, style.dualBattery) + .apply() + } + + fun loadContainerHudSettings( + context: Context, + containerId: Int, + ): Pair? { + if (containerId <= 0) return null + return runCatching { + val json = + com.winlator.cmod.runtime.container.ContainerManager(context) + .getContainerById(containerId) + ?.getExtra("hudSettings") + if (json.isNullOrEmpty()) return null + val obj = org.json.JSONObject(json) + val transparency = obj.optDouble("transparency", 1.0).toFloat() + val style = + HudStyle( + alpha = transparency, + bgDecoupled = obj.optBoolean("backgroundAlphaDecoupled", false), + bgAlpha = + obj + .optDouble( + "backgroundTransparency", + (transparency * FrameRating.BACKDROP_BASE_ALPHA).toDouble(), + ).toFloat(), + scale = obj.optDouble("scale", 1.0).toFloat(), + ) + val legacyCpuRam = obj.optBoolean("showCpuRam", true) + val legacyBattTemp = obj.optBoolean("showBattTemp", true) + val elements = + booleanArrayOf( + obj.optBoolean("showFPS", true), + obj.optBoolean("showRenderer", true), + obj.optBoolean("showGPU", true), + obj.optBoolean("showCPU", legacyCpuRam), + obj.optBoolean("showRAM", legacyCpuRam), + obj.optBoolean("showBattery", legacyBattTemp), + obj.optBoolean("showTemp", legacyBattTemp), + obj.optBoolean("showGraph", true), + obj.optBoolean("showCpuTemp", false), + ) + style to elements + }.getOrNull() + } + + fun saveContainerHudSettings( + context: Context, + containerId: Int, + style: HudStyle, + elements: BooleanArray, + ) { + if (containerId <= 0) return + runCatching { + val container = + com.winlator.cmod.runtime.container.ContainerManager(context) + .getContainerById(containerId) ?: return + val obj = org.json.JSONObject() + obj.put("transparency", style.alpha.toDouble()) + obj.put("backgroundAlphaDecoupled", style.bgDecoupled) + obj.put("backgroundTransparency", style.bgAlpha.toDouble()) + obj.put("scale", style.scale.toDouble()) + obj.put("showFPS", elements.getOrElse(0) { true }) + obj.put("showRenderer", elements.getOrElse(1) { true }) + obj.put("showGPU", elements.getOrElse(2) { true }) + obj.put("showCPU", elements.getOrElse(3) { true }) + obj.put("showRAM", elements.getOrElse(4) { true }) + obj.put("showBattery", elements.getOrElse(5) { true }) + obj.put("showTemp", elements.getOrElse(6) { true }) + obj.put("showGraph", elements.getOrElse(7) { true }) + obj.put("showCpuTemp", elements.getOrElse(8) { false }) + container.putExtra("hudSettings", obj.toString()) + container.saveData() + } + } + + fun libretroRendererLabel(): String = "OpenGL" + + fun createFrameRating( + context: Context, + rendererLabel: String, + ): FrameRating { + val rating = FrameRating(context, HashMap()) + rating.setRenderer(rendererLabel) + rating.setHudElevation(HUD_ELEVATION) + rating.visibility = View.GONE + return rating + } + + fun attachFrameRating( + parent: ViewGroup, + rating: FrameRating, + below: View? = null, + ) { + if (rating.parent != null) return + val lp = + FrameLayout.LayoutParams( + FrameLayout.LayoutParams.WRAP_CONTENT, + FrameLayout.LayoutParams.WRAP_CONTENT, + ) + val index = below?.let { parent.indexOfChild(it) } ?: -1 + if (index >= 0) parent.addView(rating, index, lp) else parent.addView(rating, lp) + } + + fun buildHudEntries( + context: Context, + hudVisible: Boolean, + style: HudStyle, + elements: BooleanArray, + onMaster: (Boolean) -> Unit, + onStyle: (HudStyle) -> Unit, + onElements: (BooleanArray) -> Unit, + onRebuild: () -> Unit, + ): List { + val entries = mutableListOf() + entries += + RetroMenuEntry.Toggle(context.getString(R.string.retro_lr_performance_hud), checked = hudVisible) { value -> + onMaster(value) + onRebuild() + } + if (!hudVisible) return entries + entries += + RetroMenuEntry.Slider( + label = context.getString(R.string.retro_lr_alpha), + valueText = "${(style.alpha * 100).toInt()}%", + value = style.alpha, + min = 0.1f, + max = 1f, + step = 0.05f, + ) { value -> + val next = + if (!style.bgDecoupled) { + style.copy( + alpha = value, + bgAlpha = (value * FrameRating.BACKDROP_BASE_ALPHA).coerceIn(0.1f, 1f), + ) + } else { + style.copy(alpha = value) + } + onStyle(next) + onRebuild() + } + entries += + RetroMenuEntry.Toggle(context.getString(R.string.retro_lr_background_alpha), checked = style.bgDecoupled) { value -> + val next = + if (!value) { + style.copy( + bgDecoupled = false, + bgAlpha = (style.alpha * FrameRating.BACKDROP_BASE_ALPHA).coerceIn(0.1f, 1f), + ) + } else { + style.copy(bgDecoupled = true) + } + onStyle(next) + onRebuild() + } + if (style.bgDecoupled) { + entries += + RetroMenuEntry.Slider( + label = context.getString(R.string.retro_lr_background), + valueText = "${(style.bgAlpha * 100).toInt()}%", + value = style.bgAlpha, + min = 0.1f, + max = 1f, + step = 0.05f, + ) { value -> + onStyle(style.copy(bgAlpha = value)) + onRebuild() + } + } + entries += + RetroMenuEntry.Slider( + label = context.getString(R.string.retro_lr_scale), + valueText = "${(style.scale * 100).toInt()}%", + value = style.scale, + min = 0.3f, + max = 2f, + step = 0.05f, + ) { value -> + onStyle(style.copy(scale = value)) + onRebuild() + } + entries += + RetroMenuEntry.Toggle(context.getString(R.string.retro_lr_numeric_frametime), checked = style.frametimeNumeric) { value -> + onStyle(style.copy(frametimeNumeric = value)) + onRebuild() + } + entries += + RetroMenuEntry.Toggle(context.getString(R.string.retro_lr_dual_series_battery), checked = style.dualBattery) { value -> + onStyle(style.copy(dualBattery = value)) + onRebuild() + } + entries += + RetroMenuEntry.Chips( + label = context.getString(R.string.retro_lr_hud_elements), + items = ELEMENT_ORDER.map { context.getString(ELEMENT_LABEL_RES[it]) }, + states = ELEMENT_ORDER.map { elements[it] }, + ) { position -> + val index = ELEMENT_ORDER[position] + val next = elements.copyOf() + next[index] = !next[index] + onElements(next) + onRebuild() + } + return entries + } + + fun suppressNativePs2Osd() { + runCatching { + kr.co.iefriends.pcsx2.NativeApp.osdShowFPS(false) + kr.co.iefriends.pcsx2.NativeApp.osdShowVPS(false) + kr.co.iefriends.pcsx2.NativeApp.osdShowSpeed(false) + kr.co.iefriends.pcsx2.NativeApp.osdShowCPU(false) + kr.co.iefriends.pcsx2.NativeApp.osdShowGPU(false) + kr.co.iefriends.pcsx2.NativeApp.osdShowResolution(false) + kr.co.iefriends.pcsx2.NativeApp.osdShowGSStats(false) + kr.co.iefriends.pcsx2.NativeApp.osdShowFrameTimes(false) + kr.co.iefriends.pcsx2.NativeApp.osdShowHardwareInfo(false) + kr.co.iefriends.pcsx2.NativeApp.osdShowVersion(false) + kr.co.iefriends.pcsx2.NativeApp.osdShowSettings(false) + kr.co.iefriends.pcsx2.NativeApp.osdShowInputs(false) + kr.co.iefriends.pcsx2.NativeApp.osdShowGpuStats(false) + } + } + + class Ps2FrameSource( + private val ratingProvider: () -> FrameRating?, + private val enabledProvider: () -> Boolean, + ) { + private val handler = Handler(Looper.getMainLooper()) + private var lastCount = -1 + private var running = false + private val tick = + object : Runnable { + override fun run() { + if (!running) return + val rating = ratingProvider() + if (enabledProvider() && rating != null && + com.armsx2.runtime.MainActivityRuntime.isNativeReady() + ) { + val count = runCatching { kr.co.iefriends.pcsx2.NativeApp.getPresentedFrameCount() }.getOrDefault(0) + if (lastCount >= 0 && count >= lastCount) { + val delta = (count - lastCount).coerceAtMost(8) + repeat(delta) { rating.recordGameFrame() } + } + lastCount = count + } + handler.postDelayed(this, 16L) + } + } + + fun start() { + if (running) return + running = true + lastCount = -1 + handler.post(tick) + } + + fun stop() { + running = false + handler.removeCallbacks(tick) + } + } + + class MenuToggleGate(private val minIntervalMs: Long = 350L) { + private var lastToggleMs = 0L + + fun allow(): Boolean { + val now = SystemClock.uptimeMillis() + if (now - lastToggleMs < minIntervalMs) return false + lastToggleMs = now + return true + } + } +} + +data class HudStyle( + val alpha: Float = 1f, + val bgDecoupled: Boolean = false, + val bgAlpha: Float = FrameRating.BACKDROP_BASE_ALPHA, + val scale: Float = 1f, + val frametimeNumeric: Boolean = false, + val dualBattery: Boolean = false, +) diff --git a/app/src/main/feature/retro/RetroInputView.kt b/app/src/main/feature/retro/RetroInputView.kt new file mode 100644 index 000000000..434cc2c62 --- /dev/null +++ b/app/src/main/feature/retro/RetroInputView.kt @@ -0,0 +1,2517 @@ +package com.winlator.cmod.feature.retro + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.DashPathEffect +import android.graphics.LinearGradient +import android.graphics.Paint +import android.graphics.Path +import android.graphics.RadialGradient +import android.graphics.RectF +import android.graphics.Shader +import android.os.VibrationEffect +import android.os.Vibrator +import android.view.KeyEvent +import android.view.MotionEvent +import android.view.View +import com.winlator.cmod.runtime.input.controls.GameHubLayout +import kotlin.math.hypot +import kotlin.math.max +import kotlin.math.min + +class RetroInputView( + context: Context, + private val listener: Listener, + private val system: RetroSystem? = null, +) : View(context) { + interface Listener { + fun onButton( + keyCode: Int, + down: Boolean, + ) + + fun onDpad( + x: Float, + y: Float, + ) + + fun onStick( + x: Float, + y: Float, + ) + + fun onRightStick( + x: Float, + y: Float, + ) + + fun onMenu() + } + + private enum class GlassShape { CIRCLE, PILL, TRIGGER_LT, TRIGGER_LB, TRIGGER_RT, TRIGGER_RB } + + private class GlassButton( + val keyCode: Int, + val label: String, + val shape: GlassShape, + val textScale: Float = 1f, + val bounds: RectF = RectF(), + ) + + private class CButton( + val dx: Float, + val dy: Float, + val glyph: String, + val bounds: RectF = RectF(), + ) + + private data class OverlayConfig( + val hasXY: Boolean, + val hasShoulders: Boolean, + val hasTriggers: Boolean, + val hasStick: Boolean, + val leftTriggerLabel: String = "L2", + val rightTriggerLabel: String = "R2", + val leftShoulderLabel: String = "L", + val rightShoulderLabel: String = "R", + val showLeftShoulder: Boolean = true, + val showRightTrigger: Boolean = true, + val flatFaces: Boolean = false, + val hasDualSticks: Boolean = false, + val faceTop: String = "X", + val faceBottom: String = "B", + val faceLeft: String = "Y", + val faceRight: String = "A", + ) + + private val config = + when (system?.id) { + RetroSystems.NES.id -> + OverlayConfig( + hasXY = false, + hasShoulders = false, + hasTriggers = false, + hasStick = false, + flatFaces = true, + ) + RetroSystems.SNES.id -> OverlayConfig(hasXY = true, hasShoulders = true, hasTriggers = false, hasStick = false) + RetroSystems.GBA.id -> OverlayConfig(hasXY = false, hasShoulders = true, hasTriggers = false, hasStick = false) + RetroSystems.GENESIS.id -> OverlayConfig(hasXY = true, hasShoulders = true, hasTriggers = false, hasStick = false) + RetroSystems.N64.id -> + OverlayConfig( + hasXY = false, + hasShoulders = true, + hasTriggers = true, + hasStick = true, + leftTriggerLabel = "Z", + showRightTrigger = false, + ) + RetroSystems.GAMECUBE.id -> + OverlayConfig( + hasXY = true, + hasShoulders = true, + hasTriggers = true, + hasStick = false, + hasDualSticks = true, + leftTriggerLabel = "L", + rightTriggerLabel = "R", + leftShoulderLabel = "Z", + rightShoulderLabel = "Z", + showLeftShoulder = false, + faceTop = "X", + faceBottom = "B", + faceLeft = "Y", + faceRight = "A", + ) + RetroSystems.WII.id -> + OverlayConfig( + hasXY = true, + hasShoulders = true, + hasTriggers = true, + hasStick = false, + hasDualSticks = true, + leftTriggerLabel = "ZL", + rightTriggerLabel = "ZR", + leftShoulderLabel = "L", + rightShoulderLabel = "R", + faceTop = "X", + faceBottom = "B", + faceLeft = "Y", + faceRight = "A", + ) + RetroSystems.PS2.id -> + OverlayConfig( + hasXY = true, + hasShoulders = true, + hasTriggers = true, + hasStick = false, + hasDualSticks = true, + faceTop = "\u25b3", + faceBottom = "\u2715", + faceLeft = "\u25a1", + faceRight = "\u25cb", + ) + RetroSystems.PSX.id -> + OverlayConfig( + hasXY = true, + hasShoulders = true, + hasTriggers = true, + hasStick = false, + faceTop = "△", + faceBottom = "✕", + faceLeft = "□", + faceRight = "○", + ) + else -> OverlayConfig(hasXY = false, hasShoulders = false, hasTriggers = false, hasStick = false) + } + + private fun faceGlyphScale(label: String): Float = + when (label) { + "\u25cb" -> 1.85f + "\u25b3" -> 1.55f + "\u25a1" -> 1.45f + "\u2715" -> 1f + else -> 1f + } + + private val buttons = mutableListOf() + private val cButtons = mutableListOf() + private val menuButton = GlassButton(0, "MENU", GlassShape.PILL, textScale = 0.75f) + private var snap = 0f + private var cStickX = 0f + private var cStickY = 0f + + private class RetroTheme( + val body: Int, + val dpad: Int, + val pill: Int, + val pillText: Int, + val button: Int, + val buttonText: Int, + val buttonColors: Map = emptyMap(), + val buttonTextColors: Map = emptyMap(), + val backplate: Int = 0, + val clusterPlate: Int = 0, + val stickCap: Int = 0xFFB4B4BA.toInt(), + val cButton: Int = 0xFFE3BE2A.toInt(), + val cText: Int = 0xFF4A3B08.toInt(), + ) + + private val theme: RetroTheme = + when (system?.id) { + RetroSystems.NES.id -> + RetroTheme( + body = 0xFFD8D5CD.toInt(), + dpad = 0xFF26262A.toInt(), + pill = 0xFF303034.toInt(), + pillText = 0xFFD8D5CD.toInt(), + button = 0xFFC03A30.toInt(), + buttonText = 0xFFF6EAE8.toInt(), + backplate = 0xFFEDEBE6.toInt(), + ) + RetroSystems.SNES.id -> + RetroTheme( + body = 0xFFCBCBD3.toInt(), + dpad = 0xFF3E3E46.toInt(), + pill = 0xFF8F8F98.toInt(), + pillText = 0xFF2F2F36.toInt(), + button = 0xFF564A9E.toInt(), + buttonText = 0xFFEDEBFA.toInt(), + buttonColors = + mapOf( + "X" to 0xFFBCB6DF.toInt(), + "Y" to 0xFFBCB6DF.toInt(), + ), + buttonTextColors = + mapOf( + "X" to 0xFF423D66.toInt(), + "Y" to 0xFF423D66.toInt(), + ), + clusterPlate = 0xFFB2B1BB.toInt(), + ) + RetroSystems.GAMEBOY.id -> + RetroTheme( + body = 0xFFC9C6C1.toInt(), + dpad = 0xFF2E2E33.toInt(), + pill = 0xFF8A8A86.toInt(), + pillText = 0xFF33333A.toInt(), + button = 0xFF8E3162.toInt(), + buttonText = 0xFFF2DEE8.toInt(), + ) + RetroSystems.GAMEBOY_COLOR.id -> + RetroTheme( + body = 0xFF5F45AC.toInt(), + dpad = 0xFF26262B.toInt(), + pill = 0xFF453D78.toInt(), + pillText = 0xFFD9D3F2.toInt(), + button = 0xFF37305E.toInt(), + buttonText = 0xFFCFC8EE.toInt(), + ) + RetroSystems.GBA.id -> + RetroTheme( + body = 0xFF7C74C6.toInt(), + dpad = 0xFF33333A.toInt(), + pill = 0xFF9C96CC.toInt(), + pillText = 0xFF3C3866.toInt(), + button = 0xFFD3CFEA.toInt(), + buttonText = 0xFF4A4670.toInt(), + ) + RetroSystems.N64.id -> + RetroTheme( + body = 0xFFA7A7AD.toInt(), + dpad = 0xFF4C4C54.toInt(), + pill = 0xFF77777F.toInt(), + pillText = 0xFFEFEFF4.toInt(), + button = 0xFF77777F.toInt(), + buttonText = 0xFFEFEFF4.toInt(), + buttonColors = + mapOf( + "A" to 0xFF2E63C9.toInt(), + "B" to 0xFF2F9E44.toInt(), + "START" to 0xFFC8362E.toInt(), + ), + stickCap = 0xFF9EA0A6.toInt(), + ) + RetroSystems.GAMECUBE.id -> + RetroTheme( + body = 0xFF6B6F78.toInt(), + dpad = 0xFF3A3D44.toInt(), + pill = 0xFF555861.toInt(), + pillText = 0xFFEDEFF4.toInt(), + button = 0xFF555861.toInt(), + buttonText = 0xFFEDEFF4.toInt(), + buttonColors = + mapOf( + "A" to 0xFF2F8F4E.toInt(), + "B" to 0xFFC8362E.toInt(), + "X" to 0xFFE8E8EC.toInt(), + "Y" to 0xFFE8E8EC.toInt(), + "START" to 0xFF3A3D44.toInt(), + "Z" to 0xFF5B3FA0.toInt(), + ), + buttonTextColors = + mapOf( + "X" to 0xFF3A3D44.toInt(), + "Y" to 0xFF3A3D44.toInt(), + ), + stickCap = 0xFF8A8E98.toInt(), + ) + RetroSystems.WII.id -> + RetroTheme( + body = 0xFFE4E6EA.toInt(), + dpad = 0xFF2C2E34.toInt(), + pill = 0xFFB8BCC4.toInt(), + pillText = 0xFF2C2E34.toInt(), + button = 0xFF2C2E34.toInt(), + buttonText = 0xFFF2F4F8.toInt(), + buttonColors = + mapOf( + "A" to 0xFF1BA0D8.toInt(), + "B" to 0xFF2C2E34.toInt(), + "X" to 0xFFD8DCE4.toInt(), + "Y" to 0xFFD8DCE4.toInt(), + "+" to 0xFF1BA0D8.toInt(), + "START" to 0xFF1BA0D8.toInt(), + ), + buttonTextColors = + mapOf( + "X" to 0xFF2C2E34.toInt(), + "Y" to 0xFF2C2E34.toInt(), + ), + stickCap = 0xFFC8CCD4.toInt(), + ) + RetroSystems.GENESIS.id, RetroSystems.MASTER_SYSTEM.id, RetroSystems.GAME_GEAR.id -> + RetroTheme( + body = 0xFF1D1D21.toInt(), + dpad = 0xFF0E0E11.toInt(), + pill = 0xFF2C2C33.toInt(), + pillText = 0xFFB9B9C2.toInt(), + button = 0xFF303038.toInt(), + buttonText = 0xFFB9B9C2.toInt(), + ) + RetroSystems.PSX.id, RetroSystems.PS2.id -> + RetroTheme( + body = 0xFFB7B7C0.toInt(), + dpad = 0xFF50505A.toInt(), + pill = 0xFF5A5A64.toInt(), + pillText = 0xFFE9E9F0.toInt(), + button = 0xFF3D3D45.toInt(), + buttonText = 0xFFE9E9F0.toInt(), + buttonTextColors = + mapOf( + "△" to 0xFF43B26A.toInt(), + "○" to 0xFFD64B45.toInt(), + "✕" to 0xFF8FA9DF.toInt(), + "□" to 0xFFD387BE.toInt(), + ), + ) + else -> + RetroTheme( + body = 0xFFC9C6C1.toInt(), + dpad = 0xFF2E2E33.toInt(), + pill = 0xFF8A8A86.toInt(), + pillText = 0xFF33333A.toInt(), + button = 0xFF55555C.toInt(), + buttonText = 0xFFEFEFF4.toInt(), + ) + } + + private var gameArea: RectF? = null + var hapticStrength = 0f + var adaptiveSticks: Boolean = false + set(value) { + if (field != value) { + field = value + stickActive = false + stick2Active = false + invalidate() + } + } + val supportsStickButtons: Boolean get() = config.hasDualSticks + var showL3R3: Boolean = true + set(value) { + if (field != value) { + field = value + if (width > 0 && height > 0) { + relayout() + invalidate() + } + } + } + var invertLX = false + var invertLY = false + var invertRX = false + var invertRY = false + + fun loadStickInversion() { + val prefs = androidx.preference.PreferenceManager.getDefaultSharedPreferences(context) + val sys = system?.id ?: return + invertLX = prefs.getBoolean("retro_inv_lx_$sys", false) + invertLY = prefs.getBoolean("retro_inv_ly_$sys", false) + invertRX = prefs.getBoolean("retro_inv_rx_$sys", false) + invertRY = prefs.getBoolean("retro_inv_ry_$sys", false) + } + + private fun ix(v: Float, inv: Boolean) = if (inv) -v else v + private val vibrator: Vibrator? = context.getSystemService(Vibrator::class.java) + + var editMode = false + private set + var onEditStateChanged: ((Boolean) -> Unit)? = null + private var customColors = RetroCustomColors() + private var overrides: MutableMap = mutableMapOf() + private var overridesLoaded = false + private var overridesPortrait = false + private var selectedId: String? = null + private var dragId: String? = null + private var dragPointerId = -1 + private var dragOffsetX = 0f + private var dragOffsetY = 0f + private var dragActive = false + private var dragDownX = 0f + private var dragDownY = 0f + private var swallowInput = false + private var dpadVisible = true + private var stickVisible = true + private var stick2Visible = true + private val hiddenControls = mutableListOf>() + private val toolbarPills = mutableListOf>() + private val trayPills = mutableListOf>() + + private val editUnit: Float + get() = snap * (if (height > width) 2f else 1f) + + fun setCustomColors(colors: RetroCustomColors) { + customColors = colors + invalidate() + } + + private fun cancelDrag() { + dragId = null + dragPointerId = -1 + dragActive = false + } + + fun enterEdit() { + if (editMode) return + releaseAll() + editMode = true + selectedId = null + cancelDrag() + onEditStateChanged?.invoke(true) + relayout() + } + + fun finishEdit() { + if (!editMode) return + editMode = false + selectedId = null + cancelDrag() + swallowInput = true + saveOverrides() + onEditStateChanged?.invoke(false) + relayout() + } + + fun resetLayout() { + overrides.clear() + RetroControlLayouts.reset(context, system?.id, height > width) + selectedId = null + relayout() + } + + private fun saveOverrides() { + RetroControlLayouts.save(context, system?.id, height > width, overrides) + } + + fun setGameArea(area: RectF?) { + if (area == gameArea) return + gameArea = area + relayout() + } + + private fun hapticTick() { + if (hapticStrength <= 0.01f) return + val amplitude = (hapticStrength * 255f).toInt().coerceIn(1, 255) + runCatching { vibrator?.vibrate(VibrationEffect.createOneShot(15, amplitude.toInt())) } + } + + private fun mix( + a: Int, + b: Int, + f: Float, + ): Int { + val inv = 1f - f + return Color.argb( + 255, + (Color.red(a) * inv + Color.red(b) * f).toInt(), + (Color.green(a) * inv + Color.green(b) * f).toInt(), + (Color.blue(a) * inv + Color.blue(b) * f).toInt(), + ) + } + + private fun lighten( + color: Int, + f: Float, + ) = mix(color, Color.WHITE, f) + + private fun darken( + color: Int, + f: Float, + ) = mix(color, Color.BLACK, f) + + private var dpadCx = 0f + private var dpadCy = 0f + private var dpadRadius = 0f + + private var stickCx = 0f + private var stickCy = 0f + private var stickRadius = 0f + private var stickPointerId = -1 + private var stickX = 0f + private var stickY = 0f + private var stick2Cx = 0f + private var stick2Cy = 0f + private var stick2Radius = 0f + private var stick2PointerId = -1 + private var stick2X = 0f + private var stick2Y = 0f + + private var stickActive = false + private var stickOriginX = 0f + private var stickOriginY = 0f + private var stick2Active = false + private var stick2OriginX = 0f + private var stick2OriginY = 0f + + private val DOUBLE_TAP_MS = 500L + private val TAP_MAX_MS = 300L + private val TAP_MAX_MAG = 0.35f + private val DEAD_ZONE_PX = 10f + private val FACE_KEYCODES = setOf( + KeyEvent.KEYCODE_BUTTON_A, KeyEvent.KEYCODE_BUTTON_B, + KeyEvent.KEYCODE_BUTTON_X, KeyEvent.KEYCODE_BUTTON_Y, + ) + private var stickDownTime = 0L + private var stickMaxMag = 0f + private var stickLastTapTime = 0L + private var stickL3Held = false + private var stick2DownTime = 0L + private var stick2MaxMag = 0f + private var stick2LastTapTime = 0L + private var stickR3Held = false + + private val pressedButtons = HashSet() + private var dpadX = 0f + private var dpadY = 0f + private var menuLatched = false + + private val pointerButton = HashMap() + private val pointerCButton = HashMap() + private var dpadPointerId = -1 + private var menuPointerId = -1 + + private var strokeWidth = 4f + private val paint = Paint(Paint.ANTI_ALIAS_FLAG) + private val path = Path() + private val arrowCenter = FloatArray(2) + + init { + isFocusable = false + isFocusableInTouchMode = false + } + + override fun onSizeChanged( + w: Int, + h: Int, + oldw: Int, + oldh: Int, + ) { + super.onSizeChanged(w, h, oldw, oldh) + relayout() + } + + fun relayout() { + val width = width.toFloat() + val height = height.toFloat() + if (width <= 0f || height <= 0f) return + val portrait = height > width + if (!overridesLoaded || overridesPortrait != portrait) { + overrides = RetroControlLayouts.load(context, system?.id, portrait) + overridesLoaded = true + overridesPortrait = portrait + cancelDrag() + } + buttons.clear() + cButtons.clear() + if (portrait) { + layoutPortrait(width, height) + } else { + layoutLandscape(width, height) + } + applyOverrides(width, height) + if (editMode) layoutEditChrome(width, height) + invalidate() + } + + private fun idFor(button: GlassButton): String = + if (button === menuButton) { + "menu" + } else { + when (button.keyCode) { + KeyEvent.KEYCODE_BUTTON_A -> "btn_a" + KeyEvent.KEYCODE_BUTTON_B -> "btn_b" + KeyEvent.KEYCODE_BUTTON_X -> "btn_x" + KeyEvent.KEYCODE_BUTTON_Y -> "btn_y" + KeyEvent.KEYCODE_BUTTON_L1 -> "l1" + KeyEvent.KEYCODE_BUTTON_R1 -> "r1" + KeyEvent.KEYCODE_BUTTON_L2 -> "l2" + KeyEvent.KEYCODE_BUTTON_R2 -> "r2" + KeyEvent.KEYCODE_BUTTON_THUMBL -> "l3" + KeyEvent.KEYCODE_BUTTON_THUMBR -> "r3" + KeyEvent.KEYCODE_BUTTON_START -> "start" + KeyEvent.KEYCODE_BUTTON_SELECT -> "select" + else -> "btn_${button.keyCode}" + } + } + + private fun reposition( + button: GlassButton, + o: RetroControlOverride, + w: Float, + h: Float, + ) { + val hw = button.bounds.width() * 0.5f * o.scale + val hh = button.bounds.height() * 0.5f * o.scale + button.bounds.set(o.x * w - hw, o.y * h - hh, o.x * w + hw, o.y * h + hh) + } + + private fun applyOverrides( + w: Float, + h: Float, + ) { + dpadVisible = true + stickVisible = true + stick2Visible = true + hiddenControls.clear() + var hideCpad = false + overrides.forEach { (id, o) -> + when (id) { + "dpad" -> + if (!o.visible) { + dpadVisible = false + hiddenControls += id to "DPAD" + } else { + dpadCx = o.x * w + dpadCy = o.y * h + dpadRadius *= o.scale + } + "stick" -> + if (config.hasStick || config.hasDualSticks) { + if (!o.visible) { + stickVisible = false + hiddenControls += id to if (config.hasDualSticks) "L-STICK" else "STICK" + } else { + stickCx = o.x * w + stickCy = o.y * h + stickRadius *= o.scale + } + } + "stick2" -> + if (config.hasDualSticks) { + if (!o.visible) { + stick2Visible = false + hiddenControls += id to "R-STICK" + } else { + stick2Cx = o.x * w + stick2Cy = o.y * h + stick2Radius *= o.scale + } + } + "cpad" -> + if (cButtons.isNotEmpty()) { + if (!o.visible) { + hideCpad = true + hiddenControls += id to "C-PAD" + } else { + val cx = cButtons.map { it.bounds.centerX() }.average().toFloat() + val cy = cButtons.map { it.bounds.centerY() }.average().toFloat() + val nx = o.x * w + val ny = o.y * h + cButtons.forEach { c -> + val rx = (c.bounds.centerX() - cx) * o.scale + val ry = (c.bounds.centerY() - cy) * o.scale + val half = c.bounds.width() * 0.5f * o.scale + c.bounds.set(nx + rx - half, ny + ry - half, nx + rx + half, ny + ry + half) + } + } + } + "menu" -> reposition(menuButton, o, w, h) + else -> { + val target = buttons.firstOrNull { idFor(it) == id } ?: return@forEach + if (!o.visible) { + buttons.remove(target) + hiddenControls += id to target.label + } else { + reposition(target, o, w, h) + } + } + } + } + if (hideCpad) cButtons.clear() + if (selectedId != null && controlRect(selectedId!!) == null) selectedId = null + } + + private fun controlRect(id: String): RectF? = + when (id) { + "dpad" -> + if (dpadVisible && dpadRadius > 0f) { + RectF(dpadCx - dpadRadius, dpadCy - dpadRadius, dpadCx + dpadRadius, dpadCy + dpadRadius) + } else { + null + } + "stick" -> + if ((config.hasStick || config.hasDualSticks) && stickVisible && stickRadius > 0f) { + RectF(stickCx - stickRadius, stickCy - stickRadius, stickCx + stickRadius, stickCy + stickRadius) + } else { + null + } + "stick2" -> + if (config.hasDualSticks && stick2Visible && stick2Radius > 0f) { + RectF( + stick2Cx - stick2Radius, + stick2Cy - stick2Radius, + stick2Cx + stick2Radius, + stick2Cy + stick2Radius, + ) + } else { + null + } + "cpad" -> + if (cButtons.isNotEmpty()) { + RectF( + cButtons.minOf { it.bounds.left }, + cButtons.minOf { it.bounds.top }, + cButtons.maxOf { it.bounds.right }, + cButtons.maxOf { it.bounds.bottom }, + ) + } else { + null + } + "menu" -> menuButton.bounds + else -> buttons.firstOrNull { idFor(it) == id }?.bounds + } + + private fun allControlIds(): List = + buildList { + addAll(buttons.map { idFor(it) }) + add("menu") + add("dpad") + if (config.hasStick || config.hasDualSticks) add("stick") + if (config.hasDualSticks) add("stick2") + add("cpad") + } + + private fun ensureOverride(id: String): RetroControlOverride { + overrides[id]?.let { return it } + val r = controlRect(id) + val o = + RetroControlOverride( + (r?.centerX() ?: width * 0.5f) / width, + (r?.centerY() ?: height * 0.5f) / height, + ) + overrides[id] = o + return o + } + + private fun moveControl( + id: String, + cx: Float, + cy: Float, + ) { + val o = ensureOverride(id) + o.x = (cx / width).coerceIn(0.02f, 0.98f) + o.y = (cy / height).coerceIn(0.02f, 0.98f) + relayout() + } + + private fun scaleControl( + id: String, + delta: Float, + ) { + val o = ensureOverride(id) + o.scale = (o.scale + delta).coerceIn(0.6f, 1.8f) + saveOverrides() + relayout() + } + + private fun setControlVisible( + id: String, + visible: Boolean, + ) { + val o = ensureOverride(id) + o.visible = visible + saveOverrides() + relayout() + } + + private fun layoutLandscape( + width: Float, + height: Float, + ) { + if (config.hasStick) { + layoutN64(width, height) + return + } + snap = width / 100f + val margin = snap * 2.5f + val bottomGap = snap * 9f + var faceRadius = snap * 3f + strokeWidth = max(2f, snap * 0.18f) + + val trigW = snap * 10.4f + val trigH = snap * 5.2f + val trigGap = snap * 1.5f + + var leftCursor = margin + var rightCursor = margin + if (config.hasTriggers) { + val lt = + GlassButton(KeyEvent.KEYCODE_BUTTON_L2, config.leftTriggerLabel, GlassShape.TRIGGER_LT, textScale = 1.3f) + lt.bounds.set(margin, leftCursor, margin + trigW, leftCursor + trigH) + buttons += lt + leftCursor += trigH + trigGap + if (config.showRightTrigger) { + val rt = + GlassButton( + KeyEvent.KEYCODE_BUTTON_R2, + config.rightTriggerLabel, + GlassShape.TRIGGER_RT, + textScale = 1.3f, + ) + rt.bounds.set(width - margin - trigW, rightCursor, width - margin, rightCursor + trigH) + buttons += rt + rightCursor += trigH + trigGap + } + } + if (config.hasShoulders) { + val leftShape = if (config.hasTriggers) GlassShape.TRIGGER_LB else GlassShape.TRIGGER_LT + val rightShape = if (config.hasTriggers) GlassShape.TRIGGER_RB else GlassShape.TRIGGER_RT + if (config.showLeftShoulder) { + val lb = + GlassButton( + KeyEvent.KEYCODE_BUTTON_L1, + config.leftShoulderLabel, + leftShape, + textScale = 1.3f, + ) + lb.bounds.set(margin, leftCursor, margin + trigW, leftCursor + trigH) + buttons += lb + } + val rb = + GlassButton( + KeyEvent.KEYCODE_BUTTON_R1, + config.rightShoulderLabel, + rightShape, + textScale = 1.3f, + ) + rb.bounds.set(width - margin - trigW, rightCursor, width - margin, rightCursor + trigH) + buttons += rb + leftCursor += trigH + trigGap + } + + var spread = snap * 5.5f + var clusterCx = width - margin - faceRadius - spread + val rightBarWidth = gameArea?.let { width - it.right } ?: 0f + if (rightBarWidth > snap * 8f) { + val clusterHalf = if (config.hasXY) faceRadius + spread else faceRadius * 2.45f + val avail = rightBarWidth * 0.5f - snap + if (clusterHalf > avail) { + val fit = (avail / clusterHalf).coerceAtLeast(0.62f) + faceRadius *= fit + spread *= fit + } + clusterCx = width - rightBarWidth * 0.5f + } + val clusterCy = + if (config.hasDualSticks) { + dpadCy - dpadRadius + spread + faceRadius + } else { + height - bottomGap - faceRadius - spread + } + var clusterTop = height + fun addFace( + keyCode: Int, + label: String, + cx: Float, + cy: Float, + ) { + val button = GlassButton(keyCode, label, GlassShape.CIRCLE, textScale = faceGlyphScale(label)) + button.bounds.set(cx - faceRadius, cy - faceRadius, cx + faceRadius, cy + faceRadius) + buttons += button + clusterTop = min(clusterTop, button.bounds.top) + } + if (config.hasXY) { + addFace(KeyEvent.KEYCODE_BUTTON_X, config.faceTop, clusterCx, clusterCy - spread) + addFace(KeyEvent.KEYCODE_BUTTON_B, config.faceBottom, clusterCx, clusterCy + spread) + addFace(KeyEvent.KEYCODE_BUTTON_Y, config.faceLeft, clusterCx - spread, clusterCy) + addFace(KeyEvent.KEYCODE_BUTTON_A, config.faceRight, clusterCx + spread, clusterCy) + } else if (config.flatFaces) { + addFace(KeyEvent.KEYCODE_BUTTON_B, "B", clusterCx - faceRadius * 1.35f, clusterCy + spread * 0.5f) + addFace(KeyEvent.KEYCODE_BUTTON_A, "A", clusterCx + faceRadius * 1.35f, clusterCy + spread * 0.5f) + } else { + addFace(KeyEvent.KEYCODE_BUTTON_B, "B", clusterCx - faceRadius * 1.1f, clusterCy + spread * 0.5f + faceRadius * 0.5f) + addFace(KeyEvent.KEYCODE_BUTTON_A, "A", clusterCx + faceRadius * 1.1f, clusterCy + spread * 0.5f - faceRadius * 1.1f) + } + + val pillW = snap * 6f + val pillH = snap * 3f + val pillGap = snap * 1.2f + stickRadius = 0f + dpadRadius = snap * 7.5f + dpadCx = margin + dpadRadius + val leftBarWidth = gameArea?.left ?: 0f + if (leftBarWidth > snap * 8f) { + val avail = leftBarWidth - snap * 2f + if (dpadRadius * 2f > avail) dpadRadius = (avail * 0.5f).coerceAtLeast(snap * 5f) + dpadCx = leftBarWidth * 0.5f + } + dpadCy = height - bottomGap - dpadRadius + + if (config.hasDualSticks) { + stickRadius = snap * 5.5f + stick2Radius = stickRadius + dpadCy -= stickRadius * 0.9f + stickCx = dpadCx + dpadRadius + snap * 0.8f + stickRadius + stickCy = height - snap * 4.5f - stickRadius + stick2Cx = width - stickCx + stick2Cy = stickCy + + if (showL3R3) { + val l3r = faceRadius * 0.82f + val l3cy = height - snap * 3.2f - l3r + val l3cx = margin + l3r + snap * 0.5f + val r3cx = width - margin - l3r - snap * 0.5f + val l3 = GlassButton(KeyEvent.KEYCODE_BUTTON_THUMBL, "L3", GlassShape.CIRCLE, textScale = 0.8f) + l3.bounds.set(l3cx - l3r, l3cy - l3r, l3cx + l3r, l3cy + l3r) + buttons += l3 + val r3 = GlassButton(KeyEvent.KEYCODE_BUTTON_THUMBR, "R3", GlassShape.CIRCLE, textScale = 0.8f) + r3.bounds.set(r3cx - l3r, l3cy - l3r, r3cx + l3r, l3cy + l3r) + buttons += r3 + } + } + + if (config.hasTriggers && config.hasXY) { + val rowY = height - snap * 2.5f - pillH + var pillX = (width - pillW * 3f - pillGap * 2f) * 0.5f + menuButton.bounds.set(pillX, rowY, pillX + pillW, rowY + pillH) + pillX += pillW + pillGap + val select = GlassButton(KeyEvent.KEYCODE_BUTTON_SELECT, "SELECT", GlassShape.PILL, textScale = 0.75f) + select.bounds.set(pillX, rowY, pillX + pillW, rowY + pillH) + buttons += select + pillX += pillW + pillGap + val start = GlassButton(KeyEvent.KEYCODE_BUTTON_START, "START", GlassShape.PILL, textScale = 0.75f) + start.bounds.set(pillX, rowY, pillX + pillW, rowY + pillH) + buttons += start + return + } + + val pillY = clusterTop - pillH - snap * 3.5f + val start = GlassButton(KeyEvent.KEYCODE_BUTTON_START, "START", GlassShape.PILL, textScale = 0.75f) + start.bounds.set(width - margin - pillW, pillY, width - margin, pillY + pillH) + buttons += start + val select = GlassButton(KeyEvent.KEYCODE_BUTTON_SELECT, "SELECT", GlassShape.PILL, textScale = 0.75f) + select.bounds.set( + width - margin - pillW * 2 - pillGap, + pillY, + width - margin - pillW - pillGap, + pillY + pillH, + ) + buttons += select + + val menuW = snap * 6f + val menuY = + min( + max(pillY, leftCursor), + dpadCy - dpadRadius - pillH - snap * 3f, + ) + menuButton.bounds.set(dpadCx - menuW * 0.5f, menuY, dpadCx + menuW * 0.5f, menuY + pillH) + } + + private fun layoutN64( + width: Float, + height: Float, + ) { + snap = width / 100f + strokeWidth = max(2f, snap * 0.18f) + val margin = snap * 2.5f + val trigW = snap * 10.4f + val trigH = snap * 5.2f + val trigGap = snap * 1.5f + + val lb = GlassButton(KeyEvent.KEYCODE_BUTTON_L1, "L", GlassShape.TRIGGER_LT, textScale = 1.3f) + lb.bounds.set(margin, margin, margin + trigW, margin + trigH) + buttons += lb + val rb = GlassButton(KeyEvent.KEYCODE_BUTTON_R1, "R", GlassShape.TRIGGER_RT, textScale = 1.3f) + rb.bounds.set(width - margin - trigW, margin, width - margin, margin + trigH) + buttons += rb + val z = + GlassButton(KeyEvent.KEYCODE_BUTTON_L2, config.leftTriggerLabel, GlassShape.TRIGGER_RB, textScale = 1.3f) + z.bounds.set( + width - margin - trigW, + margin + trigH + trigGap, + width - margin, + margin + trigH * 2 + trigGap, + ) + buttons += z + + val faceRadius = snap * 3f + val spread = snap * 5.5f + var clusterCx = width - margin - faceRadius - spread + val rightBarWidth = gameArea?.let { width - it.right } ?: 0f + if (rightBarWidth >= (faceRadius + spread) * 2f + snap * 2f) { + clusterCx = width - rightBarWidth * 0.5f + } + val clusterCy = height - snap * 4.5f - faceRadius - spread + val bCx = clusterCx - faceRadius * 0.9f + val bCy = clusterCy + spread * 0.5f - faceRadius * 0.9f + val bButton = GlassButton(KeyEvent.KEYCODE_BUTTON_Y, "B", GlassShape.CIRCLE) + bButton.bounds.set(bCx - faceRadius, bCy - faceRadius, bCx + faceRadius, bCy + faceRadius) + buttons += bButton + val aCx = clusterCx + faceRadius * 0.9f + val aCy = clusterCy + spread * 0.5f + faceRadius * 0.9f + val aButton = GlassButton(KeyEvent.KEYCODE_BUTTON_B, "A", GlassShape.CIRCLE) + aButton.bounds.set(aCx - faceRadius, aCy - faceRadius, aCx + faceRadius, aCy + faceRadius) + buttons += aButton + + val pillW = snap * 6f + val pillH = snap * 3f + val pillGap = snap * 1.2f + val pillY = height - snap * 2.5f - pillH + var pillX = (width - pillW * 3f - pillGap * 2f) * 0.5f + menuButton.bounds.set(pillX, pillY, pillX + pillW, pillY + pillH) + pillX += pillW + pillGap + val select = GlassButton(KeyEvent.KEYCODE_BUTTON_SELECT, "SELECT", GlassShape.PILL, textScale = 0.75f) + select.bounds.set(pillX, pillY, pillX + pillW, pillY + pillH) + buttons += select + pillX += pillW + pillGap + val start = GlassButton(KeyEvent.KEYCODE_BUTTON_START, "START", GlassShape.PILL, textScale = 0.75f) + start.bounds.set(pillX, pillY, pillX + pillW, pillY + pillH) + buttons += start + + stickRadius = snap * 7f + stickCx = margin + stickRadius + snap * 1f + val leftBarWidth = gameArea?.left ?: 0f + if (leftBarWidth >= stickRadius * 2f + snap * 2f) { + stickCx = leftBarWidth * 0.5f + } + stickCy = height - snap * 5.5f - stickRadius + dpadRadius = snap * 6.5f + dpadCx = stickCx + dpadCy = stickCy - stickRadius - snap * 2f - dpadRadius + + val cRadius = snap * 2.4f + val cSpread = snap * 3.6f + val cCx = clusterCx + snap * 2f + val topOfFaces = bCy - faceRadius + val bottomOfTriggers = margin + trigH * 2 + trigGap + val cCy = + min( + (bottomOfTriggers + topOfFaces) * 0.5f + snap * 2f, + topOfFaces - snap * 1.5f - cSpread - cRadius, + ) + fun addC( + dx: Float, + dy: Float, + glyph: String, + x: Float, + y: Float, + ) { + val c = CButton(dx, dy, glyph) + c.bounds.set(x - cRadius, y - cRadius, x + cRadius, y + cRadius) + cButtons += c + } + addC(0f, -1f, "▲", cCx, cCy - cSpread) + addC(0f, 1f, "▼", cCx, cCy + cSpread) + addC(-1f, 0f, "◀", cCx - cSpread, cCy) + addC(1f, 0f, "▶", cCx + cSpread, cCy) + } + + private val portraitGameAspect: Float + get() = + when (system?.id) { + RetroSystems.GAMEBOY.id, RetroSystems.GAMEBOY_COLOR.id -> 0.9f + RetroSystems.GBA.id -> 2f / 3f + else -> 0.75f + } + + private fun portraitZoneTop( + width: Float, + height: Float, + ): Float = max(width * portraitGameAspect + snap * 8f, height * 0.42f) + + private fun layoutPortrait( + width: Float, + height: Float, + ) { + if (config.hasStick) { + layoutPortraitN64(width, height) + return + } + snap = width / 100f + strokeWidth = max(2f, snap * 0.4f) + stickRadius = 0f + val zoneTop = portraitZoneTop(width, height) + val zoneH = height - zoneTop + val margin = snap * 5f + val trigW = snap * 24f + val trigH = snap * 8f + val trigGap = snap * 1.5f + + var sideCursor = zoneTop + snap * 2f + if (config.hasTriggers) { + val lt = GlassButton(KeyEvent.KEYCODE_BUTTON_L2, config.leftTriggerLabel, GlassShape.TRIGGER_LT, textScale = 1.3f) + lt.bounds.set(margin, sideCursor, margin + trigW, sideCursor + trigH) + buttons += lt + if (config.showRightTrigger) { + val rt = + GlassButton( + KeyEvent.KEYCODE_BUTTON_R2, + config.rightTriggerLabel, + GlassShape.TRIGGER_RT, + textScale = 1.3f, + ) + rt.bounds.set(width - margin - trigW, sideCursor, width - margin, sideCursor + trigH) + buttons += rt + } + sideCursor += trigH + trigGap + } + if (config.hasShoulders) { + val leftShape = if (config.hasTriggers) GlassShape.TRIGGER_LB else GlassShape.TRIGGER_LT + val rightShape = if (config.hasTriggers) GlassShape.TRIGGER_RB else GlassShape.TRIGGER_RT + if (config.showLeftShoulder) { + val lb = + GlassButton( + KeyEvent.KEYCODE_BUTTON_L1, + config.leftShoulderLabel, + leftShape, + textScale = 1.3f, + ) + lb.bounds.set(margin, sideCursor, margin + trigW, sideCursor + trigH) + buttons += lb + } + val rb = + GlassButton( + KeyEvent.KEYCODE_BUTTON_R1, + config.rightShoulderLabel, + rightShape, + textScale = 1.3f, + ) + rb.bounds.set(width - margin - trigW, sideCursor, width - margin, sideCursor + trigH) + buttons += rb + sideCursor += trigH + trigGap + } + + val rowCy = max(zoneTop + zoneH * 0.45f, sideCursor + snap * 18f) + dpadRadius = snap * 15f + dpadCx = margin + dpadRadius + dpadCy = rowCy + + fun addFace( + keyCode: Int, + label: String, + cx: Float, + cy: Float, + radius: Float, + ) { + val button = GlassButton(keyCode, label, GlassShape.CIRCLE, textScale = faceGlyphScale(label)) + button.bounds.set(cx - radius, cy - radius, cx + radius, cy + radius) + buttons += button + } + if (config.hasXY) { + val faceRadius = snap * 6.5f + val spread = snap * 12f + val clusterCx = width - margin - faceRadius - spread + addFace(KeyEvent.KEYCODE_BUTTON_X, config.faceTop, clusterCx, rowCy - spread, faceRadius) + addFace(KeyEvent.KEYCODE_BUTTON_B, config.faceBottom, clusterCx, rowCy + spread, faceRadius) + addFace(KeyEvent.KEYCODE_BUTTON_Y, config.faceLeft, clusterCx - spread, rowCy, faceRadius) + addFace(KeyEvent.KEYCODE_BUTTON_A, config.faceRight, clusterCx + spread, rowCy, faceRadius) + } else if (config.flatFaces) { + val faceRadius = snap * 8.5f + addFace(KeyEvent.KEYCODE_BUTTON_A, "A", width - margin - faceRadius, rowCy, faceRadius) + addFace( + KeyEvent.KEYCODE_BUTTON_B, + "B", + width - margin - faceRadius * 3.7f, + rowCy, + faceRadius, + ) + } else { + val faceRadius = snap * 8.5f + addFace(KeyEvent.KEYCODE_BUTTON_A, "A", width - margin - faceRadius, rowCy - faceRadius * 0.9f, faceRadius) + addFace( + KeyEvent.KEYCODE_BUTTON_B, + "B", + width - margin - faceRadius * 3f - snap * 2f, + rowCy + faceRadius * 0.9f, + faceRadius, + ) + } + + val pillW = snap * 13f + val pillH = snap * 5.5f + val pillGap = snap * 2f + val pillY = height - margin - pillH + val select = GlassButton(KeyEvent.KEYCODE_BUTTON_SELECT, "SELECT", GlassShape.PILL, textScale = 0.75f) + select.bounds.set(width * 0.5f - pillGap * 0.5f - pillW, pillY, width * 0.5f - pillGap * 0.5f, pillY + pillH) + buttons += select + val start = GlassButton(KeyEvent.KEYCODE_BUTTON_START, "START", GlassShape.PILL, textScale = 0.75f) + start.bounds.set(width * 0.5f + pillGap * 0.5f, pillY, width * 0.5f + pillGap * 0.5f + pillW, pillY + pillH) + buttons += start + + val menuW = snap * 13f + menuButton.bounds.set( + width * 0.5f - menuW * 0.5f, + zoneTop + snap * 1.5f, + width * 0.5f + menuW * 0.5f, + zoneTop + snap * 1.5f + pillH, + ) + } + + private fun layoutPortraitN64( + width: Float, + height: Float, + ) { + snap = width / 100f + strokeWidth = max(2f, snap * 0.4f) + val zoneTop = portraitZoneTop(width, height) + val margin = snap * 5f + val trigW = snap * 24f + val trigH = snap * 8f + val trigGap = snap * 1.5f + + val lb = GlassButton(KeyEvent.KEYCODE_BUTTON_L1, "L", GlassShape.TRIGGER_LT, textScale = 1.3f) + lb.bounds.set(margin, zoneTop + snap * 2f, margin + trigW, zoneTop + snap * 2f + trigH) + buttons += lb + val rb = GlassButton(KeyEvent.KEYCODE_BUTTON_R1, "R", GlassShape.TRIGGER_RT, textScale = 1.3f) + rb.bounds.set(width - margin - trigW, zoneTop + snap * 2f, width - margin, zoneTop + snap * 2f + trigH) + buttons += rb + val z = GlassButton(KeyEvent.KEYCODE_BUTTON_L2, config.leftTriggerLabel, GlassShape.TRIGGER_RB, textScale = 1.3f) + z.bounds.set( + width - margin - trigW, + zoneTop + snap * 2f + trigH + trigGap, + width - margin, + zoneTop + snap * 2f + trigH * 2 + trigGap, + ) + buttons += z + + val pillW = snap * 13f + val pillH = snap * 5.5f + val pillGap = snap * 2f + val pillY = height - margin - pillH + val select = GlassButton(KeyEvent.KEYCODE_BUTTON_SELECT, "SELECT", GlassShape.PILL, textScale = 0.75f) + select.bounds.set(width * 0.5f - pillGap * 0.5f - pillW, pillY, width * 0.5f - pillGap * 0.5f, pillY + pillH) + buttons += select + val start = GlassButton(KeyEvent.KEYCODE_BUTTON_START, "START", GlassShape.PILL, textScale = 0.75f) + start.bounds.set(width * 0.5f + pillGap * 0.5f, pillY, width * 0.5f + pillGap * 0.5f + pillW, pillY + pillH) + buttons += start + + val menuW = snap * 13f + menuButton.bounds.set( + width * 0.5f - menuW * 0.5f, + zoneTop + snap * 1.5f, + width * 0.5f + menuW * 0.5f, + zoneTop + snap * 1.5f + pillH, + ) + + stickRadius = snap * 12f + stickCx = margin + stickRadius + stickCy = pillY - snap * 2f - stickRadius + dpadRadius = snap * 10f + dpadCx = stickCx + dpadCy = stickCy - stickRadius - snap * 2f - dpadRadius + + val faceRadius = snap * 7.5f + val clusterCx = width - margin - faceRadius - snap * 9f + val aCy = stickCy + val aCx = clusterCx + faceRadius * 0.9f + val bCx = clusterCx - faceRadius * 0.9f + val bCy = aCy - faceRadius * 1.8f + val bButton = GlassButton(KeyEvent.KEYCODE_BUTTON_Y, "B", GlassShape.CIRCLE) + bButton.bounds.set(bCx - faceRadius, bCy - faceRadius, bCx + faceRadius, bCy + faceRadius) + buttons += bButton + val aButton = GlassButton(KeyEvent.KEYCODE_BUTTON_B, "A", GlassShape.CIRCLE) + aButton.bounds.set(aCx - faceRadius, aCy - faceRadius, aCx + faceRadius, aCy + faceRadius) + buttons += aButton + + val cRadius = snap * 4.5f + val cSpread = snap * 6.5f + val cCx = clusterCx + snap * 1f + val shouldersBottom = zoneTop + snap * 2f + trigH * 2 + trigGap + val facesTop = bCy - faceRadius + val cCy = (shouldersBottom + facesTop) * 0.5f + fun addC( + dx: Float, + dy: Float, + glyph: String, + x: Float, + y: Float, + ) { + val c = CButton(dx, dy, glyph) + c.bounds.set(x - cRadius, y - cRadius, x + cRadius, y + cRadius) + cButtons += c + } + addC(0f, -1f, "▲", cCx, cCy - cSpread) + addC(0f, 1f, "▼", cCx, cCy + cSpread) + addC(-1f, 0f, "◀", cCx - cSpread, cCy) + addC(1f, 0f, "▶", cCx + cSpread, cCy) + } + + override fun onDraw(canvas: Canvas) { + super.onDraw(canvas) + if (gameArea == null && !editMode) return + paint.strokeJoin = Paint.Join.ROUND + paint.strokeCap = Paint.Cap.ROUND + drawShellBackground(canvas) + if (editMode) canvas.drawColor(0x2E000000) + drawClusterPlate(canvas) + drawFacePlate(canvas) + if (dpadVisible) drawDpad(canvas) + val adaptive = adaptiveSticks && !editMode + if ((config.hasStick || config.hasDualSticks) && stickVisible && (!adaptive || stickActive)) { + drawStick(canvas, if (adaptive) stickOriginX else stickCx, if (adaptive) stickOriginY else stickCy) + } + if (config.hasDualSticks && stick2Visible && (!adaptive || stick2Active)) { + drawStick2(canvas, adaptive) + } + buttons.forEach { drawThemedButton(canvas, it, pressedButtons.contains(it.keyCode)) } + cButtons.forEach { drawCButton(canvas, it) } + drawThemedButton(canvas, menuButton, menuLatched) + if (editMode) drawEditChrome(canvas) + } + + private fun shadowTint(alpha: Int): Int { + val c = customColors.shadow ?: return Color.argb(alpha, 0, 0, 0) + return Color.argb(alpha, Color.red(c), Color.green(c), Color.blue(c)) + } + + private fun luminance(color: Int): Float = + (0.299f * Color.red(color) + 0.587f * Color.green(color) + 0.114f * Color.blue(color)) / 255f + + private fun drawShellBackground(canvas: Canvas) { + val area = gameArea ?: return + val w = width.toFloat() + val h = height.toFloat() + paint.shader = null + paint.style = Paint.Style.FILL + paint.color = customColors.body ?: theme.body + if (area.top > 0f) canvas.drawRect(0f, 0f, w, area.top, paint) + if (area.bottom < h) canvas.drawRect(0f, area.bottom, w, h, paint) + if (area.left > 0f) canvas.drawRect(0f, area.top, area.left, area.bottom, paint) + if (area.right < w) canvas.drawRect(area.right, area.top, w, area.bottom, paint) + } + + private fun drawFacePlate(canvas: Canvas) { + if (theme.backplate == 0) return + val faces = buttons.filter { it.shape == GlassShape.CIRCLE } + if (faces.isEmpty()) return + val pad = faces.first().bounds.width() * 0.28f + val left = faces.minOf { it.bounds.left } - pad + val top = faces.minOf { it.bounds.top } - pad + val right = faces.maxOf { it.bounds.right } + pad + val bottom = faces.maxOf { it.bounds.bottom } + pad + if (right - left > faces.first().bounds.width() * 3.6f || + bottom - top > faces.first().bounds.height() * 3.6f + ) { + return + } + val corner = (bottom - top) * 0.24f + paint.shader = null + paint.style = Paint.Style.FILL + paint.color = theme.backplate + canvas.drawRoundRect(left, top, right, bottom, corner, corner, paint) + paint.style = Paint.Style.STROKE + paint.strokeWidth = strokeWidth + paint.color = darken(theme.backplate, 0.16f) + canvas.drawRoundRect(left, top, right, bottom, corner, corner, paint) + } + + private fun drawClusterPlate(canvas: Canvas) { + if (theme.clusterPlate == 0 || !config.hasXY) return + val faces = buttons.filter { it.shape == GlassShape.CIRCLE } + if (faces.size < 3) return + val cx = faces.map { it.bounds.centerX() }.average().toFloat() + val cy = faces.map { it.bounds.centerY() }.average().toFloat() + val reach = + faces.maxOf { + hypot(it.bounds.centerX() - cx, it.bounds.centerY() - cy) + it.bounds.width() * 0.5f + } + if (reach > faces.first().bounds.width() * 2.2f) return + val radius = reach + snap * 1.4f + paint.shader = + RadialGradient( + cx, + cy, + radius, + intArrayOf(theme.clusterPlate, theme.clusterPlate, darken(theme.clusterPlate, 0.12f)), + floatArrayOf(0f, 0.8f, 1f), + Shader.TileMode.CLAMP, + ) + paint.style = Paint.Style.FILL + canvas.drawCircle(cx, cy, radius, paint) + paint.shader = null + paint.style = Paint.Style.STROKE + paint.strokeWidth = strokeWidth + paint.color = darken(theme.clusterPlate, 0.22f) + canvas.drawCircle(cx, cy, radius, paint) + } + + private fun buttonFill(button: GlassButton): Int = + customColors.button + ?: theme.buttonColors[button.label] + ?: if (button.shape == GlassShape.CIRCLE) theme.button else theme.pill + + private fun buttonTextColor(button: GlassButton): Int = + customColors.text + ?: theme.buttonTextColors[button.label] + ?: if (button.shape == GlassShape.CIRCLE) theme.buttonText else theme.pillText + + private fun drawThemedButton( + canvas: Canvas, + button: GlassButton, + pressed: Boolean, + ) { + val b = button.bounds + val color = buttonFill(button) + if (button.shape == GlassShape.CIRCLE) { + drawRoundButton( + canvas, + b.centerX(), + b.centerY(), + b.width() * 0.5f, + color, + buttonTextColor(button), + button.label, + pressed, + if (button.label.length > 1) 0.62f else 0.92f * button.textScale, + ) + return + } + val depth = b.height() * 0.08f + val dy = if (pressed) depth * 0.7f else 0f + buildShapePath(button) + path.offset(0f, depth) + paint.shader = null + paint.style = Paint.Style.FILL + paint.color = shadowTint(if (pressed) 40 else 70) + canvas.drawPath(path, paint) + buildShapePath(button) + path.offset(0f, dy) + paint.alpha = 255 + paint.shader = + LinearGradient( + b.left, + b.top + dy, + b.left, + b.bottom + dy, + intArrayOf( + lighten(color, if (pressed) 0.06f else 0.24f), + color, + darken(color, if (pressed) 0.24f else 0.14f), + ), + floatArrayOf(0f, 0.5f, 1f), + Shader.TileMode.CLAMP, + ) + canvas.drawPath(path, paint) + paint.shader = null + paint.style = Paint.Style.STROKE + paint.strokeWidth = strokeWidth + paint.color = darken(color, 0.38f) + canvas.drawPath(path, paint) + paint.style = Paint.Style.FILL + paint.color = buttonTextColor(button) + paint.textAlign = Paint.Align.CENTER + paint.isFakeBoldText = true + paint.textSize = b.height() * (if (button.shape == GlassShape.PILL) 0.44f else 0.5f) * button.textScale / 0.75f * 0.75f + val maxTextWidth = b.width() - b.height() * 0.5f + if (button.label.isNotEmpty() && paint.measureText(button.label) > maxTextWidth) { + paint.textSize = paint.textSize * maxTextWidth / paint.measureText(button.label) + } + val textY = b.centerY() + dy - (paint.descent() + paint.ascent()) * 0.5f + canvas.drawText(button.label, b.centerX(), textY, paint) + paint.isFakeBoldText = false + } + + private fun drawRoundButton( + canvas: Canvas, + cx: Float, + cy: Float, + radius: Float, + color: Int, + textColor: Int, + label: String, + pressed: Boolean, + textScale: Float, + ) { + val depth = radius * 0.12f + val dy = if (pressed) depth * 0.7f else 0f + val bodyCy = cy + dy + + paint.style = Paint.Style.FILL + paint.alpha = 255 + paint.shader = + RadialGradient( + cx, + cy + depth, + radius * 1.18f, + shadowTint(if (pressed) 55 else 95), + Color.TRANSPARENT, + Shader.TileMode.CLAMP, + ) + canvas.drawCircle(cx, cy + depth, radius * 1.18f, paint) + + paint.shader = + RadialGradient( + cx - radius * 0.35f, + bodyCy - radius * 0.45f, + radius * 1.9f, + intArrayOf( + lighten(color, if (pressed) 0.08f else 0.3f), + color, + darken(color, if (pressed) 0.28f else 0.16f), + ), + floatArrayOf(0f, 0.55f, 1f), + Shader.TileMode.CLAMP, + ) + canvas.drawCircle(cx, bodyCy, radius, paint) + paint.shader = null + + paint.style = Paint.Style.STROKE + paint.strokeWidth = strokeWidth + paint.color = darken(color, 0.4f) + canvas.drawCircle(cx, bodyCy, radius - strokeWidth * 0.5f, paint) + + if (!pressed) { + paint.style = Paint.Style.FILL + paint.shader = + RadialGradient( + cx - radius * 0.34f, + bodyCy - radius * 0.4f, + radius * 0.62f, + Color.argb(70, 255, 255, 255), + Color.TRANSPARENT, + Shader.TileMode.CLAMP, + ) + canvas.drawCircle(cx - radius * 0.34f, bodyCy - radius * 0.4f, radius * 0.62f, paint) + paint.shader = null + } + + if (label.isNotEmpty()) { + paint.style = Paint.Style.FILL + paint.color = textColor + paint.textAlign = Paint.Align.CENTER + paint.isFakeBoldText = true + paint.textSize = radius * textScale * 1.05f + val maxTextWidth = radius * (if (label.length == 1) 2.4f else 1.7f) + if (paint.measureText(label) > maxTextWidth) { + paint.textSize = paint.textSize * maxTextWidth / paint.measureText(label) + } + val textY = bodyCy - (paint.descent() + paint.ascent()) * 0.5f + canvas.drawText(label, cx, textY, paint) + paint.isFakeBoldText = false + } + } + + private fun drawCButton( + canvas: Canvas, + button: CButton, + ) { + val b = button.bounds + val pressed = + (button.dx != 0f && cStickX == button.dx) || (button.dy != 0f && cStickY == button.dy) + drawRoundButton( + canvas, + b.centerX(), + b.centerY(), + b.width() * 0.5f, + customColors.button ?: theme.cButton, + customColors.text ?: theme.cText, + button.glyph, + pressed, + 0.8f, + ) + } + + private fun buildShapePath(button: GlassButton) { + val b = button.bounds + when (button.shape) { + GlassShape.CIRCLE -> { + path.reset() + path.addCircle(b.centerX(), b.centerY(), b.width() * 0.5f, Path.Direction.CW) + } + GlassShape.PILL -> { + path.reset() + val r = b.height() * 0.5f + path.addRoundRect(b.left, b.top, b.right, b.bottom, r, r, Path.Direction.CW) + } + GlassShape.TRIGGER_LT -> + GameHubLayout.buildTriggerPath(path, GameHubLayout.RenderShape.TRIGGER_LT, b.left, b.top, b.right, b.bottom) + GlassShape.TRIGGER_LB -> + GameHubLayout.buildTriggerPath(path, GameHubLayout.RenderShape.TRIGGER_LB, b.left, b.top, b.right, b.bottom) + GlassShape.TRIGGER_RT -> + GameHubLayout.buildTriggerPath(path, GameHubLayout.RenderShape.TRIGGER_RT, b.left, b.top, b.right, b.bottom) + GlassShape.TRIGGER_RB -> + GameHubLayout.buildTriggerPath(path, GameHubLayout.RenderShape.TRIGGER_RB, b.left, b.top, b.right, b.bottom) + } + } + + private fun drawDpad(canvas: Canvas) { + val paint = Paint(Paint.ANTI_ALIAS_FLAG) + val path = Path() + val color = customColors.button ?: theme.dpad + val arm = dpadRadius * 0.36f + val corner = arm * 0.5f + val cx = dpadCx + val cy = dpadCy + val r = dpadRadius + val depth = r * 0.05f + val pressedUp = dpadY < -0.1f + val pressedDown = dpadY > 0.1f + val pressedLeft = dpadX < -0.1f + val pressedRight = dpadX > 0.1f + + path.reset() + path.addRoundRect(cx - r, cy - arm + depth, cx + r, cy + arm + depth, corner, corner, Path.Direction.CW) + path.addRoundRect(cx - arm, cy - r + depth, cx + arm, cy + r + depth, corner, corner, Path.Direction.CW) + paint.shader = null + paint.style = Paint.Style.FILL + paint.color = shadowTint(80) + canvas.drawPath(path, paint) + + path.reset() + path.addRoundRect(cx - r, cy - arm, cx + r, cy + arm, corner, corner, Path.Direction.CW) + path.addRoundRect(cx - arm, cy - r, cx + arm, cy + r, corner, corner, Path.Direction.CW) + paint.alpha = 255 + paint.shader = + LinearGradient( + cx, + cy - r, + cx, + cy + r, + intArrayOf(lighten(color, 0.2f), color, darken(color, 0.2f)), + floatArrayOf(0f, 0.5f, 1f), + Shader.TileMode.CLAMP, + ) + canvas.drawPath(path, paint) + paint.shader = null + + fun pressArm( + left: Float, + top: Float, + right: Float, + bottom: Float, + ) { + paint.style = Paint.Style.FILL + paint.color = Color.argb(90, 0, 0, 0) + canvas.drawRoundRect(left, top, right, bottom, corner, corner, paint) + } + if (pressedUp) pressArm(cx - arm, cy - r, cx + arm, cy - arm * 0.4f) + if (pressedDown) pressArm(cx - arm, cy + arm * 0.4f, cx + arm, cy + r) + if (pressedLeft) pressArm(cx - r, cy - arm, cx - arm * 0.4f, cy + arm) + if (pressedRight) pressArm(cx + arm * 0.4f, cy - arm, cx + r, cy + arm) + + paint.style = Paint.Style.STROKE + paint.strokeWidth = strokeWidth + paint.color = darken(color, 0.45f) + path.reset() + path.addRoundRect(cx - r, cy - arm, cx + r, cy + arm, corner, corner, Path.Direction.CW) + val vertical = Path() + vertical.addRoundRect(cx - arm, cy - r, cx + arm, cy + r, corner, corner, Path.Direction.CW) + path.op(vertical, Path.Op.UNION) + canvas.drawPath(path, paint) + + paint.style = Paint.Style.FILL + paint.shader = + RadialGradient( + cx, + cy, + arm * 0.85f, + darken(color, 0.3f), + color, + Shader.TileMode.CLAMP, + ) + canvas.drawCircle(cx, cy, arm * 0.85f, paint) + paint.shader = null + + val tip = arm * 0.5f + val arrowBase = + customColors.text + ?: if (luminance(color) < 0.55f) 0xFFF3F4F7.toInt() else 0xFF17181C.toInt() + fun arrowPath( + tx: Float, + ty: Float, + dxu: Float, + dyu: Float, + ) { + path.reset() + path.moveTo(tx + dxu * tip, ty + dyu * tip) + path.lineTo(tx - dyu * tip * 0.8f - dxu * tip * 0.5f, ty + dxu * tip * 0.8f - dyu * tip * 0.5f) + path.lineTo(tx + dyu * tip * 0.8f - dxu * tip * 0.5f, ty - dxu * tip * 0.8f - dyu * tip * 0.5f) + path.close() + } + fun arrow( + tx: Float, + ty: Float, + dxu: Float, + dyu: Float, + ) { + arrowPath(tx, ty + tip * 0.14f, dxu, dyu) + paint.color = shadowTint(120) + canvas.drawPath(path, paint) + arrowPath(tx, ty, dxu, dyu) + paint.color = arrowBase + canvas.drawPath(path, paint) + } + val arrowDist = r * 0.66f + arrow(cx, cy - arrowDist, 0f, -1f) + arrow(cx, cy + arrowDist, 0f, 1f) + arrow(cx - arrowDist, cy, -1f, 0f) + arrow(cx + arrowDist, cy, 1f, 0f) + } + + private fun drawStick2( + canvas: Canvas, + adaptive: Boolean = false, + ) { + val ocx = stickCx + val ocy = stickCy + val orad = stickRadius + val ox = stickX + val oy = stickY + val op = stickPointerId + stickCx = stick2Cx + stickCy = stick2Cy + stickRadius = stick2Radius + stickX = stick2X + stickY = stick2Y + stickPointerId = stick2PointerId + if (adaptive) { + drawStick(canvas, stick2OriginX, stick2OriginY) + } else { + drawStick(canvas) + } + stickCx = ocx + stickCy = ocy + stickRadius = orad + stickX = ox + stickY = oy + stickPointerId = op + } + + private fun drawPsStick( + canvas: Canvas, + cx: Float = stickCx, + cy: Float = stickCy, + ) { + val paint = Paint(Paint.ANTI_ALIAS_FLAG) + val engaged = stickPointerId != -1 + val wellColor = darken(customColors.body ?: theme.body, 0.16f) + paint.shader = null + paint.style = Paint.Style.FILL + paint.alpha = 255 + paint.shader = + RadialGradient( + cx, + cy, + stickRadius, + intArrayOf(darken(wellColor, 0.32f), wellColor, lighten(wellColor, 0.1f)), + floatArrayOf(0f, 0.78f, 1f), + Shader.TileMode.CLAMP, + ) + canvas.drawCircle(cx, cy, stickRadius, paint) + paint.shader = null + paint.style = Paint.Style.STROKE + paint.strokeWidth = strokeWidth + paint.color = darken(wellColor, 0.4f) + canvas.drawCircle(cx, cy, stickRadius, paint) + + val thumbX = cx + stickX * stickRadius * 0.5f + val thumbY = cy + stickY * stickRadius * 0.5f + val thumbRadius = stickRadius * 0.6f + val capColor = customColors.button ?: 0xFF33333A.toInt() + paint.style = Paint.Style.FILL + paint.shader = + RadialGradient( + thumbX, + thumbY + thumbRadius * 0.2f, + thumbRadius * 1.3f, + shadowTint(100), + Color.TRANSPARENT, + Shader.TileMode.CLAMP, + ) + canvas.drawCircle(thumbX, thumbY + thumbRadius * 0.18f, thumbRadius * 1.3f, paint) + paint.alpha = 255 + paint.shader = + RadialGradient( + thumbX - thumbRadius * 0.28f, + thumbY - thumbRadius * 0.32f, + thumbRadius * 1.9f, + intArrayOf( + lighten(capColor, if (engaged) 0.12f else 0.28f), + capColor, + darken(capColor, 0.3f), + ), + floatArrayOf(0f, 0.5f, 1f), + Shader.TileMode.CLAMP, + ) + canvas.drawCircle(thumbX, thumbY, thumbRadius, paint) + paint.shader = + RadialGradient( + thumbX, + thumbY + thumbRadius * 0.08f, + thumbRadius * 0.72f, + intArrayOf( + darken(capColor, if (engaged) 0.34f else 0.24f), + darken(capColor, 0.12f), + lighten(capColor, 0.18f), + ), + floatArrayOf(0f, 0.75f, 1f), + Shader.TileMode.CLAMP, + ) + canvas.drawCircle(thumbX, thumbY, thumbRadius * 0.72f, paint) + paint.shader = null + paint.style = Paint.Style.STROKE + paint.strokeWidth = strokeWidth + paint.color = darken(capColor, 0.42f) + canvas.drawCircle(thumbX, thumbY, thumbRadius, paint) + paint.strokeWidth = strokeWidth * 0.7f + paint.color = lighten(capColor, 0.08f) + canvas.drawCircle(thumbX, thumbY, thumbRadius * 0.72f, paint) + } + + private fun drawStick( + canvas: Canvas, + cx: Float = stickCx, + cy: Float = stickCy, + ) { + if (config.hasDualSticks) { + drawPsStick(canvas, cx, cy) + return + } + val engaged = stickPointerId != -1 + val paint = Paint(Paint.ANTI_ALIAS_FLAG) + val wellColor = darken(customColors.button ?: theme.dpad, 0.1f) + paint.shader = null + paint.style = Paint.Style.FILL + + path.reset() + for (i in 0 until 8) { + val angle = Math.toRadians((i * 45 - 22.5).toDouble()) + val px = cx + stickRadius * Math.cos(angle).toFloat() + val py = cy + stickRadius * Math.sin(angle).toFloat() + if (i == 0) path.moveTo(px, py) else path.lineTo(px, py) + } + path.close() + paint.shader = + RadialGradient( + cx, + cy, + stickRadius, + intArrayOf(darken(wellColor, 0.35f), wellColor, lighten(wellColor, 0.08f)), + floatArrayOf(0f, 0.75f, 1f), + Shader.TileMode.CLAMP, + ) + canvas.drawPath(path, paint) + paint.shader = null + paint.style = Paint.Style.STROKE + paint.strokeWidth = strokeWidth + paint.color = darken(wellColor, 0.4f) + canvas.drawPath(path, paint) + + val thumbX = cx + stickX * stickRadius * 0.5f + val thumbY = cy + stickY * stickRadius * 0.5f + val thumbRadius = stickRadius * 0.5f + val capColor = customColors.button ?: theme.stickCap + paint.style = Paint.Style.FILL + paint.shader = + RadialGradient( + thumbX, + thumbY + thumbRadius * 0.18f, + thumbRadius * 1.25f, + shadowTint(90), + Color.TRANSPARENT, + Shader.TileMode.CLAMP, + ) + canvas.drawCircle(thumbX, thumbY + thumbRadius * 0.18f, thumbRadius * 1.25f, paint) + paint.shader = + RadialGradient( + thumbX - thumbRadius * 0.3f, + thumbY - thumbRadius * 0.35f, + thumbRadius * 1.8f, + intArrayOf( + lighten(capColor, if (engaged) 0.1f else 0.3f), + capColor, + darken(capColor, 0.22f), + ), + floatArrayOf(0f, 0.55f, 1f), + Shader.TileMode.CLAMP, + ) + canvas.drawCircle(thumbX, thumbY, thumbRadius, paint) + paint.shader = null + paint.style = Paint.Style.STROKE + paint.strokeWidth = strokeWidth + paint.color = darken(capColor, 0.35f) + canvas.drawCircle(thumbX, thumbY, thumbRadius - strokeWidth * 0.5f, paint) + canvas.drawCircle(thumbX, thumbY, thumbRadius * 0.55f, paint) + } + + private fun layoutEditChrome( + width: Float, + height: Float, + ) { + toolbarPills.clear() + trayPills.clear() + val u = editUnit + val pillH = u * 3.4f + val gap = u * 0.9f + val textPaint = paint + textPaint.textSize = pillH * 0.42f + textPaint.isFakeBoldText = true + val actions = + listOf( + "done" to "DONE", + "reset" to "RESET", + "minus" to "−", + "plus" to "+", + "hide" to "HIDE", + ) + val widths = + actions.map { (_, label) -> + max(textPaint.measureText(label) + pillH * 1.1f, pillH * 1.4f) + } + textPaint.isFakeBoldText = false + val totalW = widths.sum() + gap * (actions.size - 1) + var x = (width - totalW) * 0.5f + val y = u * 1.2f + actions.forEachIndexed { index, (action, label) -> + toolbarPills += Triple(action, label, RectF(x, y, x + widths[index], y + pillH)) + x += widths[index] + gap + } + if (hiddenControls.isNotEmpty()) { + textPaint.textSize = pillH * 0.38f + val trayY = y + pillH + gap + val trayWidths = + hiddenControls.map { (_, label) -> + max(textPaint.measureText("+ $label") + pillH * 1.0f, pillH * 1.3f) + } + var trayX = (width - trayWidths.sum() - gap * (hiddenControls.size - 1)) * 0.5f + hiddenControls.forEachIndexed { index, (id, label) -> + trayPills += Triple(id, "+ $label", RectF(trayX, trayY, trayX + trayWidths[index], trayY + pillH)) + trayX += trayWidths[index] + gap + } + } + } + + private fun drawChromePill( + canvas: Canvas, + rect: RectF, + label: String, + accent: Boolean, + enabled: Boolean = true, + ) { + val r = rect.height() * 0.5f + paint.shader = null + paint.style = Paint.Style.FILL + paint.color = if (accent) 0xF22196F3.toInt() else 0xF21C222C.toInt() + canvas.drawRoundRect(rect, r, r, paint) + paint.style = Paint.Style.STROKE + paint.strokeWidth = strokeWidth + paint.color = if (accent) 0xFF64B5F6.toInt() else 0xFF3A4354.toInt() + canvas.drawRoundRect(rect, r, r, paint) + paint.style = Paint.Style.FILL + paint.color = if (enabled) 0xFFF2F5FA.toInt() else 0x66F2F5FA + paint.textAlign = Paint.Align.CENTER + paint.isFakeBoldText = true + paint.textSize = rect.height() * (if (label.startsWith("+ ")) 0.38f else 0.42f) + val textY = rect.centerY() - (paint.descent() + paint.ascent()) * 0.5f + canvas.drawText(label, rect.centerX(), textY, paint) + paint.isFakeBoldText = false + } + + private fun drawEditChrome(canvas: Canvas) { + val u = editUnit + selectedId?.let { id -> + controlRect(id)?.let { rect -> + val pad = u * 0.7f + paint.shader = null + paint.style = Paint.Style.STROKE + paint.strokeWidth = max(2f, u * 0.22f) + paint.color = 0xFF29B6F6.toInt() + paint.pathEffect = DashPathEffect(floatArrayOf(u * 0.9f, u * 0.6f), 0f) + canvas.drawRoundRect( + rect.left - pad, + rect.top - pad, + rect.right + pad, + rect.bottom + pad, + u, + u, + paint, + ) + paint.pathEffect = null + } + } + val hideEnabled = selectedId != null && selectedId != "menu" + val sizeEnabled = selectedId != null + toolbarPills.forEach { (action, label, rect) -> + val enabled = + when (action) { + "hide" -> hideEnabled + "minus", "plus" -> sizeEnabled + else -> true + } + drawChromePill(canvas, rect, label, accent = action == "done", enabled = enabled) + } + trayPills.forEach { (_, label, rect) -> + drawChromePill(canvas, rect, label, accent = false) + } + val hintY = (toolbarPills.firstOrNull()?.third?.bottom ?: 0f) + + (if (trayPills.isEmpty()) u * 2.2f else u * 6.2f) + paint.style = Paint.Style.FILL + paint.color = 0xCCFFFFFF.toInt() + paint.textAlign = Paint.Align.CENTER + paint.textSize = u * 1.4f + canvas.drawText( + if (selectedId == null) "Tap a control to select, drag to move" else "Drag to move · +/− to resize", + width * 0.5f, + hintY, + paint, + ) + } + + private fun controlAt( + x: Float, + y: Float, + ): String? { + val u = editUnit + var best: String? = null + var bestArea = Float.MAX_VALUE + allControlIds().forEach { id -> + val rect = controlRect(id) ?: return@forEach + if (x >= rect.left - u && x <= rect.right + u && y >= rect.top - u && y <= rect.bottom + u) { + val area = rect.width() * rect.height() + if (area < bestArea) { + bestArea = area + best = id + } + } + } + return best + } + + private fun editTouch(event: MotionEvent) { + when (event.actionMasked) { + MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> { + val index = event.actionIndex + val x = event.getX(index) + val y = event.getY(index) + toolbarPills.firstOrNull { it.third.contains(x, y) }?.let { (action, _, _) -> + hapticTick() + cancelDrag() + when (action) { + "done" -> finishEdit() + "reset" -> resetLayout() + "minus" -> selectedId?.let { scaleControl(it, -0.1f) } + "plus" -> selectedId?.let { scaleControl(it, 0.1f) } + "hide" -> + selectedId?.takeIf { it != "menu" }?.let { + setControlVisible(it, false) + selectedId = null + } + } + return + } + trayPills.firstOrNull { it.third.contains(x, y) }?.let { (id, _, _) -> + hapticTick() + cancelDrag() + setControlVisible(id, true) + selectedId = id + return + } + if (dragId == null) { + val hit = controlAt(x, y) + selectedId = hit + if (hit != null) { + val rect = controlRect(hit) + dragId = hit + dragPointerId = event.getPointerId(index) + dragActive = false + dragDownX = x + dragDownY = y + dragOffsetX = (rect?.centerX() ?: x) - x + dragOffsetY = (rect?.centerY() ?: y) - y + hapticTick() + } + } + } + MotionEvent.ACTION_MOVE -> { + val id = dragId ?: return + val pointerIndex = event.findPointerIndex(dragPointerId) + if (pointerIndex < 0) return + val x = event.getX(pointerIndex) + val y = event.getY(pointerIndex) + if (!dragActive && hypot(x - dragDownX, y - dragDownY) < editUnit * 0.6f) return + dragActive = true + moveControl(id, x + dragOffsetX, y + dragOffsetY) + } + MotionEvent.ACTION_POINTER_UP, MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { + val ended = + event.actionMasked == MotionEvent.ACTION_UP || + event.actionMasked == MotionEvent.ACTION_CANCEL || + event.getPointerId(event.actionIndex) == dragPointerId + if (ended && dragId != null) { + val moved = dragActive + cancelDrag() + if (moved) saveOverrides() + } + } + } + } + + fun releaseAll() { + for (keyCode in pressedButtons) listener.onButton(keyCode, false) + pressedButtons.clear() + pointerButton.clear() + pointerCButton.clear() + dpadPointerId = -1 + menuPointerId = -1 + if (dpadX != 0f || dpadY != 0f) { + dpadX = 0f + dpadY = 0f + listener.onDpad(0f, 0f) + } + if (stickPointerId != -1 || stickX != 0f || stickY != 0f) { + stickPointerId = -1 + stickX = 0f + stickY = 0f + listener.onStick(0f, 0f) + } + stickActive = false + if (stickL3Held) { + stickL3Held = false + listener.onButton(KeyEvent.KEYCODE_BUTTON_THUMBL, false) + } + if (cStickX != 0f || cStickY != 0f) { + cStickX = 0f + cStickY = 0f + listener.onRightStick(0f, 0f) + } + if (stick2PointerId != -1 || stick2X != 0f || stick2Y != 0f) { + stick2PointerId = -1 + stick2X = 0f + stick2Y = 0f + listener.onRightStick(0f, 0f) + } + stick2Active = false + if (stickR3Held) { + stickR3Held = false + listener.onButton(KeyEvent.KEYCODE_BUTTON_THUMBR, false) + } + menuLatched = false + invalidate() + } + + override fun onTouchEvent(event: MotionEvent): Boolean { + when (event.actionMasked) { + MotionEvent.ACTION_DOWN, + MotionEvent.ACTION_POINTER_DOWN, + MotionEvent.ACTION_MOVE, + MotionEvent.ACTION_POINTER_UP, + MotionEvent.ACTION_UP, + MotionEvent.ACTION_CANCEL, + -> + if (editMode) { + editTouch(event) + } else if (swallowInput) { + if (event.actionMasked == MotionEvent.ACTION_UP || + event.actionMasked == MotionEvent.ACTION_CANCEL + ) { + swallowInput = false + } + } else { + recompute(event) + } + else -> return false + } + invalidate() + return true + } + + private fun hitButton( + button: GlassButton, + x: Float, + y: Float, + ): Boolean { + val b = button.bounds + val inflate = snap * 1.2f + return if (button.shape == GlassShape.CIRCLE) { + val r = b.width() * 0.5f + inflate + hypot(x - b.centerX(), y - b.centerY()) <= r + } else { + x >= b.left - inflate && x <= b.right + inflate && + y >= b.top - inflate && y <= b.bottom + inflate + } + } + + private fun inStickHomeZone( + x: Float, + y: Float, + rightHalf: Boolean, + ): Boolean { + val w = width.toFloat() + val h = height.toFloat() + if (w <= 0f || h <= 0f) return false + val top = h * 0.42f + val midX = w * 0.5f + val inHalf = if (rightHalf) x >= midX else x < midX + return inHalf && y >= top + } + + private fun hitsOtherControl( + x: Float, + y: Float, + ): Boolean { + val pad = DEAD_ZONE_PX + fun inPadded(b: RectF): Boolean = + x >= b.left - pad && x <= b.right + pad && y >= b.top - pad && y <= b.bottom + pad + if (menuPointerId == -1 && inPadded(menuButton.bounds)) return true + for (button in buttons) { + if (inPadded(button.bounds)) return true + } + val face = buttons.filter { it.keyCode in FACE_KEYCODES } + if (face.size >= 3) { + val l = face.minOf { it.bounds.left } - pad + val t = face.minOf { it.bounds.top } - pad + val r = face.maxOf { it.bounds.right } + pad + val b = face.maxOf { it.bounds.bottom } + pad + if (x in l..r && y in t..b) return true + } + for (c in cButtons) { + val reach = c.bounds.width() * 0.5f + snap * 1.2f + pad + if (hypot(x - c.bounds.centerX(), y - c.bounds.centerY()) <= reach) return true + } + if (dpadVisible && hypot(x - dpadCx, y - dpadCy) <= dpadRadius * 1.4f + pad) return true + return false + } + + private fun recompute(event: MotionEvent) { + val adaptive = adaptiveSticks + val now = event.eventTime + val released = + event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL + val liftedPointer = + if (event.actionMasked == MotionEvent.ACTION_POINTER_UP) event.actionIndex else -1 + val downId = + when (event.actionMasked) { + MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> + event.getPointerId(event.actionIndex) + else -> -1 + } + + val activeIds = HashSet() + if (!released) { + for (i in 0 until event.pointerCount) { + if (i == liftedPointer) continue + activeIds.add(event.getPointerId(i)) + } + } + pointerButton.keys.retainAll(activeIds) + pointerCButton.keys.retainAll(activeIds) + if (dpadPointerId != -1 && dpadPointerId !in activeIds) dpadPointerId = -1 + if (menuPointerId != -1 && menuPointerId !in activeIds) menuPointerId = -1 + + val newPressed = HashSet() + var newDpadX = 0f + var newDpadY = 0f + var newCX = 0f + var newCY = 0f + var menuTouched = false + var stickSeen = false + var newStickX = stickX + var newStickY = stickY + var stick2Seen = false + var newStick2X = stick2X + var newStick2Y = stick2Y + + if (!released) { + for (i in 0 until event.pointerCount) { + if (i == liftedPointer) continue + val x = event.getX(i) + val y = event.getY(i) + val pointerId = event.getPointerId(i) + val isNewDown = pointerId == downId + + if (config.hasDualSticks && stick2Visible) { + if (pointerId == stick2PointerId) { + stick2Seen = true + val ocx = if (stick2Active) stick2OriginX else stick2Cx + val ocy = if (stick2Active) stick2OriginY else stick2Cy + newStick2X = ((x - ocx) / stick2Radius).coerceIn(-1f, 1f) + newStick2Y = ((y - ocy) / stick2Radius).coerceIn(-1f, 1f) + stick2MaxMag = max(stick2MaxMag, hypot(newStick2X, newStick2Y)) + continue + } + if (isNewDown && stick2PointerId == -1) { + var grabbed = false + if (adaptive) { + if (inStickHomeZone(x, y, rightHalf = true) && !hitsOtherControl(x, y)) { + stick2PointerId = pointerId + stick2Seen = true + stick2Active = true + stick2OriginX = x + stick2OriginY = y + hapticTick() + newStick2X = 0f + newStick2Y = 0f + grabbed = true + } + } else if (hypot(x - stick2Cx, y - stick2Cy) <= stick2Radius * 1.3f) { + stick2PointerId = pointerId + stick2Seen = true + hapticTick() + newStick2X = ((x - stick2Cx) / stick2Radius).coerceIn(-1f, 1f) + newStick2Y = ((y - stick2Cy) / stick2Radius).coerceIn(-1f, 1f) + grabbed = true + } + if (grabbed) { + stick2DownTime = now + stick2MaxMag = 0f + if (!showL3R3 && stick2LastTapTime != 0L && now - stick2LastTapTime <= DOUBLE_TAP_MS) { + stickR3Held = true + stick2LastTapTime = 0L + listener.onButton(KeyEvent.KEYCODE_BUTTON_THUMBR, true) + hapticTick() + } + continue + } + } + } + + if ((config.hasStick || config.hasDualSticks) && stickVisible) { + if (pointerId == stickPointerId) { + stickSeen = true + val ocx = if (stickActive) stickOriginX else stickCx + val ocy = if (stickActive) stickOriginY else stickCy + newStickX = ((x - ocx) / stickRadius).coerceIn(-1f, 1f) + newStickY = ((y - ocy) / stickRadius).coerceIn(-1f, 1f) + stickMaxMag = max(stickMaxMag, hypot(newStickX, newStickY)) + continue + } + if (isNewDown && stickPointerId == -1) { + var grabbed = false + if (adaptive) { + if (inStickHomeZone(x, y, rightHalf = false) && !hitsOtherControl(x, y)) { + stickPointerId = pointerId + stickSeen = true + stickActive = true + stickOriginX = x + stickOriginY = y + hapticTick() + newStickX = 0f + newStickY = 0f + grabbed = true + } + } else if (hypot(x - stickCx, y - stickCy) <= stickRadius * 1.3f) { + stickPointerId = pointerId + stickSeen = true + hapticTick() + newStickX = ((x - stickCx) / stickRadius).coerceIn(-1f, 1f) + newStickY = ((y - stickCy) / stickRadius).coerceIn(-1f, 1f) + grabbed = true + } + if (grabbed) { + stickDownTime = now + stickMaxMag = 0f + if (!showL3R3 && stickLastTapTime != 0L && now - stickLastTapTime <= DOUBLE_TAP_MS) { + stickL3Held = true + stickLastTapTime = 0L + listener.onButton(KeyEvent.KEYCODE_BUTTON_THUMBL, true) + hapticTick() + } + continue + } + } + } + + if (pointerId == menuPointerId) { + menuTouched = true + continue + } + if (isNewDown && menuPointerId == -1 && hitButton(menuButton, x, y)) { + menuPointerId = pointerId + menuTouched = true + continue + } + + val ownedC = pointerCButton[pointerId] + if (ownedC != null) { + if (ownedC.dx != 0f) newCX = ownedC.dx + if (ownedC.dy != 0f) newCY = ownedC.dy + continue + } + if (isNewDown) { + var cHit = false + for (c in cButtons) { + val reach = c.bounds.width() * 0.5f + snap * 1.2f + if (hypot(x - c.bounds.centerX(), y - c.bounds.centerY()) <= reach) { + pointerCButton[pointerId] = c + if (c.dx != 0f) newCX = c.dx + if (c.dy != 0f) newCY = c.dy + cHit = true + break + } + } + if (cHit) continue + } + + val ownedB = pointerButton[pointerId] + if (ownedB != null) { + newPressed.add(ownedB) + continue + } + if (isNewDown) { + var buttonHit = false + for (button in buttons) { + if (hitButton(button, x, y)) { + pointerButton[pointerId] = button.keyCode + newPressed.add(button.keyCode) + buttonHit = true + break + } + } + if (buttonHit) continue + } + + if (dpadVisible && (pointerId == dpadPointerId || + (isNewDown && dpadPointerId == -1 && + hypot(x - dpadCx, y - dpadCy) <= dpadRadius * 1.4f)) + ) { + dpadPointerId = pointerId + val dxToPad = x - dpadCx + val dyToPad = y - dpadCy + val dz = dpadRadius * 0.24f + if (dxToPad > dz) newDpadX = 1f else if (dxToPad < -dz) newDpadX = -1f + if (dyToPad > dz) newDpadY = 1f else if (dyToPad < -dz) newDpadY = -1f + } + } + } + + if (newCX != cStickX || newCY != cStickY) { + if (newCX != 0f || newCY != 0f) hapticTick() + cStickX = newCX + cStickY = newCY + listener.onRightStick(ix(cStickX, invertRX), ix(cStickY, invertRY)) + } + + if (!stickSeen && stickPointerId != -1) { + stickPointerId = -1 + stickActive = false + newStickX = 0f + newStickY = 0f + stickLastTapTime = if (now - stickDownTime < TAP_MAX_MS && stickMaxMag < TAP_MAX_MAG) now else 0L + if (stickL3Held) { + stickL3Held = false + listener.onButton(KeyEvent.KEYCODE_BUTTON_THUMBL, false) + } + } + if (newStickX != stickX || newStickY != stickY) { + stickX = newStickX + stickY = newStickY + listener.onStick(ix(stickX, invertLX), ix(stickY, invertLY)) + } + + if (!stick2Seen && stick2PointerId != -1) { + stick2PointerId = -1 + stick2Active = false + newStick2X = 0f + newStick2Y = 0f + stick2LastTapTime = if (now - stick2DownTime < TAP_MAX_MS && stick2MaxMag < TAP_MAX_MAG) now else 0L + if (stickR3Held) { + stickR3Held = false + listener.onButton(KeyEvent.KEYCODE_BUTTON_THUMBR, false) + } + } + if (newStick2X != stick2X || newStick2Y != stick2Y) { + stick2X = newStick2X + stick2Y = newStick2Y + listener.onRightStick(ix(stick2X, invertRX), ix(stick2Y, invertRY)) + } + + for (keyCode in pressedButtons) { + if (!newPressed.contains(keyCode)) listener.onButton(keyCode, false) + } + for (keyCode in newPressed) { + if (!pressedButtons.contains(keyCode)) { + hapticTick() + listener.onButton(keyCode, true) + } + } + pressedButtons.clear() + pressedButtons.addAll(newPressed) + + if (newDpadX != dpadX || newDpadY != dpadY) { + if (newDpadX != 0f || newDpadY != 0f) hapticTick() + dpadX = newDpadX + dpadY = newDpadY + listener.onDpad(dpadX, dpadY) + } + + if (menuTouched && !menuLatched) { + menuLatched = true + hapticTick() + listener.onMenu() + } else if (!menuTouched) { + menuLatched = false + } + } +} diff --git a/app/src/main/feature/retro/RetroNetplay.kt b/app/src/main/feature/retro/RetroNetplay.kt new file mode 100644 index 000000000..3e808ffd9 --- /dev/null +++ b/app/src/main/feature/retro/RetroNetplay.kt @@ -0,0 +1,1198 @@ +package com.winlator.cmod.feature.retro + +import android.content.Context +import android.net.wifi.WifiManager +import android.os.Handler +import android.os.Looper +import android.provider.Settings +import android.view.KeyEvent +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import com.swordfish.libretrodroid.GLRetroView +import java.io.BufferedInputStream +import java.io.BufferedOutputStream +import java.io.DataInputStream +import java.io.DataOutputStream +import java.net.DatagramPacket +import java.net.DatagramSocket +import java.net.InetAddress +import java.net.InetSocketAddress +import java.net.NetworkInterface +import java.net.ServerSocket +import java.net.Socket +import java.net.SocketTimeoutException +import java.nio.charset.StandardCharsets +import java.util.UUID +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.atomic.AtomicBoolean +import kotlin.concurrent.thread + +enum class RetroNetplayPhase { + IDLE, + HOSTING, + SCANNING, + SCAN_RESULTS, + CONNECTING, + IN_ROOM, +} + +data class RetroNetplayDiscoveredRoom( + val hostAddress: String, + val port: Int, + val systemId: String, + val gameName: String, + val hostPlayerName: String, + val roomId: String, + val lastSeenMs: Long = System.currentTimeMillis(), +) + +data class RetroNetplayMember( + val name: String, + val isHost: Boolean, + val isLocal: Boolean, +) + +object RetroNetplayLobby { + const val DEFAULT_TCP_PORT = 55435 + const val DISCOVERY_PORT = 55436 + internal const val DISCOVERY_MAGIC = "WNNP1" + + var phase by mutableStateOf(RetroNetplayPhase.IDLE) + private set + var statusText by mutableStateOf("") + private set + var members by mutableStateOf>(emptyList()) + private set + var discovered by mutableStateOf>(emptyList()) + private set + var roomTitle by mutableStateOf("") + private set + var isHost by mutableStateOf(false) + private set + var localPlayerName by mutableStateOf("Player") + private set + + var isGameLink by mutableStateOf(false) + private set + + private var pendingGameLinkHost: Boolean? = null + private var pendingGameLinkPort: Int = RetroGameLink.DEFAULT_PORT + private var pendingGameLinkPeerIp: String = "" + + var eventToast by mutableStateOf(null) + private set + + private var session: RetroNetplaySession? = null + private var advertiser: NetplayAdvertiser? = null + private var scanner: NetplayScanner? = null + private val main = Handler(Looper.getMainLooper()) + private var toastClearToken = 0 + + fun canStartSession(): Boolean = + phase == RetroNetplayPhase.IDLE || + phase == RetroNetplayPhase.SCANNING || + phase == RetroNetplayPhase.SCAN_RESULTS + + fun isInRoomSession(): Boolean = + phase == RetroNetplayPhase.HOSTING || + phase == RetroNetplayPhase.CONNECTING || + phase == RetroNetplayPhase.IN_ROOM + + private fun pushToast(message: String) { + main.post { + val token = ++toastClearToken + eventToast = message + main.postDelayed({ + if (toastClearToken == token) eventToast = null + }, 2_800L) + } + } + + fun notifyPeerJoined(peerName: String) { + val peer = peerName.ifBlank { "Player 2" } + main.post { + discovered = emptyList() + phase = RetroNetplayPhase.IN_ROOM + statusText = "Ready" + val local = + members.firstOrNull { it.isLocal } + ?: RetroNetplayMember(localPlayerName, isHost = isHost, isLocal = true) + members = + if (isHost) { + listOf( + local.copy(isHost = true, isLocal = true), + RetroNetplayMember(peer, isHost = false, isLocal = false), + ) + } else { + listOf( + RetroNetplayMember(peer, isHost = true, isLocal = false), + local.copy(isHost = false, isLocal = true), + ) + } + pushToast("$peer connected") + } + } + + fun notifyPeerLeft(peerName: String = "Player") { + val left = peerName.ifBlank { "Player" } + main.post { + if (isHost) { + phase = RetroNetplayPhase.HOSTING + statusText = "Waiting for a player…" + members = + listOf( + RetroNetplayMember(localPlayerName, isHost = true, isLocal = true), + ) + } + pushToast("$left disconnected") + } + } + + fun clearToast() { + toastClearToken++ + eventToast = null + } + + fun defaultPlayerName(context: Context): String { + val saved = RetroDefaults.netplayPlayerName(context).trim() + if (saved.isNotEmpty()) return saved + val device = + runCatching { + Settings.Global.getString(context.contentResolver, Settings.Global.DEVICE_NAME) + }.getOrNull()?.trim().orEmpty() + return device.ifBlank { "Player" } + } + + fun bindLocalName(context: Context) { + localPlayerName = defaultPlayerName(context) + } + + fun localIpv4Addresses(): List { + val out = mutableListOf() + runCatching { + NetworkInterface.getNetworkInterfaces()?.toList().orEmpty().forEach { nif -> + if (!nif.isUp || nif.isLoopback) return@forEach + nif.inetAddresses.toList().forEach { addr -> + if (addr.isLoopbackAddress || addr.hostAddress?.contains(':') == true) return@forEach + val ip = addr.hostAddress ?: return@forEach + if (ip.isNotBlank()) out += ip + } + } + } + return out.distinct() + } + + fun host( + systemId: String, + gameName: String, + playerName: String, + port: Int, + context: Context? = null, + retroView: GLRetroView? = null, + ) { + leave(silent = true) + isHost = true + localPlayerName = playerName.ifBlank { "Host" } + roomTitle = gameName + discovered = emptyList() + isGameLink = RetroOnlineSupport.supportsGameLink(systemId) + phase = RetroNetplayPhase.HOSTING + val usePort = + if (isGameLink) RetroGameLink.clampPort(port) else port + val localIp = localIpv4Addresses().firstOrNull() + statusText = + if (isGameLink) { + if (localIp != null) { + "Game Link host · $localIp:$usePort" + } else { + "Game Link host · port $usePort" + } + } else if (localIp != null) { + "Waiting on $localIp:$usePort…" + } else { + "Waiting for a player on port $usePort…" + } + members = + listOf( + RetroNetplayMember(localPlayerName, isHost = true, isLocal = true), + ) + val roomId = UUID.randomUUID().toString().take(8) + advertiser = + NetplayAdvertiser( + appContext = context?.applicationContext, + tcpPort = usePort, + systemId = systemId, + gameName = gameName, + hostPlayerName = localPlayerName, + roomId = roomId, + ).also { it.start() } + + if (isGameLink) { + pendingGameLinkHost = true + pendingGameLinkPort = + if (RetroOnlineSupport.isGbaNetpacket(systemId)) { + RetroGameLink.GBA_NETPACKET_PORT + } else { + usePort + } + pendingGameLinkPeerIp = "" + startPresenceListener() + bindNetpacketPeerListener() + if (retroView != null) { + val ok = + if (RetroOnlineSupport.isGbaNetpacket(systemId)) { + RetroGameLink.startGbaHost(retroView, pendingGameLinkPort) + } else { + RetroGameLink.startHost(retroView, pendingGameLinkPort) + true + } + phase = RetroNetplayPhase.HOSTING + statusText = + if (ok) { + "Game Link host · waiting for player on $pendingGameLinkPort" + } else { + "Game Link host failed (need gpSP / netpacket)" + } + pushToast(if (ok) "Hosting — waiting for player" else "Game Link host failed") + } + return + } + + val s = + RetroNetplaySession( + retroView = retroView, + localPort = 0, + remotePort = 1, + isHost = true, + onStatus = { msg -> main.post { statusText = msg } }, + onPeerJoined = { peerName -> + notifyPeerJoined(peerName.ifBlank { "Player 2" }) + }, + onPeerLeft = { + val left = members.firstOrNull { !it.isLocal }?.name ?: "Player" + if (phase == RetroNetplayPhase.IN_ROOM || phase == RetroNetplayPhase.HOSTING) { + notifyPeerLeft(left) + } + }, + onEnded = { ended -> + main.post { + if (session === ended && phase != RetroNetplayPhase.IDLE) { + leave(silent = false, message = "Room closed") + } + } + }, + ) + startPresenceListener() + session = s + s.startHost(usePort) + } + + fun join( + host: String, + port: Int, + playerName: String, + gameName: String, + systemId: String? = null, + retroView: GLRetroView? = null, + ) { + leave(silent = true) + isHost = false + localPlayerName = playerName.ifBlank { "Player 2" } + roomTitle = gameName + discovered = emptyList() + isGameLink = + systemId != null && RetroOnlineSupport.supportsGameLink(systemId) + phase = RetroNetplayPhase.CONNECTING + val usePort = + if (isGameLink) RetroGameLink.clampPort(port) else port + statusText = "Connecting to $host:$usePort…" + members = emptyList() + + if (isGameLink) { + pendingGameLinkHost = false + pendingGameLinkPort = + if (RetroOnlineSupport.isGbaNetpacket(systemId)) { + RetroGameLink.GBA_NETPACKET_PORT + } else { + usePort + } + pendingGameLinkPeerIp = host + members = + listOf( + RetroNetplayMember(host, isHost = true, isLocal = false), + RetroNetplayMember(localPlayerName, isHost = false, isLocal = true), + ) + if (retroView != null) { + val ok = + if (RetroOnlineSupport.isGbaNetpacket(systemId)) { + RetroGameLink.startGbaClient(retroView, host, pendingGameLinkPort) + } else { + RetroGameLink.startClient(retroView, host, pendingGameLinkPort) + true + } + phase = RetroNetplayPhase.IN_ROOM + statusText = + if (ok) { + "Game Link client · $host:$pendingGameLinkPort" + } else { + "Game Link join failed (need gpSP / netpacket)" + } + if (ok) { + pushToast("Connected to host") + sendPresenceJoin(host, pendingGameLinkPort, localPlayerName) + } else { + pushToast("Game Link join failed") + } + } else { + phase = RetroNetplayPhase.IN_ROOM + statusText = "Game Link ready · launch game to link $host" + sendPresenceJoin(host, pendingGameLinkPort, localPlayerName) + } + return + } + + val s = + RetroNetplaySession( + retroView = retroView, + localPort = 1, + remotePort = 0, + isHost = false, + onStatus = { msg -> main.post { statusText = msg } }, + onPeerJoined = { peerName -> + val peer = peerName.ifBlank { "Host" } + main.post { + discovered = emptyList() + phase = RetroNetplayPhase.IN_ROOM + statusText = "Ready" + members = + listOf( + RetroNetplayMember(peer, isHost = true, isLocal = false), + RetroNetplayMember(localPlayerName, isHost = false, isLocal = true), + ) + pushToast("Connected to $peer") + } + sendPresenceJoin(host, usePort, localPlayerName) + }, + onPeerLeft = { + main.post { + pushToast("Host disconnected") + leave(silent = false, message = "Host disconnected") + } + }, + onEnded = { ended -> + main.post { + if (session === ended && phase != RetroNetplayPhase.IDLE) { + leave(silent = false, message = "Disconnected") + } + } + }, + ) + session = s + s.startClient(host, usePort, localPlayerName) + } + + fun attachEmulator(retroView: GLRetroView): Boolean { + if (isGameLink && pendingGameLinkHost != null) { + val hasNetpacket = runCatching { retroView.netpacketHasCore() }.getOrDefault(false) + val ok = + if (pendingGameLinkHost == true) { + if (hasNetpacket) { + RetroGameLink.startGbaHost(retroView, pendingGameLinkPort) + } else { + RetroGameLink.startHost(retroView, pendingGameLinkPort) + true + } + } else if (hasNetpacket) { + RetroGameLink.startGbaClient( + retroView, + pendingGameLinkPeerIp, + pendingGameLinkPort, + ) + } else { + RetroGameLink.startClient( + retroView, + pendingGameLinkPeerIp, + pendingGameLinkPort, + ) + true + } + phase = RetroNetplayPhase.IN_ROOM + statusText = + if (ok) { + if (pendingGameLinkHost == true) { + "Game Link host active · port $pendingGameLinkPort" + } else { + "Game Link client · ${pendingGameLinkPeerIp}:$pendingGameLinkPort" + } + } else { + "Game Link attach failed" + } + if (ok) { + if (pendingGameLinkHost == true) { + startPresenceListener() + bindNetpacketPeerListener() + pushToast("Hosting — waiting for player") + } else { + pushToast("Connected to host") + sendPresenceJoin( + pendingGameLinkPeerIp, + pendingGameLinkPort, + localPlayerName, + ) + } + } else { + pushToast("Game Link failed") + } + return true + } + val s = session ?: return false + if (!isInRoomSession()) return false + s.attachRetroView(retroView) + if (isHost) { + startPresenceListener() + } else { + } + return true + } + + fun prepareMultiplayerPads(retroView: GLRetroView) { + runCatching { + retroView.setControllerType(0, 1) + retroView.setControllerType(1, 1) + } + } + + fun scan( + context: Context, + systemId: String?, + durationMs: Long = 6_500L, + ) { + if (phase == RetroNetplayPhase.HOSTING || phase == RetroNetplayPhase.IN_ROOM || + phase == RetroNetplayPhase.CONNECTING + ) { + return + } + scanner?.stop() + scanner = null + phase = RetroNetplayPhase.SCANNING + statusText = "Scanning local network…" + discovered = emptyList() + val app = context.applicationContext + scanner = + NetplayScanner(appContext = app, systemIdFilter = systemId) { rooms -> + main.post { + discovered = rooms + if (phase == RetroNetplayPhase.SCANNING) { + statusText = + if (rooms.isEmpty()) { + "Looking for rooms…" + } else { + "Found ${rooms.size} room${if (rooms.size == 1) "" else "s"}…" + } + } + } + }.also { + it.start(durationMs) { + main.post { + if (phase == RetroNetplayPhase.SCANNING) { + phase = RetroNetplayPhase.SCAN_RESULTS + statusText = + if (discovered.isEmpty()) { + "No rooms found on Wi‑Fi" + } else { + "Found ${discovered.size} room${if (discovered.size == 1) "" else "s"}" + } + } + } + } + } + } + + fun stopScan() { + scanner?.stop() + scanner = null + if (phase == RetroNetplayPhase.SCANNING) { + phase = RetroNetplayPhase.SCAN_RESULTS + statusText = + if (discovered.isEmpty()) { + "Scan stopped" + } else { + "Found ${discovered.size} room${if (discovered.size == 1) "" else "s"}" + } + } + } + + fun dismissScanResults() { + if (phase == RetroNetplayPhase.SCANNING) { + scanner?.stop() + scanner = null + } + if (phase == RetroNetplayPhase.SCANNING || phase == RetroNetplayPhase.SCAN_RESULTS) { + phase = RetroNetplayPhase.IDLE + discovered = emptyList() + statusText = "" + } + } + + fun leave( + silent: Boolean = false, + message: String = "Left room", + retroView: GLRetroView? = null, + ) { + if (!isHost && pendingGameLinkPeerIp.isNotBlank()) { + sendPresenceLeave(pendingGameLinkPeerIp, pendingGameLinkPort, localPlayerName) + } + scanner?.stop() + scanner = null + advertiser?.stop() + advertiser = null + stopPresenceListener() + unbindNetpacketPeerListener() + val s = session + session = null + s?.stop() + if (isGameLink) { + RetroGameLink.stop(retroView) + } + pendingGameLinkHost = null + pendingGameLinkPeerIp = "" + isGameLink = false + phase = RetroNetplayPhase.IDLE + members = emptyList() + roomTitle = "" + discovered = emptyList() + isHost = false + if (!silent) { + statusText = message + main.postDelayed({ + if (phase == RetroNetplayPhase.IDLE && statusText == message) { + statusText = "" + } + }, 2_500L) + } else { + statusText = "" + } + } + + private const val PRESENCE_JOIN = "WNNPJ" + private const val PRESENCE_LEAVE = "WNNPL" + private var presenceSocket: DatagramSocket? = null + private val presenceRunning = AtomicBoolean(false) + + private fun startPresenceListener() { + stopPresenceListener() + if (!presenceRunning.compareAndSet(false, true)) return + thread(name = "retro-netplay-presence", isDaemon = true) { + try { + val sock = DatagramSocket(null) + presenceSocket = sock + sock.reuseAddress = true + sock.broadcast = true + sock.soTimeout = 500 + sock.bind(InetSocketAddress(DISCOVERY_PORT)) + val buf = ByteArray(256) + while (presenceRunning.get()) { + val packet = DatagramPacket(buf, buf.size) + try { + sock.receive(packet) + } catch (_: SocketTimeoutException) { + continue + } catch (_: Throwable) { + break + } + val text = + String(packet.data, packet.offset, packet.length, StandardCharsets.UTF_8) + val parts = text.split('|') + if (parts.size < 2) continue + val name = parts[1].ifBlank { "Player" } + when (parts[0]) { + PRESENCE_JOIN -> { + if (isHost && + (phase == RetroNetplayPhase.HOSTING || phase == RetroNetplayPhase.IN_ROOM) + ) { + notifyPeerJoined(name) + } + } + PRESENCE_LEAVE -> { + if (isHost && phase == RetroNetplayPhase.IN_ROOM) { + notifyPeerLeft(name) + } + } + } + } + } catch (_: Throwable) { + } finally { + runCatching { presenceSocket?.close() } + presenceSocket = null + presenceRunning.set(false) + } + } + } + + private fun stopPresenceListener() { + presenceRunning.set(false) + runCatching { presenceSocket?.close() } + presenceSocket = null + } + + private fun sendPresenceJoin( + host: String, + port: Int, + name: String, + ) { + thread(name = "retro-netplay-presence-send", isDaemon = true) { + runCatching { + val payload = + "$PRESENCE_JOIN|${name.replace('|', '/').take(24)}|$port" + .toByteArray(StandardCharsets.UTF_8) + DatagramSocket().use { sock -> + sock.broadcast = true + val addr = InetAddress.getByName(host) + sock.send( + DatagramPacket(payload, payload.size, addr, DISCOVERY_PORT), + ) + runCatching { + sock.send( + DatagramPacket( + payload, + payload.size, + InetAddress.getByName("255.255.255.255"), + DISCOVERY_PORT, + ), + ) + } + } + } + } + } + + private fun sendPresenceLeave( + host: String, + port: Int, + name: String, + ) { + thread(name = "retro-netplay-presence-leave", isDaemon = true) { + runCatching { + val payload = + "$PRESENCE_LEAVE|${name.replace('|', '/').take(24)}|$port" + .toByteArray(StandardCharsets.UTF_8) + DatagramSocket().use { sock -> + sock.send( + DatagramPacket( + payload, + payload.size, + InetAddress.getByName(host), + DISCOVERY_PORT, + ), + ) + } + } + } + } + + private fun bindNetpacketPeerListener() { + runCatching { + com.swordfish.libretrodroid.LibretroDroid.setNetpacketPeerListener { joined, _ -> + if (joined) { + notifyPeerJoined("Player 2") + } else { + notifyPeerLeft("Player 2") + } + } + } + } + + private fun unbindNetpacketPeerListener() { + runCatching { + com.swordfish.libretrodroid.LibretroDroid.setNetpacketPeerListener(null) + } + } + + fun activeSession(): RetroNetplaySession? = session + + fun sendLocalKey(keyCode: Int, action: Int) { + session?.sendLocalKey(keyCode, action) + } + + fun sendLocalMotion(source: Int, x: Float, y: Float) { + session?.sendLocalMotion(source, x, y) + } + + fun onFrameRendered() { + session?.onFrameRendered() + } +} + +private fun acquireMulticastLock(appContext: Context?): WifiManager.MulticastLock? { + if (appContext == null) return null + return runCatching { + val wifi = appContext.applicationContext.getSystemService(Context.WIFI_SERVICE) as? WifiManager + ?: return null + wifi.createMulticastLock("winnative-netplay").apply { + setReferenceCounted(false) + acquire() + } + }.getOrNull() +} + +private class NetplayAdvertiser( + private val appContext: Context?, + private val tcpPort: Int, + private val systemId: String, + private val gameName: String, + private val hostPlayerName: String, + private val roomId: String, +) { + private val running = AtomicBoolean(false) + private var socket: DatagramSocket? = null + private var multicastLock: WifiManager.MulticastLock? = null + + fun start() { + if (!running.compareAndSet(false, true)) return + thread(name = "retro-netplay-advertise", isDaemon = true) { + try { + multicastLock = acquireMulticastLock(appContext) + val sock = DatagramSocket() + socket = sock + sock.broadcast = true + val payload = + buildString { + append(RetroNetplayLobby.DISCOVERY_MAGIC) + append('|') + append(systemId.replace('|', '/')) + append('|') + append(tcpPort) + append('|') + append(gameName.replace('|', '/').take(48)) + append('|') + append(hostPlayerName.replace('|', '/').take(24)) + append('|') + append(roomId) + }.toByteArray(StandardCharsets.UTF_8) + val broadcast = InetAddress.getByName("255.255.255.255") + while (running.get()) { + val packet = + DatagramPacket( + payload, + payload.size, + broadcast, + RetroNetplayLobby.DISCOVERY_PORT, + ) + runCatching { sock.send(packet) } + runCatching { + NetworkInterface.getNetworkInterfaces()?.toList().orEmpty().forEach { nif -> + if (!nif.isUp || nif.isLoopback) return@forEach + nif.interfaceAddresses.forEach { addr -> + val b = addr.broadcast ?: return@forEach + sock.send( + DatagramPacket(payload, payload.size, b, RetroNetplayLobby.DISCOVERY_PORT), + ) + } + } + } + Thread.sleep(800L) + } + } catch (_: Throwable) { + } finally { + runCatching { socket?.close() } + socket = null + runCatching { if (multicastLock?.isHeld == true) multicastLock?.release() } + multicastLock = null + running.set(false) + } + } + } + + fun stop() { + running.set(false) + runCatching { socket?.close() } + socket = null + runCatching { if (multicastLock?.isHeld == true) multicastLock?.release() } + multicastLock = null + } +} + +private class NetplayScanner( + private val appContext: Context?, + private val systemIdFilter: String?, + private val onUpdate: (List) -> Unit, +) { + private val running = AtomicBoolean(false) + private var socket: DatagramSocket? = null + private var multicastLock: WifiManager.MulticastLock? = null + private val rooms = ConcurrentHashMap() + + fun start( + durationMs: Long, + onFinished: () -> Unit, + ) { + if (!running.compareAndSet(false, true)) return + thread(name = "retro-netplay-scan", isDaemon = true) { + try { + multicastLock = acquireMulticastLock(appContext) + val sock = DatagramSocket(null) + socket = sock + sock.reuseAddress = true + sock.broadcast = true + sock.soTimeout = 350 + sock.bind(InetSocketAddress(RetroNetplayLobby.DISCOVERY_PORT)) + val buf = ByteArray(512) + val deadline = System.currentTimeMillis() + durationMs + while (running.get() && System.currentTimeMillis() < deadline) { + val packet = DatagramPacket(buf, buf.size) + try { + sock.receive(packet) + } catch (_: SocketTimeoutException) { + continue + } catch (_: Throwable) { + break + } + val text = + String(packet.data, packet.offset, packet.length, StandardCharsets.UTF_8) + val hostAddr = packet.address?.hostAddress ?: continue + val room = parse(text, hostAddr) ?: continue + if (systemIdFilter != null && room.systemId != systemIdFilter) continue + rooms[room.roomId + "@" + room.hostAddress] = room + onUpdate(rooms.values.sortedBy { it.gameName.lowercase() }) + } + } catch (_: Throwable) { + } finally { + runCatching { socket?.close() } + socket = null + runCatching { if (multicastLock?.isHeld == true) multicastLock?.release() } + multicastLock = null + running.set(false) + onFinished() + } + } + } + + fun stop() { + running.set(false) + runCatching { socket?.close() } + socket = null + } + + private fun parse( + text: String, + address: String, + ): RetroNetplayDiscoveredRoom? { + val parts = text.split('|') + if (parts.size < 6) return null + if (parts[0] != RetroNetplayLobby.DISCOVERY_MAGIC) return null + val port = parts[2].toIntOrNull() ?: return null + return RetroNetplayDiscoveredRoom( + hostAddress = address, + port = port.coerceIn(1, 65535), + systemId = parts[1], + gameName = parts[3], + hostPlayerName = parts[4], + roomId = parts[5], + ) + } +} + +class RetroNetplaySession( + retroView: GLRetroView?, + private val localPort: Int, + private val remotePort: Int, + private val isHost: Boolean, + private val onStatus: (String) -> Unit, + private val onPeerJoined: (peerName: String) -> Unit = {}, + private val onPeerLeft: () -> Unit = {}, + private val onEnded: (RetroNetplaySession) -> Unit = {}, +) { + private val running = AtomicBoolean(false) + private val main = Handler(Looper.getMainLooper()) + private val remoteKeys = ConcurrentHashMap.newKeySet() + private var socket: Socket? = null + private var server: ServerSocket? = null + private var out: DataOutputStream? = null + private var frameCounter = 0 + private var peerName: String = "" + + @Volatile + private var retroView: GLRetroView? = retroView + + fun attachRetroView(view: GLRetroView) { + retroView = view + RetroNetplayLobby.prepareMultiplayerPads(view) + if (isHost) { + pushStateNow() + } else { + requestState() + } + } + + companion object { + private const val MSG_KEY = 1 + private const val MSG_STATE = 2 + private const val MSG_HELLO = 3 + private const val MSG_MOTION = 4 + private const val MSG_STATE_REQUEST = 5 + private const val STATE_EVERY_FRAMES = 600 + private const val RETRO_DEVICE_JOYPAD = 1 + } + + val isRunning: Boolean get() = running.get() + + fun startHost(listenPort: Int) { + if (!running.compareAndSet(false, true)) return + retroView?.let { RetroNetplayLobby.prepareMultiplayerPads(it) } + thread(name = "retro-netplay-host", isDaemon = true) { + try { + onStatus("Waiting for a player…") + val ss = ServerSocket() + server = ss + ss.reuseAddress = true + ss.bind(InetSocketAddress(listenPort)) + while (running.get()) { + val client = + try { + ss.accept() + } catch (_: Throwable) { + break + } + socket = client + wire(client) + handshakeAsHost(client) + val joinedName = peerName.ifBlank { "Player 2" } + onStatus("$joinedName joined") + onPeerJoined(joinedName) + pushStateNow() + readLoop(client) + cleanupSocketOnly() + onPeerLeft() + if (!running.get()) break + onStatus("Waiting for a player…") + } + } catch (t: Throwable) { + if (running.get()) onStatus(t.message ?: "Host failed") + } finally { + val wasRunning = running.get() + stopInternal() + if (wasRunning) onEnded(this) + } + } + } + + fun startClient( + host: String, + port: Int, + localName: String, + ) { + if (!running.compareAndSet(false, true)) return + retroView?.let { RetroNetplayLobby.prepareMultiplayerPads(it) } + thread(name = "retro-netplay-client", isDaemon = true) { + try { + onStatus("Connecting…") + val s = Socket() + socket = s + s.tcpNoDelay = true + s.connect(InetSocketAddress(host, port), 12_000) + wire(s) + handshakeAsClient(s, localName) + onStatus("Connected") + onPeerJoined(peerName) + requestState() + readLoop(s) + } catch (t: Throwable) { + if (running.get()) onStatus(t.message ?: "Connect failed") + } finally { + val wasRunning = running.get() + stopInternal() + if (wasRunning) onEnded(this) + } + } + } + + private fun requestState() { + val stream = out ?: return + thread(name = "retro-netplay-state-req", isDaemon = true) { + runCatching { + synchronized(stream) { + stream.writeInt(MSG_STATE_REQUEST) + stream.flush() + } + } + } + } + + private fun pushStateNow() { + val view = retroView ?: return + val stream = out ?: return + if (!isHost || !running.get()) return + thread(name = "retro-netplay-state-push", isDaemon = true) { + runCatching { + val state = view.serializeState() + synchronized(stream) { + stream.writeInt(MSG_STATE) + stream.writeInt(state.size) + stream.write(state) + stream.flush() + } + } + } + } + + private fun handshakeAsHost(s: Socket) { + val input = DataInputStream(BufferedInputStream(s.getInputStream())) + val stream = out ?: return + val type = input.readInt() + if (type != MSG_HELLO) throw IllegalStateException("Bad handshake") + peerName = input.readUTF().ifBlank { "Player 2" } + synchronized(stream) { + stream.writeInt(MSG_HELLO) + stream.writeUTF(RetroNetplayLobby.localPlayerName.ifBlank { "Host" }) + stream.flush() + } + } + + private fun handshakeAsClient( + s: Socket, + localName: String, + ) { + val stream = out ?: return + synchronized(stream) { + stream.writeInt(MSG_HELLO) + stream.writeUTF(localName) + stream.flush() + } + val input = DataInputStream(BufferedInputStream(s.getInputStream())) + val type = input.readInt() + if (type != MSG_HELLO) throw IllegalStateException("Bad handshake") + peerName = input.readUTF().ifBlank { "Host" } + } + + private fun wire(s: Socket) { + s.tcpNoDelay = true + out = DataOutputStream(BufferedOutputStream(s.getOutputStream())) + } + + private fun readLoop(s: Socket) { + val input = DataInputStream(BufferedInputStream(s.getInputStream())) + while (running.get() && !s.isClosed) { + val type = + try { + input.readInt() + } catch (_: Throwable) { + break + } + when (type) { + MSG_KEY -> { + val keyCode = input.readInt() + val action = input.readInt() + main.post { + if (!running.get()) return@post + if (action == KeyEvent.ACTION_DOWN) remoteKeys.add(keyCode) else remoteKeys.remove(keyCode) + retroView?.sendKeyEvent(action, keyCode, remotePort) + } + } + MSG_MOTION -> { + val source = input.readInt() + val x = input.readFloat() + val y = input.readFloat() + main.post { + if (!running.get()) return@post + retroView?.sendMotionEvent(source, x, y, remotePort) + } + } + MSG_STATE -> { + val len = input.readInt().coerceIn(0, 8 * 1024 * 1024) + val bytes = ByteArray(len) + input.readFully(bytes) + if (!isHost) { + main.post { + val view = retroView ?: return@post + runCatching { view.unserializeState(bytes) } + remoteKeys.forEach { code -> + view.sendKeyEvent(KeyEvent.ACTION_DOWN, code, remotePort) + } + } + } + } + MSG_STATE_REQUEST -> { + if (isHost) pushStateNow() + } + MSG_HELLO -> { + runCatching { input.readUTF() } + } + else -> break + } + } + } + + fun sendLocalKey( + keyCode: Int, + action: Int, + ) { + val stream = out ?: return + if (!running.get()) return + thread(name = "retro-netplay-send", isDaemon = true) { + runCatching { + synchronized(stream) { + stream.writeInt(MSG_KEY) + stream.writeInt(keyCode) + stream.writeInt(action) + stream.flush() + } + } + } + } + + fun sendLocalMotion( + source: Int, + x: Float, + y: Float, + ) { + val stream = out ?: return + if (!running.get()) return + thread(name = "retro-netplay-motion", isDaemon = true) { + runCatching { + synchronized(stream) { + stream.writeInt(MSG_MOTION) + stream.writeInt(source) + stream.writeFloat(x) + stream.writeFloat(y) + stream.flush() + } + } + } + } + + fun onFrameRendered() { + if (!isHost || !running.get() || out == null || retroView == null) return + frameCounter++ + if (frameCounter % STATE_EVERY_FRAMES != 0) return + pushStateNow() + } + + fun stop() { + stopInternal() + } + + private fun cleanupSocketOnly() { + runCatching { out?.close() } + runCatching { socket?.close() } + out = null + socket = null + val view = retroView + remoteKeys.forEach { code -> + main.post { view?.sendKeyEvent(KeyEvent.ACTION_UP, code, remotePort) } + } + remoteKeys.clear() + } + + private fun stopInternal() { + if (!running.getAndSet(false)) { + cleanupSocketOnly() + runCatching { server?.close() } + server = null + return + } + cleanupSocketOnly() + runCatching { server?.close() } + server = null + } +} diff --git a/app/src/main/feature/retro/RetroNetplayEditField.kt b/app/src/main/feature/retro/RetroNetplayEditField.kt new file mode 100644 index 000000000..962677c57 --- /dev/null +++ b/app/src/main/feature/retro/RetroNetplayEditField.kt @@ -0,0 +1,175 @@ +package com.winlator.cmod.feature.retro + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Delete +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.Icon +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.OutlinedTextFieldDefaults +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.winlator.cmod.R +import com.winlator.cmod.shared.theme.GameSettingsStyle + +@Composable +fun RetroNetplayEditField( + label: String, + value: String, + placeholder: String, + numeric: Boolean = false, + onChange: (String) -> Unit, +) { + var editing by remember { mutableStateOf(false) } + var draft by remember(value) { mutableStateOf(value) } + + Column( + modifier = + Modifier + .fillMaxWidth() + .padding(vertical = 6.dp), + ) { + Text( + label, + color = GameSettingsStyle.TextSecondary, + fontSize = 11.sp, + fontWeight = FontWeight.Medium, + ) + Spacer(Modifier.height(4.dp)) + + if (editing) { + Row( + Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + OutlinedTextField( + value = draft, + onValueChange = { draft = it }, + singleLine = true, + placeholder = { Text(placeholder, fontSize = 12.sp) }, + keyboardOptions = + if (numeric) { + KeyboardOptions(keyboardType = KeyboardType.Number) + } else { + KeyboardOptions.Default + }, + colors = + OutlinedTextFieldDefaults.colors( + focusedBorderColor = GameSettingsStyle.AccentBlue, + unfocusedBorderColor = GameSettingsStyle.CardBorder, + focusedTextColor = GameSettingsStyle.TextPrimary, + unfocusedTextColor = GameSettingsStyle.TextPrimary, + ), + modifier = Modifier.weight(1f), + ) + NetplayPillButton( + text = stringResource(R.string.retro_gs_save), + color = GameSettingsStyle.AccentBlue, + ) { + onChange(draft.trim()) + editing = false + } + } + } else { + Row( + Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + value.ifBlank { placeholder }, + color = + if (value.isBlank()) { + GameSettingsStyle.TextDim + } else { + GameSettingsStyle.TextPrimary + }, + fontSize = 13.sp, + fontWeight = FontWeight.Medium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + NetplayPillButton( + text = stringResource(R.string.common_ui_edit), + color = GameSettingsStyle.AccentBlue, + ) { + draft = value + editing = true + } + if (value.isNotBlank()) { + NetplayIconPillButton( + icon = Icons.Outlined.Delete, + color = GameSettingsStyle.DangerRed, + contentDescription = stringResource(R.string.retro_scr_delete), + ) { + draft = "" + onChange("") + } + } + } + } + } +} + +@Composable +private fun NetplayPillButton( + text: String, + color: Color, + onClick: () -> Unit, +) { + OutlinedButton( + onClick = onClick, + border = BorderStroke(1.dp, color), + colors = ButtonDefaults.outlinedButtonColors(contentColor = color), + contentPadding = PaddingValues(horizontal = 14.dp, vertical = 4.dp), + modifier = Modifier.height(38.dp), + ) { + Text(text, fontSize = 12.sp, fontWeight = FontWeight.Medium, maxLines = 1) + } +} + +@Composable +private fun NetplayIconPillButton( + icon: ImageVector, + color: Color, + contentDescription: String, + onClick: () -> Unit, +) { + OutlinedButton( + onClick = onClick, + border = BorderStroke(1.dp, color), + colors = ButtonDefaults.outlinedButtonColors(contentColor = color), + contentPadding = PaddingValues(0.dp), + modifier = Modifier.height(38.dp).width(46.dp), + ) { + Icon(icon, contentDescription = contentDescription, modifier = Modifier.size(18.dp)) + } +} diff --git a/app/src/main/feature/retro/RetroNetplayUi.kt b/app/src/main/feature/retro/RetroNetplayUi.kt new file mode 100644 index 000000000..d50da7de9 --- /dev/null +++ b/app/src/main/feature/retro/RetroNetplayUi.kt @@ -0,0 +1,683 @@ +package com.winlator.cmod.feature.retro + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.slideInVertically +import androidx.compose.animation.slideOutVertically +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Group +import androidx.compose.material.icons.outlined.Link +import androidx.compose.material.icons.outlined.Search +import androidx.compose.material.icons.outlined.Wifi +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.winlator.cmod.R +import com.winlator.cmod.shared.theme.GameSettingsStyle + +private val RoomBg = Color(0xF0121824) +private val RoomBorder = Color(0xFF1A9FFF).copy(alpha = 0.45f) +private val OnlineDot = Color(0xFF3FB950) +private val RoomCardBg = Color(0xFF141C28) +private val RoomCardBorder = Color(0xFF2A3A4E) + +@Composable +fun RetroNetplayRoomBanner( + onLeave: () -> Unit, + onJoinRoom: ((RetroNetplayDiscoveredRoom) -> Unit)? = null, + modifier: Modifier = Modifier, +) { + val phase = RetroNetplayLobby.phase + val status = RetroNetplayLobby.statusText + val discovered = RetroNetplayLobby.discovered + val showResults = + phase == RetroNetplayPhase.SCAN_RESULTS || + phase == RetroNetplayPhase.SCANNING || + (phase == RetroNetplayPhase.IDLE && discovered.isNotEmpty()) + if (!showResults) return + + Column( + modifier = + modifier + .fillMaxWidth(0.78f) + .background(RoomBg, RoundedCornerShape(12.dp)) + .border(1.dp, RoomBorder, RoundedCornerShape(12.dp)) + .padding(horizontal = 12.dp, vertical = 10.dp), + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + Icon( + imageVector = + when (phase) { + RetroNetplayPhase.SCANNING, RetroNetplayPhase.SCAN_RESULTS -> Icons.Outlined.Search + else -> Icons.Outlined.Wifi + }, + contentDescription = null, + tint = GameSettingsStyle.AccentBlue, + modifier = Modifier.size(18.dp), + ) + Spacer(Modifier.width(8.dp)) + Column(Modifier.weight(1f)) { + Text( + text = + when (phase) { + RetroNetplayPhase.SCANNING -> stringResource(R.string.retro_netplay_scanning) + RetroNetplayPhase.SCAN_RESULTS -> stringResource(R.string.retro_netplay_scan_results) + else -> stringResource(R.string.retro_netplay_title) + }, + color = Color(0xFFF0F4FF), + fontSize = 13.sp, + fontWeight = FontWeight.SemiBold, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (status.isNotBlank()) { + Text( + status, + color = Color(0xFF93A6BC), + fontSize = 11.sp, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + } + if (phase == RetroNetplayPhase.SCANNING) { + CircularProgressIndicator( + modifier = Modifier.size(16.dp).padding(end = 4.dp), + strokeWidth = 2.dp, + color = GameSettingsStyle.AccentBlue, + ) + } + TextButton(onClick = onLeave) { + Text( + text = + when (phase) { + RetroNetplayPhase.SCANNING -> stringResource(R.string.retro_netplay_stop_scan) + else -> stringResource(R.string.retro_netplay_dismiss) + }, + color = GameSettingsStyle.DangerRed, + fontSize = 12.sp, + ) + } + } + + if (discovered.isNotEmpty()) { + Spacer(Modifier.height(8.dp)) + discovered.forEach { room -> + RoomResultRow( + room = room, + onClick = + if (onJoinRoom != null) { + { onJoinRoom(room) } + } else { + null + }, + ) + Spacer(Modifier.height(4.dp)) + } + } + } +} + +@Composable +private fun RoomResultRow( + room: RetroNetplayDiscoveredRoom, + onClick: (() -> Unit)?, +) { + Row( + modifier = + Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(8.dp)) + .background(RoomCardBg) + .border(1.dp, RoomCardBorder, RoundedCornerShape(8.dp)) + .then( + if (onClick != null) { + Modifier.clickable(onClick = onClick) + } else { + Modifier + }, + ) + .padding(horizontal = 10.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon( + Icons.Outlined.Link, + contentDescription = null, + tint = GameSettingsStyle.AccentBlue, + modifier = Modifier.size(16.dp), + ) + Spacer(Modifier.width(8.dp)) + Column(Modifier.weight(1f)) { + Text( + "${room.gameName} · ${room.hostPlayerName}", + color = Color(0xFFF0F4FF), + fontSize = 12.sp, + fontWeight = FontWeight.Medium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text( + "${room.hostAddress}:${room.port}", + color = Color(0xFF93A6BC), + fontSize = 11.sp, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + if (onClick != null) { + Text( + stringResource(R.string.retro_netplay_join_room), + color = GameSettingsStyle.AccentBlue, + fontSize = 12.sp, + fontWeight = FontWeight.SemiBold, + ) + } + } +} + +@Composable +fun RetroNetplayEventToast(modifier: Modifier = Modifier) { + val message = RetroNetplayLobby.eventToast + AnimatedVisibility( + visible = !message.isNullOrBlank(), + enter = fadeIn() + slideInVertically { it / 2 }, + exit = fadeOut() + slideOutVertically { it / 2 }, + modifier = modifier, + ) { + Text( + text = message.orEmpty(), + color = Color(0xFFF0F4FF), + fontSize = 12.sp, + fontWeight = FontWeight.Medium, + textAlign = TextAlign.Center, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + modifier = + Modifier + .clip(RoundedCornerShape(20.dp)) + .background(Color(0xE0121824)) + .border(1.dp, RoomBorder, RoundedCornerShape(20.dp)) + .padding(horizontal = 14.dp, vertical = 8.dp), + ) + } +} + +@Composable +fun RetroNetplaySettingsSection( + systemId: String, + version: Int, + onChanged: () -> Unit, +) { + val context = LocalContext.current + @Suppress("UNUSED_EXPRESSION") + version + val enabled = RetroDefaults.netplayEnabled(context, systemId) + val mode = RetroDefaults.netplayLaunchMode(context, systemId) + val host = RetroDefaults.netplayHost(context, systemId) + val port = RetroDefaults.netplayPort(context, systemId) + val player = RetroDefaults.netplayPlayerName(context) + val roomLabel = + RetroSystems.fromId(systemId)?.displayName + ?: stringResource(R.string.retro_netplay_title) + + val phase = RetroNetplayLobby.phase + val status = RetroNetplayLobby.statusText + val discovered = RetroNetplayLobby.discovered + val members = RetroNetplayLobby.members + val scanning = phase == RetroNetplayPhase.SCANNING + val inSession = + phase == RetroNetplayPhase.HOSTING || + phase == RetroNetplayPhase.IN_ROOM || + phase == RetroNetplayPhase.CONNECTING + + val isGameLink = RetroOnlineSupport.supportsGameLink(systemId) + val effectivePort = + if (isGameLink) RetroGameLink.clampPort(port) else port + + fun startHostNow() { + RetroNetplayLobby.bindLocalName(context) + RetroNetplayLobby.host( + systemId = systemId, + gameName = roomLabel, + playerName = RetroNetplayLobby.defaultPlayerName(context), + port = effectivePort, + context = context, + retroView = null, + ) + onChanged() + } + + fun joinNow(address: String, joinPort: Int = effectivePort, game: String = roomLabel) { + val target = address.trim() + if (target.isBlank()) return + RetroNetplayLobby.bindLocalName(context) + RetroNetplayLobby.join( + host = target, + port = joinPort, + playerName = RetroNetplayLobby.defaultPlayerName(context), + gameName = game, + systemId = systemId, + retroView = null, + ) + onChanged() + } + + RetroSettingGroup { + RetroGroupTitle(stringResource(R.string.retro_gs_section_online)) + Text( + stringResource( + if (isGameLink) { + R.string.retro_netplay_help_game_link + } else { + R.string.retro_netplay_help + }, + ), + color = GameSettingsStyle.TextSecondary, + fontSize = 12.sp, + softWrap = true, + maxLines = 8, + lineHeight = 16.sp, + overflow = TextOverflow.Clip, + modifier = + Modifier + .fillMaxWidth() + .padding(bottom = 8.dp), + ) + RetroSettingSwitch( + stringResource(R.string.retro_gs_netplay_enable), + enabled, + subtitle = stringResource(R.string.retro_gs_netplay_enable_subtitle), + ) { + if (it) { + RetroDefaults.setNetplayEnabled(context, systemId, true) + if (RetroDefaults.netplayLaunchMode(context, systemId) !in setOf("host", "join")) { + RetroDefaults.setNetplayLaunchMode(context, systemId, "off") + } + } else { + RetroDefaults.clearNetplayArm(context, systemId) + if (inSession || + phase == RetroNetplayPhase.SCANNING || + phase == RetroNetplayPhase.SCAN_RESULTS + ) { + RetroNetplayLobby.leave(silent = true) + } + } + onChanged() + } + if (enabled) { + RetroSettingTextField( + stringResource(R.string.retro_netplay_player_name), + player, + stringResource(R.string.retro_netplay_player_name_hint), + ) { + RetroDefaults.setNetplayPlayerName(context, it) + onChanged() + } + Text( + stringResource(R.string.retro_netplay_launch_mode), + color = GameSettingsStyle.TextSecondary, + fontSize = 11.sp, + fontWeight = FontWeight.Medium, + modifier = Modifier.padding(top = 8.dp, bottom = 4.dp), + ) + Row( + Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + listOf( + "host" to R.string.retro_netplay_mode_host, + "join" to R.string.retro_netplay_mode_join, + ).forEach { (id, labelRes) -> + val selected = mode == id + OutlinedButton( + onClick = { + RetroDefaults.setNetplayLaunchMode(context, systemId, id) + if (id == "host") { + startHostNow() + } else if (RetroNetplayLobby.isHost && inSession) { + RetroNetplayLobby.leave(silent = true) + } + onChanged() + }, + modifier = Modifier.weight(1f), + border = + BorderStroke( + 1.dp, + if (selected) { + GameSettingsStyle.AccentBlue + } else { + GameSettingsStyle.CardBorder + }, + ), + colors = + ButtonDefaults.outlinedButtonColors( + contentColor = + if (selected) { + GameSettingsStyle.AccentBlue + } else { + GameSettingsStyle.TextPrimary + }, + ), + ) { + Text(stringResource(labelRes), fontSize = 12.sp, maxLines = 1) + } + } + } + + RetroNetplayEditField( + label = stringResource(R.string.retro_gs_netplay_port), + value = port.toString(), + placeholder = RetroNetplayLobby.DEFAULT_TCP_PORT.toString(), + numeric = true, + ) { entered -> + val p = entered.toIntOrNull() ?: RetroNetplayLobby.DEFAULT_TCP_PORT + RetroDefaults.setNetplayPort(context, systemId, p) + onChanged() + } + + if (inSession) { + Spacer(Modifier.height(10.dp)) + Text( + when { + RetroNetplayLobby.isHost && phase == RetroNetplayPhase.HOSTING -> + stringResource(R.string.retro_netplay_hosting_room) + phase == RetroNetplayPhase.CONNECTING -> + stringResource(R.string.retro_netplay_connecting) + else -> stringResource(R.string.retro_netplay_in_room) + }, + color = GameSettingsStyle.AccentBlue, + fontSize = 12.sp, + fontWeight = FontWeight.SemiBold, + ) + if (status.isNotBlank()) { + Text( + status, + color = GameSettingsStyle.TextSecondary, + fontSize = 11.sp, + softWrap = true, + maxLines = 3, + lineHeight = 15.sp, + overflow = TextOverflow.Clip, + modifier = + Modifier + .fillMaxWidth() + .padding(top = 2.dp, bottom = 6.dp), + ) + } + members.forEach { member -> + val line = + buildString { + append(member.name) + if (member.isHost) append(" · Host") + if (member.isLocal) append(" · You") + if (!member.isHost && !member.isLocal) append(" · Joined") + } + Row( + Modifier + .fillMaxWidth() + .padding(vertical = 3.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon( + Icons.Outlined.Group, + contentDescription = null, + tint = GameSettingsStyle.AccentBlue, + modifier = Modifier.size(16.dp), + ) + Spacer(Modifier.width(8.dp)) + Text( + line, + color = GameSettingsStyle.TextPrimary, + fontSize = 13.sp, + softWrap = true, + maxLines = 2, + overflow = TextOverflow.Clip, + modifier = Modifier.weight(1f), + ) + } + } + TextButton( + onClick = { + RetroNetplayLobby.leave(silent = false) + onChanged() + }, + modifier = Modifier.padding(top = 4.dp), + ) { + Text( + stringResource(R.string.retro_netplay_leave), + color = GameSettingsStyle.DangerRed, + fontSize = 12.sp, + ) + } + Text( + stringResource(R.string.retro_netplay_prelaunch_hint), + color = GameSettingsStyle.TextDim, + fontSize = 11.sp, + softWrap = true, + maxLines = 4, + lineHeight = 15.sp, + overflow = TextOverflow.Clip, + modifier = + Modifier + .fillMaxWidth() + .padding(top = 4.dp), + ) + } else if (mode == "host") { + Text( + stringResource(R.string.retro_netplay_host_mode_hint), + color = GameSettingsStyle.TextDim, + fontSize = 11.sp, + softWrap = true, + maxLines = 5, + lineHeight = 15.sp, + overflow = TextOverflow.Clip, + modifier = + Modifier + .fillMaxWidth() + .padding(top = 8.dp), + ) + OutlinedButton( + onClick = { startHostNow() }, + modifier = + Modifier + .fillMaxWidth() + .padding(top = 8.dp), + border = BorderStroke(1.dp, GameSettingsStyle.AccentBlue), + colors = + ButtonDefaults.outlinedButtonColors( + contentColor = GameSettingsStyle.AccentBlue, + ), + ) { + Icon(Icons.Outlined.Group, contentDescription = null, modifier = Modifier.size(16.dp)) + Spacer(Modifier.width(8.dp)) + Text(stringResource(R.string.retro_netplay_host_action), fontSize = 12.sp) + } + } + + if (mode == "join" && !inSession) { + RetroNetplayEditField( + label = stringResource(R.string.retro_gs_netplay_host), + value = host, + placeholder = stringResource(R.string.retro_gs_netplay_host_hint), + ) { + RetroDefaults.setNetplayHost(context, systemId, it) + onChanged() + } + + Spacer(Modifier.height(10.dp)) + Text( + stringResource(R.string.retro_netplay_find_rooms), + color = GameSettingsStyle.TextSecondary, + fontSize = 11.sp, + fontWeight = FontWeight.Medium, + modifier = Modifier.padding(bottom = 6.dp), + ) + if (discovered.isNotEmpty()) { + discovered.forEach { room -> + RoomResultRow( + room = room, + onClick = { + joinNow( + address = room.hostAddress, + joinPort = room.port, + game = room.gameName.ifBlank { roomLabel }, + ) + }, + ) + Spacer(Modifier.height(6.dp)) + } + Text( + stringResource(R.string.retro_netplay_select_room_hint), + color = GameSettingsStyle.TextDim, + fontSize = 11.sp, + softWrap = true, + maxLines = 3, + modifier = Modifier.fillMaxWidth(), + ) + Spacer(Modifier.height(10.dp)) + } else if (phase == RetroNetplayPhase.SCAN_RESULTS) { + Text( + stringResource(R.string.retro_netplay_no_rooms), + color = GameSettingsStyle.TextDim, + fontSize = 12.sp, + modifier = Modifier.padding(bottom = 8.dp), + ) + } + Row( + Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + OutlinedButton( + onClick = { + if (scanning) { + RetroNetplayLobby.stopScan() + } else { + RetroNetplayLobby.scan(context, systemId) + } + onChanged() + }, + border = + BorderStroke( + 1.dp, + if (scanning) GameSettingsStyle.AccentBlue else GameSettingsStyle.CardBorder, + ), + colors = + ButtonDefaults.outlinedButtonColors( + contentColor = + if (scanning) { + GameSettingsStyle.AccentBlue + } else { + GameSettingsStyle.TextPrimary + }, + ), + modifier = Modifier.weight(1f), + ) { + if (scanning) { + CircularProgressIndicator( + modifier = Modifier.size(14.dp), + strokeWidth = 2.dp, + color = GameSettingsStyle.AccentBlue, + ) + Spacer(Modifier.width(8.dp)) + Text(stringResource(R.string.retro_netplay_stop_scan), fontSize = 12.sp) + } else { + Icon( + Icons.Outlined.Search, + contentDescription = null, + modifier = Modifier.size(16.dp), + ) + Spacer(Modifier.width(6.dp)) + Text(stringResource(R.string.retro_netplay_scan_action), fontSize = 12.sp) + } + } + if (scanning || phase == RetroNetplayPhase.SCAN_RESULTS || discovered.isNotEmpty()) { + TextButton( + onClick = { + RetroNetplayLobby.dismissScanResults() + onChanged() + }, + ) { + Text( + stringResource(R.string.retro_netplay_dismiss), + color = GameSettingsStyle.TextSecondary, + fontSize = 12.sp, + ) + } + } + } + + if (host.isNotBlank()) { + OutlinedButton( + onClick = { joinNow(host) }, + modifier = + Modifier + .fillMaxWidth() + .padding(top = 8.dp), + border = BorderStroke(1.dp, GameSettingsStyle.AccentBlue), + colors = + ButtonDefaults.outlinedButtonColors( + contentColor = GameSettingsStyle.AccentBlue, + ), + ) { + Icon(Icons.Outlined.Link, contentDescription = null, modifier = Modifier.size(16.dp)) + Spacer(Modifier.width(8.dp)) + Text(stringResource(R.string.retro_netplay_join_action), fontSize = 12.sp) + } + } + + if (status.isNotBlank() && + (scanning || phase == RetroNetplayPhase.SCAN_RESULTS || discovered.isNotEmpty()) + ) { + Text( + status, + color = + if (discovered.isEmpty() && phase == RetroNetplayPhase.SCAN_RESULTS) { + GameSettingsStyle.TextDim + } else { + GameSettingsStyle.AccentBlue + }, + fontSize = 12.sp, + modifier = Modifier.padding(top = 8.dp), + ) + } + } + + Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) { + RetroNetplayEventToast(Modifier.padding(top = 10.dp)) + } + } + } +} diff --git a/app/src/main/feature/retro/RetroOnlineSupport.kt b/app/src/main/feature/retro/RetroOnlineSupport.kt new file mode 100644 index 000000000..05f44fe8b --- /dev/null +++ b/app/src/main/feature/retro/RetroOnlineSupport.kt @@ -0,0 +1,59 @@ +package com.winlator.cmod.feature.retro + +import android.content.Context + +enum class RetroOnlineMode { + NONE, + DEV9_ONLINE, + LIBRETRO_NETPLAY, + GAME_LINK, + DOLPHIN_NETPLAY, +} + +object RetroOnlineSupport { + fun modeFor(systemId: String?): RetroOnlineMode = + when (systemId) { + RetroSystems.PS2.id -> RetroOnlineMode.DEV9_ONLINE + RetroSystems.NES.id, + RetroSystems.SNES.id, + RetroSystems.GENESIS.id, + RetroSystems.MASTER_SYSTEM.id, + RetroSystems.GAME_GEAR.id, + RetroSystems.N64.id, + RetroSystems.PSX.id, + -> RetroOnlineMode.LIBRETRO_NETPLAY + RetroSystems.GAMEBOY.id, + RetroSystems.GAMEBOY_COLOR.id, + RetroSystems.GBA.id, + -> RetroOnlineMode.GAME_LINK + RetroSystems.GAMECUBE.id, + RetroSystems.WII.id, + -> RetroOnlineMode.DOLPHIN_NETPLAY + else -> RetroOnlineMode.NONE + } + + fun isGbaNetpacket(systemId: String?): Boolean = systemId == RetroSystems.GBA.id + + fun supportsDev9(systemId: String?): Boolean = modeFor(systemId) == RetroOnlineMode.DEV9_ONLINE + + fun supportsNetplayCore(systemId: String?): Boolean = + modeFor(systemId) == RetroOnlineMode.LIBRETRO_NETPLAY + + fun supportsGameLink(systemId: String?): Boolean = + modeFor(systemId) == RetroOnlineMode.GAME_LINK + + fun supportsDolphinNetplay(systemId: String?): Boolean = + modeFor(systemId) == RetroOnlineMode.DOLPHIN_NETPLAY + + fun supportsMultiplayerUi(systemId: String?): Boolean = + supportsNetplayCore(systemId) || supportsGameLink(systemId) + + fun supportsNetplay(context: Context, systemId: String?): Boolean { + if (!supportsNetplayCore(systemId) && !supportsGameLink(systemId)) return false + val system = RetroSystems.fromId(systemId) ?: return false + if (system.isExternal || system.coreFileName.isBlank()) return false + return RetroCoreManager.isCoreAvailable(context, system) + } + + fun netplayFrontendReady(): Boolean = true +} diff --git a/app/src/main/feature/retro/RetroRomArchive.kt b/app/src/main/feature/retro/RetroRomArchive.kt new file mode 100644 index 000000000..800f143b1 --- /dev/null +++ b/app/src/main/feature/retro/RetroRomArchive.kt @@ -0,0 +1,117 @@ +package com.winlator.cmod.feature.retro + +import android.content.Context +import java.io.File +import java.util.zip.ZipFile +import java.util.zip.ZipInputStream +import org.apache.commons.compress.archivers.sevenz.SevenZFile + +object RetroRomArchive { + private val ARCHIVE_EXTS = setOf("zip", "7z") + private const val MAX_INNER_BYTES = 96L * 1024 * 1024 + + data class Inner(val name: String, val size: Long) + + fun isArchive(path: String?): Boolean = + path != null && path.substringAfterLast('.', "").lowercase() in ARCHIVE_EXTS + + fun detect(path: String): RetroSystem? { + val inner = innerRom(path) ?: return null + return RetroSystems.fromExtension(inner.name.substringAfterLast('.', "")) + } + + fun innerRom(path: String): Inner? { + val f = File(path) + if (!f.isFile) return null + val entries = + runCatching { + when (path.substringAfterLast('.', "").lowercase()) { + "zip" -> zipNames(f) + "7z" -> sevenZNames(f) + else -> emptyList() + } + }.getOrDefault(emptyList()) + return entries.firstOrNull { playableRom(it.name, it.size) } + } + + fun extractTo(context: Context, path: String): File? { + val inner = innerRom(path) ?: return null + val outDir = File(context.cacheDir, "retro_extracted").apply { mkdirs() } + val target = File(outDir, File(inner.name).name) + if (target.isFile && target.length() == inner.size) return target + val ok = + runCatching { + when (path.substringAfterLast('.', "").lowercase()) { + "zip" -> extractZip(File(path), inner.name, target) + "7z" -> extractSevenZ(context, File(path), inner.name, target) + else -> false + } + }.getOrDefault(false) + return if (ok && target.isFile) target else null + } + + private fun playableRom(name: String, size: Long): Boolean { + if (size <= 0L || size > MAX_INNER_BYTES) return false + val sys = RetroSystems.fromExtension(name.substringAfterLast('.', "")) ?: return false + return sys.id != RetroSystems.PS2.id && sys.id != RetroSystems.PSX.id + } + + private fun zipNames(f: File): List { + val out = ArrayList() + ZipFile(f).use { zip -> + val e = zip.entries() + while (e.hasMoreElements()) { + val entry = e.nextElement() + if (!entry.isDirectory) out.add(Inner(entry.name, entry.size)) + } + } + return out + } + + private fun sevenZNames(f: File): List { + val out = ArrayList() + SevenZFile(f).use { z -> + var entry = z.nextEntry + while (entry != null) { + if (!entry.isDirectory) out.add(Inner(entry.name, entry.size)) + entry = z.nextEntry + } + } + return out + } + + private fun extractZip(f: File, entryName: String, target: File): Boolean { + ZipInputStream(f.inputStream().buffered()).use { zin -> + var e = zin.nextEntry + while (e != null) { + if (e.name == entryName) { + target.outputStream().use { zin.copyTo(it) } + return true + } + e = zin.nextEntry + } + } + return false + } + + private fun extractSevenZ(context: Context, f: File, entryName: String, target: File): Boolean { + SevenZFile(f).use { z -> + var entry = z.nextEntry + while (entry != null) { + if (entry.name == entryName) { + target.outputStream().use { out -> + val buf = ByteArray(64 * 1024) + while (true) { + val n = z.read(buf) + if (n < 0) break + out.write(buf, 0, n) + } + } + return true + } + entry = z.nextEntry + } + } + return false + } +} diff --git a/app/src/main/feature/retro/RetroRomScanner.kt b/app/src/main/feature/retro/RetroRomScanner.kt new file mode 100644 index 000000000..7487dcd6c --- /dev/null +++ b/app/src/main/feature/retro/RetroRomScanner.kt @@ -0,0 +1,55 @@ +package com.winlator.cmod.feature.retro + +import android.content.Context +import com.winlator.cmod.feature.shortcuts.LibraryShortcutUtils +import com.winlator.cmod.runtime.container.ContainerManager +import java.io.File + +object RetroRomScanner { + data class Result(val added: Int, val removed: Int) + + fun scanConfiguredFolder(context: Context): Result { + val dir = RetroDefaults.romsDir(context)?.let(::File) ?: return Result(0, 0) + if (!dir.isDirectory) return Result(0, 0) + return scan(context, dir) + } + + fun scan(context: Context, dir: File): Result { + val dirPath = dir.absolutePath + val retro = + runCatching { + ContainerManager(context).loadShortcuts().filter { RetroShortcuts.isRetroShortcut(it) } + }.getOrDefault(emptyList()) + + var removed = 0 + retro.forEach { shortcut -> + val rom = RetroShortcuts.romPath(shortcut) + if (rom.isNotBlank() && isUnder(rom, dirPath) && !File(rom).isFile) { + if (LibraryShortcutUtils.deleteShortcutArtifacts(context, shortcut)) removed++ + } + } + + val existing = + retro.mapNotNull { RetroShortcuts.romPath(it).takeIf { p -> p.isNotBlank() && File(p).isFile } }.toHashSet() + val roms = + dir.walkTopDown() + .maxDepth(4) + .filter { it.isFile && RetroSystems.isRetroRom(it.absolutePath) } + .filter { it.absolutePath !in existing } + .toList() + var added = 0 + for (rom in roms) { + val system = RetroSystems.detectForFile(rom.absolutePath) ?: continue + val name = rom.nameWithoutExtension.trim().ifBlank { rom.name } + if (RetroShortcuts.create(context, name, rom.absolutePath, system)) added++ + } + + RetroBoxart.ensureArtworkAsync(context) + return Result(added, removed) + } + + private fun isUnder(path: String, dir: String): Boolean { + val d = if (dir.endsWith("/")) dir else "$dir/" + return path == dir || path.startsWith(d) + } +} diff --git a/app/src/main/feature/retro/RetroSaveImport.kt b/app/src/main/feature/retro/RetroSaveImport.kt new file mode 100644 index 000000000..a62fecbb4 --- /dev/null +++ b/app/src/main/feature/retro/RetroSaveImport.kt @@ -0,0 +1,108 @@ +package com.winlator.cmod.feature.retro + +import android.content.Context +import java.io.ByteArrayInputStream +import java.io.File +import java.util.zip.ZipInputStream +import org.apache.commons.compress.archivers.sevenz.SevenZFile + +object RetroSaveImport { + private val SAVE_EXTS = setOf("srm", "sav", "eep", "sra", "fla", "mpk", "bkr", "dsv", "mcr", "sms", "state", "st0", "ss0") + private const val MAX_SAVE_BYTES = 16 * 1024 * 1024 + + sealed class Result { + data class Success(val name: String, val bytes: Int) : Result() + data class Invalid(val reason: String) : Result() + } + + private data class Entry(val name: String, val bytes: ByteArray) + + fun import(context: Context, gameName: String, sourceName: String, raw: ByteArray): Result { + if (raw.isEmpty()) return Result.Invalid("The file is empty.") + + val entries = + when (archiveKind(raw)) { + "zip" -> runCatching { unzip(raw) }.getOrNull() + ?: return Result.Invalid("This archive could not be read.") + "7z" -> runCatching { un7z(context, raw) }.getOrNull() + ?: return Result.Invalid("This 7z archive could not be read.") + "rar" -> return Result.Invalid("RAR archives aren't supported — extract the save first, then import it.") + else -> listOf(Entry(sourceName, raw)) + } + + val candidates = entries.filter { it.bytes.isNotEmpty() && !isRom(it.name) && it.bytes.size <= MAX_SAVE_BYTES } + if (candidates.isEmpty()) { + return if (entries.any { isRom(it.name) }) { + Result.Invalid("That looks like a ROM, not a save file.") + } else { + Result.Invalid("No valid save file was found inside.") + } + } + + val chosen = + candidates.firstOrNull { ext(it.name) in SAVE_EXTS } + ?: candidates.maxByOrNull { it.bytes.size }!! + + return runCatching { + RetroSaveStates.sramFile(context, gameName).writeBytes(chosen.bytes) + Result.Success(chosen.name, chosen.bytes.size) + }.getOrElse { Result.Invalid("Could not write the save to storage.") } + } + + private fun archiveKind(b: ByteArray): String? { + if (b.size >= 4 && b[0] == 0x50.toByte() && b[1] == 0x4B.toByte() && + (b[2] == 0x03.toByte() || b[2] == 0x05.toByte() || b[2] == 0x07.toByte()) + ) { + return "zip" + } + if (b.size >= 6 && b[0] == 0x37.toByte() && b[1] == 0x7A.toByte() && + b[2] == 0xBC.toByte() && b[3] == 0xAF.toByte() && b[4] == 0x27.toByte() && b[5] == 0x1C.toByte() + ) { + return "7z" + } + if (b.size >= 4 && b[0] == 0x52.toByte() && b[1] == 0x61.toByte() && + b[2] == 0x72.toByte() && b[3] == 0x21.toByte() + ) { + return "rar" + } + return null + } + + private fun unzip(raw: ByteArray): List { + val out = ArrayList() + ZipInputStream(ByteArrayInputStream(raw)).use { zin -> + var e = zin.nextEntry + while (e != null) { + if (!e.isDirectory) out.add(Entry(File(e.name).name, zin.readBytes())) + e = zin.nextEntry + } + } + return out + } + + private fun un7z(context: Context, raw: ByteArray): List { + val tmp = File.createTempFile("import", ".7z", context.cacheDir) + return try { + tmp.writeBytes(raw) + val out = ArrayList() + SevenZFile(tmp).use { z -> + var e = z.nextEntry + while (e != null) { + if (!e.isDirectory) { + val buf = ByteArray(e.size.toInt().coerceAtLeast(0)) + z.read(buf) + out.add(Entry(File(e.name).name, buf)) + } + e = z.nextEntry + } + } + out + } finally { + tmp.delete() + } + } + + private fun ext(name: String): String = name.substringAfterLast('.', "").lowercase() + + private fun isRom(name: String): Boolean = ext(name) in RetroSystems.allExtensions +} diff --git a/app/src/main/feature/retro/RetroSaveStates.kt b/app/src/main/feature/retro/RetroSaveStates.kt new file mode 100644 index 000000000..883c950e0 --- /dev/null +++ b/app/src/main/feature/retro/RetroSaveStates.kt @@ -0,0 +1,227 @@ +package com.winlator.cmod.feature.retro + +import android.content.Context +import org.json.JSONObject +import java.io.File + +object RetroSaveStates { + const val SLOT_COUNT = 10 + + data class SlotInfo( + val slot: Int, + val customName: String?, + val timestampMs: Long, + val exists: Boolean, + val sizeBytes: Long, + ) + + fun safeName(gameName: String): String = gameName.replace(Regex("[^A-Za-z0-9._-]"), "_") + + fun cloudGameId( + systemId: String?, + gameName: String, + ): String = "retro_${systemId ?: "unknown"}_${safeName(gameName)}" + + fun gameDir( + context: Context, + gameName: String, + ): File { + val dir = File(context.filesDir, "retro/games/${safeName(gameName)}") + dir.mkdirs() + return dir + } + + fun slotFile( + context: Context, + gameName: String, + slot: Int, + ): File = File(gameDir(context, gameName), "slot$slot.state") + + fun cloudDir( + context: Context, + gameName: String, + ): File { + val dir = File(gameDir(context, gameName), "sram") + dir.mkdirs() + return dir + } + + fun sramFile( + context: Context, + gameName: String, + ): File = File(cloudDir(context, gameName), "${safeName(gameName)}.srm") + + fun migrateLegacyCloudLayout(context: Context, gameName: String) { + runCatching { + val game = gameDir(context, gameName) + val sram = cloudDir(context, gameName) + game.listFiles()?.forEach { f -> + if (f.isFile && f.name.endsWith(".srm")) { + f.copyTo(File(sram, f.name), overwrite = true) + f.delete() + } + } + } + } + + private fun metaFile(dir: File): File = File(dir, "slots.json") + + private fun readMeta(dir: File): JSONObject = + runCatching { JSONObject(metaFile(dir).readText()) }.getOrDefault(JSONObject()) + + private fun writeMetaAtomic( + dir: File, + meta: JSONObject, + ) { + runCatching { + val tmp = File(dir, "slots.json.tmp") + tmp.writeText(meta.toString()) + if (!tmp.renameTo(metaFile(dir))) { + metaFile(dir).writeText(meta.toString()) + tmp.delete() + } + } + } + + fun recordIdentity( + context: Context, + gameName: String, + systemId: String?, + ) { + val dir = gameDir(context, gameName) + val meta = readMeta(dir) + if (meta.optString("game") == gameName && meta.optString("system") == (systemId ?: "")) return + meta.put("game", gameName) + meta.put("system", systemId ?: "") + writeMetaAtomic(dir, meta) + } + + fun migrateLegacy( + context: Context, + gameName: String, + ) { + runCatching { + val dir = gameDir(context, gameName) + val safe = safeName(gameName) + val legacyState = File(File(context.filesDir, "retro/states"), "$safe.state") + val slot1 = File(dir, "slot1.state") + if (legacyState.isFile && !slot1.exists()) legacyState.renameTo(slot1) + val legacySram = File(File(context.filesDir, "retro/saves"), "$safe.srm") + val sram = sramFile(context, gameName) + if (legacySram.isFile && !sram.exists()) legacySram.renameTo(sram) + val flatSram = File(dir, "$safe.srm") + if (flatSram.isFile && !sram.exists()) flatSram.renameTo(sram) + } + } + + fun listSlots( + context: Context, + gameName: String, + ): List { + val dir = gameDir(context, gameName) + val names = readMeta(dir).optJSONObject("names") ?: JSONObject() + return (1..SLOT_COUNT).map { slot -> + val file = File(dir, "slot$slot.state") + SlotInfo( + slot = slot, + customName = names.optString(slot.toString()).ifEmpty { null }, + timestampMs = if (file.isFile) file.lastModified() else 0L, + exists = file.isFile, + sizeBytes = if (file.isFile) file.length() else 0L, + ) + } + } + + fun writeSlot( + context: Context, + gameName: String, + slot: Int, + bytes: ByteArray, + ): Boolean = + runCatching { + require(bytes.isNotEmpty()) + val target = slotFile(context, gameName, slot) + val tmp = File(target.parentFile, "slot$slot.state.tmp") + tmp.writeBytes(bytes) + if (tmp.length() != bytes.size.toLong()) { + tmp.delete() + return false + } + if (!tmp.renameTo(target)) { + target.writeBytes(bytes) + tmp.delete() + } + true + }.getOrDefault(false) + + fun readSlot( + context: Context, + gameName: String, + slot: Int, + ): ByteArray? = + runCatching { + val file = slotFile(context, gameName, slot) + if (!file.isFile || file.length() == 0L) return null + file.readBytes() + }.getOrNull() + + fun renameSlot( + context: Context, + gameName: String, + slot: Int, + name: String?, + ) { + val dir = gameDir(context, gameName) + val meta = readMeta(dir) + val names = meta.optJSONObject("names") ?: JSONObject() + if (name.isNullOrBlank()) names.remove(slot.toString()) else names.put(slot.toString(), name.take(48)) + meta.put("names", names) + writeMetaAtomic(dir, meta) + } + + fun hasAnySave( + context: Context, + gameName: String, + ): Boolean { + if (sramFile(context, gameName).isFile) return true + return (1..SLOT_COUNT).any { slotFile(context, gameName, it).isFile } + } + + fun latestLocalTimestamp( + context: Context, + gameName: String, + ): Long { + var latest = 0L + val sram = sramFile(context, gameName) + if (sram.isFile) latest = maxOf(latest, sram.lastModified()) + (1..SLOT_COUNT).forEach { slot -> + val file = slotFile(context, gameName, slot) + if (file.isFile) latest = maxOf(latest, file.lastModified()) + } + return latest + } + + fun relativeTime(timestampMs: Long): String { + if (timestampMs <= 0L) return "Empty" + val delta = System.currentTimeMillis() - timestampMs + if (delta < 60_000L) return "just now" + val minutes = delta / 60_000L + if (minutes < 60) return "$minutes minute${if (minutes == 1L) "" else "s"} ago" + val hours = minutes / 60 + val remMinutes = minutes % 60 + if (hours < 24) { + return if (remMinutes > 0) { + "$hours hour${if (hours == 1L) "" else "s"} $remMinutes minute${if (remMinutes == 1L) "" else "s"} ago" + } else { + "$hours hour${if (hours == 1L) "" else "s"} ago" + } + } + val days = hours / 24 + val remHours = hours % 24 + return if (remHours > 0) { + "$days day${if (days == 1L) "" else "s"} $remHours hour${if (remHours == 1L) "" else "s"} ago" + } else { + "$days day${if (days == 1L) "" else "s"} ago" + } + } +} diff --git a/app/src/main/feature/retro/RetroSettingsDialog.kt b/app/src/main/feature/retro/RetroSettingsDialog.kt new file mode 100644 index 000000000..0768aaa14 --- /dev/null +++ b/app/src/main/feature/retro/RetroSettingsDialog.kt @@ -0,0 +1,269 @@ +package com.winlator.cmod.feature.retro + +import android.app.Activity +import android.app.Dialog +import android.net.Uri +import android.os.Build +import android.view.ViewGroup +import android.view.Window +import android.view.WindowManager +import android.widget.Toast +import androidx.activity.ComponentActivity +import androidx.activity.result.ActivityResultLauncher +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.platform.ComposeView +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.Density +import androidx.lifecycle.DefaultLifecycleObserver +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.setViewTreeLifecycleOwner +import androidx.savedstate.SavedStateRegistryOwner +import androidx.savedstate.setViewTreeSavedStateRegistryOwner +import com.winlator.cmod.R +import com.winlator.cmod.feature.library.GameSettingsNav +import com.winlator.cmod.feature.shortcuts.LibraryShortcutArtwork +import com.winlator.cmod.runtime.container.Shortcut +import com.winlator.cmod.shared.android.ImageUtils +import com.winlator.cmod.shared.io.FileUtils +import com.winlator.cmod.shared.theme.WinNativeTheme +import com.winlator.cmod.shared.ui.nav.PANE_DIR_ACTIVATE +import com.winlator.cmod.shared.ui.nav.PaneNavWindowHandlers +import com.winlator.cmod.shared.ui.nav.bindPaneNav +import com.winlator.cmod.shared.ui.toast.WinToast + +class RetroSettingsDialog( + private val activity: Activity, + private val shortcut: Shortcut, +) { + private val state = RetroSettingsState(shortcut, activity) + private val nav = GameSettingsNav() + private var restorePaneNav: (() -> Unit)? = null + private var pendingArtworkSlot = LibraryShortcutArtwork.LibraryArtworkSlot.GAME_CARD + + private val artworkPickerLauncher: ActivityResultLauncher>? = + (activity as? ComponentActivity)?.activityResultRegistry?.register( + "retro_artwork_picker", + ActivityResultContracts.OpenDocument(), + ) { uri: Uri? -> + if (uri != null) saveSelectedArtwork(uri) + } + + private val biosPickerLauncher: ActivityResultLauncher>? = + (activity as? ComponentActivity)?.activityResultRegistry?.register( + "retro_bios_picker", + ActivityResultContracts.OpenDocument(), + ) { uri: Uri? -> + if (uri != null) { + RetroBiosImport.importFromUri(activity, uri) + .onSuccess { + Toast.makeText(activity, activity.getString(R.string.retro_scr_bios_imported, it), Toast.LENGTH_SHORT).show() + state.biosRefresh++ + } + .onFailure { + Toast.makeText(activity, it.message ?: activity.getString(R.string.retro_scr_invalid_bios_file), Toast.LENGTH_LONG).show() + } + } + } + + private val hddPickerLauncher: ActivityResultLauncher>? = + (activity as? ComponentActivity)?.activityResultRegistry?.register( + "retro_hdd_picker", + ActivityResultContracts.OpenDocument(), + ) { uri: Uri? -> + if (uri != null) { + state.hddImporting = true + Toast.makeText(activity, activity.getString(R.string.retro_scr_importing), Toast.LENGTH_SHORT).show() + Thread { + val result = RetroHddImport.importFromUri(activity, uri) + activity.runOnUiThread { + state.hddImporting = false + result + .onSuccess { name -> + state.hddImage = name + state.hddRefresh++ + Toast.makeText(activity, activity.getString(R.string.retro_scr_hdd_imported, name), Toast.LENGTH_LONG).show() + } + .onFailure { + Toast.makeText(activity, it.message ?: activity.getString(R.string.retro_scr_invalid_hdd_file), Toast.LENGTH_LONG).show() + } + } + }.start() + } + } + + private val cheatFilePickerLauncher: ActivityResultLauncher>? = + (activity as? ComponentActivity)?.activityResultRegistry?.register( + "retro_cheat_file_picker", + ActivityResultContracts.OpenDocument(), + ) { uri: Uri? -> + val serial = state.gameSerial + if (uri != null && serial != null) { + val isPatch = state.pendingImportIsPatch + Thread { + val text = runCatching { activity.contentResolver.openInputStream(uri)?.bufferedReader()?.use { it.readText() } }.getOrNull() + val imported = if (text != null) parsePnachFile(text, if (isPatch) "patches" else "custom") else emptyList() + activity.runOnUiThread { + if (imported.isNotEmpty()) { + val existing = Ps2CheatStaging.read(activity, serial, isPatch) + val merged = existing.filterNot { e -> imported.any { it.name == e.name } } + imported + Ps2CheatStaging.write(activity, serial, isPatch, serial, merged) + state.cheatsRefresh++ + Toast.makeText(activity, activity.getString(R.string.retro_scr_hdd_imported, imported.first().name), Toast.LENGTH_SHORT).show() + } else { + Toast.makeText(activity, activity.getString(R.string.retro_scr_cheat_invalid), Toast.LENGTH_LONG).show() + } + } + }.start() + } + } + + init { + state.requestImportHdd = { hddPickerLauncher?.launch(arrayOf("*/*")) } + state.requestImportCheatFile = { isPatch -> + state.pendingImportIsPatch = isPatch + cheatFilePickerLauncher?.launch(arrayOf("*/*")) + } + } + + private fun saveSelectedArtwork(uri: Uri) { + val bitmap = ImageUtils.getBitmapFromUri(activity, uri, 1024) + if (bitmap == null) { + WinToast.show(activity, R.string.shortcuts_library_artwork_failed, Toast.LENGTH_SHORT) + return + } + val slot = pendingArtworkSlot + val previousPath = shortcut.getExtra(slot.extraKey) + val outputFile = LibraryShortcutArtwork.buildManagedViewArtworkFile(activity, shortcut, slot) + val system = RetroShortcuts.systemForShortcut(shortcut) + val saved = + if (system != null && RetroBoxart.caseArtEnabled(activity) && slot != LibraryShortcutArtwork.LibraryArtworkSlot.GAME_CARD) { + RetroBoxart.composeCustom(activity, system, shortcut.getExtra("custom_name", shortcut.name), bitmap, outputFile) + } else { + FileUtils.saveBitmapToFile(bitmap, outputFile) + } + if (!saved) { + WinToast.show(activity, R.string.shortcuts_library_artwork_failed, Toast.LENGTH_SHORT) + return + } + if (previousPath.isNotBlank() && previousPath != outputFile.absolutePath) { + LibraryShortcutArtwork.deleteManagedArtwork(activity, previousPath) + } + shortcut.putExtra(slot.extraKey, outputFile.absolutePath) + shortcut.saveData() + state.syncArtwork() + } + + private fun clearArtwork(slot: LibraryShortcutArtwork.LibraryArtworkSlot) { + LibraryShortcutArtwork.deleteManagedArtwork(activity, shortcut.getExtra(slot.extraKey)) + shortcut.putExtra(slot.extraKey, null) + shortcut.saveData() + state.syncArtwork() + } + + private val dialog: Dialog = + Dialog(activity, R.style.ContentDialog).apply { + requestWindowFeature(Window.FEATURE_NO_TITLE) + setCancelable(true) + setCanceledOnTouchOutside(false) + setOwnerActivity(activity) + window?.apply { + setBackgroundDrawableResource(android.R.color.transparent) + setLayout( + WindowManager.LayoutParams.MATCH_PARENT, + WindowManager.LayoutParams.MATCH_PARENT, + ) + setDimAmount(0.5f) + addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND) + setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + isNavigationBarContrastEnforced = false + } + } + setOnDismissListener { + restorePaneNav?.invoke() + restorePaneNav = null + } + } + + init { + val composeView = + ComposeView(activity).apply { + layoutParams = + ViewGroup.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.MATCH_PARENT, + ) + setViewTreeLifecycleOwner(activity as LifecycleOwner) + setViewTreeSavedStateRegistryOwner(activity as SavedStateRegistryOwner) + setContent { + WinNativeTheme { + val defaultDensity = LocalDensity.current + CompositionLocalProvider( + LocalDensity provides Density(defaultDensity.density, fontScale = 1f), + ) { + RetroGameSettingsContent( + state = state, + nav = nav, + onPickArtwork = { slot -> + pendingArtworkSlot = slot + artworkPickerLauncher?.launch(arrayOf("image/*")) + }, + onRemoveArtwork = { slot -> clearArtwork(slot) }, + onImportBios = { biosPickerLauncher?.launch(arrayOf("*/*")) }, + onSave = { + state.save() + dialog.dismiss() + }, + onCancel = { dialog.dismiss() }, + ) + } + } + } + } + dialog.setContentView(composeView) + (activity as LifecycleOwner).lifecycle.addObserver( + object : DefaultLifecycleObserver { + override fun onDestroy(owner: LifecycleOwner) { + if (dialog.isShowing) dialog.dismiss() + } + }, + ) + } + + fun show() { + dialog.show() + restorePaneNav?.invoke() + restorePaneNav = + dialog.window?.bindPaneNav( + PaneNavWindowHandlers( + onDir = { nav.dpad(it) }, + onActivate = { nav.dpad(PANE_DIR_ACTIVATE) }, + onDismiss = { if (nav.onContentBack?.invoke() != true) dialog.dismiss() }, + onStart = { nav.onSave?.invoke() }, + ), + ) + dialog.window?.apply { + applyDialogLayout() + decorView.post { applyDialogLayout() } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + val params = attributes + params.flags = params.flags or WindowManager.LayoutParams.FLAG_BLUR_BEHIND + params.blurBehindRadius = 10 + attributes = params + } + } + } + + private fun Window.applyDialogLayout() { + val dm = activity.resources.displayMetrics + val hostView = activity.window?.decorView + val hostWidth = hostView?.width?.takeIf { it > 0 } ?: dm.widthPixels + val hostHeight = hostView?.height?.takeIf { it > 0 } ?: dm.heightPixels + val screenWidthDp = hostWidth / dm.density + val needsNearFullWidth = screenWidthDp < 820f + val widthFactor = if (needsNearFullWidth) 0.96f else 0.88f + val heightFactor = if (needsNearFullWidth) 0.90f else 0.88f + setLayout((hostWidth * widthFactor).toInt(), (hostHeight * heightFactor).toInt()) + } +} diff --git a/app/src/main/feature/retro/RetroShortcuts.kt b/app/src/main/feature/retro/RetroShortcuts.kt new file mode 100644 index 000000000..46431fef5 --- /dev/null +++ b/app/src/main/feature/retro/RetroShortcuts.kt @@ -0,0 +1,320 @@ +package com.winlator.cmod.feature.retro + +import android.content.Context +import android.content.Intent +import android.widget.Toast +import com.winlator.cmod.runtime.container.ContainerManager +import com.winlator.cmod.runtime.container.Shortcut +import com.winlator.cmod.shared.io.FileUtils +import java.io.File +import java.util.UUID + +object RetroShortcuts { + const val KEY_SYSTEM = "retro_system" + const val KEY_ROM = "rom_path" + const val KEY_CORE = "retro_core" + const val KEY_SHADER = "retro_shader" + const val KEY_UPSCALE = "retro_upscale" + const val KEY_SGSR = "retro_sgsr" + const val KEY_TOUCH_CONTROLS = "retro_touch_controls" + const val KEY_ADAPTIVE_STICKS = "retro_adaptive_sticks" + const val KEY_HDD_IMAGE = "retro_ps2_hdd_image" + const val KEY_HDD_ENABLE = "retro_ps2_hdd_enable" + const val KEY_AUDIO = "retro_audio" + const val KEY_HUD = "retro_hud" + + const val EXTRA_PS2_ROM_PATH = "wn_ps2_rom_path" + const val EXTRA_PS2_GAME_NAME = "wn_ps2_game_name" + const val VAR_PREFIX = "retro_var_" + + fun coreVariables(shortcut: Shortcut): HashMap { + val vars = HashMap() + val extras = shortcut.extraData + val keys = extras.keys() + while (keys.hasNext()) { + val key = keys.next() + if (key.startsWith(VAR_PREFIX)) { + val value = shortcut.getExtra(key) + if (value.isNotEmpty()) vars[key.removePrefix(VAR_PREFIX)] = value + } + } + return vars + } + + fun resolvedCoreVariables( + context: Context, + shortcut: Shortcut, + ): HashMap { + val vars = coreVariables(shortcut) + val system = systemForShortcut(shortcut) ?: return vars + RetroCoreOptions.forSystem(system).forEach { option -> + if (!vars.containsKey(option.key)) { + vars[option.key] = RetroDefaults.coreOption(context, system.id, option.key, option.defaultValue) + } + } + if (RetroCoreManager.usesDolphinCore(system)) { + RetroCoreOptions.sanitizeDolphinVariables(vars) + } + return vars + } + + @JvmStatic + fun isRetroShortcut(shortcut: Shortcut): Boolean = shortcut.getExtra(KEY_SYSTEM).isNotEmpty() + + fun systemForShortcut(shortcut: Shortcut): RetroSystem? = RetroSystems.fromId(shortcut.getExtra(KEY_SYSTEM)) + + fun romPath(shortcut: Shortcut): String = shortcut.getExtra(KEY_ROM) + + data class LibraryCapabilities( + val systemId: String? = null, + val romPath: String? = null, + val system: RetroSystem? = null, + ) { + val isRetro: Boolean get() = system != null + val isExternal: Boolean get() = system?.isExternal == true + val showBootToDesktop: Boolean get() = !isRetro + val showSaveTransfer: Boolean get() = isRetro && !isExternal + val showCheats: Boolean get() = isRetro && !isExternal + val showAchievements: Boolean + get() = system != null && RetroAchievementsManager.consoleId(system.id) != 0 + val sourceLabel: String? + get() = system?.badgeLabel + } + + fun libraryCapabilities(shortcut: Shortcut?): LibraryCapabilities { + if (shortcut == null || !isRetroShortcut(shortcut)) return LibraryCapabilities() + val system = systemForShortcut(shortcut) + return LibraryCapabilities( + systemId = system?.id, + romPath = romPath(shortcut).takeIf { it.isNotEmpty() }, + system = system, + ) + } + + fun libraryCapabilitiesForSystemId( + systemId: String?, + romPath: String? = null, + ): LibraryCapabilities { + val system = RetroSystems.fromId(systemId) ?: return LibraryCapabilities() + return LibraryCapabilities( + systemId = system.id, + romPath = romPath?.takeIf { it.isNotEmpty() }, + system = system, + ) + } + + fun create( + context: Context, + name: String, + romPath: String, + system: RetroSystem, + ): Boolean { + val container = ContainerManager(context).retroContainer + + val desktopDir = container.desktopDir + if (!desktopDir.exists()) desktopDir.mkdirs() + + val safeName = name.replace("/", "_").replace("\\", "_") + val shortcutFile = File(desktopDir, "$safeName.desktop") + val shortcutUuid = UUID.randomUUID().toString() + + val content = + buildString { + append("[Desktop Entry]\n") + append("Type=Application\n") + append("Name=$name\n") + append("Exec=retro:${system.id}\n") + append("Icon=custom_game\n") + append("\n[Extra Data]\n") + append("game_source=CUSTOM\n") + append("custom_name=$name\n") + append("$KEY_SYSTEM=${system.id}\n") + append("$KEY_ROM=$romPath\n") + append("$KEY_CORE=${system.coreFileName}\n") + append("uuid=$shortcutUuid\n") + append("container_id=${container.id}\n") + append("use_container_defaults=1\n") + } + + FileUtils.writeString(shortcutFile, content) + RetroBoxart.ensureArtworkAsync(context) + return true + } + + @JvmStatic + fun launch( + context: Context, + shortcut: Shortcut, + ) { + val system = systemForShortcut(shortcut) + if (!RetroBundle.requireInstalled(context)) return + if (system != null && system.isExternal) { + recordLaunchStats(context, shortcut.getExtra("custom_name", shortcut.name)) + launchEmbeddedPs2(context, shortcut) + return + } + if (RetroCoreManager.usesDolphinCore(system) && embeddedDolphinEnabled(context)) { + recordLaunchStats(context, shortcut.getExtra("custom_name", shortcut.name)) + DolphinEmbedLaunch.launch(context, shortcut) + return + } + context.startActivity(launchIntent(context, shortcut)) + } + + fun embeddedDolphinEnabled(context: Context): Boolean = + androidx.preference.PreferenceManager + .getDefaultSharedPreferences(context) + .getBoolean("wn.gc.embedded", true) + + private fun recordLaunchStats( + context: Context, + gameName: String, + ) { + val prefs = context.getSharedPreferences("playtime_stats", Context.MODE_PRIVATE) + prefs.edit() + .putInt("${gameName}_play_count", prefs.getInt("${gameName}_play_count", 0) + 1) + .putLong("${gameName}_last_played", System.currentTimeMillis()) + .apply() + } + + private fun launchEmbeddedPs2( + context: Context, + shortcut: Shortcut, + ) { + val rom = File(romPath(shortcut)) + if (!rom.isFile) { + Toast.makeText(context, context.getString(com.winlator.cmod.R.string.retro_rom_missing), Toast.LENGTH_LONG).show() + return + } + if (!ps2GpuSupported(context)) { + Toast.makeText( + context, + context.getString(com.winlator.cmod.R.string.retro_ps2_device_unsupported), + Toast.LENGTH_LONG, + ).show() + return + } + Ps2GameOverlay.install() + kotlin.concurrent.thread(name = "WnPs2Launch") { + val biosPath = ensurePs2Bios(context) + if (biosPath == null) { + android.os.Handler(android.os.Looper.getMainLooper()).post { + Toast.makeText( + context, + context.getString( + com.winlator.cmod.R.string.retro_lr_bios_required_title, + RetroSystems.PS2.shortName, + ) + "\n" + context.getString(com.winlator.cmod.R.string.retro_scr_ps2_bios_format), + Toast.LENGTH_LONG, + ).show() + } + return@thread + } + val prefs = context.getSharedPreferences("ARMSX2", Context.MODE_PRIVATE) + val touchControls = prefs.getBoolean("wn.ps2.touchcontrols", RetroDefaults.touchControls(context, RetroSystems.PS2.id)) + val adaptiveSticks = prefs.getBoolean("wn.ps2.adaptivesticks", RetroDefaults.adaptiveSticks(context, RetroSystems.PS2.id)) + val driverPref = (prefs.getString("wn.ps2.driver", "") ?: "").trim() + val customDriverId = + if (driverPref.isEmpty() || driverPref.equals("system", ignoreCase = true)) "" else driverPref + prefs.edit().apply { + putBoolean("setupComplete", true) + putBoolean("wn.controls", true) + putBoolean("wn.ps2.touchcontrols", touchControls) + putBoolean("wn.ps2.adaptivesticks", adaptiveSticks) + putString("wn.ps2.hddimage", shortcut.getExtra(KEY_HDD_IMAGE)) + putBoolean("wn.ps2.hdd", shortcut.getExtra(KEY_HDD_ENABLE) == "1") + putString("romsDirs", org.json.JSONArray().put(rom.parent ?: "").toString()) + putString("bios", biosPath) + putString("customDriverId", customDriverId) + commit() + } + val uri = + try { + androidx.core.content.FileProvider.getUriForFile(context, "${context.packageName}.tileprovider", rom) + } catch (e: IllegalArgumentException) { + android.net.Uri.fromFile(rom) + } + val intent = + Intent(Intent.ACTION_VIEW).apply { + setClassName(context, "com.armsx2.Main") + setDataAndType(uri, "application/octet-stream") + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION) + putExtra(EXTRA_PS2_ROM_PATH, rom.absolutePath) + putExtra(EXTRA_PS2_GAME_NAME, shortcut.getExtra("custom_name", shortcut.name)) + } + android.os.Handler(android.os.Looper.getMainLooper()).post { + runCatching { context.startActivity(intent) } + } + } + } + + private fun ps2GpuSupported(context: Context): Boolean = + runCatching { + val am = context.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager + am.deviceConfigurationInfo.glEsVersion.toDouble() + }.getOrDefault(Double.MAX_VALUE) >= 3.1 + + private fun ensurePs2Bios(context: Context): String? { + val biosDir = File(context.getExternalFilesDir(null) ?: context.filesDir, "bios") + if (!biosDir.exists()) biosDir.mkdirs() + val existing = biosDir.listFiles()?.firstOrNull { it.isFile && it.length() >= 3L * 1024 * 1024 } + if (existing != null) return existing.absolutePath + val sources = + listOf( + File("/storage/emulated/0/Download/bios"), + File(RetroCoreManager.systemDir(context), "bios"), + File("/storage/emulated/0/Download"), + ) + for (dir in sources) { + val candidate = + dir.listFiles()?.firstOrNull { + it.isFile && it.length() in (3L * 1024 * 1024)..(8L * 1024 * 1024) && + (it.name.endsWith(".bin", true) || it.name.endsWith(".BIN") || it.name.contains("ROM0")) + } ?: continue + val target = File(biosDir, candidate.name) + runCatching { candidate.copyTo(target, overwrite = true) } + if (target.isFile) return target.absolutePath + } + return null + } + + @JvmStatic + fun launchIntent( + context: Context, + shortcut: Shortcut, + ): Intent = + Intent(context, RetroActivity::class.java).apply { + val sysId = shortcut.getExtra(KEY_SYSTEM) + putExtra(RetroActivity.EXTRA_ROM_PATH, shortcut.getExtra(KEY_ROM)) + putExtra(RetroActivity.EXTRA_SYSTEM_ID, sysId) + putExtra(RetroActivity.EXTRA_GAME_NAME, shortcut.getExtra("custom_name", shortcut.name)) + putExtra(RetroActivity.EXTRA_SHORTCUT_PATH, shortcut.file.absolutePath) + putExtra(RetroActivity.EXTRA_CONTAINER_ID, shortcut.container.id) + putExtra( + RetroActivity.EXTRA_SHADER, + shortcut.getExtra(KEY_SHADER).ifEmpty { RetroDefaults.shader(context, sysId) }, + ) + putExtra( + RetroActivity.EXTRA_UPSCALE, + shortcut.getExtra(KEY_UPSCALE).ifEmpty { RetroDefaults.upscale(context, sysId) }, + ) + putExtra( + RetroActivity.EXTRA_SGSR, + shortcut.getExtra(KEY_SGSR).ifEmpty { if (RetroDefaults.sgsr(context, sysId)) "1" else "0" } == "1", + ) + putExtra( + RetroActivity.EXTRA_TOUCH_CONTROLS, + shortcut.getExtra(KEY_TOUCH_CONTROLS).ifEmpty { if (RetroDefaults.touchControls(context, sysId)) "1" else "0" } != "0", + ) + putExtra( + RetroActivity.EXTRA_ADAPTIVE_STICKS, + shortcut.getExtra(KEY_ADAPTIVE_STICKS).ifEmpty { if (RetroDefaults.adaptiveSticks(context, sysId)) "1" else "0" } == "1", + ) + putExtra( + RetroActivity.EXTRA_AUDIO, + shortcut.getExtra(KEY_AUDIO).ifEmpty { if (RetroDefaults.audio(context, sysId)) "1" else "0" } != "0", + ) + putExtra(RetroActivity.EXTRA_HUD, RetroDefaults.hud(context, sysId)) + putExtra(RetroActivity.EXTRA_VARIABLES, resolvedCoreVariables(context, shortcut)) + } +} diff --git a/app/src/main/feature/retro/RetroSystem.kt b/app/src/main/feature/retro/RetroSystem.kt new file mode 100644 index 000000000..7e10c85f6 --- /dev/null +++ b/app/src/main/feature/retro/RetroSystem.kt @@ -0,0 +1,201 @@ +package com.winlator.cmod.feature.retro + +import java.util.Locale + +data class RetroSystem( + val id: String, + val displayName: String, + val shortName: String, + val coreFileName: String, + val extensions: Set, + val needsBios: Boolean = false, + val biosFiles: List = emptyList(), + val badgeLabel: String = shortName, +) { + val isExternal: Boolean get() = coreFileName.isBlank() +} + +object RetroSystems { + val NES = + RetroSystem( + id = "nes", + displayName = "Nintendo Entertainment System", + shortName = "NES", + coreFileName = "libfceumm_libretro_android.so", + extensions = setOf("nes", "unf", "unif"), + ) + val SNES = + RetroSystem( + id = "snes", + displayName = "Super Nintendo", + shortName = "SNES", + coreFileName = "libsnes9x_libretro_android.so", + extensions = setOf("smc", "sfc", "swc", "fig", "bs"), + ) + val GAMEBOY = + RetroSystem( + id = "gb", + displayName = "Game Boy", + shortName = "GB", + coreFileName = "libgambatte_libretro_android.so", + extensions = setOf("gb"), + ) + val GAMEBOY_COLOR = + RetroSystem( + id = "gbc", + displayName = "Game Boy Color", + shortName = "GBC", + coreFileName = "libgambatte_libretro_android.so", + extensions = setOf("gbc"), + ) + val GBA = + RetroSystem( + id = "gba", + displayName = "Game Boy Advance", + shortName = "GBA", + coreFileName = "libmgba_libretro_android.so", + extensions = setOf("gba"), + ) + + const val GBA_MULTIPLAYER_CORE = "libgpsp_libretro_android.so" + const val DOLPHIN_LIBRETRO_CORE = "libdolphin_libretro_android.so" + val GENESIS = + RetroSystem( + id = "genesis", + displayName = "Sega Genesis / Mega Drive", + shortName = "Genesis", + coreFileName = "libgenesis_plus_gx_libretro_android.so", + extensions = setOf("gen", "md", "smd", "bin"), + badgeLabel = "SEGA", + ) + val MASTER_SYSTEM = + RetroSystem( + id = "sms", + displayName = "Sega Master System", + shortName = "Master System", + coreFileName = "libgenesis_plus_gx_libretro_android.so", + extensions = setOf("sms"), + badgeLabel = "SMS", + ) + val GAME_GEAR = + RetroSystem( + id = "gg", + displayName = "Sega Game Gear", + shortName = "Game Gear", + coreFileName = "libgenesis_plus_gx_libretro_android.so", + extensions = setOf("gg"), + badgeLabel = "GG", + ) + val N64 = + RetroSystem( + id = "n64", + displayName = "Nintendo 64", + shortName = "N64", + coreFileName = "libmupen64plus_next_gles3_libretro_android.so", + extensions = setOf("n64", "z64", "v64"), + ) + val PSX = + RetroSystem( + id = "psx", + displayName = "Sony PlayStation", + shortName = "PS1", + coreFileName = "libmednafen_psx_libretro_android.so", + extensions = setOf("cue", "chd", "pbp", "m3u", "iso"), + needsBios = true, + biosFiles = listOf("scph5501.bin", "scph5500.bin", "scph5502.bin", "scph1001.bin", "scph7001.bin"), + ) + + val PS2 = + RetroSystem( + id = "ps2", + displayName = "Sony PlayStation 2", + shortName = "PS2", + coreFileName = "", + extensions = setOf("iso", "bin", "chd", "cso", "zso", "mdf", "nrg", "img"), + badgeLabel = "PS2", + ) + + val GAMECUBE = + RetroSystem( + id = "gc", + displayName = "Nintendo GameCube", + shortName = "GameCube", + coreFileName = DOLPHIN_LIBRETRO_CORE, + extensions = setOf("gcm", "tgc", "gcz", "ciso", "dol", "elf", "rvz", "iso", "m3u"), + badgeLabel = "GameCube", + ) + + val WII = + RetroSystem( + id = "wii", + displayName = "Nintendo Wii", + shortName = "Wii", + coreFileName = DOLPHIN_LIBRETRO_CORE, + extensions = setOf("wbfs", "wad", "rvz", "gcz", "ciso", "iso", "dol", "elf", "m3u"), + badgeLabel = "Wii", + ) + + val ALL = + listOf( + NES, SNES, GAMEBOY, GAMEBOY_COLOR, GBA, GENESIS, MASTER_SYSTEM, GAME_GEAR, + N64, PSX, PS2, GAMECUBE, WII, + ) + + private val PSX_ONLY_EXTENSIONS = setOf("cue", "chd", "pbp", "m3u") + private val PS2_ONLY_EXTENSIONS = setOf("cso", "zso", "mdf", "nrg", "img") + private val GC_ONLY_EXTENSIONS = setOf("gcm", "tgc") + private val WII_ONLY_EXTENSIONS = setOf("wbfs", "wad") + private val DOLPHIN_SHARED_EXTENSIONS = setOf("rvz", "gcz", "ciso", "dol", "elf") + private const val PS2_SIZE_THRESHOLD = 900L * 1024 * 1024 + private const val WII_SIZE_THRESHOLD = 1500L * 1024 * 1024 + + val allExtensions: Set = ALL.flatMap { it.extensions }.toSet() - "exe" + + fun fromId(id: String?): RetroSystem? { + if (id.isNullOrBlank()) return null + val normalized = id.trim().lowercase(Locale.US) + return ALL.firstOrNull { it.id == normalized } + } + + fun fromExtension(extension: String?): RetroSystem? { + if (extension.isNullOrBlank()) return null + val ext = extension.trim().lowercase(Locale.US).removePrefix(".") + if (ext == "exe") return null + if (ext in WII_ONLY_EXTENSIONS) return WII + if (ext in GC_ONLY_EXTENSIONS) return GAMECUBE + if (ext in DOLPHIN_SHARED_EXTENSIONS) return GAMECUBE + if (ext in PS2_ONLY_EXTENSIONS) return PS2 + if (ext in PSX_ONLY_EXTENSIONS || ext == "iso") return PSX + return ALL.firstOrNull { ext in it.extensions } + } + + fun fromRomPath(path: String?): RetroSystem? { + if (path.isNullOrBlank()) return null + val ext = path.substringAfterLast('.', "") + return fromExtension(ext) + } + + fun detectForFile(path: String): RetroSystem? { + val ext = path.substringAfterLast('.', "").lowercase(Locale.US) + if (RetroRomArchive.isArchive(path)) return RetroRomArchive.detect(path) + if (ext in WII_ONLY_EXTENSIONS) return WII + if (ext in GC_ONLY_EXTENSIONS) return GAMECUBE + val size = runCatching { java.io.File(path).length() }.getOrDefault(0L) + if (ext in DOLPHIN_SHARED_EXTENSIONS) { + return if (size > WII_SIZE_THRESHOLD) WII else GAMECUBE + } + val detected = fromExtension(ext) ?: return null + if (ext == "bin" && size > 16L * 1024 * 1024) return PSX + if (detected.id == PSX.id && ext in setOf("iso", "chd", "bin") && size > PS2_SIZE_THRESHOLD) { + return PS2 + } + return detected + } + + fun isRetroRom(path: String?): Boolean { + if (path.isNullOrBlank()) return false + val ext = path.substringAfterLast('.', "").lowercase(Locale.US) + if (RetroRomArchive.isArchive(path)) return RetroRomArchive.detect(path) != null + return ext in allExtensions + } +} diff --git a/app/src/main/feature/settings/nav/SettingsNavGraph.kt b/app/src/main/feature/settings/nav/SettingsNavGraph.kt index 222c743b4..adad043bb 100644 --- a/app/src/main/feature/settings/nav/SettingsNavGraph.kt +++ b/app/src/main/feature/settings/nav/SettingsNavGraph.kt @@ -197,6 +197,12 @@ fun SettingsHost( composable(SettingsRoutes.fromNavItem(SettingsNavItem.OTHER)) { AndroidFragment() } + composable(SettingsRoutes.fromNavItem(SettingsNavItem.RETRO)) { + com.winlator.cmod.feature.retro.RetroDefaultsScreen(bridge = bridge) + } + composable(SettingsRoutes.fromNavItem(SettingsNavItem.CREDITS)) { + com.winlator.cmod.feature.retro.RetroCreditsScreen(bridge = bridge) + } } } } diff --git a/app/src/main/feature/settings/nav/SettingsNavSidebar.kt b/app/src/main/feature/settings/nav/SettingsNavSidebar.kt index 9eff46898..bb5a05b37 100644 --- a/app/src/main/feature/settings/nav/SettingsNavSidebar.kt +++ b/app/src/main/feature/settings/nav/SettingsNavSidebar.kt @@ -36,10 +36,12 @@ import androidx.compose.material.icons.automirrored.outlined.ArrowBack import androidx.compose.material.icons.outlined.AccountCircle import androidx.compose.material.icons.outlined.BugReport import androidx.compose.material.icons.outlined.Extension +import androidx.compose.material.icons.outlined.Info import androidx.compose.material.icons.outlined.Memory import androidx.compose.material.icons.outlined.ShoppingBag import androidx.compose.material.icons.outlined.SportsEsports import androidx.compose.material.icons.outlined.Tune +import androidx.compose.material.icons.outlined.VideogameAsset import androidx.compose.material.icons.outlined.ViewInAr import androidx.compose.material.icons.outlined.Widgets import androidx.compose.material3.Icon @@ -93,6 +95,7 @@ enum class NavSection { ACCOUNTS, SYSTEM, TOOLS, + CREDITS, } enum class SettingsNavItem( @@ -108,8 +111,10 @@ enum class SettingsNavItem( COMPONENTS(R.id.main_menu_contents, Icons.Outlined.Extension, R.string.settings_content_components, NavSection.SYSTEM), DRIVERS(R.id.main_menu_adrenotools_gpu_drivers, Icons.Outlined.Memory, R.string.settings_drivers_title, NavSection.SYSTEM), INPUT_CONTROLS(R.id.main_menu_input_controls, Icons.Outlined.SportsEsports, R.string.common_ui_input_controls, NavSection.SYSTEM), + RETRO(R.id.main_menu_retro, Icons.Outlined.VideogameAsset, R.string.settings_retro_title, NavSection.SYSTEM), OTHER(R.id.main_menu_other, Icons.Outlined.Widgets, R.string.common_ui_other, NavSection.SYSTEM), DEBUG(R.id.main_menu_advanced, Icons.Outlined.BugReport, R.string.settings_debug_title, NavSection.TOOLS), + CREDITS(R.id.main_menu_credits, Icons.Outlined.Info, R.string.retro_scr_tab_credits, NavSection.CREDITS), ; companion object { diff --git a/app/src/main/feature/shortcuts/ShortcutSettingsComposeDialog.kt b/app/src/main/feature/shortcuts/ShortcutSettingsComposeDialog.kt index 75fc5471b..dc3d1ae69 100644 --- a/app/src/main/feature/shortcuts/ShortcutSettingsComposeDialog.kt +++ b/app/src/main/feature/shortcuts/ShortcutSettingsComposeDialog.kt @@ -2397,6 +2397,12 @@ class ShortcutSettingsComposeDialog private constructor( // Show / Dismiss fun show() { + if (com.winlator.cmod.feature.retro.RetroShortcuts.isRetroShortcut(shortcut)) { + com.winlator.cmod.feature.retro + .RetroSettingsDialog(activity, shortcut) + .show() + return + } dialog.show() restorePaneNav?.invoke() restorePaneNav = dialog.window?.bindPaneNav( diff --git a/app/src/main/feature/shortcuts/ShortcutsFragment.java b/app/src/main/feature/shortcuts/ShortcutsFragment.java index 7924d7cd3..46bd533fa 100644 --- a/app/src/main/feature/shortcuts/ShortcutsFragment.java +++ b/app/src/main/feature/shortcuts/ShortcutsFragment.java @@ -221,6 +221,11 @@ private void runFromShortcut(Shortcut shortcut) { Activity activity = getActivity(); if (activity == null) return; + if (com.winlator.cmod.feature.retro.RetroShortcuts.isRetroShortcut(shortcut)) { + com.winlator.cmod.feature.retro.RetroShortcuts.launch(activity, shortcut); + return; + } + Intent intent = new Intent(activity, XServerDisplayActivity.class); intent.putExtra("container_id", shortcut.container.id); intent.putExtra("shortcut_path", shortcut.file.getPath()); diff --git a/app/src/main/feature/sync/google/GameSaveBackupManager.kt b/app/src/main/feature/sync/google/GameSaveBackupManager.kt index d45535755..8361b7aa1 100644 --- a/app/src/main/feature/sync/google/GameSaveBackupManager.kt +++ b/app/src/main/feature/sync/google/GameSaveBackupManager.kt @@ -742,6 +742,26 @@ object GameSaveBackupManager { } } + fun retroSaveDir(context: Context, shortcut: Shortcut?): File? { + val system = shortcut + ?.getExtra(com.winlator.cmod.feature.retro.RetroShortcuts.KEY_SYSTEM) + ?.takeIf { it.isNotBlank() } ?: return null + val gameName = shortcut.getExtra("custom_name", shortcut.name) + return when { + system == com.winlator.cmod.feature.retro.RetroSystems.PS2.id -> + File(com.armsx2.runtime.MainActivityRuntime.assetCopyRoot(context), "memcards") + com.winlator.cmod.feature.retro.RetroCoreManager + .usesDolphinCore(com.winlator.cmod.feature.retro.RetroSystems.fromId(system)) -> + com.winlator.cmod.feature.retro.DolphinCloudSync.stagingDir( + context, + com.winlator.cmod.feature.retro.RetroSaveStates.cloudGameId(system, gameName), + ) + else -> com.winlator.cmod.feature.retro.RetroSaveStates.gameDir(context, gameName) + } + } + + fun customGameId(containerId: Int, shortcutFileName: String): String = "$containerId:$shortcutFileName" + /** Custom-game save sources in priority order: explicit customSaveDir, then the customSaveWindowsPath extra, then the legacy custom_game_folder extra, then the prefix's users/xuser/{Documents,Saved Games,AppData}. */ private fun getCustomSaveSources( context: Context, @@ -749,6 +769,28 @@ object GameSaveBackupManager { customSaveDir: File?, forRestore: Boolean, ): List { + val retroShortcut = + parseCustomGameId(gameId)?.let { (cid, f) -> findCustomShortcutByContainerAndFile(context, cid, f) } + ?: findCustomShortcutByGameId(context, gameId) + if (!forRestore && retroShortcut != null) { + val sys = retroShortcut.getExtra(com.winlator.cmod.feature.retro.RetroShortcuts.KEY_SYSTEM) + if (sys.isNotBlank()) { + com.winlator.cmod.feature.retro.DolphinCloudSync.refreshForBackup( + context, + sys, + retroShortcut.getExtra("custom_name", retroShortcut.name), + ) + } + } + val dir = retroSaveDir(context, retroShortcut) + if (dir != null) { + return if (forRestore || (dir.exists() && !dir.listFiles().isNullOrEmpty())) { + listOf(SaveBackupSource("retro/save", dir)) + } else { + emptyList() + } + } + val sources = linkedMapOf() val pickerDir = customSaveDir ?: resolveCustomSaveAndroidDir(context, gameId, null) diff --git a/app/src/main/feature/sync/ui/CloudSavesUIContent.kt b/app/src/main/feature/sync/ui/CloudSavesUIContent.kt index 1a42c91e8..f9f7870c1 100644 --- a/app/src/main/feature/sync/ui/CloudSavesUIContent.kt +++ b/app/src/main/feature/sync/ui/CloudSavesUIContent.kt @@ -36,6 +36,7 @@ import androidx.compose.material.icons.automirrored.outlined.ArrowBack import androidx.compose.material.icons.automirrored.outlined.OpenInNew import androidx.compose.material.icons.outlined.CloudSync import androidx.compose.material.icons.outlined.CloudUpload +import androidx.compose.material.icons.outlined.Delete import androidx.compose.material.icons.outlined.Download import androidx.compose.material.icons.outlined.Edit import androidx.compose.material.icons.outlined.FolderOpen @@ -121,6 +122,7 @@ private val CloudBorder = Color(0xFF2A2A3A) private val CloudAccent = Color(0xFF5CC8FF) private val CloudSuccess = Color(0xFF65D394) private val CloudWarning = Color(0xFFFFB85C) +private val CloudDanger = Color(0xFFE07B6B) @Composable internal fun CloudSavesContent( @@ -132,6 +134,7 @@ internal fun CloudSavesContent( gameId: String, gameName: String, shortcut: Shortcut?, + retroSaveDir: java.io.File? = null, onCloudSyncToggle: (Boolean) -> Unit, onOfflineModeToggle: (Boolean) -> Unit, onSyncFromCloud: () -> Unit, @@ -155,6 +158,10 @@ internal fun CloudSavesContent( var entryPendingRename by remember { mutableStateOf(null) } + var entryPendingDelete by remember { + mutableStateOf(null) + } + var deleteInProgress by remember { mutableStateOf(false) } val steamManagedCloud = gameSource == GameSaveBackupManager.GameSource.STEAM val targetContainerId = shortcut @@ -391,7 +398,7 @@ internal fun CloudSavesContent( ) } - if (!steamManagedCloud) { + if (!steamManagedCloud && retroSaveDir == null) { var customSavePath by remember(shortcut?.file?.absolutePath, historyRefreshKey) { mutableStateOf(shortcut?.let { GameSaveBackupManager.getCustomGameSaveWindowsPath(it) }) } @@ -591,6 +598,7 @@ internal fun CloudSavesContent( gameName = gameName, origin = GameSaveBackupManager.BackupOrigin.MANUAL, authMode = GoogleAuthMode.INTERACTIVE, + customSaveDir = retroSaveDir, containerHint = targetContainer, ) } @@ -767,6 +775,7 @@ internal fun CloudSavesContent( }, onRestore = { entry -> entryPendingRestore = entry }, onRename = { entry -> entryPendingRename = entry }, + onDelete = { entry -> entryPendingDelete = entry }, onDownload = { entry -> pendingCloudFileDownload = entry runCatching { @@ -793,6 +802,81 @@ internal fun CloudSavesContent( } } + entryPendingDelete?.let { entry -> + val whenLabel = + remember(entry.timestampMs) { + android.text.format.DateUtils + .getRelativeTimeSpanString( + entry.timestampMs, + System.currentTimeMillis(), + android.text.format.DateUtils.MINUTE_IN_MILLIS, + ).toString() + } + LaunchDangerConfirmDialog( + visible = true, + title = stringResource(R.string.cloud_saves_history_delete_confirm_title), + message = stringResource(R.string.cloud_saves_history_delete_confirm_body, whenLabel), + confirmLabel = stringResource(R.string.cloud_saves_history_delete), + icon = Icons.Outlined.Delete, + titleTextAlign = TextAlign.Center, + messageTextAlign = TextAlign.Center, + accentColor = CloudDanger, + onDismissRequest = { entryPendingDelete = null }, + onConfirm = { + val target = entryPendingDelete ?: return@LaunchDangerConfirmDialog + entryPendingDelete = null + scope.launch { + deleteInProgress = true + val result = + runCatching { + GameSaveBackupManager.deleteGoogleEntry(activity, target) + }.getOrElse { + GameSaveBackupManager.BackupResult(false, it.message ?: "") + } + deleteInProgress = false + notify( + if (result.success) { + context.getString(R.string.cloud_saves_history_delete_success) + } else { + context.getString(R.string.cloud_saves_history_delete_failed) + }, + Toast.LENGTH_SHORT, + ) + historyRefreshKey++ + } + }, + ) + } + + if (deleteInProgress) { + Dialog( + onDismissRequest = { deleteInProgress = false }, + properties = DialogProperties(dismissOnClickOutside = false), + ) { + Surface( + shape = RoundedCornerShape(12.dp), + color = CloudPanel, + border = BorderStroke(1.dp, CloudBorder), + ) { + Row( + modifier = Modifier.padding(20.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + CircularProgressIndicator( + modifier = Modifier.size(26.dp), + color = CloudDanger, + strokeWidth = 3.dp, + ) + Spacer(Modifier.width(16.dp)) + Text( + text = stringResource(R.string.cloud_saves_deleting), + color = Color.White, + ) + } + } + } + } + entryPendingRestore?.let { entry -> val whenLabel = remember(entry.timestampMs) { @@ -877,6 +961,7 @@ internal fun CloudSavesContent( target, gameSource, gameId, + customSaveDir = retroSaveDir, containerHint = targetContainer, ) } @@ -1106,6 +1191,7 @@ private fun SaveHistorySection( onRefresh: () -> Unit, onRestore: (GameSaveBackupManager.BackupHistoryEntry) -> Unit, onRename: (GameSaveBackupManager.BackupHistoryEntry) -> Unit, + onDelete: (GameSaveBackupManager.BackupHistoryEntry) -> Unit, onDownload: (GameSaveBackupManager.BackupHistoryEntry) -> Unit, ) { Row( @@ -1182,6 +1268,7 @@ private fun SaveHistorySection( entry = entry, onRestore = { onRestore(entry) }, onRename = { onRename(entry) }, + onDelete = { onDelete(entry) }, onDownload = { onDownload(entry) }, ) if (index < entries.lastIndex) { @@ -1203,6 +1290,7 @@ private fun SaveHistoryRow( entry: GameSaveBackupManager.BackupHistoryEntry, onRestore: () -> Unit, onRename: () -> Unit, + onDelete: () -> Unit, onDownload: () -> Unit, ) { val whenLabel = @@ -1332,6 +1420,14 @@ private fun SaveHistoryRow( tint = TextPrimary, onClick = onRename, ) + if (entry.storage == GameSaveBackupManager.BackupStorage.GOOGLE) { + HistoryIconButton( + icon = Icons.Outlined.Delete, + contentDescription = stringResource(R.string.cloud_saves_history_delete), + tint = CloudDanger, + onClick = onDelete, + ) + } } } } diff --git a/app/src/main/jniLibs/arm64-v8a/libdolphin_libretro_android.so b/app/src/main/jniLibs/arm64-v8a/libdolphin_libretro_android.so new file mode 100755 index 000000000..54c17947d --- /dev/null +++ b/app/src/main/jniLibs/arm64-v8a/libdolphin_libretro_android.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:052d5e6b5e9fa6aa24716b516202fcd20ed083c3d967ed2886dc0f715b6079f0 +size 15737744 diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 9919ec9cb..50b9410c9 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1621,6 +1621,779 @@ Ruta instalada: La creación de la carpeta falló Actualizar + Retro + Transferir partida + Importa una partida guardada local para este juego o exporta la partida actual. + Importar partida + Exportar partida + Partida importada + No se pudo importar la partida + Partida exportada + No se pudo exportar la partida + Aún no existe ninguna partida guardada para este juego + Trucos + Los trucos están desactivados en el modo Hardcore + + + Guardar + Cancelar + Guardar estado + Cargar estado + Logros + Trucos + Tarjetas de memoria + Avance rápido + Reiniciar + Cambiar disco + Ranura %1$d + Toca para cargar + Vacía + Toca para sobrescribir + Vacía — toca para guardar + La ranura %1$d está vacía + Ranura %1$d cargada + No se pudo cargar la ranura %1$d + Guardado en la ranura %1$d + Error al guardar + • Ranura 1 + • Ranura 2 + • Toca para usar + Nueva tarjeta de memoria + Importar tarjeta + Activar en línea (DEV9) + Adaptador de red de PS2: reinicia el juego para conectarlo + Dispositivo Ethernet + Modo DNS + DNS principal + DNS secundario + opcional + IP automática (DHCP) + Servidor: %1$s + toca para definir la IP (en blanco la elimina) + %1$s → IP + Agregar host de servidor + Nuevo nombre de host del servidor + p. ej. bf2.playbattlefront.com + Controles en pantalla + Editar disposición + Restablecer disposición + Disposición restablecida + Stick izquierdo: invertir X + Stick izquierdo: invertir Y + Stick derecho: invertir X + Stick derecho: invertir Y + Color de botones + Color de letras + Color de sombra + Color de fondo + Restablecer colores + Renderizador + Vulkan + OpenGL + Software + Escala de resolución + 1x (nativo) + 1.5x + 2x + 3x + 4x + Relación de aspecto + Estirar + Automático (estándar) + 4:3 + 16:9 + Filtro de pantalla + Más cercano + Bilineal (suave) + Bilineal (nítido) + Filtro de texturas + Bilineal (forzado) + Bilineal (PS2) + Bilineal (sprites) + Precisión de mezcla + Mínima + Básica + Media + Alta + Completa + Máxima + Shader CRT / TV + Desactivado + Líneas de escaneo + Diagonal + Triangular + Onda + Lottes + 4xRGSS + NxAGSS + Saltar fotogramas + Desactivado + Saltar 1 + Saltar 2 + Saltar 3 + Mipmapping + Volumen + %1$d%% + Silenciar + Intercambiar canales estéreo + Frecuencia de ciclos EE + 50% + 60% + 75% + 100% (predeterminado) + 130% + 180% + 300% + Salto de ciclos EE + Desactivado + 1 + 2 + 3 + VU1 instantáneo + VU multihilo (MTVU) + CDVD rápido + FPS + Velocidad de emulación + Uso de CPU + Uso de GPU + Resolución interna + Modo de desentrelazado + Automático + Desactivado + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + Relación de aspecto de FMV + Antidesenfoque + Parches panorámicos + Parches sin entrelazado + VU Flag Hack + Detección de bucle INTC + Detección de bucle de espera + Estiramiento de tiempo de audio + Búfer de audio + Latencia de salida + %1$d ms + Tiempos de fotograma + Estadísticas de GS + Información de hardware + Versión + Visualización de entradas + Menú + Pantalla + Rendimiento + HUD + Sonido + En línea + Controles + Reanudar + Pausar + Salir + BIOS importada: %1$s + Archivo de BIOS no válido + Juego retro no válido + ROM no encontrada: %1$s + No se pudo leer la ROM dentro de este archivo + Núcleo no instalado: %1$s + Trucos activados: los logros están desactivados en esta sesión + Guardado en la nube restaurado + Error al restaurar + Existe un guardado en la nube más reciente para %1$s. ¿Deseas sincronizar y cuál guardado en la nube prefieres conservar? + Guardado en la nube + Retro + No se pudo cargar el núcleo del emulador + No se pudo cargar la ROM + Gráficos no compatibles con este núcleo + Error del emulador + Predeterminado + CRT + LCD + Nítido + SGSR + Escalado SGSR + Nativo + Sonido + Stick izquierdo: invertir X + Stick izquierdo: invertir Y + Stick derecho: invertir X + Stick derecho: invertir Y + Controles en pantalla + Respuesta háptica + Vertical + Horizontal + Editar disposición (%1$s) + Restablecer disposición %1$s + Disposición %1$s restablecida + Color de botones + Color de letras + Color de sombra + Color de fondo + Restablecer colores + Colores restablecidos + HUD de rendimiento + Alfa + Alfa del fondo + Fondo + Escala + Tiempo de fotograma numérico + Batería de doble serie + ELEMENTOS DEL HUD + FPS + Consola + GPU + CPU + RAM + Batería + Temp. + Gráfica + Temp. CPU + Guardar estado + Cargar estado + La carga de estados está desactivada en modo Hardcore + Logros + Trucos + Los trucos están desactivados en modo Hardcore + Reiniciar + Avance rápido + El avance rápido está desactivado en modo Hardcore + HUD + Disco %1$d/%2$d + Reanudar + Pausar + Salir + Guardado en la ranura %1$d + No se pudo guardar el estado + Se requiere la BIOS de %1$s + Los juegos de PlayStation necesitan un archivo de BIOS real de la consola que debes proporcionar. Importa una BIOS (scph5501.bin, scph5500.bin, scph5502.bin, scph1001.bin o scph7001.bin) para continuar. + Importar BIOS… + Cancelar + La ranura %1$d está vacía + Ranura %1$d cargada + No se pudo cargar el estado + Ranura %1$d + Renombrar ranura %1$d + General + Gráficos + Rendimiento + HUD + Entrada + Audio + En línea + Cancelar + Guardar + Predeterminado + CRT + LCD + Nítido + 2x + 4x + Nativo + JUEGO + Nombre + Sistema + Núcleo del emulador + Ruta de la ROM + BIOS de %1$s + Instalada + Ninguna: necesaria para ejecutar juegos de %1$s + Importar BIOS… + Eliminar BIOS + IMÁGENES DE LA BIBLIOTECA + Imagen de la ficha del juego + Imagen de cuadrícula + Imagen de carrusel + Imagen de lista + Imagen personalizada establecida + Establecer imagen + Eliminar + VIDEO + Filtro de video + SGSR + Escalado SGSR + HUD de rendimiento + NÚCLEO + Renderizador + Vulkan + OpenGL + Software + Escala de resolución + 1x (nativo) + 1.5x + 2x + 3x + 4x + Relación de aspecto + Estirar + Automático (estándar) + 4:3 + 16:9 + Filtro de pantalla + Más cercano + Bilineal (suave) + Bilineal (nítido) + Filtro de texturas + Bilineal (forzado) + Bilineal (PS2) + Bilineal (sprites) + Precisión de mezcla + Mínima + Básica + Media + Alta + Completa + Máxima + Shader CRT / TV + Desactivado + Líneas de escaneo + Diagonal + Triangular + Onda + Lottes + 4xRGSS + NxAGSS + Saltar fotogramas + Saltar 1 + Saltar 2 + Saltar 3 + Mipmapping + RENDIMIENTO + Frecuencia de ciclos EE + 50% + 60% + 75% + 100% (predeterminado) + 130% + 180% + 300% + Salto de ciclos EE + 1 + 2 + 3 + VU1 instantáneo + VU multihilo (MTVU) + CDVD rápido + HUD DE RENDIMIENTO + FPS + Velocidad de emulación + Uso de CPU + Uso de GPU + Resolución interna + Modo de desentrelazado + Automático + Desactivado + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + Relación de aspecto de FMV + Antidesenfoque + Parches panorámicos + Parches sin entrelazado + VU Flag Hack + Detección de bucle INTC + Detección de bucle de espera + Estiramiento de tiempo de audio + Búfer de audio + Latencia de salida + %1$d ms + Tiempos de fotograma + Estadísticas de GS + Información de hardware + Versión + Visualización de entradas + Arranque rápido + EN LÍNEA (DEV9) + Activar en línea + Dispositivo Ethernet + Automático + Wi-Fi + Modo DNS + Manual + Interno + DNS principal + DNS secundario + opcional + IP automática (DHCP) + ENTRADA + Controles en pantalla + Respuesta háptica + AUDIO + Volumen + Silenciar + Intercambiar canales estéreo + Sonido + VALORES RETRO PREDETERMINADOS + Valores predeterminados aplicados a los juegos de cada consola salvo que se modifiquen en los ajustes propios de un juego. + RETROACHIEVEMENTS + Cuenta + Sesión iniciada + Sin sesión iniciada: abre los Logros de un juego para iniciar sesión + Logros activados + Modo Hardcore de forma predeterminada (sin estados guardados) + Cerrar sesión + BIOS DE PLAYSTATION + Instalada + Ninguna: los juegos de PS1 requieren una BIOS + Importar BIOS de PS1… + BIOS de PS1 eliminada + No hay ninguna BIOS que eliminar + Eliminar BIOS de PS1 + BIOS DE PLAYSTATION 2 + Ninguna: los juegos de PS2 requieren una BIOS + Formato + Volcado combinado en un solo archivo (.bin con región etiquetada, ~4MB). No se aceptan conjuntos ROM0/MEC/NVM separados. + Importar BIOS de PS2… + BIOS de PS2 eliminada + Eliminar BIOS de PS2 + IMÁGENES DE LA BIBLIOTECA + Imagen retro de la caja (cartucho / caja de CD) + Imagen de la caja + Se obtiene automáticamente de thumbnails.libretro.com al importar; una imagen personalizada siempre la reemplaza. + CARPETA DE ROMS + Carpeta + Sin definir: elige una carpeta para importar juegos automáticamente + Importación automática + Los juegos nuevos de esta carpeta se añaden automáticamente a tu biblioteca con la consola correcta detectada. + Seleccionar carpeta de ROMs + Seleccionar carpeta de ROMs… + Cambiar carpeta de ROMs… + Analizar ahora + VALORES PREDETERMINADOS DE LA CONSOLA + Toca una consola para configurar sus ajustes predeterminados. + Renderizador + Escalar resolución + Relación de aspecto + Estirar + Automático (estándar) + 4:3 + 16:9 + Filtro de pantalla + Más cercano + Bilineal (suave) + Bilineal (nítido) + Filtro de texturas + Bilineal (forzado) + Bilineal (PS2) + Bilineal (sprites) + Precisión de mezcla + Mínima + Básica + Media + Alta + Completa + Máxima + Shader CRT / TV + Desactivado + Líneas de escaneo + Diagonal + Triangular + Onda + Lottes + 4xRGSS + NxAGSS + Saltar fotogramas + Saltar 1 + Saltar 2 + Saltar 3 + Mipmapping + Frecuencia de ciclos EE + 50% + 60% + 75% + 100% (predeterminado) + 130% + 180% + 300% + Salto de ciclos EE + Desactivado + 1 + 2 + 3 + VU1 instantáneo + VU multihilo (MTVU) + CDVD rápido + Controles táctiles en pantalla + Sonido + Intercambiar canales estéreo + HUD: FPS + HUD: velocidad de emulación + HUD: uso de CPU + HUD: uso de GPU + HUD: resolución interna + Activar en línea (DEV9) + Dispositivo Ethernet + Automático + Wi-Fi + Modo DNS + Manual + Interno + DNS principal + DNS secundario + opcional + IP automática (DHCP) + Shader + Escalado SGSR + HUD de rendimiento + CRÉDITOS & LICENCIAS + Algunas funciones de WinNative se basan en estos proyectos de código abierto. Toca para ver cada fuente. + Predeterminados + Créditos + ¿Activar el modo Hardcore? + El modo Hardcore reinicia el juego ahora y desactiva la carga de estados guardados, el avance rápido y los trucos. Se perderá cualquier progreso sin guardar. ¿Continuar? + Cancelar + Activar + BIOS importada: %1$s + Archivo de BIOS no válido + BIOS de PS2 importada: %1$s + Archivo de BIOS de PS2 no válido + No hay ningún número de serie de juego para buscar trucos. + Se aplicaron %1$d truco(s). + No se pudieron aplicar los trucos. + Trucos + Aplicar + No se encontraron trucos para este juego. + Logros + Inicia sesión en RetroAchievements + Nombre de usuario + Contraseña + Error de inicio de sesión + Iniciando sesión… + Iniciar sesión + %1$d/%2$d • %3$d pts + No hay logros para este juego. + Atrás + Activado + Desactivado + Renombrar + Guardar + Conflicto de guardado en la nube + Conservar guardado local + A + Menú + Pantalla + HUD + Sonido + Controles + Biblioteca actualizada + ROMs: %1$s + %1$d añadidos + %1$d eliminados + Predeterminado + CRT + LCD + Nítido + Nativo + Relación de aspecto + Filtro NTSC + Coloración + Corrección de color + Quitar límite de sprites + Resolución + Emulación de framebuffer + Tramado + Hack de pantalla ancha + 8:7 (nativo) + 4:3 (TV) + Desactivado + RF + Compuesto + S-Video + RGB + Automático + Pantalla GBA + Pantalla GBC + Activado + 320x240 (nativo) + 640x480 + 960x720 + 1280x960 + 4:3 + 16:9 + 16:9 ajustado + Nativo + Interna + Activado (16:9) + RETROACHIEVEMENTS + Inicia sesión con tu cuenta de RetroAchievements para conseguir y seguir logros de juegos retro. + Nombre de usuario + Contraseña + Introduce tu nombre de usuario y contraseña + Error de inicio de sesión + Iniciar sesión + Tu contraseña solo se usa una vez para obtener un token de inicio de sesión, que se almacena de forma segura en el dispositivo. + Logros activados + Modo Hardcore (sin estados guardados) + %1$d / %2$d puntos + No se encontraron logros para este juego. + Cerrar sesión + TRUCOS + Nombre + Código + Cancelar + Guardar + Truco %1$d + Aún no hay trucos. Añade un código de truco para este juego. + Añadir truco + + Controlador de GPU + Sistema (Predeterminado) + Instala los controladores Turnip en Configuración \u2192 Controladores. Los mismos controladores funcionan para juegos de PC y de PS2. + + HDD de PS2 (DEV9) + Unidad interna virtual para juegos basados en HDD como Final Fantasy XI. Reinicia el juego. + Unidad interna virtual para juegos basados en HDD como Final Fantasy XI. + Modo DNS configurado en Internal para que tus hosts de servidor personalizados tengan efecto. + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + Add Cheat + Cheat name + Codes (one per line, e.g. 2021A268 00000000) + Custom + Enter a name and at least one valid code + Add + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + PS2 HDD Images + A .raw HDD image, or a .zip containing one (e.g. a game’s downloaded HDD with maps/DLC) + Import HDD Image + Importing… + Imported %1$s + Could not import HDD image + Removed %1$s + Remove %1$s + HDD Image + None + Cheats + Patches + PATCH + Custom + Applied %1$d cheat(s), %2$d patch(es). + No cheats or patches found for this game. + Cheat + Patch + Add + Núcleo de CPU + Núcleo doble + Trucos internos + Resolución interna + Renderizador + Posición de la barra de sensores + Omitir intro de BIOS + + + + + + + Abajo + Intérprete en caché + Hardware + Intérprete + JIT + Ratón / Toque + Palanca derecha (absoluta) + Palanca derecha (relativa) + Software + Estirar + Arriba + Omisión de VBI (salto de fotogramas automático) + Pantalla panorámica + Puntero del Wiimote + Los cambios se aplican la próxima vez que inicies este juego. + Inicia este juego una vez para detectar el número de serie del disco; luego los trucos y parches aparecerán aquí. + Omisión de autenticación DNAS: necesaria para el juego en línea + Aplicado automáticamente (en línea) + Trucos & parches + Tamaño: %1$s + Importar imagen de HDD + Quitar + Habilitar NetPlay + Desactivado de forma predeterminada. Habilítalo y luego elige Alojar o Unirse antes de iniciar.\nSe vuelve a desactivar cuando sales del juego. + Dirección del anfitrión + IP o nombre de host + Sesión de anfitrión + Activado = esperar a un jugador. Desactivado = unirse a la dirección del anfitrión + NetPlay usa puertos de multijugador local a través de TCP (jugador 1 anfitrión / jugador 2 cliente). El juego en línea de PS2 usa Ethernet DEV9 en su lugar. + Puerto + Tarjeta de memoria %1$d + Captura de pantalla + Usar guardado en la nube + LAN (IP directa) + Conectando… + Conexión + En línea (código de anfitrión) + Descartar + El NetPlay de GameCube/Wii usa el motor propio de Dolphin. Anfitrión = Jugador 1, Unirse = Jugador 2. Elige Alojar o Unirse y un tipo de conexión antes de iniciar; ambos dispositivos arrancan el mismo juego juntos. + Comparte la IP de Wi‑Fi de tu dispositivo y este puerto con el Jugador 2. El juego comienza automáticamente cuando se conecta. + Cuando el juego arranca se muestra un código de anfitrión; compártelo con el Jugador 2. El juego comienza automáticamente cuando se conecta. + Ingresa la IP de Wi‑Fi y el puerto del anfitrión, luego inicia para conectarte. + Ingresa el código de anfitrión del Jugador 1, luego inicia para conectarte. + Habilita NetPlay en la configuración del juego y elige Alojar o Unirse antes de iniciar + Buscar salas en Wi‑Fi + Game Link · cada pantalla es su propia consola portátil + El multijugador de GBA usa gpSP + adaptador inalámbrico. Asegúrate de que libgpsp esté instalado. + Multijugador de pantalla compartida a través de Wi‑Fi (como RetroArch).\nAnfitrión = Jugador 1, Unirse = Jugador 2. Ambos dispositivos muestran el mismo juego. + Game Link a través de Wi‑Fi: cada dispositivo ejecuta su propio juego.\nGB/GBC: enlace serie de Gambatte (Pokémon Gen 1–2).\nGBA: adaptador inalámbrico de gpSP (combates de Pokémon RF/VH/Esmeralda). + Alojar sala + Código de anfitrión + Código de anfitrión de traversal proporcionado por el anfitrión + Alojando sala + Toca Alojar para abrir una sala para esta sesión de juego, luego inicia el juego. NetPlay se desactiva cuando sales. + En la sala + Unirse por IP + Te uniste + Unirse + Al iniciar + Salir + Anfitrión = J1 · Unirse = J2 · el mismo juego en ambas pantallas + Alojar + Unirse + Manual + No se encontraron salas. Asegúrate de que el anfitrión esté en la misma red Wi‑Fi y alojando una sala. + Nombre para mostrar + Se muestra a otros jugadores + %1$d conectados + La sala está abierta solo para esta sesión. Inicia cuando estés listo. Salir del juego desactiva NetPlay. + Jugadores + Buscar Wi‑Fi + Buscar de nuevo + Busca salas abiertas en la misma red Wi‑Fi, o únete por dirección IP. + Buscando en Wi‑Fi… + Resultados de la búsqueda + Toca una sala para unirte ahora (no guarda la IP para el próximo inicio). + Detener búsqueda + NetPlay + %1$s se conectó + %1$s se desconectó + Esperando jugadores… + La compatibilidad con PlayStation 2 llegará pronto + Mostrar botones L3 / R3 + Cuando está desactivado, toca dos veces una palanca para pulsar L3 / R3 + INDICADORES DEL CONTROLADOR TURNIP + Se aplican solo cuando se selecciona un controlador de GPU personalizado arriba. + No se encontró el archivo del juego + Eliminar + Importar desde archivo… + Cargando… + NetPlay + Wii Home + Cambiar consola + Identificar como consola + Ahora identificado como %1$s ReShade Aplica un efecto ReShade (.fx) a los juegos DXVK/VKD3D (Vulkan) mediante la capa vkBasalt integrada. Coloca cada efecto en su propia carpeta en Android/data/<package>/files/ReShade/. El ajuste de parámetros en vivo y el interruptor en el juego llegarán con la actualización de la capa de recarga en caliente. @@ -1656,4 +2429,27 @@ Ruta instalada: Activar ReShade No hay efectos ReShade en este conjunto. Agrega efectos en la configuración de este juego (o del contenedor) para cambiarlos y ajustarlos aquí. Este efecto no expone parámetros ajustables. + Eliminando guardado… + Eliminar + ¿Eliminar permanentemente el guardado en la nube de %1$s? Esta acción no se puede deshacer. + Eliminar guardado en la nube + No se pudo eliminar el guardado en la nube + Guardado en la nube eliminado + Descarga primero los núcleos de consola — Configuración › Retro + Este dispositivo no puede ejecutar la emulación de PS2: necesita OpenGL ES 3.1 o posterior. + Buscar actualizaciones + Buscando actualizaciones… + Descargar núcleos de consola + Descargando… %1$d / %2$d MB + Núcleos de consola + Instalado — compilación %1$s + Instalado — compilación %1$s (falló la búsqueda de actualizaciones) + Instalando… + No instalado: descárgalo para jugar juegos retro + Estado + Actualizar núcleos de consola + Actualización disponible — compilación %1$s (%2$d MB) + Verificando la descarga… + Procesando… + Sistema diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 7c2bc7ae8..7c83507ff 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -1623,6 +1623,779 @@ Installeret sti: Kør i baggrunden Hold chatten kørende, efter du afslutter WinNative Opdater + Retro + Overfør gemt spil + Importer et lokalt gemt spil til dette spil, eller eksporter det aktuelle gemte spil. + Importer gemt spil + Eksporter gemt spil + Gemt spil importeret + Kunne ikke importere gemt spil + Gemt spil eksporteret + Kunne ikke eksportere gemt spil + Der findes endnu ikke et gemt spil til dette spil + Snydekoder + Snydekoder er deaktiveret i Hardcore-tilstand + + + Gem + Annuller + Gem tilstand + Indlæs gemt tilstand + Præstationer + Snydekoder + Memory Cards + Spol frem + Nulstil + Skift disk + Slot %1$d + Tryk for at indlæse + Tom + Tryk for at overskrive + Tom – tryk for at gemme + Slot %1$d er tom + Indlæste slot %1$d + Kunne ikke indlæse slot %1$d + Gemt i slot %1$d + Gem mislykkedes + • Slot 1 + • Slot 2 + • Tryk for at bruge + Nyt Memory Card + Importér kort + Aktivér online (DEV9) + PS2-netværksadapter – genstarter spillet for at tilslutte den + Ethernet-enhed + DNS-tilstand + Primær DNS + Sekundær DNS + valgfri + Auto-IP (DHCP) + Server: %1$s + tryk for at angive IP (tom fjerner) + %1$s → IP + Tilføj serverhost + Nyt servernavn + f.eks. bf2.playbattlefront.com + Skærmknapper + Rediger layout + Nulstil layout + Layout nulstillet + Venstre stik: Invertér X + Venstre stik: Invertér Y + Højre stik: Invertér X + Højre stik: Invertér Y + Knapfarve + Bogstavfarve + Skyggefarve + Baggrundsfarve + Nulstil farver + Renderer + Vulkan + OpenGL + Software + Opløsningsskala + 1x (Native) + 1.5x + 2x + 3x + 4x + Billedformat + Stræk + Auto (Standard) + 4:3 + 16:9 + Skærmfilter + Nærmeste + Bilineær (Blød) + Bilineær (Skarp) + Teksturfilter + Bilineær (Tvunget) + Bilineær (PS2) + Bilineær (Sprites) + Blandingsnøjagtighed + Minimum + Grundlæggende + Middel + Høj + Fuld + Maksimum + CRT-/TV-shader + Fra + Scanline + Diagonal + Triangular + Wave + Lottes + 4xRGSS + NxAGSS + Frame Skip + Fra + Spring 1 over + Spring 2 over + Spring 3 over + Mipmapping + Lydstyrke + %1$d%% + Lyd fra + Byt stereokanaler + EE-cyklushastighed + 50% + 60% + 75% + 100% (Standard) + 130% + 180% + 300% + EE-cyklusspring + Fra + 1 + 2 + 3 + Instant VU1 + Multi-Threaded VU (MTVU) + Hurtig CDVD + FPS + Emuleringshastighed + CPU-forbrug + GPU-forbrug + Intern opløsning + Deinterlace-tilstand + Auto + Fra + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + FMV-billedformat + Anti-slør + Widescreen-patches + No-interlace-patches + VU Flag Hack + INTC-spin-registrering + Venteløkke-registrering + Lyd-timestretch + Lydbuffer + Outputlatens + %1$d ms + Frametider + GS-statistik + Hardwareinfo + Version + Inputvisning + Menu + Skærm + Ydeevne + HUD + Lyd + Online + Kontroller + Fortsæt + Pause + Afslut + BIOS importeret: %1$s + Ugyldig BIOS-fil + Ugyldigt retrospil + ROM ikke fundet: %1$s + Kunne ikke læse ROM\'en i dette arkiv + Kerne ikke installeret: %1$s + Snydekoder aktiveret – præstationer er deaktiveret for denne session + Cloud-gem gendannet + Gendannelse mislykkedes + Der findes et nyere cloud-gem for %1$s. Vil du synkronisere, og hvilket cloud-gem foretrækker du at beholde? + Cloud-gem + Retro + Emulatorkernen kunne ikke indlæses + ROM kunne ikke indlæses + Grafik understøttes ikke af denne kerne + Emulatorfejl + Standard + CRT + LCD + Skarp + SGSR + SGSR-opskalering + Native + Lyd + Venstre stik: Invertér X + Venstre stik: Invertér Y + Højre stik: Invertér X + Højre stik: Invertér Y + Skærmknapper + Haptisk feedback + Stående + Liggende + Rediger layout (%1$s) + Nulstil %1$s-layout + %1$s-layout nulstillet + Knapfarve + Bogstavfarve + Skyggefarve + Baggrundsfarve + Nulstil farver + Farver nulstillet + Ydeevne-HUD + Alfa + Baggrundsalfa + Baggrund + Skala + Numerisk frametid + Dual-serie batteri + HUD-ELEMENTER + FPS + Konsol + GPU + CPU + RAM + Batteri + Temp. + Graf + CPU-temp. + Gem tilstand + Indlæs gemt tilstand + Indlæsning af tilstande er deaktiveret i Hardcore-tilstand + Præstationer + Snydekoder + Snydekoder er deaktiveret i Hardcore-tilstand + Nulstil + Spol frem + Spol frem er deaktiveret i Hardcore-tilstand + HUD + Disk %1$d/%2$d + Fortsæt + Pause + Afslut + Gemt i slot %1$d + Kunne ikke gemme tilstand + %1$s BIOS påkrævet + PlayStation-spil kræver en rigtig konsol-BIOS-fil, som du selv skal levere. Importér en BIOS (scph5501.bin, scph5500.bin, scph5502.bin, scph1001.bin eller scph7001.bin) for at fortsætte. + Importér BIOS… + Annuller + Slot %1$d er tom + Indlæste slot %1$d + Kunne ikke indlæse tilstand + Slot %1$d + Omdøb slot %1$d + Generelt + Grafik + Ydeevne + HUD + Input + Lyd + Online + Annuller + Gem + Standard + CRT + LCD + Skarp + 2x + 4x + Native + SPIL + Navn + System + Emulatorkerne + ROM-sti + %1$s BIOS + Installeret + Ingen – påkrævet for at køre %1$s-spil + Importér BIOS… + Fjern BIOS + BIBLIOTEKSGRAFIK + Spilkortbillede + Gitterbillede + Karrusellbillede + Listebillede + Brugerdefineret billede angivet + Angiv billede + Fjern + VIDEO + Videofilter + SGSR + SGSR-opskalering + Ydeevne-HUD + KERNE + Renderer + Vulkan + OpenGL + Software + Opløsningsskala + 1x (Native) + 1.5x + 2x + 3x + 4x + Billedformat + Stræk + Auto (Standard) + 4:3 + 16:9 + Skærmfilter + Nærmeste + Bilineær (Blød) + Bilineær (Skarp) + Teksturfilter + Bilineær (Tvunget) + Bilineær (PS2) + Bilineær (Sprites) + Blandingsnøjagtighed + Minimum + Grundlæggende + Middel + Høj + Fuld + Maksimum + CRT-/TV-shader + Fra + Scanline + Diagonal + Triangular + Wave + Lottes + 4xRGSS + NxAGSS + Frame Skip + Spring 1 over + Spring 2 over + Spring 3 over + Mipmapping + YDEEVNE + EE-cyklushastighed + 50% + 60% + 75% + 100% (Standard) + 130% + 180% + 300% + EE-cyklusspring + 1 + 2 + 3 + Instant VU1 + Multi-Threaded VU (MTVU) + Hurtig CDVD + YDEEVNE-HUD + FPS + Emuleringshastighed + CPU-forbrug + GPU-forbrug + Intern opløsning + Deinterlace-tilstand + Auto + Fra + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + FMV-billedformat + Anti-slør + Widescreen-patches + No-interlace-patches + VU Flag Hack + INTC-spin-registrering + Venteløkke-registrering + Lyd-timestretch + Lydbuffer + Outputlatens + %1$d ms + Frametider + GS-statistik + Hardwareinfo + Version + Inputvisning + Hurtig opstart + ONLINE (DEV9) + Aktivér online + Ethernet-enhed + Auto + Wi-Fi + DNS-tilstand + Manuel + Intern + Primær DNS + Sekundær DNS + valgfri + Auto-IP (DHCP) + INPUT + Skærmknapper + Haptisk feedback + LYD + Lydstyrke + Lyd fra + Byt stereokanaler + Lyd + RETRO-STANDARDER + Standarder, der anvendes på hver konsols spil, medmindre de tilsidesættes i et spils egne indstillinger. + RETROACHIEVEMENTS + Konto + Logget ind + Ikke logget ind – åbn et spils præstationer for at logge ind + Præstationer aktiveret + Hardcore-tilstand som standard (ingen gemte tilstande) + Log ud + PLAYSTATION BIOS + Installeret + Ingen – PS1-spil kræver en BIOS + Importér PS1 BIOS… + PS1 BIOS fjernet + Ingen BIOS at fjerne + Fjern PS1 BIOS + PLAYSTATION 2 BIOS + Ingen – PS2-spil kræver en BIOS + Format + Sammenlagt enkeltfil-dump (regionsmærket .bin, ~4 MB). Opdelte ROM0/MEC/NVM-sæt accepteres ikke. + Importér PS2 BIOS… + PS2 BIOS fjernet + Fjern PS2 BIOS + BIBLIOTEKSGRAFIK + Retro coverart (kassette / cd-cover) + Coverart + Hentes automatisk fra thumbnails.libretro.com ved import; et brugerdefineret billede tilsidesætter det altid. + ROMS-MAPPE + Mappe + Ikke angivet – vælg en mappe for automatisk import af spil + Auto-import + Nye spil i denne mappe tilføjes automatisk til dit bibliotek med den korrekte konsol registreret. + Vælg ROMs-mappe + Vælg ROMs-mappe… + Skift ROMs-mappe… + Scan nu + KONSOL-STANDARDER + Tryk på en konsol for at angive dens standardindstillinger. + Renderer + Opskalér opløsning + Billedformat + Stræk + Auto (Standard) + 4:3 + 16:9 + Skærmfilter + Nærmeste + Bilineær (Blød) + Bilineær (Skarp) + Teksturfilter + Bilineær (Tvunget) + Bilineær (PS2) + Bilineær (Sprites) + Blandingsnøjagtighed + Minimum + Grundlæggende + Middel + Høj + Fuld + Maksimum + CRT-/TV-shader + Fra + Scanline + Diagonal + Triangular + Wave + Lottes + 4xRGSS + NxAGSS + Frame Skip + Spring 1 over + Spring 2 over + Spring 3 over + Mipmapping + EE-cyklushastighed + 50% + 60% + 75% + 100% (Standard) + 130% + 180% + 300% + EE-cyklusspring + Fra + 1 + 2 + 3 + Instant VU1 + Multi-Threaded VU (MTVU) + Hurtig CDVD + Berøringsknapper på skærmen + Lyd + Byt stereokanaler + HUD: FPS + HUD: Emuleringshastighed + HUD: CPU-forbrug + HUD: GPU-forbrug + HUD: Intern opløsning + Aktivér online (DEV9) + Ethernet-enhed + Auto + Wi-Fi + DNS-tilstand + Manuel + Intern + Primær DNS + Sekundær DNS + valgfri + Auto-IP (DHCP) + Shader + SGSR-opskalering + Ydeevne-HUD + MEDVIRKENDE & LICENSER + Nogle af WinNatives funktioner er bygget på disse open source-projekter. Tryk for at se hver kilde. + Standarder + Medvirkende + Aktivér Hardcore-tilstand? + Hardcore-tilstand nulstiller spillet nu og deaktiverer indlæsning af gemte tilstande, spol frem og snydekoder. Ugemt fremskridt går tabt. Fortsæt? + Annuller + Aktivér + BIOS importeret: %1$s + Ugyldig BIOS-fil + PS2 BIOS importeret: %1$s + Ugyldig PS2 BIOS-fil + Intet spilserienummer at slå snydekoder op for. + Anvendte %1$d snydekode(r). + Kunne ikke anvende snydekoder. + Snydekoder + Anvend + Ingen snydekoder fundet for dette spil. + Præstationer + Log ind på RetroAchievements + Brugernavn + Adgangskode + Login mislykkedes + Logger ind… + Log ind + %1$d/%2$d • %3$d p. + Ingen præstationer for dette spil. + Tilbage + Aktiveret + Deaktiveret + Omdøb + Gem + Cloud-gemmekonflikt + Behold lokalt gem + A + Menu + Skærm + HUD + Lyd + Kontroller + Bibliotek opdateret + ROMs: %1$s + tilføjet %1$d + fjernet %1$d + Standard + CRT + LCD + Skarp + Native + Billedformat + NTSC-filter + Farvelægning + Farvekorrektion + Fjern sprite-grænse + Opløsning + Framebuffer-emulering + Dithering + Widescreen-hack + 8:7 (Native) + 4:3 (TV) + Fra + RF + Composite + S-Video + RGB + Auto + GBA-skærm + GBC-skærm + Til + 320x240 (Native) + 640x480 + 960x720 + 1280x960 + 4:3 + 16:9 + 16:9 justeret + Native + Intern + Til (16:9) + RETROACHIEVEMENTS + Log ind med din RetroAchievements-konto for at optjene og følge præstationer for retrospil. + Brugernavn + Adgangskode + Indtast dit brugernavn og din adgangskode + Login mislykkedes + Log ind + Din adgangskode bruges kun én gang til at hente et login-token, som gemmes sikkert på enheden. + Præstationer aktiveret + Hardcore-tilstand (ingen gemte tilstande) + %1$d / %2$d point + Ingen præstationer fundet for dette spil. + Log ud + SNYDEKODER + Navn + Kode + Annuller + Gem + Snydekode %1$d + Ingen snydekoder endnu. Tilføj en snydekode til dette spil. + Tilføj snydekode + + GPU-driver + System (Standard) + Installer Turnip-drivere under Indstillinger \u2192 Drivere. De samme drivere virker til både PC- og PS2-spil. + + PS2 HDD (DEV9) + Virtuelt internt drev til HDD-baserede spil som Final Fantasy XI. Genstarter spillet. + Virtuelt internt drev til HDD-baserede spil som Final Fantasy XI. + DNS-tilstand indstillet til Internal, så dine tilpassede serverhosts træder i kraft. + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + Add Cheat + Cheat name + Codes (one per line, e.g. 2021A268 00000000) + Custom + Enter a name and at least one valid code + Add + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + PS2 HDD Images + A .raw HDD image, or a .zip containing one (e.g. a game’s downloaded HDD with maps/DLC) + Import HDD Image + Importing… + Imported %1$s + Could not import HDD image + Removed %1$s + Remove %1$s + HDD Image + None + Cheats + Patches + PATCH + Custom + Applied %1$d cheat(s), %2$d patch(es). + No cheats or patches found for this game. + Cheat + Patch + Add +CPU-kerne +Dobbeltkerne +Interne snydekoder +Intern opløsning +Renderer +Placering af sensorbjælke +Spring BIOS-intro over + + + + + + +Nederst +Cachet fortolker +Hardware +Fortolker +JIT +Mus / berøring +Højre stik (absolut) +Højre stik (relativt) +Software +Stræk +Øverst +VBI-spring (auto-billedspring) +Bredformat +Wiimote-markør +Ændringer træder i kraft, næste gang du starter dette spil. +Start dette spil én gang, så dets diskserienummer kan registreres, hvorefter snydekoder og patches vises her. +DNAS-godkendelsesomgåelse — påkrævet for onlinespil +Anvendes automatisk (online) +Snydekoder & patches +Størrelse: %1$s +Importér HDD-billede +Fjern +Aktivér NetPlay +Slået fra som standard. Aktivér, og vælg derefter Vær vært eller Deltag før start.\nSlås fra igen, når du forlader spillet. +Værtsadresse +IP eller værtsnavn +Værtssession +Til = vent på en spiller. Fra = deltag på værtsadresse +NetPlay bruger lokale multiplayer-porte over TCP (spiller 1 vært / spiller 2 klient). PS2-online bruger i stedet DEV9 Ethernet. +Port +Hukommelseskort %1$d +Skærmbillede +Brug cloud-gemning +LAN (direkte IP) +Opretter forbindelse… +Forbindelse +Online (værtskode) +Afvis +GameCube/Wii NetPlay bruger Dolphin\'s egen motor. Vært = Spiller 1, Deltag = Spiller 2. Vælg Vær vært eller Deltag og en forbindelsestype før start; begge enheder starter det samme spil sammen. +Del din enheds Wi‑Fi-IP og denne port med Spiller 2. Spillet starter automatisk, når de opretter forbindelse. +En værtskode vises, når spillet starter — del den med Spiller 2. Spillet starter automatisk, når de opretter forbindelse. +Indtast værtens Wi‑Fi-IP og port, og start derefter for at oprette forbindelse. +Indtast værtskoden fra Spiller 1, og start derefter for at oprette forbindelse. +Aktivér NetPlay i spilindstillinger, og vælg Vær vært eller Deltag før start +Find rum på Wi‑Fi +Game Link · hver skærm er sin egen håndholdte konsol +GBA-multiplayer bruger gpSP + trådløs adapter. Sørg for, at libgpsp er installeret. +Multiplayer med delt skærm over Wi‑Fi (ligesom RetroArch).\nVært = Spiller 1, Deltag = Spiller 2. Begge enheder viser det samme spil. +Game Link over Wi‑Fi — hver enhed kører sit eget spil.\nGB/GBC: Gambatte seriel forbindelse (Pokémon Gen 1–2).\nGBA: gpSP trådløs adapter (Pokémon FR/LG/Emerald-kampe). +Vær vært for rum +Værtskode +Traversal-værtskode fra værten +Er vært for rum +Tryk på Vær vært for at åbne et rum til denne spilsession, og start derefter spillet. NetPlay slås fra, når du afslutter. +I rum +Deltag via IP +Deltog +Deltag +Ved start +Forlad +Vært = P1 · Deltag = P2 · samme spil på begge skærme +Vær vært +Deltag +Manuel +Ingen rum fundet. Sørg for, at værten er på det samme Wi‑Fi og er vært for et rum. +Vist navn +Vises til andre spillere +%1$d tilsluttet +Rummet er kun åbent for denne session. Start, når du er klar. Når du afslutter spillet, slås NetPlay fra. +Spillere +Scan Wi‑Fi +Scan igen +Scan det samme Wi‑Fi for åbne rum, eller deltag via IP-adresse. +Scanner Wi‑Fi… +Scanningsresultater +Tryk på et rum for at deltage nu (gemmer ikke IP\'en til næste start). +Stop scanning +NetPlay +%1$s tilsluttet +%1$s afbrudt +Venter på spillere… +PlayStation 2-understøttelse kommer snart +Vis L3 / R3-knapper +Når slået fra, dobbelttryk på et stik for at klikke L3 / R3 +TURNIP-DRIVERFLAG +Anvendes kun, når en tilpasset GPU-driver er valgt ovenfor. +Spilfil ikke fundet +Slet +Importér fra fil… +Indlæser… +NetPlay + Wii Home + Skift konsol + Identificer som konsol + Identificeret nu som %1$s ReShade Anvend en ReShade-effekt (.fx) på DXVK/VKD3D-spil (Vulkan) via det indbyggede vkBasalt-lag. Læg hver effekt i sin egen mappe under Android/data/<package>/files/ReShade/. Justering af parametre i realtid og kontakten i spillet kommer med opdateringen af live-reload-laget. @@ -1658,4 +2431,27 @@ Installeret sti: Aktivér ReShade Ingen ReShade-effekter i dette sæt. Tilføj effekter i dette spils indstillinger (eller containerens) for at skifte og justere dem her. Denne effekt har ingen justerbare parametre. + Sletter save… + Slet + Vil du slette cloud-savet fra %1$s permanent? Dette kan ikke fortrydes. + Slet cloud-save + Kunne ikke slette cloud-save + Cloud-save slettet + Hent konsolkernerne først — Indstillinger › Retro + Denne enhed kan ikke køre PS2-emulering — den kræver OpenGL ES 3.1 eller nyere. + Søg efter opdateringer + Søger efter opdateringer… + Hent konsolkerner + Henter… %1$d / %2$d MB + Konsolkerner + Installeret — build %1$s + Installeret — build %1$s (kunne ikke søge efter opdateringer) + Installerer… + Ikke installeret — hent for at spille retrospil + Status + Opdater konsolkerner + Opdatering tilgængelig — build %1$s (%2$d MB) + Bekræfter download… + Arbejder… + System diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 303dbfa8e..4ca6be5cf 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1623,6 +1623,779 @@ Installierter Pfad: Im Hintergrund ausführen Chat nach dem Beenden von WinNative weiterlaufen lassen Aktualisieren + Retro + Spielstand übertragen + Importiere einen lokalen Spielstand für dieses Spiel oder exportiere den aktuellen Spielstand. + Spielstand importieren + Spielstand exportieren + Spielstand importiert + Spielstand konnte nicht importiert werden + Spielstand exportiert + Spielstand konnte nicht exportiert werden + Für dieses Spiel existiert noch kein Spielstand + Cheats + Cheats sind im Hardcore-Modus deaktiviert + + + Speichern + Abbrechen + Spielstand speichern + Spielstand laden + Erfolge + Cheats + Memory Cards + Schnellvorlauf + Zurücksetzen + Disc wechseln + Slot %1$d + Zum Laden tippen + Leer + Zum Überschreiben tippen + Leer – zum Speichern tippen + Slot %1$d ist leer + Slot %1$d geladen + Slot %1$d konnte nicht geladen werden + In Slot %1$d gespeichert + Speichern fehlgeschlagen + • Slot 1 + • Slot 2 + • Zum Verwenden tippen + Neue Memory Card + Card importieren + Online aktivieren (DEV9) + PS2-Netzwerkadapter – startet das Spiel neu, um ihn zu verbinden + Ethernet-Gerät + DNS-Modus + Primärer DNS + Sekundärer DNS + optional + Auto-IP (DHCP) + Server: %1$s + tippen, um IP festzulegen (leer entfernt) + %1$s → IP + Server-Host hinzufügen + Neuer Server-Hostname + z. B. bf2.playbattlefront.com + Bildschirmsteuerung + Layout bearbeiten + Layout zurücksetzen + Layout zurückgesetzt + Linker Stick: X umkehren + Linker Stick: Y umkehren + Rechter Stick: X umkehren + Rechter Stick: Y umkehren + Tastenfarbe + Buchstabenfarbe + Schattenfarbe + Hintergrundfarbe + Farben zurücksetzen + Renderer + Vulkan + OpenGL + Software + Auflösungsskalierung + 1x (Nativ) + 1.5x + 2x + 3x + 4x + Seitenverhältnis + Strecken + Auto (Standard) + 4:3 + 16:9 + Anzeigefilter + Nächster + Bilinear (Weich) + Bilinear (Scharf) + Texturfilter + Bilinear (Erzwungen) + Bilinear (PS2) + Bilinear (Sprites) + Blending-Genauigkeit + Minimum + Einfach + Mittel + Hoch + Voll + Maximum + CRT-/TV-Shader + Aus + Scanline + Diagonal + Triangular + Wave + Lottes + 4xRGSS + NxAGSS + Frame Skip + Aus + 1 überspringen + 2 überspringen + 3 überspringen + Mipmapping + Lautstärke + %1$d%% + Stumm + Stereokanäle tauschen + EE-Taktrate + 50% + 60% + 75% + 100% (Standard) + 130% + 180% + 300% + EE-Zyklus überspringen + Aus + 1 + 2 + 3 + Instant VU1 + Multi-Threaded VU (MTVU) + Schnelles CDVD + FPS + Emulationsgeschwindigkeit + CPU-Auslastung + GPU-Auslastung + Interne Auflösung + Deinterlace-Modus + Auto + Aus + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + FMV-Seitenverhältnis + Anti-Blur + Breitbild-Patches + No-Interlace-Patches + VU-Flag-Hack + INTC-Spin-Erkennung + Warteschleifen-Erkennung + Audio-Timestretch + Audio-Puffer + Ausgabelatenz + %1$d ms + Frametimes + GS-Statistiken + Hardware-Info + Version + Eingabeanzeige + Menü + Anzeige + Leistung + HUD + Ton + Online + Steuerung + Fortsetzen + Pause + Beenden + BIOS importiert: %1$s + Ungültige BIOS-Datei + Ungültiges Retro-Spiel + ROM nicht gefunden: %1$s + Die ROM in diesem Archiv konnte nicht gelesen werden + Core nicht installiert: %1$s + Cheats aktiviert – Erfolge sind für diese Sitzung deaktiviert + Cloud-Spielstand wiederhergestellt + Wiederherstellung fehlgeschlagen + Für %1$s existiert ein neuerer Cloud-Spielstand. Möchtest du synchronisieren, und welchen Cloud-Spielstand möchtest du behalten? + Cloud-Spielstand + Retro + Emulator-Core konnte nicht geladen werden + ROM konnte nicht geladen werden + Grafik für diesen Core nicht unterstützt + Emulatorfehler + Standard + CRT + LCD + Scharf + SGSR + SGSR-Upscale + Nativ + Ton + Linker Stick: X umkehren + Linker Stick: Y umkehren + Rechter Stick: X umkehren + Rechter Stick: Y umkehren + Bildschirmsteuerung + Haptisches Feedback + Hochformat + Querformat + Layout bearbeiten (%1$s) + %1$s-Layout zurücksetzen + %1$s-Layout zurückgesetzt + Tastenfarbe + Buchstabenfarbe + Schattenfarbe + Hintergrundfarbe + Farben zurücksetzen + Farben zurückgesetzt + Leistungs-HUD + Alpha + Hintergrund-Alpha + Hintergrund + Skalierung + Numerische Frame-Zeit + Dual-Serien-Akku + HUD-ELEMENTE + FPS + Konsole + GPU + CPU + RAM + Akku + Temp. + Diagramm + CPU-Temp. + Spielstand speichern + Spielstand laden + Das Laden von Spielständen ist im Hardcore-Modus deaktiviert + Erfolge + Cheats + Cheats sind im Hardcore-Modus deaktiviert + Zurücksetzen + Schnellvorlauf + Schnellvorlauf ist im Hardcore-Modus deaktiviert + HUD + Disc %1$d/%2$d + Fortsetzen + Pause + Beenden + In Slot %1$d gespeichert + Spielstand konnte nicht gespeichert werden + %1$s-BIOS erforderlich + PlayStation-Spiele benötigen eine echte Konsolen-BIOS-Datei, die du selbst bereitstellen musst. Importiere ein BIOS (scph5501.bin, scph5500.bin, scph5502.bin, scph1001.bin oder scph7001.bin), um fortzufahren. + BIOS importieren… + Abbrechen + Slot %1$d ist leer + Slot %1$d geladen + Spielstand konnte nicht geladen werden + Slot %1$d + Slot %1$d umbenennen + Allgemein + Grafik + Leistung + HUD + Eingabe + Audio + Online + Abbrechen + Speichern + Standard + CRT + LCD + Scharf + 2x + 4x + Nativ + SPIEL + Name + System + Emulator-Core + ROM-Pfad + %1$s-BIOS + Installiert + Keins – erforderlich für %1$s-Spiele + BIOS importieren… + BIOS entfernen + BIBLIOTHEKS-ARTWORK + Spielkartenbild + Rasterbild + Karussellbild + Listenbild + Eigenes Bild festgelegt + Bild festlegen + Entfernen + VIDEO + Videofilter + SGSR + SGSR-Upscale + Leistungs-HUD + CORE + Renderer + Vulkan + OpenGL + Software + Auflösungsskalierung + 1x (Nativ) + 1.5x + 2x + 3x + 4x + Seitenverhältnis + Strecken + Auto (Standard) + 4:3 + 16:9 + Anzeigefilter + Nächster + Bilinear (Weich) + Bilinear (Scharf) + Texturfilter + Bilinear (Erzwungen) + Bilinear (PS2) + Bilinear (Sprites) + Blending-Genauigkeit + Minimum + Einfach + Mittel + Hoch + Voll + Maximum + CRT-/TV-Shader + Aus + Scanline + Diagonal + Triangular + Wave + Lottes + 4xRGSS + NxAGSS + Frame Skip + 1 überspringen + 2 überspringen + 3 überspringen + Mipmapping + LEISTUNG + EE-Taktrate + 50% + 60% + 75% + 100% (Standard) + 130% + 180% + 300% + EE-Zyklus überspringen + 1 + 2 + 3 + Instant VU1 + Multi-Threaded VU (MTVU) + Schnelles CDVD + LEISTUNGS-HUD + FPS + Emulationsgeschwindigkeit + CPU-Auslastung + GPU-Auslastung + Interne Auflösung + Deinterlace-Modus + Auto + Aus + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + FMV-Seitenverhältnis + Anti-Blur + Breitbild-Patches + No-Interlace-Patches + VU-Flag-Hack + INTC-Spin-Erkennung + Warteschleifen-Erkennung + Audio-Timestretch + Audio-Puffer + Ausgabelatenz + %1$d ms + Frametimes + GS-Statistiken + Hardware-Info + Version + Eingabeanzeige + Schnellstart + ONLINE (DEV9) + Online aktivieren + Ethernet-Gerät + Auto + Wi-Fi + DNS-Modus + Manuell + Intern + Primärer DNS + Sekundärer DNS + optional + Auto-IP (DHCP) + EINGABE + Bildschirmsteuerung + Haptisches Feedback + AUDIO + Lautstärke + Stumm + Stereokanäle tauschen + Ton + RETRO-STANDARDS + Standards, die auf die Spiele jeder Konsole angewendet werden, sofern sie nicht in den eigenen Einstellungen eines Spiels überschrieben werden. + RETROACHIEVEMENTS + Konto + Angemeldet + Nicht angemeldet – öffne die Erfolge eines Spiels, um dich anzumelden + Erfolge aktiviert + Hardcore-Modus standardmäßig (keine Spielstände) + Abmelden + PLAYSTATION-BIOS + Installiert + Keins – PS1-Spiele benötigen ein BIOS + PS1-BIOS importieren… + PS1-BIOS entfernt + Kein BIOS zum Entfernen + PS1-BIOS entfernen + PLAYSTATION 2-BIOS + Keins – PS2-Spiele benötigen ein BIOS + Format + Zusammengeführter Einzeldatei-Dump (regionsmarkierte .bin, ~4 MB). Geteilte ROM0/MEC/NVM-Sets werden nicht akzeptiert. + PS2-BIOS importieren… + PS2-BIOS entfernt + PS2-BIOS entfernen + BIBLIOTHEKS-ARTWORK + Retro-Hüllenbild (Modul / CD-Hülle) + Verpackungsbild + Beim Import automatisch von thumbnails.libretro.com abgerufen; ein eigenes Bild hat immer Vorrang. + ROMS-ORDNER + Ordner + Nicht festgelegt – wähle einen Ordner zum automatischen Importieren von Spielen + Auto-Import + Neue Spiele in diesem Ordner werden automatisch mit der richtigen erkannten Konsole zu deiner Bibliothek hinzugefügt. + ROMs-Ordner auswählen + ROMs-Ordner auswählen… + ROMs-Ordner ändern… + Jetzt scannen + KONSOLEN-STANDARDS + Tippe auf eine Konsole, um ihre Standardeinstellungen festzulegen. + Renderer + Auflösung hochskalieren + Seitenverhältnis + Strecken + Auto (Standard) + 4:3 + 16:9 + Anzeigefilter + Nächster + Bilinear (Weich) + Bilinear (Scharf) + Texturfilter + Bilinear (Erzwungen) + Bilinear (PS2) + Bilinear (Sprites) + Blending-Genauigkeit + Minimum + Einfach + Mittel + Hoch + Voll + Maximum + CRT-/TV-Shader + Aus + Scanline + Diagonal + Triangular + Wave + Lottes + 4xRGSS + NxAGSS + Frame Skip + 1 überspringen + 2 überspringen + 3 überspringen + Mipmapping + EE-Taktrate + 50% + 60% + 75% + 100% (Standard) + 130% + 180% + 300% + EE-Zyklus überspringen + Aus + 1 + 2 + 3 + Instant VU1 + Multi-Threaded VU (MTVU) + Schnelles CDVD + Bildschirm-Touch-Steuerung + Ton + Stereokanäle tauschen + HUD: FPS + HUD: Emulationsgeschwindigkeit + HUD: CPU-Auslastung + HUD: GPU-Auslastung + HUD: Interne Auflösung + Online aktivieren (DEV9) + Ethernet-Gerät + Auto + Wi-Fi + DNS-Modus + Manuell + Intern + Primärer DNS + Sekundärer DNS + optional + Auto-IP (DHCP) + Shader + SGSR-Upscaling + Leistungs-HUD + MITWIRKENDE & LIZENZEN + Einige Funktionen von WinNative basieren auf diesen Open-Source-Projekten. Tippe, um die jeweilige Quelle anzuzeigen. + Standards + Mitwirkende + Hardcore-Modus aktivieren? + Der Hardcore-Modus setzt das Spiel jetzt zurück und deaktiviert das Laden von Spielständen, Schnellvorlauf und Cheats. Nicht gespeicherter Fortschritt geht verloren. Fortfahren? + Abbrechen + Aktivieren + BIOS importiert: %1$s + Ungültige BIOS-Datei + PS2-BIOS importiert: %1$s + Ungültige PS2-BIOS-Datei + Keine Spielserie zum Nachschlagen von Cheats. + %1$d Cheat(s) angewendet. + Cheats konnten nicht angewendet werden. + Cheats + Anwenden + Keine Cheats für dieses Spiel gefunden. + Erfolge + Bei RetroAchievements anmelden + Benutzername + Passwort + Anmeldung fehlgeschlagen + Anmeldung läuft… + Anmelden + %1$d/%2$d • %3$d Pkt. + Keine Erfolge für dieses Spiel. + Zurück + Aktiviert + Deaktiviert + Umbenennen + Speichern + Cloud-Speicherkonflikt + Lokalen Spielstand behalten + A + Menü + Anzeige + HUD + Ton + Steuerung + Bibliothek aktuell + ROMs: %1$s + %1$d hinzugefügt + %1$d entfernt + Standard + CRT + LCD + Scharf + Nativ + Seitenverhältnis + NTSC-Filter + Kolorierung + Farbkorrektur + Sprite-Limit entfernen + Auflösung + Framebuffer-Emulation + Dithering + Widescreen-Hack + 8:7 (Nativ) + 4:3 (TV) + Aus + RF + Composite + S-Video + RGB + Auto + GBA-Bildschirm + GBC-Bildschirm + Ein + 320x240 (Nativ) + 640x480 + 960x720 + 1280x960 + 4:3 + 16:9 + 16:9 angepasst + Nativ + Intern + Ein (16:9) + RETROACHIEVEMENTS + Melde dich mit deinem RetroAchievements-Konto an, um Erfolge für Retro-Spiele zu verdienen und zu verfolgen. + Benutzername + Passwort + Gib deinen Benutzernamen und dein Passwort ein + Anmeldung fehlgeschlagen + Anmelden + Dein Passwort wird nur einmal verwendet, um ein Anmelde-Token zu erhalten, das sicher auf dem Gerät gespeichert wird. + Erfolge aktiviert + Hardcore-Modus (keine Spielstände) + %1$d / %2$d Punkte + Keine Erfolge für dieses Spiel gefunden. + Abmelden + CHEATS + Name + Code + Abbrechen + Speichern + Cheat %1$d + Noch keine Cheats. Füge einen Cheat-Code für dieses Spiel hinzu. + Cheat hinzufügen + + GPU-Treiber + System (Standard) + Installiere Turnip-Treiber unter Einstellungen \u2192 Treiber. Dieselben Treiber funktionieren für PC- und PS2-Spiele. + + PS2-HDD (DEV9) + Virtuelles internes Laufwerk für HDD-basierte Spiele wie Final Fantasy XI. Startet das Spiel neu. + Virtuelles internes Laufwerk für HDD-basierte Spiele wie Final Fantasy XI. + DNS-Modus auf Internal gesetzt, damit deine benutzerdefinierten Server-Hosts wirksam werden. + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + Add Cheat + Cheat name + Codes (one per line, e.g. 2021A268 00000000) + Custom + Enter a name and at least one valid code + Add + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + PS2 HDD Images + A .raw HDD image, or a .zip containing one (e.g. a game’s downloaded HDD with maps/DLC) + Import HDD Image + Importing… + Imported %1$s + Could not import HDD image + Removed %1$s + Remove %1$s + HDD Image + None + Cheats + Patches + PATCH + Custom + Applied %1$d cheat(s), %2$d patch(es). + No cheats or patches found for this game. + Cheat + Patch + Add + CPU-Kern + Dual Core + Interne Cheats + Interne Auflösung + Renderer + Position der Sensorleiste + BIOS-Intro überspringen + + + + + + + Unten + Zwischengespeicherter Interpreter + Hardware + Interpreter + JIT + Maus / Touch + Rechter Stick (absolut) + Rechter Stick (relativ) + Software + Strecken + Oben + VBI-Skip (automatisches Frameskip) + Breitbild + Wiimote-Zeiger + Änderungen werden beim nächsten Start dieses Spiels wirksam. + Starte dieses Spiel einmal, damit seine Disc-Seriennummer erkannt werden kann, dann erscheinen hier Cheats und Patches. + DNAS-Authentifizierungs-Bypass — erforderlich für Online-Spiel + Automatisch angewendet (Online) + Cheats & Patches + Größe: %1$s + HDD-Image importieren + Entfernen + NetPlay aktivieren + Standardmäßig aus. Aktivieren, dann vor dem Start Host oder Beitreten wählen.\nWird beim Verlassen des Spiels wieder ausgeschaltet. + Host-Adresse + IP oder Hostname + Host-Sitzung + Ein = auf einen Spieler warten. Aus = Host-Adresse beitreten + NetPlay verwendet lokale Mehrspieler-Ports über TCP (Spieler 1 Host / Spieler 2 Client). PS2-Online verwendet stattdessen DEV9-Ethernet. + Port + Memory Card %1$d + Screenshot + Cloud-Speicherstand verwenden + LAN (direkte IP) + Verbinden… + Verbindung + Online (Host-Code) + Schließen + GameCube/Wii-NetPlay verwendet Dolphins eigene Engine. Host = Spieler 1, Beitreten = Spieler 2. Wähle vor dem Start Host oder Beitreten und einen Verbindungstyp; beide Geräte booten dasselbe Spiel gemeinsam. + Teile die Wi‑Fi-IP deines Geräts und diesen Port mit Spieler 2. Das Spiel startet automatisch, sobald er sich verbindet. + Beim Booten des Spiels wird ein Host-Code angezeigt — teile ihn mit Spieler 2. Das Spiel startet automatisch, sobald er sich verbindet. + Gib die Wi‑Fi-IP und den Port des Hosts ein und starte dann, um zu verbinden. + Gib den Host-Code von Spieler 1 ein und starte dann, um zu verbinden. + Aktiviere NetPlay in den Spieleinstellungen und wähle vor dem Start Host oder Beitreten + Räume im Wi‑Fi finden + Game Link · jeder Bildschirm ist ein eigener Handheld + GBA-Mehrspieler verwendet gpSP + Wireless-Adapter. Stelle sicher, dass libgpsp installiert ist. + Mehrspieler mit geteiltem Bildschirm über Wi‑Fi (wie RetroArch).\nHost = Spieler 1, Beitreten = Spieler 2. Beide Geräte zeigen dasselbe Spiel. + Game Link über Wi‑Fi — jedes Gerät führt sein eigenes Spiel aus.\nGB/GBC: Gambatte-Serial-Link (Pokémon Gen 1–2).\nGBA: gpSP-Wireless-Adapter (Pokémon FR/LG/Emerald-Kämpfe). + Raum hosten + Host-Code + Traversal-Host-Code vom Host + Raum wird gehostet + Tippe auf Host, um für diese Spielsitzung einen Raum zu öffnen, und starte dann das Spiel. NetPlay wird beim Verlassen ausgeschaltet. + Im Raum + Per IP beitreten + Beigetreten + Beitreten + Beim Start + Verlassen + Host = P1 · Beitreten = P2 · dasselbe Spiel auf beiden Bildschirmen + Host + Beitreten + Manuell + Keine Räume gefunden. Stelle sicher, dass der Host im selben Wi‑Fi ist und einen Raum hostet. + Anzeigename + Wird anderen Spielern angezeigt + %1$d verbunden + Der Raum ist nur für diese Sitzung geöffnet. Starte, wenn du bereit bist. Beim Verlassen des Spiels wird NetPlay ausgeschaltet. + Spieler + Wi‑Fi scannen + Erneut scannen + Scanne dasselbe Wi‑Fi nach offenen Räumen oder tritt per IP-Adresse bei. + Wi‑Fi wird gescannt… + Scan-Ergebnisse + Tippe auf einen Raum, um jetzt beizutreten (speichert die IP nicht für den nächsten Start). + Scan stoppen + NetPlay + %1$s verbunden + %1$s getrennt + Warten auf Spieler… + PlayStation 2-Unterstützung kommt bald + L3 / R3-Tasten anzeigen + Wenn aus, doppeltippe einen Stick, um L3 / R3 zu klicken + TURNIP-TREIBER-FLAGS + Wird nur angewendet, wenn oben ein benutzerdefinierter GPU-Treiber ausgewählt ist. + Spieldatei nicht gefunden + Löschen + Aus Datei importieren… + Wird geladen… + NetPlay + Wii Home + Konsole wechseln + Als Konsole identifizieren + Jetzt identifiziert als %1$s ReShade Wende über die integrierte vkBasalt-Ebene einen ReShade-Effekt (.fx) auf DXVK/VKD3D-Spiele (Vulkan) an. Lege jeden Effekt in einen eigenen Ordner unter Android/data/<package>/files/ReShade/. Live-Parameteranpassung und der In-Game-Schalter kommen mit dem Live-Reload-Ebenen-Update. @@ -1658,4 +2431,27 @@ Installierter Pfad: ReShade aktivieren Keine ReShade-Effekte in dieser Zusammenstellung. Füge Effekte in den Einstellungen dieses Spiels (oder des Containers) hinzu, um sie hier zu wechseln und anzupassen. Dieser Effekt bietet keine einstellbaren Parameter. + Speicherstand wird gelöscht… + Löschen + Cloud-Speicherstand von %1$s endgültig löschen? Das kann nicht rückgängig gemacht werden. + Cloud-Speicherstand löschen + Cloud-Speicherstand konnte nicht gelöscht werden + Cloud-Speicherstand gelöscht + Lade zuerst die Konsolen-Cores herunter — Einstellungen › Retro + Dieses Gerät kann keine PS2-Emulation ausführen — es benötigt OpenGL ES 3.1 oder neuer. + Nach Updates suchen + Suche nach Updates… + Konsolen-Cores herunterladen + Wird heruntergeladen… %1$d / %2$d MB + Konsolen-Cores + Installiert — Build %1$s + Installiert — Build %1$s (Update-Suche fehlgeschlagen) + Wird installiert… + Nicht installiert — herunterladen, um Retro-Spiele zu spielen + Status + Konsolen-Cores aktualisieren + Update verfügbar — Build %1$s (%2$d MB) + Download wird geprüft… + Wird ausgeführt… + System diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 5cc622090..372afbba5 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1622,6 +1622,779 @@ Ruta instalada: Ejecutar en segundo plano Mantener el chat activo después de salir de WinNative Actualizar + Retro + Transferir partida + Importa una partida guardada local para este juego o exporta la partida actual. + Importar partida + Exportar partida + Partida importada + No se pudo importar la partida + Partida exportada + No se pudo exportar la partida + Aún no existe ninguna partida guardada para este juego + Trucos + Los trucos están desactivados en el modo Hardcore + + + Guardar + Cancelar + Guardar estado + Cargar estado + Logros + Trucos + Tarjetas de memoria + Avance rápido + Reiniciar + Cambiar disco + Ranura %1$d + Toca para cargar + Vacía + Toca para sobrescribir + Vacía — toca para guardar + La ranura %1$d está vacía + Ranura %1$d cargada + No se pudo cargar la ranura %1$d + Guardado en la ranura %1$d + Error al guardar + • Ranura 1 + • Ranura 2 + • Toca para usar + Nueva tarjeta de memoria + Importar tarjeta + Activar conexión (DEV9) + Adaptador de red de PS2: reinicia el juego para conectarlo + Dispositivo Ethernet + Modo DNS + DNS principal + DNS secundario + opcional + IP automática (DHCP) + Servidor: %1$s + toca para definir la IP (en blanco la elimina) + %1$s → IP + Añadir host de servidor + Nuevo nombre de host del servidor + p. ej. bf2.playbattlefront.com + Controles en pantalla + Editar disposición + Restablecer disposición + Disposición restablecida + Stick izquierdo: invertir X + Stick izquierdo: invertir Y + Stick derecho: invertir X + Stick derecho: invertir Y + Color de botones + Color de letras + Color de sombra + Color de fondo + Restablecer colores + Renderizador + Vulkan + OpenGL + Software + Escala de resolución + 1x (nativa) + 1.5x + 2x + 3x + 4x + Relación de aspecto + Estirar + Automática (estándar) + 4:3 + 16:9 + Filtro de pantalla + Más cercano + Bilineal (suave) + Bilineal (nítido) + Filtro de texturas + Bilineal (forzado) + Bilineal (PS2) + Bilineal (sprites) + Precisión de mezcla + Mínima + Básica + Media + Alta + Completa + Máxima + Shader CRT / TV + Desactivado + Líneas de escaneo + Diagonal + Triangular + Onda + Lottes + 4xRGSS + NxAGSS + Saltar fotogramas + Desactivado + Saltar 1 + Saltar 2 + Saltar 3 + Mipmapping + Volumen + %1$d%% + Silenciar + Intercambiar canales estéreo + Frecuencia de ciclos EE + 50% + 60% + 75% + 100% (predeterminado) + 130% + 180% + 300% + Salto de ciclos EE + Desactivado + 1 + 2 + 3 + VU1 instantáneo + VU multihilo (MTVU) + CDVD rápido + FPS + Velocidad de emulación + Uso de CPU + Uso de GPU + Resolución interna + Modo de desentrelazado + Automático + Desactivado + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + Relación de aspecto de FMV + Antidesenfoque + Parches panorámicos + Parches sin entrelazado + VU Flag Hack + Detección de bucle INTC + Detección de bucle de espera + Estiramiento de tiempo de audio + Búfer de audio + Latencia de salida + %1$d ms + Tiempos de fotograma + Estadísticas de GS + Información de hardware + Versión + Visualización de entradas + Menú + Pantalla + Rendimiento + HUD + Sonido + En línea + Controles + Reanudar + Pausar + Salir + BIOS importada: %1$s + Archivo de BIOS no válido + Juego retro no válido + ROM no encontrada: %1$s + No se pudo leer la ROM dentro de este archivo + Núcleo no instalado: %1$s + Trucos activados: los logros están desactivados en esta sesión + Partida en la nube restaurada + Error al restaurar + Existe una partida en la nube más reciente para %1$s. ¿Deseas sincronizar y qué partida en la nube prefieres conservar? + Partida en la nube + Retro + No se pudo cargar el núcleo del emulador + No se pudo cargar la ROM + Gráficos no compatibles con este núcleo + Error del emulador + Predeterminado + CRT + LCD + Nítido + SGSR + Escalado SGSR + Nativa + Sonido + Stick izquierdo: invertir X + Stick izquierdo: invertir Y + Stick derecho: invertir X + Stick derecho: invertir Y + Controles en pantalla + Respuesta háptica + Vertical + Horizontal + Editar disposición (%1$s) + Restablecer disposición %1$s + Disposición %1$s restablecida + Color de botones + Color de letras + Color de sombra + Color de fondo + Restablecer colores + Colores restablecidos + HUD de rendimiento + Alfa + Alfa del fondo + Fondo + Escala + Tiempo de fotograma numérico + Batería de doble serie + ELEMENTOS DEL HUD + FPS + Consola + GPU + CPU + RAM + Batería + Temp. + Gráfica + Temp. CPU + Guardar estado + Cargar estado + La carga de estados está desactivada en modo Hardcore + Logros + Trucos + Los trucos están desactivados en modo Hardcore + Reiniciar + Avance rápido + El avance rápido está desactivado en modo Hardcore + HUD + Disco %1$d/%2$d + Reanudar + Pausar + Salir + Guardado en la ranura %1$d + No se pudo guardar el estado + Se requiere la BIOS de %1$s + Los juegos de PlayStation necesitan un archivo de BIOS real de la consola que debes proporcionar. Importa una BIOS (scph5501.bin, scph5500.bin, scph5502.bin, scph1001.bin o scph7001.bin) para continuar. + Importar BIOS… + Cancelar + La ranura %1$d está vacía + Ranura %1$d cargada + No se pudo cargar el estado + Ranura %1$d + Renombrar ranura %1$d + General + Gráficos + Rendimiento + HUD + Entrada + Audio + En línea + Cancelar + Guardar + Predeterminado + CRT + LCD + Nítido + 2x + 4x + Nativa + JUEGO + Nombre + Sistema + Núcleo del emulador + Ruta de la ROM + BIOS de %1$s + Instalada + Ninguna: necesaria para ejecutar juegos de %1$s + Importar BIOS… + Quitar BIOS + ILUSTRACIONES DE LA BIBLIOTECA + Imagen de la ficha del juego + Imagen de cuadrícula + Imagen de carrusel + Imagen de lista + Imagen personalizada establecida + Establecer imagen + Quitar + VÍDEO + Filtro de vídeo + SGSR + Escalado SGSR + HUD de rendimiento + NÚCLEO + Renderizador + Vulkan + OpenGL + Software + Escala de resolución + 1x (nativa) + 1.5x + 2x + 3x + 4x + Relación de aspecto + Estirar + Automática (estándar) + 4:3 + 16:9 + Filtro de pantalla + Más cercano + Bilineal (suave) + Bilineal (nítido) + Filtro de texturas + Bilineal (forzado) + Bilineal (PS2) + Bilineal (sprites) + Precisión de mezcla + Mínima + Básica + Media + Alta + Completa + Máxima + Shader CRT / TV + Desactivado + Líneas de escaneo + Diagonal + Triangular + Onda + Lottes + 4xRGSS + NxAGSS + Saltar fotogramas + Saltar 1 + Saltar 2 + Saltar 3 + Mipmapping + RENDIMIENTO + Frecuencia de ciclos EE + 50% + 60% + 75% + 100% (predeterminado) + 130% + 180% + 300% + Salto de ciclos EE + 1 + 2 + 3 + VU1 instantáneo + VU multihilo (MTVU) + CDVD rápido + HUD DE RENDIMIENTO + FPS + Velocidad de emulación + Uso de CPU + Uso de GPU + Resolución interna + Modo de desentrelazado + Automático + Desactivado + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + Relación de aspecto de FMV + Antidesenfoque + Parches panorámicos + Parches sin entrelazado + VU Flag Hack + Detección de bucle INTC + Detección de bucle de espera + Estiramiento de tiempo de audio + Búfer de audio + Latencia de salida + %1$d ms + Tiempos de fotograma + Estadísticas de GS + Información de hardware + Versión + Visualización de entradas + Arranque rápido + EN LÍNEA (DEV9) + Activar conexión + Dispositivo Ethernet + Automático + Wi-Fi + Modo DNS + Manual + Interno + DNS principal + DNS secundario + opcional + IP automática (DHCP) + ENTRADA + Controles en pantalla + Respuesta háptica + AUDIO + Volumen + Silenciar + Intercambiar canales estéreo + Sonido + VALORES RETRO PREDETERMINADOS + Valores predeterminados aplicados a los juegos de cada consola salvo que se modifiquen en los ajustes propios de un juego. + RETROACHIEVEMENTS + Cuenta + Sesión iniciada + Sin sesión iniciada: abre los Logros de un juego para iniciar sesión + Logros activados + Modo Hardcore de forma predeterminada (sin estados guardados) + Cerrar sesión + BIOS DE PLAYSTATION + Instalada + Ninguna: los juegos de PS1 requieren una BIOS + Importar BIOS de PS1… + BIOS de PS1 eliminada + No hay ninguna BIOS que eliminar + Quitar BIOS de PS1 + BIOS DE PLAYSTATION 2 + Ninguna: los juegos de PS2 requieren una BIOS + Formato + Volcado combinado en un solo archivo (.bin con región etiquetada, ~4MB). No se aceptan conjuntos ROM0/MEC/NVM separados. + Importar BIOS de PS2… + BIOS de PS2 eliminada + Quitar BIOS de PS2 + ILUSTRACIONES DE LA BIBLIOTECA + Ilustración retro de la caja (cartucho / caja de CD) + Ilustración de la caja + Se obtiene automáticamente de thumbnails.libretro.com al importar; una imagen personalizada siempre la sustituye. + CARPETA DE ROMS + Carpeta + Sin definir: elige una carpeta para importar juegos automáticamente + Importación automática + Los juegos nuevos de esta carpeta se añaden automáticamente a tu biblioteca con la consola correcta detectada. + Seleccionar carpeta de ROMs + Seleccionar carpeta de ROMs… + Cambiar carpeta de ROMs… + Analizar ahora + VALORES PREDETERMINADOS DE LA CONSOLA + Toca una consola para configurar sus ajustes predeterminados. + Renderizador + Escalar resolución + Relación de aspecto + Estirar + Automática (estándar) + 4:3 + 16:9 + Filtro de pantalla + Más cercano + Bilineal (suave) + Bilineal (nítido) + Filtro de texturas + Bilineal (forzado) + Bilineal (PS2) + Bilineal (sprites) + Precisión de mezcla + Mínima + Básica + Media + Alta + Completa + Máxima + Shader CRT / TV + Desactivado + Líneas de escaneo + Diagonal + Triangular + Onda + Lottes + 4xRGSS + NxAGSS + Saltar fotogramas + Saltar 1 + Saltar 2 + Saltar 3 + Mipmapping + Frecuencia de ciclos EE + 50% + 60% + 75% + 100% (predeterminado) + 130% + 180% + 300% + Salto de ciclos EE + Desactivado + 1 + 2 + 3 + VU1 instantáneo + VU multihilo (MTVU) + CDVD rápido + Controles táctiles en pantalla + Sonido + Intercambiar canales estéreo + HUD: FPS + HUD: velocidad de emulación + HUD: uso de CPU + HUD: uso de GPU + HUD: resolución interna + Activar conexión (DEV9) + Dispositivo Ethernet + Automático + Wi-Fi + Modo DNS + Manual + Interno + DNS principal + DNS secundario + opcional + IP automática (DHCP) + Shader + Escalado SGSR + HUD de rendimiento + CRÉDITOS & LICENCIAS + Algunas de las funciones de WinNative se basan en estos proyectos de código abierto. Toca para ver cada fuente. + Predeterminados + Créditos + ¿Activar el modo Hardcore? + El modo Hardcore reinicia el juego ahora y desactiva la carga de estados guardados, el avance rápido y los trucos. Se perderá cualquier progreso sin guardar. ¿Continuar? + Cancelar + Activar + BIOS importada: %1$s + Archivo de BIOS no válido + BIOS de PS2 importada: %1$s + Archivo de BIOS de PS2 no válido + No hay ningún número de serie de juego para buscar trucos. + Se aplicaron %1$d truco(s). + No se pudieron aplicar los trucos. + Trucos + Aplicar + No se encontraron trucos para este juego. + Logros + Inicia sesión en RetroAchievements + Nombre de usuario + Contraseña + Error de inicio de sesión + Iniciando sesión… + Iniciar sesión + %1$d/%2$d • %3$d pts + No hay logros para este juego. + Atrás + Activado + Desactivado + Renombrar + Guardar + Conflicto de partida en la nube + Conservar partida local + A + Menú + Pantalla + HUD + Sonido + Controles + Biblioteca actualizada + ROMs: %1$s + %1$d añadidos + %1$d eliminados + Predeterminado + CRT + LCD + Nítido + Nativa + Relación de aspecto + Filtro NTSC + Coloración + Corrección de color + Quitar límite de sprites + Resolución + Emulación de framebuffer + Tramado + Hack panorámico + 8:7 (nativa) + 4:3 (TV) + Desactivado + RF + Compuesto + S-Video + RGB + Automático + Pantalla GBA + Pantalla GBC + Activado + 320x240 (nativa) + 640x480 + 960x720 + 1280x960 + 4:3 + 16:9 + 16:9 ajustado + Nativa + Interna + Activado (16:9) + RETROACHIEVEMENTS + Inicia sesión con tu cuenta de RetroAchievements para conseguir y seguir logros de juegos retro. + Nombre de usuario + Contraseña + Introduce tu nombre de usuario y contraseña + Error de inicio de sesión + Iniciar sesión + Tu contraseña solo se usa una vez para obtener un token de inicio de sesión, que se almacena de forma segura en el dispositivo. + Logros activados + Modo Hardcore (sin estados guardados) + %1$d / %2$d puntos + No se encontraron logros para este juego. + Cerrar sesión + TRUCOS + Nombre + Código + Cancelar + Guardar + Truco %1$d + Aún no hay trucos. Añade un código de truco para este juego. + Añadir truco + + Controlador de GPU + Sistema (Predeterminado) + Instala los controladores Turnip en Ajustes \u2192 Controladores. Los mismos controladores funcionan para juegos de PC y de PS2. + + HDD de PS2 (DEV9) + Unidad interna virtual para juegos basados en HDD como Final Fantasy XI. Reinicia el juego. + Unidad interna virtual para juegos basados en HDD como Final Fantasy XI. + Modo DNS configurado en Internal para que tus hosts de servidor personalizados surtan efecto. + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + Add Cheat + Cheat name + Codes (one per line, e.g. 2021A268 00000000) + Custom + Enter a name and at least one valid code + Add + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + PS2 HDD Images + A .raw HDD image, or a .zip containing one (e.g. a game’s downloaded HDD with maps/DLC) + Import HDD Image + Importing… + Imported %1$s + Could not import HDD image + Removed %1$s + Remove %1$s + HDD Image + None + Cheats + Patches + PATCH + Custom + Applied %1$d cheat(s), %2$d patch(es). + No cheats or patches found for this game. + Cheat + Patch + Add +Núcleo de CPU +Doble núcleo +Trucos internos +Resolución interna +Renderizador +Posición de la barra de sensores +Omitir intro de BIOS + + + + + + +Abajo +Intérprete en caché +Hardware +Intérprete +JIT +Ratón / Táctil +Stick derecho (absoluto) +Stick derecho (relativo) +Software +Estirar +Arriba +Omitir VBI (salto de fotogramas automático) +Panorámica +Puntero del Wiimote +Los cambios se aplican la próxima vez que inicies este juego. +Inicia este juego una vez para que se pueda detectar el número de serie del disco; entonces aparecerán aquí los trucos y parches. +Omisión de autenticación DNAS: necesaria para el juego en línea +Aplicado automáticamente (en línea) +Trucos y parches +Tamaño: %1$s +Importar imagen de HDD +Quitar +Activar NetPlay +Desactivado de forma predeterminada. Actívalo y luego elige Alojar o Unirse antes de iniciar.\nSe vuelve a desactivar cuando sales del juego. +Dirección del anfitrión +IP o nombre de host +Sesión de anfitrión +Activado = esperar a un jugador. Desactivado = unirse a la dirección del anfitrión +NetPlay usa puertos de multijugador local sobre TCP (jugador 1 anfitrión / jugador 2 cliente). El juego en línea de PS2 usa Ethernet DEV9 en su lugar. +Puerto +Tarjeta de memoria %1$d +Captura de pantalla +Usar guardado en la nube +LAN (IP directa) +Conectando… +Conexión +En línea (código de anfitrión) +Descartar +El NetPlay de GameCube/Wii usa el propio motor de Dolphin. Anfitrión = Jugador 1, Unirse = Jugador 2. Elige Alojar o Unirse y un tipo de conexión antes de iniciar; ambos dispositivos arrancan el mismo juego juntos. +Comparte la IP de Wi‑Fi de tu dispositivo y este puerto con el Jugador 2. El juego se inicia automáticamente en cuanto se conecte. +Se muestra un código de anfitrión cuando arranca el juego: compártelo con el Jugador 2. El juego se inicia automáticamente en cuanto se conecte. +Introduce la IP de Wi‑Fi y el puerto del anfitrión y luego inicia para conectar. +Introduce el código de anfitrión del Jugador 1 y luego inicia para conectar. +Activa NetPlay en los ajustes del juego y elige Alojar o Unirse antes de iniciar +Buscar salas en Wi‑Fi +Game Link · cada pantalla es su propia consola portátil +El multijugador de GBA usa gpSP + adaptador inalámbrico. Asegúrate de que libgpsp esté instalado. +Multijugador de pantalla compartida por Wi‑Fi (como RetroArch).\nAnfitrión = Jugador 1, Unirse = Jugador 2. Ambos dispositivos muestran el mismo juego. +Game Link por Wi‑Fi: cada dispositivo ejecuta su propio juego.\nGB/GBC: enlace serie de Gambatte (Pokémon Gen 1–2).\nGBA: adaptador inalámbrico de gpSP (combates de Pokémon FR/LG/Esmeralda). +Alojar sala +Código de anfitrión +Código de anfitrión de traversal del anfitrión +Alojando sala +Toca Alojar para abrir una sala para esta sesión de juego y luego inicia el juego. NetPlay se desactiva cuando sales. +En la sala +Unirse por IP +Unido +Unirse +Al iniciar +Salir +Anfitrión = J1 · Unirse = J2 · el mismo juego en ambas pantallas +Alojar +Unirse +Manual +No se encontraron salas. Asegúrate de que el anfitrión esté en el mismo Wi‑Fi y alojando una sala. +Nombre visible +Se muestra a los demás jugadores +%1$d conectados +La sala está abierta solo para esta sesión. Inicia cuando estés listo. Al salir del juego se desactiva NetPlay. +Jugadores +Buscar en Wi‑Fi +Buscar de nuevo +Busca salas abiertas en el mismo Wi‑Fi o únete por dirección IP. +Buscando en Wi‑Fi… +Resultados de la búsqueda +Toca una sala para unirte ahora (no guarda la IP para el próximo inicio). +Detener búsqueda +NetPlay +%1$s se ha conectado +%1$s se ha desconectado +Esperando a los jugadores… +La compatibilidad con PlayStation 2 llegará pronto +Mostrar botones L3 / R3 +Cuando está desactivado, toca dos veces un stick para pulsar L3 / R3 +FLAGS DEL CONTROLADOR TURNIP +Se aplican solo cuando se selecciona un controlador de GPU personalizado arriba. +Archivo del juego no encontrado +Eliminar +Importar desde archivo… +Cargando… +NetPlay + Wii Home + Cambiar de consola + Identificar como consola + Ahora identificado como %1$s ReShade Aplica un efecto ReShade (.fx) a los juegos DXVK/VKD3D (Vulkan) mediante la capa vkBasalt integrada. Coloca cada efecto en su propia carpeta en Android/data/<package>/files/ReShade/. El ajuste de parámetros en vivo y el interruptor en el juego llegarán con la actualización de la capa de recarga en caliente. @@ -1657,5 +2430,28 @@ Ruta instalada: Activar ReShade No hay efectos ReShade en este conjunto. Añade efectos en los ajustes de este juego (o del contenedor) para cambiarlos y ajustarlos aquí. Este efecto no expone parámetros ajustables. + Eliminando partida guardada… + Eliminar + ¿Eliminar permanentemente la partida guardada en la nube de %1$s? Esta acción no se puede deshacer. + Eliminar partida en la nube + No se pudo eliminar la partida en la nube + Partida en la nube eliminada + Descarga primero los núcleos de consola — Ajustes › Retro + Este dispositivo no puede ejecutar la emulación de PS2: necesita OpenGL ES 3.1 o posterior. + Buscar actualizaciones + Buscando actualizaciones… + Descargar núcleos de consola + Descargando… %1$d / %2$d MB + Núcleos de consola + Instalado — compilación %1$s + Instalado — compilación %1$s (fallo al buscar actualizaciones) + Instalando… + No instalado: descárgalo para jugar a juegos retro + Estado + Actualizar núcleos de consola + Actualización disponible — compilación %1$s (%2$d MB) + Verificando la descarga… + Procesando… + Sistema diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index f62d0a67c..7c5bbfdf3 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -1621,6 +1621,779 @@ Asennuspolku: Kansion luonti epäonnistui Päivitä + Retro + Siirrä tallennus + Tuo peliin paikallinen tallennus tai vie pelin nykyinen tallennus. + Tuo tallennus + Vie tallennus + Tallennus tuotu + Tallennuksen tuonti epäonnistui + Tallennus viety + Tallennuksen vienti epäonnistui + Tälle pelille ei ole vielä tallennusta + Huijaukset + Huijaukset on poistettu käytöstä Hardcore-tilassa + + + Tallenna + Peruuta + Tallenna tila + Lataa tallennustila + Saavutukset + Huijaukset + Muistikortit + Pikakelaus + Nollaa + Vaihda levy + Paikka %1$d + Napauta ladataksesi + Tyhjä + Napauta korvataksesi + Tyhjä — napauta tallentaaksesi + Paikka %1$d on tyhjä + Ladattiin paikka %1$d + Paikkaa %1$d ei voitu ladata + Tallennettiin paikkaan %1$d + Tallennus epäonnistui + • Paikka 1 + • Paikka 2 + • Napauta käyttääksesi + Uusi muistikortti + Tuo kortti + Ota verkko käyttöön (DEV9) + PS2-verkkosovitin — käynnistää pelin uudelleen liittääkseen sen + Ethernet-laite + DNS-tila + Ensisijainen DNS + Toissijainen DNS + valinnainen + Automaattinen IP (DHCP) + Palvelin: %1$s + napauta asettaaksesi IP:n (tyhjä poistaa) + %1$s → IP + Lisää palvelinisäntä + Uusi palvelimen isäntänimi + esim. bf2.playbattlefront.com + Näytön ohjaimet + Muokkaa asettelua + Palauta asettelu + Asettelu palautettu + Vasen sauva: käännä X + Vasen sauva: käännä Y + Oikea sauva: käännä X + Oikea sauva: käännä Y + Painikkeen väri + Kirjaimen väri + Varjon väri + Taustaväri + Palauta värit + Renderöijä + Vulkan + OpenGL + Software + Tarkkuuskerroin + 1x (natiivi) + 1.5x + 2x + 3x + 4x + Kuvasuhde + Venytä + Automaattinen (vakio) + 4:3 + 16:9 + Näyttösuodatin + Lähin + Bilineaarinen (pehmeä) + Bilineaarinen (terävä) + Tekstuurisuodatin + Bilineaarinen (pakotettu) + Bilineaarinen (PS2) + Bilineaarinen (spritet) + Sekoituksen tarkkuus + Minimi + Perus + Keskitaso + Korkea + Täysi + Maksimi + CRT / TV -sävytin + Pois + Juovat + Vino + Kolmiomainen + Aalto + Lottes + 4xRGSS + NxAGSS + Ruutujen ohitus + Pois + Ohita 1 + Ohita 2 + Ohita 3 + Mipmap-tekstuurit + Äänenvoimakkuus + %1$d%% + Mykistä + Vaihda stereokanavat + EE-syklinopeus + 50% + 60% + 75% + 100% (oletus) + 130% + 180% + 300% + EE-syklien ohitus + Pois + 1 + 2 + 3 + Välitön VU1 + Monisäikeinen VU (MTVU) + Nopea CDVD + FPS + Emulointinopeus + CPU-käyttö + GPU-käyttö + Sisäinen tarkkuus + Lomituksenpoistotila + Automaattinen + Pois + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + FMV-kuvasuhde + Sumennuksen esto + Laajakuvapaikkaukset + Lomituksenpoistopaikkaukset + VU Flag Hack + INTC-spin-tunnistus + Odotussilmukan tunnistus + Äänen aikavenytys + Äänipuskuri + Lähtöviive + %1$d ms + Kuva-ajat + GS-tilastot + Laitteistotiedot + Versio + Syötenäyttö + Valikko + Näyttö + Suorituskyky + HUD + Ääni + Verkko + Ohjaimet + Jatka + Keskeytä + Poistu + BIOS tuotu: %1$s + Virheellinen BIOS-tiedosto + Virheellinen retropeli + ROMia ei löytynyt: %1$s + ROMia ei voitu lukea tästä arkistosta + Ydintä ei ole asennettu: %1$s + Huijaukset käytössä — saavutukset ovat poissa käytöstä tässä istunnossa + Pilvitallennus palautettu + Palautus epäonnistui + Kohteelle %1$s on olemassa uudempi pilvitallennus. Haluatko synkronoida, ja minkä pilvitallennuksen haluat säilyttää? + Pilvitallennus + Retro + Emulaattoriytimen lataus epäonnistui + ROMin lataus epäonnistui + Grafiikkaa ei tueta tälle ytimelle + Emulaattorivirhe + Oletus + CRT + LCD + Terävä + SGSR + SGSR-skaalaus + Natiivi + Ääni + Vasen sauva: käännä X + Vasen sauva: käännä Y + Oikea sauva: käännä X + Oikea sauva: käännä Y + Näytön ohjaimet + Haptinen palaute + Pysty + Vaaka + Muokkaa asettelua (%1$s) + Palauta %1$s-asettelu + %1$s-asettelu palautettu + Painikkeen väri + Kirjaimen väri + Varjon väri + Taustaväri + Palauta värit + Värit palautettu + Suorituskyky-HUD + Alfa + Taustan alfa + Tausta + Skaala + Numeerinen ruutuaika + Kaksisarjainen akku + HUD-ELEMENTIT + FPS + Konsoli + GPU + CPU + RAM + Akku + Lämpötila + Kaavio + CPU-lämpötila + Tallenna tila + Lataa tallennustila + Tilojen lataus on poissa käytöstä Hardcore-tilassa + Saavutukset + Huijaukset + Huijaukset ovat poissa käytöstä Hardcore-tilassa + Nollaa + Pikakelaus + Pikakelaus on poissa käytöstä Hardcore-tilassa + HUD + Levy %1$d/%2$d + Jatka + Keskeytä + Poistu + Tallennettiin paikkaan %1$d + Tilaa ei voitu tallentaa + %1$s BIOS vaaditaan + PlayStation-pelit tarvitsevat aidon konsolin BIOS-tiedoston, joka sinun on toimitettava. Tuo BIOS (scph5501.bin, scph5500.bin, scph5502.bin, scph1001.bin tai scph7001.bin) jatkaaksesi. + Tuo BIOS… + Peruuta + Paikka %1$d on tyhjä + Ladattiin paikka %1$d + Tilaa ei voitu ladata + Paikka %1$d + Nimeä paikka %1$d uudelleen + Yleiset + Grafiikka + Suorituskyky + HUD + Syöte + Ääni + Verkko + Peruuta + Tallenna + Oletus + CRT + LCD + Terävä + 2x + 4x + Natiivi + PELI + Nimi + Järjestelmä + Emulaattoriydin + ROM-polku + %1$s BIOS + Asennettu + Ei mitään — vaaditaan %1$s-pelien ajamiseen + Tuo BIOS… + Poista BIOS + KIRJASTON KUVITUS + Pelikortin kuva + Ruudukkokuva + Karusellikuva + Luettelokuva + Mukautettu kuva asetettu + Aseta kuva + Poista + VIDEO + Videosuodatin + SGSR + SGSR-skaalaus + Suorituskyky-HUD + YDIN + Renderöijä + Vulkan + OpenGL + Software + Tarkkuuskerroin + 1x (natiivi) + 1.5x + 2x + 3x + 4x + Kuvasuhde + Venytä + Automaattinen (vakio) + 4:3 + 16:9 + Näyttösuodatin + Lähin + Bilineaarinen (pehmeä) + Bilineaarinen (terävä) + Tekstuurisuodatin + Bilineaarinen (pakotettu) + Bilineaarinen (PS2) + Bilineaarinen (spritet) + Sekoituksen tarkkuus + Minimi + Perus + Keskitaso + Korkea + Täysi + Maksimi + CRT / TV -sävytin + Pois + Juovat + Vino + Kolmiomainen + Aalto + Lottes + 4xRGSS + NxAGSS + Ruutujen ohitus + Ohita 1 + Ohita 2 + Ohita 3 + Mipmap-tekstuurit + SUORITUSKYKY + EE-syklinopeus + 50% + 60% + 75% + 100% (oletus) + 130% + 180% + 300% + EE-syklien ohitus + 1 + 2 + 3 + Välitön VU1 + Monisäikeinen VU (MTVU) + Nopea CDVD + SUORITUSKYKY-HUD + FPS + Emulointinopeus + CPU-käyttö + GPU-käyttö + Sisäinen tarkkuus + Lomituksenpoistotila + Automaattinen + Pois + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + FMV-kuvasuhde + Sumennuksen esto + Laajakuvapaikkaukset + Lomituksenpoistopaikkaukset + VU Flag Hack + INTC-spin-tunnistus + Odotussilmukan tunnistus + Äänen aikavenytys + Äänipuskuri + Lähtöviive + %1$d ms + Kuva-ajat + GS-tilastot + Laitteistotiedot + Versio + Syötenäyttö + Pikakäynnistys + VERKKO (DEV9) + Ota verkko käyttöön + Ethernet-laite + Automaattinen + Wi-Fi + DNS-tila + Manuaalinen + Sisäinen + Ensisijainen DNS + Toissijainen DNS + valinnainen + Automaattinen IP (DHCP) + SYÖTE + Näytön ohjaimet + Haptinen palaute + ÄÄNI + Äänenvoimakkuus + Mykistä + Vaihda stereokanavat + Ääni + RETRO-OLETUKSET + Oletukset, joita sovelletaan kunkin konsolin peleihin, ellei niitä ohiteta pelin omissa asetuksissa. + RETROACHIEVEMENTS + Tili + Kirjautunut sisään + Ei kirjautunut — avaa pelin Saavutukset kirjautuaksesi sisään + Saavutukset käytössä + Hardcore-tila oletuksena (ei tallennustiloja) + Kirjaudu ulos + PLAYSTATION BIOS + Asennettu + Ei mitään — PS1-pelit vaativat BIOSin + Tuo PS1 BIOS… + PS1 BIOS poistettu + Ei poistettavaa BIOSia + Poista PS1 BIOS + PLAYSTATION 2 BIOS + Ei mitään — PS2-pelit vaativat BIOSin + Muoto + Yhdistetty yhden tiedoston vedos (aluemerkitty .bin, ~4 Mt). Jaettuja ROM0/MEC/NVM-sarjoja ei hyväksytä. + Tuo PS2 BIOS… + PS2 BIOS poistettu + Poista PS2 BIOS + KIRJASTON KUVITUS + Retrokotelon kuvitus (kasetti / CD-kotelo) + Kansikuva + Haetaan automaattisesti osoitteesta thumbnails.libretro.com tuonnin yhteydessä; mukautettu kuva ohittaa sen aina. + ROM-KANSIO + Kansio + Ei asetettu — valitse kansio pelien automaattista tuontia varten + Automaattinen tuonti + Tämän kansion uudet pelit lisätään kirjastoosi automaattisesti oikea konsoli tunnistettuna. + Valitse ROM-kansio + Valitse ROM-kansio… + Vaihda ROM-kansio… + Skannaa nyt + KONSOLIOLETUKSET + Napauta konsolia asettaaksesi sen oletusasetukset. + Renderöijä + Skaalaa tarkkuutta + Kuvasuhde + Venytä + Automaattinen (vakio) + 4:3 + 16:9 + Näyttösuodatin + Lähin + Bilineaarinen (pehmeä) + Bilineaarinen (terävä) + Tekstuurisuodatin + Bilineaarinen (pakotettu) + Bilineaarinen (PS2) + Bilineaarinen (spritet) + Sekoituksen tarkkuus + Minimi + Perus + Keskitaso + Korkea + Täysi + Maksimi + CRT / TV -sävytin + Pois + Juovat + Vino + Kolmiomainen + Aalto + Lottes + 4xRGSS + NxAGSS + Ruutujen ohitus + Ohita 1 + Ohita 2 + Ohita 3 + Mipmap-tekstuurit + EE-syklinopeus + 50% + 60% + 75% + 100% (oletus) + 130% + 180% + 300% + EE-syklien ohitus + Pois + 1 + 2 + 3 + Välitön VU1 + Monisäikeinen VU (MTVU) + Nopea CDVD + Näytön kosketusohjaimet + Ääni + Vaihda stereokanavat + HUD: FPS + HUD: emulointinopeus + HUD: CPU-käyttö + HUD: GPU-käyttö + HUD: sisäinen tarkkuus + Ota verkko käyttöön (DEV9) + Ethernet-laite + Automaattinen + Wi-Fi + DNS-tila + Manuaalinen + Sisäinen + Ensisijainen DNS + Toissijainen DNS + valinnainen + Automaattinen IP (DHCP) + Sävytin + SGSR-skaalaus + Suorituskyky-HUD + TEKIJÄT & LISENSSIT + Osa WinNativen ominaisuuksista perustuu näihin avoimen lähdekoodin projekteihin. Napauta nähdäksesi kunkin lähteen. + Oletukset + Tekijät + Otetaanko Hardcore-tila käyttöön? + Hardcore-tila nollaa pelin nyt ja poistaa käytöstä tallennustilojen latauksen, pikakelauksen ja huijaukset. Kaikki tallentamaton edistyminen menetetään. Jatketaanko? + Peruuta + Ota käyttöön + BIOS tuotu: %1$s + Virheellinen BIOS-tiedosto + PS2 BIOS tuotu: %1$s + Virheellinen PS2 BIOS -tiedosto + Ei pelin sarjanumeroa, jolle etsiä huijauksia. + Otettiin käyttöön %1$d huijaus(ta). + Huijauksia ei voitu ottaa käyttöön. + Huijaukset + Ota käyttöön + Tälle pelille ei löytynyt huijauksia. + Saavutukset + Kirjaudu RetroAchievements-palveluun + Käyttäjänimi + Salasana + Kirjautuminen epäonnistui + Kirjaudutaan sisään… + Kirjaudu sisään + %1$d/%2$d • %3$d pistettä + Tälle pelille ei ole saavutuksia. + Takaisin + Käytössä + Pois käytöstä + Nimeä uudelleen + Tallenna + Pilvitallennuksen ristiriita + Säilytä paikallinen tallennus + A + Valikko + Näyttö + HUD + Ääni + Ohjaimet + Kirjasto ajan tasalla + ROMit: %1$s + lisätty %1$d + poistettu %1$d + Oletus + CRT + LCD + Terävä + Natiivi + Kuvasuhde + NTSC-suodatin + Värjäys + Värikorjaus + Poista spriterajoitus + Tarkkuus + Framebuffer-emulointi + Dithering + Laajakuvahakkeri + 8:7 (natiivi) + 4:3 (TV) + Pois + RF + Komposiitti + S-Video + RGB + Automaattinen + GBA-näyttö + GBC-näyttö + Päällä + 320x240 (natiivi) + 640x480 + 960x720 + 1280x960 + 4:3 + 16:9 + 16:9 säädetty + Natiivi + Sisäinen + Päällä (16:9) + RETROACHIEVEMENTS + Kirjaudu sisään RetroAchievements-tililläsi ansaitaksesi ja seurataksesi saavutuksia retropeleissä. + Käyttäjänimi + Salasana + Anna käyttäjänimesi ja salasanasi + Kirjautuminen epäonnistui + Kirjaudu sisään + Salasanaasi käytetään vain kerran kirjautumistunnisteen hankkimiseen, joka tallennetaan turvallisesti laitteelle. + Saavutukset käytössä + Hardcore-tila (ei tallennustiloja) + %1$d / %2$d pistettä + Tälle pelille ei löytynyt saavutuksia. + Kirjaudu ulos + HUIJAUKSET + Nimi + Koodi + Peruuta + Tallenna + Huijaus %1$d + Ei vielä huijauksia. Lisää huijauskoodi tälle pelille. + Lisää huijaus + + GPU-ajuri + Järjestelmä (Oletus) + Asenna Turnip-ajurit kohdasta Asetukset \u2192 Ajurit. Samat ajurit toimivat sekä PC- että PS2-peleissä. + + PS2 HDD (DEV9) + Virtuaalinen sisäinen asema HDD-pohjaisille peleille, kuten Final Fantasy XI. Käynnistää pelin uudelleen. + Virtuaalinen sisäinen asema HDD-pohjaisille peleille, kuten Final Fantasy XI. + DNS-tila asetettu Internal-tilaan, jotta mukautetut palvelinisännät tulevat voimaan. + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + Add Cheat + Cheat name + Codes (one per line, e.g. 2021A268 00000000) + Custom + Enter a name and at least one valid code + Add + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + PS2 HDD Images + A .raw HDD image, or a .zip containing one (e.g. a game’s downloaded HDD with maps/DLC) + Import HDD Image + Importing… + Imported %1$s + Could not import HDD image + Removed %1$s + Remove %1$s + HDD Image + None + Cheats + Patches + PATCH + Custom + Applied %1$d cheat(s), %2$d patch(es). + No cheats or patches found for this game. + Cheat + Patch + Add + Suoritinydin + Kaksoisydin + Sisäiset huijaukset + Sisäinen tarkkuus + Piirtomoottori + Sensoripalkin sijainti + Ohita BIOS-intro + + + + + + + Alhaalla + Välimuistitettu tulkki + Laitteisto + Tulkki + JIT + Hiiri / kosketus + Oikea sauva (absoluuttinen) + Oikea sauva (suhteellinen) + Ohjelmisto + Venytä + Ylhäällä + VBI-ohitus (automaattinen ruutujen ohitus) + Laajakuva + Wiimote-osoitin + Muutokset tulevat voimaan, kun käynnistät tämän pelin seuraavan kerran. + Käynnistä tämä peli kerran, jotta sen levyn sarjanumero voidaan tunnistaa, minkä jälkeen huijaukset ja korjaukset näkyvät tässä. + DNAS-todennuksen ohitus — vaaditaan verkkopeliin + Automaattisesti käytössä (verkossa) + Huijaukset & korjaukset + Koko: %1$s + Tuo HDD-levykuva + Poista + Ota NetPlay käyttöön + Oletuksena pois päältä. Ota käyttöön ja valitse sitten Isännöi tai Liity ennen käynnistystä.\nKytkeytyy taas pois, kun poistut pelistä. + Isännän osoite + IP tai isäntänimi + Isännöi istuntoa + Päällä = odota pelaajaa. Pois = liity isännän osoitteeseen + NetPlay käyttää paikallisen moninpelin portteja TCP:n kautta (pelaaja 1 isäntä / pelaaja 2 asiakas). PS2-verkkopeli käyttää sen sijaan DEV9-Ethernetiä. + Portti + Muistikortti %1$d + Kuvakaappaus + Käytä pilvitallennusta + LAN (suora IP) + Yhdistetään… + Yhteys + Verkossa (isäntäkoodi) + Hylkää + GameCube/Wii-NetPlay käyttää Dolphinin omaa moottoria. Isäntä = pelaaja 1, Liity = pelaaja 2. Valitse Isännöi tai Liity ja yhteystyyppi ennen käynnistystä; molemmat laitteet käynnistävät saman pelin yhdessä. + Jaa laitteesi Wi‑Fi-IP-osoite ja tämä portti pelaajan 2 kanssa. Peli alkaa automaattisesti, kun hän yhdistää. + Isäntäkoodi näytetään, kun peli käynnistyy — jaa se pelaajan 2 kanssa. Peli alkaa automaattisesti, kun hän yhdistää. + Syötä isännän Wi‑Fi-IP-osoite ja portti, käynnistä sitten yhdistääksesi. + Syötä isäntäkoodi pelaajalta 1, käynnistä sitten yhdistääksesi. + Ota NetPlay käyttöön peliasetuksissa ja valitse Isännöi tai Liity ennen käynnistystä + Etsi huoneita Wi‑Fi-verkosta + Game Link · jokainen näyttö on oma käsikonsolinsa + GBA-moninpeli käyttää gpSP:tä + langatonta sovitinta. Varmista, että libgpsp on asennettu. + Jaetun näytön moninpeli Wi‑Fi-verkossa (kuten RetroArch).\nIsäntä = pelaaja 1, Liity = pelaaja 2. Molemmat laitteet näyttävät saman pelin. + Game Link Wi‑Fi-verkossa — jokainen laite käyttää omaa peliään.\nGB/GBC: Gambatte-sarjalinkki (Pokémon Gen 1–2).\nGBA: gpSP langaton sovitin (Pokémon FR/LG/Emerald-taistelut). + Isännöi huonetta + Isäntäkoodi + Traversal-isäntäkoodi isännältä + Isännöidään huonetta + Napauta Isännöi avataksesi huoneen tälle peli-istunnolle, käynnistä sitten peli. NetPlay kytkeytyy pois, kun poistut. + Huoneessa + Liity IP:n kautta + Liittynyt + Liity + Käynnistettäessä + Poistu + Isäntä = P1 · Liity = P2 · sama peli molemmilla näytöillä + Isännöi + Liity + Manuaalinen + Huoneita ei löytynyt. Varmista, että isäntä on samassa Wi‑Fi-verkossa ja isännöi huonetta. + Näyttönimi + Näytetään muille pelaajille + %1$d yhdistetty + Huone on avoinna vain tälle istunnolle. Käynnistä, kun olet valmis. Pelistä poistuminen kytkee NetPlayn pois. + Pelaajat + Etsi Wi‑Fi + Etsi uudelleen + Etsi avoimia huoneita samasta Wi‑Fi-verkosta tai liity IP-osoitteen kautta. + Etsitään Wi‑Fi-verkkoa… + Hakutulokset + Napauta huonetta liittyäksesi heti (ei tallenna IP-osoitetta seuraavaa käynnistystä varten). + Lopeta haku + NetPlay + %1$s yhdistetty + %1$s katkaisi yhteyden + Odotetaan pelaajia… + PlayStation 2 -tuki tulee pian + Näytä L3-/R3-painikkeet + Kun pois päältä, napauta sauvaa kahdesti painaaksesi L3 / R3 + TURNIP-AJURIN LIPUT + Käytetään vain, kun yllä on valittu mukautettu GPU-ajuri. + Pelitiedostoa ei löytynyt + Poista + Tuo tiedostosta… + Ladataan… + NetPlay + Wii Home + Vaihda konsoli + Tunnista konsolina + Tunnistetaan nyt: %1$s ReShade Käytä ReShade-tehostetta (.fx) DXVK/VKD3D-peleissä (Vulkan) sisäänrakennetun vkBasalt-kerroksen kautta. Sijoita jokainen tehoste omaan kansioonsa polkuun Android/data/<package>/files/ReShade/. Reaaliaikainen parametrien säätö ja pelinsisäinen kytkin tulevat live-reload-kerroksen päivityksen myötä. @@ -1656,4 +2429,27 @@ Asennuspolku: Ota ReShade käyttöön Tässä kokoonpanossa ei ole ReShade-tehosteita. Lisää tehosteita tämän pelin asetuksissa (tai säiliön asetuksissa) vaihtaaksesi ja säätääksesi niitä täällä. Tällä tehosteella ei ole säädettäviä parametreja. + Poistetaan tallennusta… + Poista + Poistetaanko pilvitallennus lähteestä %1$s pysyvästi? Tätä ei voi kumota. + Poista pilvitallennus + Pilvitallennuksen poisto epäonnistui + Pilvitallennus poistettu + Lataa ensin konsoliytimet — Asetukset › Retro + Tämä laite ei pysty PS2-emulointiin — se vaatii OpenGL ES 3.1:n tai uudemman. + Tarkista päivitykset + Tarkistetaan päivityksiä… + Lataa konsoliytimet + Ladataan… %1$d / %2$d MB + Konsoliytimet + Asennettu — koontiversio %1$s + Asennettu — koontiversio %1$s (päivitysten tarkistus epäonnistui) + Asennetaan… + Ei asennettu — lataa pelataksesi retropelejä + Tila + Päivitä konsoliytimet + Päivitys saatavilla — koontiversio %1$s (%2$d MB) + Vahvistetaan latausta… + Käsitellään… + Järjestelmä diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index e8865ddbc..a176e7912 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1622,6 +1622,779 @@ Chemin installé : Exécuter en arrière-plan Garder le chat actif après avoir quitté WinNative Actualiser + Rétro + Transférer la sauvegarde + Importez une sauvegarde locale pour ce jeu ou exportez la sauvegarde actuelle. + Importer la sauvegarde + Exporter la sauvegarde + Sauvegarde importée + Impossible d\'importer la sauvegarde + Sauvegarde exportée + Impossible d\'exporter la sauvegarde + Aucune sauvegarde n\'existe encore pour ce jeu + Codes de triche + Les codes de triche sont désactivés en mode Hardcore + + + Enregistrer + Annuler + Sauvegarde rapide + Charger la sauvegarde + Succès + Codes de triche + Cartes mémoire + Avance rapide + Réinitialiser + Changer de disque + Emplacement %1$d + Appuyez pour charger + Vide + Appuyez pour écraser + Vide — appuyez pour enregistrer + L\'emplacement %1$d est vide + Emplacement %1$d chargé + Impossible de charger l\'emplacement %1$d + Enregistré dans l\'emplacement %1$d + Échec de l\'enregistrement + • Emplacement 1 + • Emplacement 2 + • Appuyez pour utiliser + Nouvelle carte mémoire + Importer une carte + Activer le mode en ligne (DEV9) + Adaptateur réseau PS2 — redémarre le jeu pour le connecter + Périphérique Ethernet + Mode DNS + DNS principal + DNS secondaire + facultatif + IP automatique (DHCP) + Serveur : %1$s + appuyez pour définir l\'IP (vide pour supprimer) + %1$s → IP + Ajouter un hôte serveur + Nouveau nom d\'hôte serveur + ex. bf2.playbattlefront.com + Commandes à l\'écran + Modifier la disposition + Réinitialiser la disposition + Disposition réinitialisée + Stick gauche : inverser X + Stick gauche : inverser Y + Stick droit : inverser X + Stick droit : inverser Y + Couleur des boutons + Couleur des lettres + Couleur de l\'ombre + Couleur de fond + Réinitialiser les couleurs + Moteur de rendu + Vulkan + OpenGL + Software + Échelle de résolution + 1x (native) + 1.5x + 2x + 3x + 4x + Rapport d\'aspect + Étirer + Auto (standard) + 4:3 + 16:9 + Filtre d\'affichage + Au plus proche + Bilinéaire (lisse) + Bilinéaire (net) + Filtre de texture + Bilinéaire (forcé) + Bilinéaire (PS2) + Bilinéaire (sprites) + Précision du mélange + Minimale + Basique + Moyenne + Élevée + Complète + Maximale + Shader CRT / TV + Désactivé + Lignes de balayage + Diagonal + Triangulaire + Onde + Lottes + 4xRGSS + NxAGSS + Saut d\'images + Désactivé + Sauter 1 + Sauter 2 + Sauter 3 + Mipmapping + Volume + %1$d%% + Muet + Inverser les canaux stéréo + Fréquence de cycle EE + 50% + 60% + 75% + 100% (par défaut) + 130% + 180% + 300% + Saut de cycle EE + Désactivé + 1 + 2 + 3 + VU1 instantané + VU multithread (MTVU) + CDVD rapide + FPS + Vitesse d\'émulation + Utilisation CPU + Utilisation GPU + Résolution interne + Mode de désentrelacement + Auto + Désactivé + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + Format d\'image des FMV + Anti-flou + Patchs écran large + Patchs anti-entrelacement + VU Flag Hack + Détection de boucle INTC + Détection de boucle d\'attente + Étirement temporel audio + Tampon audio + Latence de sortie + %1$d ms + Temps de trame + Statistiques GS + Infos matériel + Version + Affichage des entrées + Menu + Affichage + Performances + HUD + Son + En ligne + Commandes + Reprendre + Pause + Quitter + BIOS importé : %1$s + Fichier BIOS non valide + Jeu rétro non valide + ROM introuvable : %1$s + Impossible de lire la ROM dans cette archive + Core non installé : %1$s + Codes de triche activés — les succès sont désactivés pour cette session + Sauvegarde cloud restaurée + Échec de la restauration + Une sauvegarde cloud plus récente existe pour %1$s. Souhaitez-vous synchroniser, et quelle sauvegarde cloud préférez-vous conserver ? + Sauvegarde cloud + Rétro + Échec du chargement du core d\'émulation + Échec du chargement de la ROM + Graphismes non pris en charge pour ce core + Erreur de l\'émulateur + Par défaut + CRT + LCD + Net + SGSR + Mise à l\'échelle SGSR + Native + Son + Stick gauche : inverser X + Stick gauche : inverser Y + Stick droit : inverser X + Stick droit : inverser Y + Commandes à l\'écran + Retour haptique + Portrait + Paysage + Modifier la disposition (%1$s) + Réinitialiser la disposition %1$s + Disposition %1$s réinitialisée + Couleur des boutons + Couleur des lettres + Couleur de l\'ombre + Couleur de fond + Réinitialiser les couleurs + Couleurs réinitialisées + HUD de performances + Alpha + Alpha du fond + Fond + Échelle + Temps d\'image numérique + Batterie double série + ÉLÉMENTS DU HUD + FPS + Console + GPU + CPU + RAM + Batterie + Temp. + Graphique + Temp. CPU + Sauvegarde rapide + Charger la sauvegarde + Le chargement des sauvegardes est désactivé en mode Hardcore + Succès + Codes de triche + Les codes de triche sont désactivés en mode Hardcore + Réinitialiser + Avance rapide + L\'avance rapide est désactivée en mode Hardcore + HUD + Disque %1$d/%2$d + Reprendre + Pause + Quitter + Enregistré dans l\'emplacement %1$d + Impossible d\'enregistrer la sauvegarde + BIOS %1$s requis + Les jeux PlayStation nécessitent un vrai fichier BIOS de console que vous devez fournir. Importez un BIOS (scph5501.bin, scph5500.bin, scph5502.bin, scph1001.bin ou scph7001.bin) pour continuer. + Importer un BIOS… + Annuler + L\'emplacement %1$d est vide + Emplacement %1$d chargé + Impossible de charger la sauvegarde + Emplacement %1$d + Renommer l\'emplacement %1$d + Général + Graphismes + Performances + HUD + Entrée + Audio + En ligne + Annuler + Enregistrer + Par défaut + CRT + LCD + Net + 2x + 4x + Native + JEU + Nom + Système + Core d\'émulation + Chemin de la ROM + BIOS %1$s + Installé + Aucun — requis pour exécuter les jeux %1$s + Importer un BIOS… + Supprimer le BIOS + ILLUSTRATIONS DE LA BIBLIOTHÈQUE + Image de la fiche de jeu + Image en grille + Image du carrousel + Image en liste + Image personnalisée définie + Définir l\'image + Supprimer + VIDÉO + Filtre vidéo + SGSR + Mise à l\'échelle SGSR + HUD de performances + CORE + Moteur de rendu + Vulkan + OpenGL + Software + Échelle de résolution + 1x (native) + 1.5x + 2x + 3x + 4x + Rapport d\'aspect + Étirer + Auto (standard) + 4:3 + 16:9 + Filtre d\'affichage + Au plus proche + Bilinéaire (lisse) + Bilinéaire (net) + Filtre de texture + Bilinéaire (forcé) + Bilinéaire (PS2) + Bilinéaire (sprites) + Précision du mélange + Minimale + Basique + Moyenne + Élevée + Complète + Maximale + Shader CRT / TV + Désactivé + Lignes de balayage + Diagonal + Triangulaire + Onde + Lottes + 4xRGSS + NxAGSS + Saut d\'images + Sauter 1 + Sauter 2 + Sauter 3 + Mipmapping + PERFORMANCES + Fréquence de cycle EE + 50% + 60% + 75% + 100% (par défaut) + 130% + 180% + 300% + Saut de cycle EE + 1 + 2 + 3 + VU1 instantané + VU multithread (MTVU) + CDVD rapide + HUD DE PERFORMANCES + FPS + Vitesse d\'émulation + Utilisation CPU + Utilisation GPU + Résolution interne + Mode de désentrelacement + Auto + Désactivé + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + Format d\'image des FMV + Anti-flou + Patchs écran large + Patchs anti-entrelacement + VU Flag Hack + Détection de boucle INTC + Détection de boucle d\'attente + Étirement temporel audio + Tampon audio + Latence de sortie + %1$d ms + Temps de trame + Statistiques GS + Infos matériel + Version + Affichage des entrées + Démarrage rapide + EN LIGNE (DEV9) + Activer le mode en ligne + Périphérique Ethernet + Auto + Wi-Fi + Mode DNS + Manuel + Interne + DNS principal + DNS secondaire + facultatif + IP automatique (DHCP) + ENTRÉE + Commandes à l\'écran + Retour haptique + AUDIO + Volume + Muet + Inverser les canaux stéréo + Son + PARAMÈTRES RÉTRO PAR DÉFAUT + Paramètres par défaut appliqués aux jeux de chaque console, sauf modification dans les réglages propres à un jeu. + RETROACHIEVEMENTS + Compte + Connecté + Non connecté — ouvrez les Succès d\'un jeu pour vous connecter + Succès activés + Mode Hardcore par défaut (pas de sauvegardes rapides) + Se déconnecter + BIOS PLAYSTATION + Installé + Aucun — les jeux PS1 nécessitent un BIOS + Importer le BIOS PS1… + BIOS PS1 supprimé + Aucun BIOS à supprimer + Supprimer le BIOS PS1 + BIOS PLAYSTATION 2 + Aucun — les jeux PS2 nécessitent un BIOS + Format + Dump fusionné en un seul fichier (.bin marqué par région, ~4 Mo). Les jeux ROM0/MEC/NVM séparés ne sont pas acceptés. + Importer le BIOS PS2… + BIOS PS2 supprimé + Supprimer le BIOS PS2 + ILLUSTRATIONS DE LA BIBLIOTHÈQUE + Illustration rétro (cartouche / boîtier CD) + Jaquette + Récupérée automatiquement depuis thumbnails.libretro.com à l\'import ; une image personnalisée la remplace toujours. + DOSSIER DES ROMS + Dossier + Non défini — choisissez un dossier pour importer automatiquement les jeux + Import automatique + Les nouveaux jeux de ce dossier sont ajoutés automatiquement à votre bibliothèque avec la bonne console détectée. + Sélectionner le dossier des ROMs + Sélectionner le dossier des ROMs… + Changer de dossier des ROMs… + Analyser maintenant + PARAMÈTRES CONSOLE PAR DÉFAUT + Appuyez sur une console pour définir ses paramètres par défaut. + Moteur de rendu + Résolution de mise à l\'échelle + Rapport d\'aspect + Étirer + Auto (standard) + 4:3 + 16:9 + Filtre d\'affichage + Au plus proche + Bilinéaire (lisse) + Bilinéaire (net) + Filtre de texture + Bilinéaire (forcé) + Bilinéaire (PS2) + Bilinéaire (sprites) + Précision du mélange + Minimale + Basique + Moyenne + Élevée + Complète + Maximale + Shader CRT / TV + Désactivé + Lignes de balayage + Diagonal + Triangulaire + Onde + Lottes + 4xRGSS + NxAGSS + Saut d\'images + Sauter 1 + Sauter 2 + Sauter 3 + Mipmapping + Fréquence de cycle EE + 50% + 60% + 75% + 100% (par défaut) + 130% + 180% + 300% + Saut de cycle EE + Désactivé + 1 + 2 + 3 + VU1 instantané + VU multithread (MTVU) + CDVD rapide + Commandes tactiles à l\'écran + Son + Inverser les canaux stéréo + HUD : FPS + HUD : vitesse d\'émulation + HUD : utilisation CPU + HUD : utilisation GPU + HUD : résolution interne + Activer le mode en ligne (DEV9) + Périphérique Ethernet + Auto + Wi-Fi + Mode DNS + Manuel + Interne + DNS principal + DNS secondaire + facultatif + IP automatique (DHCP) + Shader + Mise à l\'échelle SGSR + HUD de performances + CRÉDITS & LICENCES + Certaines fonctionnalités de WinNative reposent sur ces projets open source. Appuyez pour voir chaque source. + Par défaut + Crédits + Activer le mode Hardcore ? + Le mode Hardcore réinitialise le jeu maintenant et désactive le chargement des sauvegardes rapides, l\'avance rapide et les codes de triche. Toute progression non enregistrée sera perdue. Continuer ? + Annuler + Activer + BIOS importé : %1$s + Fichier BIOS non valide + BIOS PS2 importé : %1$s + Fichier BIOS PS2 non valide + Aucun numéro de série de jeu pour rechercher des codes de triche. + %1$d code(s) de triche appliqué(s). + Impossible d\'appliquer les codes de triche. + Codes de triche + Appliquer + Aucun code de triche trouvé pour ce jeu. + Succès + Se connecter à RetroAchievements + Nom d\'utilisateur + Mot de passe + Échec de la connexion + Connexion en cours… + Se connecter + %1$d/%2$d • %3$d pts + Aucun succès pour ce jeu. + Retour + Activé + Désactivé + Renommer + Enregistrer + Conflit de sauvegarde cloud + Conserver la sauvegarde locale + A + Menu + Affichage + HUD + Son + Commandes + Bibliothèque à jour + ROMs : %1$s + %1$d ajouté(s) + %1$d supprimé(s) + Par défaut + CRT + LCD + Net + Native + Rapport d\'aspect + Filtre NTSC + Colorisation + Correction des couleurs + Supprimer la limite de sprites + Résolution + Émulation du framebuffer + Tramage + Hack écran large + 8:7 (native) + 4:3 (TV) + Désactivé + RF + Composite + S-Video + RGB + Auto + Écran GBA + Écran GBC + Activé + 320x240 (native) + 640x480 + 960x720 + 1280x960 + 4:3 + 16:9 + 16:9 ajusté + Native + Interne + Activé (16:9) + RETROACHIEVEMENTS + Connectez-vous avec votre compte RetroAchievements pour gagner et suivre des succès sur les jeux rétro. + Nom d\'utilisateur + Mot de passe + Saisissez votre nom d\'utilisateur et votre mot de passe + Échec de la connexion + Se connecter + Votre mot de passe n\'est utilisé qu\'une seule fois pour obtenir un jeton de connexion, stocké en toute sécurité sur l\'appareil. + Succès activés + Mode Hardcore (pas de sauvegardes rapides) + %1$d / %2$d points + Aucun succès trouvé pour ce jeu. + Se déconnecter + CODES DE TRICHE + Nom + Code + Annuler + Enregistrer + Code de triche %1$d + Aucun code de triche. Ajoutez un code de triche pour ce jeu. + Ajouter un code + + Pilote GPU + Système (Par défaut) + Installez les pilotes Turnip dans Paramètres \u2192 Pilotes. Les mêmes pilotes fonctionnent pour les jeux PC et PS2. + + HDD PS2 (DEV9) + Lecteur interne virtuel pour les jeux sur HDD comme Final Fantasy XI. Redémarre le jeu. + Lecteur interne virtuel pour les jeux sur HDD comme Final Fantasy XI. + Mode DNS réglé sur Internal pour que vos hôtes de serveur personnalisés prennent effet. + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + Add Cheat + Cheat name + Codes (one per line, e.g. 2021A268 00000000) + Custom + Enter a name and at least one valid code + Add + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + PS2 HDD Images + A .raw HDD image, or a .zip containing one (e.g. a game’s downloaded HDD with maps/DLC) + Import HDD Image + Importing… + Imported %1$s + Could not import HDD image + Removed %1$s + Remove %1$s + HDD Image + None + Cheats + Patches + PATCH + Custom + Applied %1$d cheat(s), %2$d patch(es). + No cheats or patches found for this game. + Cheat + Patch + Add +Cœur CPU +Double cœur +Codes de triche internes +Résolution interne +Moteur de rendu +Position de la barre de capteurs +Passer l\'intro du BIOS + + + + + + +Bas +Interpréteur en cache +Matériel +Interpréteur +JIT +Souris / Tactile +Stick droit (absolu) +Stick droit (relatif) +Logiciel +Étirer +Haut +Saut VBI (saut d\'image auto) +Écran large +Pointeur Wiimote +Les modifications s\'appliquent au prochain lancement de ce jeu. +Lancez ce jeu une fois pour détecter le numéro de série du disque, puis les codes de triche et correctifs apparaîtront ici. +Contournement de l\'authentification DNAS — requis pour le jeu en ligne +Appliqué automatiquement (en ligne) +Codes de triche & correctifs +Taille : %1$s +Importer une image HDD +Supprimer +Activer NetPlay +Désactivé par défaut. Activez-le, puis choisissez Héberger ou Rejoindre avant le lancement.\nSe désactive à nouveau lorsque vous quittez le jeu. +Adresse de l\'hôte +IP ou nom d\'hôte +Héberger une session +Activé = attendre un joueur. Désactivé = rejoindre l\'adresse de l\'hôte +NetPlay utilise les ports multijoueur locaux via TCP (joueur 1 hôte / joueur 2 client). Le jeu en ligne PS2 utilise plutôt l\'Ethernet DEV9. +Port +Carte mémoire %1$d +Capture d\'écran +Utiliser la sauvegarde cloud +LAN (IP directe) +Connexion… +Connexion +En ligne (code hôte) +Ignorer +Le NetPlay GameCube/Wii utilise le propre moteur de Dolphin. Hôte = Joueur 1, Rejoindre = Joueur 2. Choisissez Héberger ou Rejoindre et un type de connexion avant le lancement ; les deux appareils démarrent le même jeu ensemble. +Partagez l\'IP Wi‑Fi de votre appareil et ce port avec le Joueur 2. Le jeu démarre automatiquement dès qu\'il se connecte. +Un code hôte s\'affiche au démarrage du jeu — partagez-le avec le Joueur 2. Le jeu démarre automatiquement dès qu\'il se connecte. +Saisissez l\'IP Wi‑Fi et le port de l\'hôte, puis lancez pour vous connecter. +Saisissez le code hôte du Joueur 1, puis lancez pour vous connecter. +Activez NetPlay dans les paramètres du jeu et choisissez Héberger ou Rejoindre avant le lancement +Trouver des salons sur le Wi‑Fi +Game Link · chaque écran est sa propre console portable +Le multijoueur GBA utilise gpSP + l\'adaptateur sans fil. Assurez-vous que libgpsp est installé. +Multijoueur à écran partagé via Wi‑Fi (comme RetroArch).\nHôte = Joueur 1, Rejoindre = Joueur 2. Les deux appareils affichent le même jeu. +Game Link via Wi‑Fi — chaque appareil exécute son propre jeu.\nGB/GBC : liaison série Gambatte (Pokémon Gén 1–2).\nGBA : adaptateur sans fil gpSP (combats Pokémon RF/VF/Émeraude). +Héberger un salon +Code hôte +Code hôte de traversée fourni par l\'hôte +Hébergement du salon +Appuyez sur Héberger pour ouvrir un salon pour cette session de jeu, puis lancez le jeu. NetPlay se désactive lorsque vous quittez. +Dans le salon +Rejoindre par IP +Rejoint +Rejoindre +Au lancement +Quitter +Hôte = J1 · Rejoindre = J2 · même jeu sur les deux écrans +Héberger +Rejoindre +Manuel +Aucun salon trouvé. Assurez-vous que l\'hôte est sur le même Wi‑Fi et héberge un salon. +Nom affiché +Affiché aux autres joueurs +%1$d connecté(s) +Le salon est ouvert pour cette session uniquement. Lancez quand vous êtes prêt. Quitter le jeu désactive NetPlay. +Joueurs +Analyser le Wi‑Fi +Analyser à nouveau +Analysez le même Wi‑Fi à la recherche de salons ouverts, ou rejoignez par adresse IP. +Analyse du Wi‑Fi… +Résultats de l\'analyse +Appuyez sur un salon pour le rejoindre maintenant (n\'enregistre pas l\'IP pour le prochain lancement). +Arrêter l\'analyse +NetPlay +%1$s connecté +%1$s déconnecté +En attente des joueurs… +La prise en charge de la PlayStation 2 arrive bientôt +Afficher les boutons L3 / R3 +Lorsque désactivé, appuyez deux fois sur un stick pour cliquer L3 / R3 +DRAPEAUX DU PILOTE TURNIP +Appliqué uniquement lorsqu\'un pilote GPU personnalisé est sélectionné ci-dessus. +Fichier de jeu introuvable +Supprimer +Importer depuis un fichier… +Chargement… +NetPlay + Wii Home + Changer de console + Identifier comme console + Désormais identifié comme %1$s ReShade Appliquez un effet ReShade (.fx) aux jeux DXVK/VKD3D (Vulkan) via la couche vkBasalt intégrée. Placez chaque effet dans son propre dossier sous Android/data/<package>/files/ReShade/. Le réglage des paramètres en direct et le bouton en jeu arriveront avec la mise à jour de la couche à rechargement à chaud. @@ -1657,5 +2430,28 @@ Chemin installé : Activer ReShade Aucun effet ReShade dans cette configuration. Ajoutez des effets dans les paramètres de ce jeu (ou du conteneur) pour les changer et les régler ici. Cet effet n\'expose aucun paramètre réglable. + Suppression de la sauvegarde… + Supprimer + Supprimer définitivement la sauvegarde cloud de %1$s ? Cette action est irréversible. + Supprimer la sauvegarde cloud + Impossible de supprimer la sauvegarde cloud + Sauvegarde cloud supprimée + Téléchargez d\'abord les cœurs de console — Paramètres › Rétro + Cet appareil ne peut pas exécuter l\'émulation PS2 — il faut OpenGL ES 3.1 ou plus récent. + Rechercher des mises à jour + Recherche de mises à jour… + Télécharger les cœurs de console + Téléchargement… %1$d / %2$d Mo + Cœurs de console + Installé — build %1$s + Installé — build %1$s (échec de la recherche de mises à jour) + Installation… + Non installé — téléchargez pour jouer aux jeux rétro + État + Mettre à jour les cœurs de console + Mise à jour disponible — build %1$s (%2$d Mo) + Vérification du téléchargement… + Traitement… + Système diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 63edff4cd..ac4917737 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -1558,6 +1558,779 @@ बैकग्राउंड में चलाएँ WinNative से बाहर निकलने के बाद चैट चालू रखें रीफ़्रेश + रेट्रो + सेव ट्रांसफ़र करें + इस गेम में स्थानीय सेव फ़ाइल इंपोर्ट करें, या गेम का मौजूदा सेव एक्सपोर्ट करें। + सेव इंपोर्ट करें + सेव एक्सपोर्ट करें + सेव इंपोर्ट हो गया + सेव इंपोर्ट नहीं हो सका + सेव एक्सपोर्ट हो गया + सेव एक्सपोर्ट नहीं हो सका + इस गेम के लिए अभी कोई सेव मौजूद नहीं है + चीट + हार्डकोर मोड में चीट अक्षम हैं + + + सहेजें + रद्द करें + स्टेट सहेजें + सहेजी स्टेट लोड करें + उपलब्धियाँ + चीट्स + मेमोरी कार्ड + फ़ास्ट फ़ॉरवर्ड + रीसेट + डिस्क बदलें + स्लॉट %1$d + लोड करने हेतु टैप करें + खाली + अधिलेखित करने हेतु टैप करें + खाली — सहेजने हेतु टैप करें + स्लॉट %1$d खाली है + स्लॉट %1$d लोड किया गया + स्लॉट %1$d लोड नहीं हो सका + स्लॉट %1$d में सहेजा गया + सहेजना विफल + • स्लॉट 1 + • स्लॉट 2 + • उपयोग हेतु टैप करें + नया मेमोरी कार्ड + कार्ड आयात करें + ऑनलाइन सक्षम करें (DEV9) + PS2 नेटवर्क अडैप्टर — इसे जोड़ने हेतु गेम पुनः आरंभ करता है + ईथरनेट डिवाइस + DNS मोड + प्राथमिक DNS + द्वितीयक DNS + वैकल्पिक + स्वतः IP (DHCP) + सर्वर: %1$s + IP सेट करने हेतु टैप करें (खाली हटाता है) + %1$s → IP + सर्वर होस्ट जोड़ें + नया सर्वर होस्टनेम + उदा. bf2.playbattlefront.com + ऑन-स्क्रीन नियंत्रण + लेआउट संपादित करें + लेआउट रीसेट करें + लेआउट रीसेट हुआ + बायाँ स्टिक: X उलटें + बायाँ स्टिक: Y उलटें + दायाँ स्टिक: X उलटें + दायाँ स्टिक: Y उलटें + बटन रंग + अक्षर रंग + छाया रंग + पृष्ठभूमि रंग + रंग रीसेट करें + रेंडरर + Vulkan + OpenGL + Software + रिज़ॉल्यूशन स्केल + 1x (नेटिव) + 1.5x + 2x + 3x + 4x + आस्पेक्ट रेशियो + स्ट्रेच + स्वतः (मानक) + 4:3 + 16:9 + डिस्प्ले फ़िल्टर + निकटतम + बाइलीनियर (स्मूद) + बाइलीनियर (शार्प) + टेक्सचर फ़िल्टर + बाइलीनियर (बलपूर्वक) + बाइलीनियर (PS2) + बाइलीनियर (स्प्राइट) + ब्लेंडिंग परिशुद्धता + न्यूनतम + मूल + मध्यम + उच्च + पूर्ण + अधिकतम + CRT / TV शेडर + बंद + स्कैनलाइन + विकर्ण + त्रिकोणीय + वेव + Lottes + 4xRGSS + NxAGSS + फ़्रेम स्किप + बंद + 1 स्किप करें + 2 स्किप करें + 3 स्किप करें + मिपमैपिंग + वॉल्यूम + %1$d%% + म्यूट + स्टीरियो चैनल बदलें + EE साइकिल दर + 50% + 60% + 75% + 100% (डिफ़ॉल्ट) + 130% + 180% + 300% + EE साइकिल स्किप + बंद + 1 + 2 + 3 + इंस्टेंट VU1 + मल्टी-थ्रेडेड VU (MTVU) + फ़ास्ट CDVD + FPS + एमुलेशन गति + CPU उपयोग + GPU उपयोग + आंतरिक रिज़ॉल्यूशन + डीइंटरलेस मोड + स्वतः + बंद + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + FMV आस्पेक्ट रेशियो + एंटी-ब्लर + वाइडस्क्रीन पैच + नो-इंटरलेस पैच + VU Flag Hack + INTC स्पिन डिटेक्शन + वेट लूप डिटेक्शन + ऑडियो टाइम स्ट्रेच + ऑडियो बफर + आउटपुट लेटेंसी + %1$d ms + फ्रेम समय + GS आँकड़े + हार्डवेयर जानकारी + संस्करण + इनपुट डिस्प्ले + मेनू + डिस्प्ले + प्रदर्शन + HUD + ध्वनि + ऑनलाइन + नियंत्रण + पुनः आरंभ + रोकें + बाहर निकलें + BIOS आयात हुआ: %1$s + अमान्य BIOS फ़ाइल + अमान्य रेट्रो गेम + ROM नहीं मिला: %1$s + इस संग्रह के अंदर की ROM पढ़ी नहीं जा सकी + कोर स्थापित नहीं: %1$s + चीट्स सक्षम — इस सत्र हेतु उपलब्धियाँ अक्षम हैं + क्लाउड सेव पुनर्स्थापित हुआ + पुनर्स्थापना विफल + %1$s हेतु एक नया क्लाउड सेव मौजूद है. क्या आप सिंक करना चाहते हैं, और आप कौन-सा क्लाउड सेव रखना पसंद करेंगे? + क्लाउड सेव + रेट्रो + एमुलेटर कोर लोड करने में विफल + ROM लोड करने में विफल + इस कोर हेतु ग्राफ़िक्स समर्थित नहीं + एमुलेटर त्रुटि + डिफ़ॉल्ट + CRT + LCD + शार्प + SGSR + SGSR अपस्केल + नेटिव + ध्वनि + बायाँ स्टिक: X उलटें + बायाँ स्टिक: Y उलटें + दायाँ स्टिक: X उलटें + दायाँ स्टिक: Y उलटें + ऑन-स्क्रीन नियंत्रण + हैप्टिक फ़ीडबैक + पोर्ट्रेट + लैंडस्केप + लेआउट संपादित करें (%1$s) + %1$s लेआउट रीसेट करें + %1$s लेआउट रीसेट हुआ + बटन रंग + अक्षर रंग + छाया रंग + पृष्ठभूमि रंग + रंग रीसेट करें + रंग रीसेट हुए + प्रदर्शन HUD + अल्फा + पृष्ठभूमि अल्फा + पृष्ठभूमि + स्केल + संख्यात्मक फ़्रेमटाइम + डुअल-सीरीज़ बैटरी + HUD तत्व + FPS + कंसोल + GPU + CPU + RAM + बैटरी + तापमान + ग्राफ़ + CPU तापमान + स्टेट सहेजें + सहेजी स्टेट लोड करें + हार्डकोर मोड में स्टेट लोड करना अक्षम है + उपलब्धियाँ + चीट्स + हार्डकोर मोड में चीट्स अक्षम हैं + रीसेट + फ़ास्ट फ़ॉरवर्ड + हार्डकोर मोड में फ़ास्ट फ़ॉरवर्ड अक्षम है + HUD + डिस्क %1$d/%2$d + पुनः आरंभ + रोकें + बाहर निकलें + स्लॉट %1$d में सहेजा गया + स्टेट सहेजी नहीं जा सकी + %1$s BIOS आवश्यक + PlayStation गेम्स को एक वास्तविक कंसोल BIOS फ़ाइल की आवश्यकता होती है जो आपको उपलब्ध करानी होगी. जारी रखने हेतु एक BIOS (scph5501.bin, scph5500.bin, scph5502.bin, scph1001.bin या scph7001.bin) आयात करें. + BIOS आयात करें… + रद्द करें + स्लॉट %1$d खाली है + स्लॉट %1$d लोड किया गया + स्टेट लोड नहीं हो सकी + स्लॉट %1$d + स्लॉट %1$d का नाम बदलें + सामान्य + ग्राफ़िक्स + प्रदर्शन + HUD + इनपुट + ऑडियो + ऑनलाइन + रद्द करें + सहेजें + डिफ़ॉल्ट + CRT + LCD + शार्प + 2x + 4x + नेटिव + गेम + नाम + सिस्टम + एमुलेटर कोर + ROM पथ + %1$s BIOS + स्थापित + कोई नहीं — %1$s गेम्स चलाने हेतु आवश्यक + BIOS आयात करें… + BIOS हटाएँ + लाइब्रेरी आर्टवर्क + गेम कार्ड छवि + ग्रिड छवि + कैरोसेल छवि + सूची छवि + कस्टम छवि सेट + छवि सेट करें + हटाएँ + वीडियो + वीडियो फ़िल्टर + SGSR + SGSR अपस्केल + प्रदर्शन HUD + कोर + रेंडरर + Vulkan + OpenGL + Software + रिज़ॉल्यूशन स्केल + 1x (नेटिव) + 1.5x + 2x + 3x + 4x + आस्पेक्ट रेशियो + स्ट्रेच + स्वतः (मानक) + 4:3 + 16:9 + डिस्प्ले फ़िल्टर + निकटतम + बाइलीनियर (स्मूद) + बाइलीनियर (शार्प) + टेक्सचर फ़िल्टर + बाइलीनियर (बलपूर्वक) + बाइलीनियर (PS2) + बाइलीनियर (स्प्राइट) + ब्लेंडिंग परिशुद्धता + न्यूनतम + मूल + मध्यम + उच्च + पूर्ण + अधिकतम + CRT / TV शेडर + बंद + स्कैनलाइन + विकर्ण + त्रिकोणीय + वेव + Lottes + 4xRGSS + NxAGSS + फ़्रेम स्किप + 1 स्किप करें + 2 स्किप करें + 3 स्किप करें + मिपमैपिंग + प्रदर्शन + EE साइकिल दर + 50% + 60% + 75% + 100% (डिफ़ॉल्ट) + 130% + 180% + 300% + EE साइकिल स्किप + 1 + 2 + 3 + इंस्टेंट VU1 + मल्टी-थ्रेडेड VU (MTVU) + फ़ास्ट CDVD + प्रदर्शन HUD + FPS + एमुलेशन गति + CPU उपयोग + GPU उपयोग + आंतरिक रिज़ॉल्यूशन + डीइंटरलेस मोड + स्वतः + बंद + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + FMV आस्पेक्ट रेशियो + एंटी-ब्लर + वाइडस्क्रीन पैच + नो-इंटरलेस पैच + VU Flag Hack + INTC स्पिन डिटेक्शन + वेट लूप डिटेक्शन + ऑडियो टाइम स्ट्रेच + ऑडियो बफर + आउटपुट लेटेंसी + %1$d ms + फ्रेम समय + GS आँकड़े + हार्डवेयर जानकारी + संस्करण + इनपुट डिस्प्ले + फास्ट बूट + ऑनलाइन (DEV9) + ऑनलाइन सक्षम करें + ईथरनेट डिवाइस + स्वतः + Wi-Fi + DNS मोड + मैन्युअल + आंतरिक + प्राथमिक DNS + द्वितीयक DNS + वैकल्पिक + स्वतः IP (DHCP) + इनपुट + ऑन-स्क्रीन नियंत्रण + हैप्टिक फ़ीडबैक + ऑडियो + वॉल्यूम + म्यूट + स्टीरियो चैनल बदलें + ध्वनि + रेट्रो डिफ़ॉल्ट + प्रत्येक कंसोल के गेम्स पर लागू डिफ़ॉल्ट, जब तक कि किसी गेम की अपनी सेटिंग्स में अधिरोहित न किए जाएँ. + RETROACHIEVEMENTS + खाता + साइन इन + साइन इन नहीं — साइन इन करने हेतु किसी गेम की उपलब्धियाँ खोलें + उपलब्धियाँ सक्षम + डिफ़ॉल्ट रूप से हार्डकोर मोड (कोई सेव स्टेट नहीं) + साइन आउट + PLAYSTATION BIOS + स्थापित + कोई नहीं — PS1 गेम्स हेतु BIOS आवश्यक + PS1 BIOS आयात करें… + PS1 BIOS हटाया गया + हटाने हेतु कोई BIOS नहीं + PS1 BIOS हटाएँ + PLAYSTATION 2 BIOS + कोई नहीं — PS2 गेम्स हेतु BIOS आवश्यक + फ़ॉर्मेट + मर्ज किया गया एकल-फ़ाइल डंप (क्षेत्र-टैग .bin, ~4MB). विभाजित ROM0/MEC/NVM सेट स्वीकार्य नहीं हैं. + PS2 BIOS आयात करें… + PS2 BIOS हटाया गया + PS2 BIOS हटाएँ + लाइब्रेरी आर्टवर्क + रेट्रो केस आर्ट (कार्ट्रिज / CD केस) + बॉक्स आर्ट + आयात पर thumbnails.libretro.com से स्वतः प्राप्त; कस्टम छवि सदैव इसे अधिरोहित करती है. + ROMS फ़ोल्डर + फ़ोल्डर + सेट नहीं — गेम्स स्वतः आयात करने हेतु एक फ़ोल्डर चुनें + स्वतः-आयात + इस फ़ोल्डर के नए गेम्स सही कंसोल का पता लगाकर स्वतः आपकी लाइब्रेरी में जुड़ जाते हैं. + ROMs फ़ोल्डर चुनें + ROMs फ़ोल्डर चुनें… + ROMs फ़ोल्डर बदलें… + अभी स्कैन करें + कंसोल डिफ़ॉल्ट + इसकी डिफ़ॉल्ट सेटिंग्स सेट करने हेतु किसी कंसोल पर टैप करें. + रेंडरर + रिज़ॉल्यूशन अपस्केल करें + आस्पेक्ट रेशियो + स्ट्रेच + स्वतः (मानक) + 4:3 + 16:9 + डिस्प्ले फ़िल्टर + निकटतम + बाइलीनियर (स्मूद) + बाइलीनियर (शार्प) + टेक्सचर फ़िल्टर + बाइलीनियर (बलपूर्वक) + बाइलीनियर (PS2) + बाइलीनियर (स्प्राइट) + ब्लेंडिंग परिशुद्धता + न्यूनतम + मूल + मध्यम + उच्च + पूर्ण + अधिकतम + CRT / TV शेडर + बंद + स्कैनलाइन + विकर्ण + त्रिकोणीय + वेव + Lottes + 4xRGSS + NxAGSS + फ़्रेम स्किप + 1 स्किप करें + 2 स्किप करें + 3 स्किप करें + मिपमैपिंग + EE साइकिल दर + 50% + 60% + 75% + 100% (डिफ़ॉल्ट) + 130% + 180% + 300% + EE साइकिल स्किप + बंद + 1 + 2 + 3 + इंस्टेंट VU1 + मल्टी-थ्रेडेड VU (MTVU) + फ़ास्ट CDVD + ऑन-स्क्रीन टच नियंत्रण + ध्वनि + स्टीरियो चैनल बदलें + HUD: FPS + HUD: एमुलेशन गति + HUD: CPU उपयोग + HUD: GPU उपयोग + HUD: आंतरिक रिज़ॉल्यूशन + ऑनलाइन सक्षम करें (DEV9) + ईथरनेट डिवाइस + स्वतः + Wi-Fi + DNS मोड + मैन्युअल + आंतरिक + प्राथमिक DNS + द्वितीयक DNS + वैकल्पिक + स्वतः IP (DHCP) + शेडर + SGSR अपस्केलिंग + प्रदर्शन HUD + क्रेडिट & लाइसेंस + WinNative की कुछ सुविधाएँ इन ओपन-सोर्स परियोजनाओं पर आधारित हैं. प्रत्येक स्रोत देखने के लिए टैप करें. + डिफ़ॉल्ट + क्रेडिट + हार्डकोर मोड सक्षम करें? + हार्डकोर मोड अभी गेम रीसेट करता है और सेव स्टेट लोड करना, फ़ास्ट फ़ॉरवर्ड, और चीट्स अक्षम कर देता है. कोई भी असहेजी प्रगति खो जाएगी. जारी रखें? + रद्द करें + सक्षम करें + BIOS आयात हुआ: %1$s + अमान्य BIOS फ़ाइल + PS2 BIOS आयात हुआ: %1$s + अमान्य PS2 BIOS फ़ाइल + चीट्स खोजने हेतु कोई गेम सीरियल नहीं. + %1$d चीट(s) लागू किए गए. + चीट्स लागू नहीं किए जा सके. + चीट्स + लागू करें + इस गेम हेतु कोई चीट्स नहीं मिले. + उपलब्धियाँ + RetroAchievements में साइन इन करें + उपयोगकर्ता नाम + पासवर्ड + लॉगिन विफल + साइन इन हो रहा है… + साइन इन + %1$d/%2$d • %3$d अंक + इस गेम हेतु कोई उपलब्धियाँ नहीं. + वापस + सक्षम + अक्षम + नाम बदलें + सहेजें + क्लाउड सेव विरोध + स्थानीय सेव रखें + A + मेनू + डिस्प्ले + HUD + ध्वनि + नियंत्रण + लाइब्रेरी अद्यतित + ROMs: %1$s + %1$d जोड़े गए + %1$d हटाए गए + डिफ़ॉल्ट + CRT + LCD + शार्प + नेटिव + आस्पेक्ट रेशियो + NTSC फ़िल्टर + रंगीकरण + रंग सुधार + स्प्राइट सीमा हटाएँ + रिज़ॉल्यूशन + फ़्रेमबफ़र एमुलेशन + डिदरिंग + वाइडस्क्रीन हैक + 8:7 (नेटिव) + 4:3 (TV) + बंद + RF + कंपोज़िट + S-Video + RGB + स्वतः + GBA स्क्रीन + GBC स्क्रीन + चालू + 320x240 (नेटिव) + 640x480 + 960x720 + 1280x960 + 4:3 + 16:9 + 16:9 समायोजित + नेटिव + आंतरिक + चालू (16:9) + RETROACHIEVEMENTS + रेट्रो गेम्स हेतु उपलब्धियाँ अर्जित करने और ट्रैक करने के लिए अपने RetroAchievements खाते से साइन इन करें. + उपयोगकर्ता नाम + पासवर्ड + अपना उपयोगकर्ता नाम और पासवर्ड दर्ज करें + लॉगिन विफल + साइन इन + आपका पासवर्ड केवल एक बार लॉगिन टोकन प्राप्त करने हेतु उपयोग होता है, जो डिवाइस पर सुरक्षित रूप से संग्रहीत है. + उपलब्धियाँ सक्षम + हार्डकोर मोड (कोई सेव स्टेट नहीं) + %1$d / %2$d अंक + इस गेम हेतु कोई उपलब्धियाँ नहीं मिलीं. + साइन आउट + चीट्स + नाम + कोड + रद्द करें + सहेजें + चीट %1$d + अभी तक कोई चीट्स नहीं. इस गेम हेतु एक चीट कोड जोड़ें. + चीट जोड़ें + + GPU ड्राइवर + सिस्टम (डिफ़ॉल्ट) + Turnip ड्राइवर सेटिंग्स \u2192 ड्राइवर्स में इंस्टॉल करें। ये ड्राइवर PC और PS2 दोनों गेम्स के लिए काम करते हैं। + + PS2 HDD (DEV9) + Final Fantasy XI जैसे HDD-आधारित गेम के लिए वर्चुअल आंतरिक ड्राइव। गेम को पुनः आरंभ करता है। + Final Fantasy XI जैसे HDD-आधारित गेम के लिए वर्चुअल आंतरिक ड्राइव। + DNS मोड को Internal पर सेट किया गया ताकि आपके कस्टम सर्वर होस्ट प्रभावी हों। + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + Add Cheat + Cheat name + Codes (one per line, e.g. 2021A268 00000000) + Custom + Enter a name and at least one valid code + Add + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + PS2 HDD Images + A .raw HDD image, or a .zip containing one (e.g. a game’s downloaded HDD with maps/DLC) + Import HDD Image + Importing… + Imported %1$s + Could not import HDD image + Removed %1$s + Remove %1$s + HDD Image + None + Cheats + Patches + PATCH + Custom + Applied %1$d cheat(s), %2$d patch(es). + No cheats or patches found for this game. + Cheat + Patch + Add + CPU कोर + डुअल कोर + आंतरिक चीट्स + आंतरिक रिज़ॉल्यूशन + रेंडरर + सेंसर बार स्थिति + BIOS इंट्रो छोड़ें + + + + + + + नीचे + कैश्ड इंटरप्रेटर + हार्डवेयर + इंटरप्रेटर + JIT + माउस / टच + राइट स्टिक (एब्सोल्यूट) + राइट स्टिक (रिलेटिव) + सॉफ़्टवेयर + स्ट्रेच + ऊपर + VBI स्किप (ऑटो फ़्रेमस्किप) + वाइडस्क्रीन + Wiimote पॉइंटर + अगली बार इस गेम को लॉन्च करने पर बदलाव लागू होंगे। + इस गेम को एक बार लॉन्च करें ताकि इसका डिस्क सीरियल पहचाना जा सके, फिर चीट्स और पैच यहाँ दिखाई देंगे। + DNAS ऑथ बायपास — ऑनलाइन प्ले के लिए आवश्यक + ऑटो-लागू (ऑनलाइन) + चीट्स & पैच + आकार: %1$s + HDD इमेज इंपोर्ट करें + हटाएँ + NetPlay सक्षम करें + डिफ़ॉल्ट रूप से बंद। सक्षम करें, फिर लॉन्च से पहले Host या Join चुनें।\nगेम से बाहर निकलने पर यह फिर से बंद हो जाता है। + Host पता + IP या होस्टनेम + Host सेशन + चालू = किसी खिलाड़ी की प्रतीक्षा करें। बंद = host पते से जुड़ें + NetPlay TCP पर लोकल मल्टीप्लेयर पोर्ट का उपयोग करता है (खिलाड़ी 1 host / खिलाड़ी 2 क्लाइंट)। PS2 ऑनलाइन इसके बजाय DEV9 ईथरनेट का उपयोग करता है। + पोर्ट + मेमोरी कार्ड %1$d + स्क्रीनशॉट + क्लाउड सेव का उपयोग करें + LAN (सीधा IP) + कनेक्ट हो रहा है… + कनेक्शन + ऑनलाइन (host कोड) + खारिज करें + GameCube/Wii NetPlay Dolphin के अपने इंजन का उपयोग करता है। Host = खिलाड़ी 1, Join = खिलाड़ी 2। लॉन्च से पहले Host या Join और एक कनेक्शन प्रकार चुनें; दोनों डिवाइस एक साथ वही गेम बूट करते हैं। + अपने डिवाइस का Wi‑Fi IP और यह पोर्ट खिलाड़ी 2 के साथ साझा करें। जैसे ही वे कनेक्ट होते हैं गेम अपने आप शुरू हो जाता है। + गेम बूट होने पर एक host कोड दिखाया जाता है — इसे खिलाड़ी 2 के साथ साझा करें। जैसे ही वे कनेक्ट होते हैं गेम अपने आप शुरू हो जाता है। + host का Wi‑Fi IP और पोर्ट दर्ज करें, फिर कनेक्ट करने के लिए लॉन्च करें। + खिलाड़ी 1 से host कोड दर्ज करें, फिर कनेक्ट करने के लिए लॉन्च करें। + गेम सेटिंग्स में NetPlay सक्षम करें और लॉन्च से पहले Host या Join चुनें + Wi‑Fi पर रूम खोजें + Game Link · प्रत्येक स्क्रीन अपना अलग हैंडहेल्ड है + GBA मल्टीप्लेयर gpSP + Wireless Adapter का उपयोग करता है। सुनिश्चित करें कि libgpsp इंस्टॉल है। + Wi‑Fi पर साझा-स्क्रीन मल्टीप्लेयर (RetroArch की तरह)।\nHost = खिलाड़ी 1, Join = खिलाड़ी 2। दोनों डिवाइस वही गेम दिखाते हैं। + Wi‑Fi पर Game Link — प्रत्येक डिवाइस अपना गेम चलाता है।\nGB/GBC: Gambatte सीरियल लिंक (Pokémon Gen 1–2)।\nGBA: gpSP Wireless Adapter (Pokémon FR/LG/Emerald बैटल)। + रूम होस्ट करें + Host कोड + host से ट्रैवर्सल host कोड + रूम होस्ट हो रहा है + इस प्ले सेशन के लिए एक रूम खोलने हेतु Host टैप करें, फिर गेम लॉन्च करें। बाहर निकलने पर NetPlay बंद हो जाता है। + रूम में + IP द्वारा जुड़ें + जुड़ गए + Join + लॉन्च पर + छोड़ें + Host = P1 · Join = P2 · दोनों स्क्रीन पर वही गेम + Host + Join + मैन्युअल + कोई रूम नहीं मिला। सुनिश्चित करें कि host उसी Wi‑Fi पर है और एक रूम होस्ट कर रहा है। + प्रदर्शन नाम + अन्य खिलाड़ियों को दिखाया गया + %1$d जुड़े + रूम केवल इस सेशन के लिए खुला है। तैयार होने पर लॉन्च करें। गेम से बाहर निकलने पर NetPlay बंद हो जाता है। + खिलाड़ी + Wi‑Fi स्कैन करें + फिर से स्कैन करें + खुले रूम के लिए उसी Wi‑Fi को स्कैन करें, या IP पते द्वारा जुड़ें। + Wi‑Fi स्कैन हो रहा है… + स्कैन परिणाम + अभी जुड़ने के लिए किसी रूम पर टैप करें (अगले लॉन्च के लिए IP सहेजता नहीं है)। + स्कैन रोकें + NetPlay + %1$s जुड़ गया + %1$s डिस्कनेक्ट हो गया + खिलाड़ियों की प्रतीक्षा हो रही है… + PlayStation 2 समर्थन जल्द ही आ रहा है + L3 / R3 बटन दिखाएँ + बंद होने पर, L3 / R3 क्लिक करने के लिए स्टिक को डबल-टैप करें + TURNIP ड्राइवर फ़्लैग + केवल तभी लागू होता है जब ऊपर एक कस्टम GPU ड्राइवर चुना गया हो। + गेम फ़ाइल नहीं मिली + हटाएँ + फ़ाइल से इंपोर्ट करें… + लोड हो रहा है… + NetPlay + Wii Home + कंसोल बदलें + कंसोल के रूप में पहचानें + अब %1$s के रूप में पहचाना गया ReShade अंतर्निहित vkBasalt लेयर के माध्यम से DXVK/VKD3D (Vulkan) गेम पर ReShade प्रभाव (.fx) लागू करें। प्रत्येक प्रभाव को Android/data/<package>/files/ReShade/ के अंतर्गत उसके अपने फ़ोल्डर में रखें। लाइव पैरामीटर ट्यूनिंग और इन-गेम टॉगल लाइव-रीलोड लेयर अपडेट के साथ आएंगे। @@ -1593,4 +2366,27 @@ ReShade सक्षम करें इस लोडआउट में कोई ReShade प्रभाव नहीं है। उन्हें यहाँ बदलने और ट्यून करने के लिए इस गेम की सेटिंग (या कंटेनर की) में प्रभाव जोड़ें। यह प्रभाव कोई समायोज्य पैरामीटर प्रदान नहीं करता। + सेव हटाया जा रहा है… + हटाएं + %1$s से क्लाउड सेव को हमेशा के लिए हटाएं? इसे पूर्ववत नहीं किया जा सकता। + क्लाउड सेव हटाएं + क्लाउड सेव नहीं हटाया जा सका + क्लाउड सेव हटा दिया गया + पहले कंसोल कोर डाउनलोड करें — सेटिंग्स › रेट्रो + यह डिवाइस PS2 एमुलेशन नहीं चला सकता — इसके लिए OpenGL ES 3.1 या नया चाहिए। + अपडेट जांचें + अपडेट जांचे जा रहे हैं… + कंसोल कोर डाउनलोड करें + डाउनलोड हो रहा है… %1$d / %2$d MB + कंसोल कोर + इंस्टॉल है — बिल्ड %1$s + इंस्टॉल है — बिल्ड %1$s (अपडेट जांच विफल) + इंस्टॉल हो रहा है… + इंस्टॉल नहीं है — रेट्रो गेम खेलने के लिए डाउनलोड करें + स्थिति + कंसोल कोर अपडेट करें + अपडेट उपलब्ध — बिल्ड %1$s (%2$d MB) + डाउनलोड सत्यापित हो रहा है… + काम चल रहा है… + सिस्टम diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 99e2cf56c..fca66e2a1 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1622,6 +1622,779 @@ Percorso installato: Esegui in background Mantieni la chat attiva dopo aver chiuso WinNative Aggiorna + Retro + Trasferisci salvataggio + Importa un salvataggio locale per questo gioco o esporta il salvataggio attuale. + Importa salvataggio + Esporta salvataggio + Salvataggio importato + Impossibile importare il salvataggio + Salvataggio esportato + Impossibile esportare il salvataggio + Non esiste ancora alcun salvataggio per questo gioco + Trucchi + I trucchi sono disattivati in modalità Hardcore + + + Salva + Annulla + Salvataggio rapido + Carica salvataggio rapido + Obiettivi + Trucchi + Memory card + Avanzamento rapido + Reimposta + Cambia disco + Slot %1$d + Tocca per caricare + Vuoto + Tocca per sovrascrivere + Vuoto — tocca per salvare + Lo slot %1$d è vuoto + Slot %1$d caricato + Impossibile caricare lo slot %1$d + Salvato nello slot %1$d + Salvataggio non riuscito + • Slot 1 + • Slot 2 + • Tocca per usare + Nuova memory card + Importa card + Attiva modalità online (DEV9) + Adattatore di rete PS2 — riavvia il gioco per collegarlo + Dispositivo Ethernet + Modalità DNS + DNS primario + DNS secondario + facoltativo + IP automatico (DHCP) + Server: %1$s + tocca per impostare l\'IP (vuoto per rimuovere) + %1$s → IP + Aggiungi host server + Nuovo nome host server + es. bf2.playbattlefront.com + Comandi a schermo + Modifica layout + Reimposta layout + Layout reimpostato + Stick sinistro: inverti X + Stick sinistro: inverti Y + Stick destro: inverti X + Stick destro: inverti Y + Colore pulsanti + Colore lettere + Colore ombra + Colore sfondo + Reimposta colori + Renderer + Vulkan + OpenGL + Software + Scala risoluzione + 1x (nativa) + 1.5x + 2x + 3x + 4x + Proporzioni + Allunga + Auto (standard) + 4:3 + 16:9 + Filtro schermo + Più vicino + Bilineare (morbido) + Bilineare (nitido) + Filtro texture + Bilineare (forzato) + Bilineare (PS2) + Bilineare (sprite) + Precisione fusione + Minima + Base + Media + Alta + Completa + Massima + Shader CRT / TV + Off + Scanline + Diagonale + Triangolare + Onda + Lottes + 4xRGSS + NxAGSS + Salto fotogrammi + Off + Salta 1 + Salta 2 + Salta 3 + Mipmapping + Volume + %1$d%% + Muto + Inverti canali stereo + Frequenza cicli EE + 50% + 60% + 75% + 100% (predefinito) + 130% + 180% + 300% + Salto cicli EE + Off + 1 + 2 + 3 + VU1 istantaneo + VU multi-thread (MTVU) + CDVD rapido + FPS + Velocità emulazione + Utilizzo CPU + Utilizzo GPU + Risoluzione interna + Modalità deinterlacciamento + Auto + Off + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + Rapporto d\'aspetto FMV + Anti-sfocatura + Patch widescreen + Patch no-interlace + VU Flag Hack + Rilevamento spin INTC + Rilevamento loop di attesa + Time stretch audio + Buffer audio + Latenza di uscita + %1$d ms + Tempi dei frame + Statistiche GS + Info hardware + Versione + Visualizzazione input + Menu + Schermo + Prestazioni + HUD + Audio + Online + Comandi + Riprendi + Pausa + Esci + BIOS importato: %1$s + File BIOS non valido + Gioco retro non valido + ROM non trovata: %1$s + Impossibile leggere la ROM in questo archivio + Core non installato: %1$s + Trucchi attivati — gli obiettivi sono disattivati per questa sessione + Salvataggio cloud ripristinato + Ripristino non riuscito + Esiste un salvataggio cloud più recente per %1$s. Vuoi sincronizzare, e quale salvataggio cloud preferisci conservare? + Salvataggio cloud + Retro + Impossibile caricare il core di emulazione + Impossibile caricare la ROM + Grafica non supportata per questo core + Errore dell\'emulatore + Predefinito + CRT + LCD + Nitido + SGSR + Upscaling SGSR + Nativa + Audio + Stick sinistro: inverti X + Stick sinistro: inverti Y + Stick destro: inverti X + Stick destro: inverti Y + Comandi a schermo + Feedback aptico + Verticale + Orizzontale + Modifica layout (%1$s) + Reimposta layout %1$s + Layout %1$s reimpostato + Colore pulsanti + Colore lettere + Colore ombra + Colore sfondo + Reimposta colori + Colori reimpostati + HUD prestazioni + Alfa + Alfa sfondo + Sfondo + Scala + Frametime numerico + Batteria doppia serie + ELEMENTI HUD + FPS + Console + GPU + CPU + RAM + Batteria + Temp. + Grafico + Temp. CPU + Salvataggio rapido + Carica salvataggio rapido + Il caricamento dei salvataggi è disattivato in modalità Hardcore + Obiettivi + Trucchi + I trucchi sono disattivati in modalità Hardcore + Reimposta + Avanzamento rapido + L\'avanzamento rapido è disattivato in modalità Hardcore + HUD + Disco %1$d/%2$d + Riprendi + Pausa + Esci + Salvato nello slot %1$d + Impossibile salvare lo stato + BIOS %1$s richiesto + I giochi PlayStation richiedono un vero file BIOS di console che devi fornire. Importa un BIOS (scph5501.bin, scph5500.bin, scph5502.bin, scph1001.bin o scph7001.bin) per continuare. + Importa BIOS… + Annulla + Lo slot %1$d è vuoto + Slot %1$d caricato + Impossibile caricare lo stato + Slot %1$d + Rinomina slot %1$d + Generale + Grafica + Prestazioni + HUD + Input + Audio + Online + Annulla + Salva + Predefinito + CRT + LCD + Nitido + 2x + 4x + Nativa + GIOCO + Nome + Sistema + Core emulatore + Percorso ROM + BIOS %1$s + Installato + Nessuno — richiesto per eseguire i giochi %1$s + Importa BIOS… + Rimuovi BIOS + ILLUSTRAZIONI LIBRERIA + Immagine scheda gioco + Immagine griglia + Immagine carosello + Immagine elenco + Immagine personalizzata impostata + Imposta immagine + Rimuovi + VIDEO + Filtro video + SGSR + Upscaling SGSR + HUD prestazioni + CORE + Renderer + Vulkan + OpenGL + Software + Scala risoluzione + 1x (nativa) + 1.5x + 2x + 3x + 4x + Proporzioni + Allunga + Auto (standard) + 4:3 + 16:9 + Filtro schermo + Più vicino + Bilineare (morbido) + Bilineare (nitido) + Filtro texture + Bilineare (forzato) + Bilineare (PS2) + Bilineare (sprite) + Precisione fusione + Minima + Base + Media + Alta + Completa + Massima + Shader CRT / TV + Off + Scanline + Diagonale + Triangolare + Onda + Lottes + 4xRGSS + NxAGSS + Salto fotogrammi + Salta 1 + Salta 2 + Salta 3 + Mipmapping + PRESTAZIONI + Frequenza cicli EE + 50% + 60% + 75% + 100% (predefinito) + 130% + 180% + 300% + Salto cicli EE + 1 + 2 + 3 + VU1 istantaneo + VU multi-thread (MTVU) + CDVD rapido + HUD PRESTAZIONI + FPS + Velocità emulazione + Utilizzo CPU + Utilizzo GPU + Risoluzione interna + Modalità deinterlacciamento + Auto + Off + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + Rapporto d\'aspetto FMV + Anti-sfocatura + Patch widescreen + Patch no-interlace + VU Flag Hack + Rilevamento spin INTC + Rilevamento loop di attesa + Time stretch audio + Buffer audio + Latenza di uscita + %1$d ms + Tempi dei frame + Statistiche GS + Info hardware + Versione + Visualizzazione input + Avvio rapido + ONLINE (DEV9) + Attiva modalità online + Dispositivo Ethernet + Auto + Wi-Fi + Modalità DNS + Manuale + Interno + DNS primario + DNS secondario + facoltativo + IP automatico (DHCP) + INPUT + Comandi a schermo + Feedback aptico + AUDIO + Volume + Muto + Inverti canali stereo + Audio + IMPOSTAZIONI RETRO PREDEFINITE + Impostazioni predefinite applicate ai giochi di ogni console, salvo modifiche nelle impostazioni del singolo gioco. + RETROACHIEVEMENTS + Account + Connesso + Non connesso — apri gli Obiettivi di un gioco per accedere + Obiettivi attivati + Modalità Hardcore per impostazione predefinita (nessun salvataggio rapido) + Disconnetti + BIOS PLAYSTATION + Installato + Nessuno — i giochi PS1 richiedono un BIOS + Importa BIOS PS1… + BIOS PS1 rimosso + Nessun BIOS da rimuovere + Rimuovi BIOS PS1 + BIOS PLAYSTATION 2 + Nessuno — i giochi PS2 richiedono un BIOS + Formato + Dump unito in un singolo file (.bin con tag regione, ~4 MB). I set ROM0/MEC/NVM separati non sono accettati. + Importa BIOS PS2… + BIOS PS2 rimosso + Rimuovi BIOS PS2 + ILLUSTRAZIONI LIBRERIA + Illustrazione retro (cartuccia / custodia CD) + Copertina + Recuperata automaticamente da thumbnails.libretro.com all\'importazione; un\'immagine personalizzata la sostituisce sempre. + CARTELLA ROM + Cartella + Non impostata — scegli una cartella per importare automaticamente i giochi + Importazione automatica + I nuovi giochi in questa cartella vengono aggiunti automaticamente alla libreria con la console corretta rilevata. + Seleziona cartella ROM + Seleziona cartella ROM… + Cambia cartella ROM… + Scansiona ora + IMPOSTAZIONI CONSOLE PREDEFINITE + Tocca una console per impostare le impostazioni predefinite. + Renderer + Risoluzione upscaling + Proporzioni + Allunga + Auto (standard) + 4:3 + 16:9 + Filtro schermo + Più vicino + Bilineare (morbido) + Bilineare (nitido) + Filtro texture + Bilineare (forzato) + Bilineare (PS2) + Bilineare (sprite) + Precisione fusione + Minima + Base + Media + Alta + Completa + Massima + Shader CRT / TV + Off + Scanline + Diagonale + Triangolare + Onda + Lottes + 4xRGSS + NxAGSS + Salto fotogrammi + Salta 1 + Salta 2 + Salta 3 + Mipmapping + Frequenza cicli EE + 50% + 60% + 75% + 100% (predefinito) + 130% + 180% + 300% + Salto cicli EE + Off + 1 + 2 + 3 + VU1 istantaneo + VU multi-thread (MTVU) + CDVD rapido + Comandi touch a schermo + Audio + Inverti canali stereo + HUD: FPS + HUD: velocità emulazione + HUD: utilizzo CPU + HUD: utilizzo GPU + HUD: risoluzione interna + Attiva modalità online (DEV9) + Dispositivo Ethernet + Auto + Wi-Fi + Modalità DNS + Manuale + Interno + DNS primario + DNS secondario + facoltativo + IP automatico (DHCP) + Shader + Upscaling SGSR + HUD prestazioni + CREDITI & LICENZE + Alcune funzioni di WinNative si basano su questi progetti open source. Tocca per visualizzare ogni fonte. + Predefiniti + Crediti + Attivare la modalità Hardcore? + La modalità Hardcore reimposta il gioco ora e disattiva il caricamento dei salvataggi rapidi, l\'avanzamento rapido e i trucchi. Ogni progresso non salvato andrà perso. Continuare? + Annulla + Attiva + BIOS importato: %1$s + File BIOS non valido + BIOS PS2 importato: %1$s + File BIOS PS2 non valido + Nessun numero di serie del gioco per cercare i trucchi. + Applicati %1$d trucco/trucchi. + Impossibile applicare i trucchi. + Trucchi + Applica + Nessun trucco trovato per questo gioco. + Obiettivi + Accedi a RetroAchievements + Nome utente + Password + Accesso non riuscito + Accesso in corso… + Accedi + %1$d/%2$d • %3$d pt + Nessun obiettivo per questo gioco. + Indietro + Attivato + Disattivato + Rinomina + Salva + Conflitto salvataggio cloud + Mantieni salvataggio locale + A + Menu + Schermo + HUD + Audio + Comandi + Libreria aggiornata + ROM: %1$s + %1$d aggiunti + %1$d rimossi + Predefinito + CRT + LCD + Nitido + Nativa + Proporzioni + Filtro NTSC + Colorazione + Correzione colore + Rimuovi limite sprite + Risoluzione + Emulazione framebuffer + Dithering + Hack widescreen + 8:7 (nativa) + 4:3 (TV) + Off + RF + Composito + S-Video + RGB + Auto + Schermo GBA + Schermo GBC + On + 320x240 (nativa) + 640x480 + 960x720 + 1280x960 + 4:3 + 16:9 + 16:9 adattato + Nativa + Interna + On (16:9) + RETROACHIEVEMENTS + Accedi con il tuo account RetroAchievements per ottenere e monitorare gli obiettivi dei giochi retro. + Nome utente + Password + Inserisci nome utente e password + Accesso non riuscito + Accedi + La tua password viene usata una sola volta per ottenere un token di accesso, memorizzato in modo sicuro sul dispositivo. + Obiettivi attivati + Modalità Hardcore (nessun salvataggio rapido) + %1$d / %2$d punti + Nessun obiettivo trovato per questo gioco. + Disconnetti + TRUCCHI + Nome + Codice + Annulla + Salva + Trucco %1$d + Nessun trucco. Aggiungi un codice trucco per questo gioco. + Aggiungi trucco + + Driver GPU + Sistema (Predefinito) + Installa i driver Turnip in Impostazioni \u2192 Driver. Gli stessi driver funzionano sia per i giochi PC che PS2. + + HDD PS2 (DEV9) + Unità interna virtuale per giochi basati su HDD come Final Fantasy XI. Riavvia il gioco. + Unità interna virtuale per giochi basati su HDD come Final Fantasy XI. + Modalità DNS impostata su Internal affinché i tuoi host server personalizzati abbiano effetto. + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + Add Cheat + Cheat name + Codes (one per line, e.g. 2021A268 00000000) + Custom + Enter a name and at least one valid code + Add + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + PS2 HDD Images + A .raw HDD image, or a .zip containing one (e.g. a game’s downloaded HDD with maps/DLC) + Import HDD Image + Importing… + Imported %1$s + Could not import HDD image + Removed %1$s + Remove %1$s + HDD Image + None + Cheats + Patches + PATCH + Custom + Applied %1$d cheat(s), %2$d patch(es). + No cheats or patches found for this game. + Cheat + Patch + Add + Core CPU + Dual Core + Trucchi interni + Risoluzione interna + Renderer + Posizione della barra sensori + Salta l\'intro del BIOS + + + + + + + In basso + Interprete con cache + Hardware + Interprete + JIT + Mouse / Tocco + Stick destro (assoluto) + Stick destro (relativo) + Software + Allunga + In alto + Salto VBI (Frameskip automatico) + Widescreen + Puntatore Wiimote + Le modifiche verranno applicate al prossimo avvio di questo gioco. + Avvia questo gioco una volta per rilevare il numero di serie del disco, poi trucchi e patch appariranno qui. + Bypass autenticazione DNAS — necessario per il gioco online + Applicati automaticamente (Online) + Trucchi & Patch + Dimensione: %1$s + Importa immagine HDD + Rimuovi + Abilita NetPlay + Disattivato per impostazione predefinita. Abilitalo, poi scegli Ospita o Unisciti prima dell\'avvio.\nSi disattiva di nuovo quando esci dal gioco. + Indirizzo host + IP o nome host + Ospita sessione + On = attendi un giocatore. Off = unisciti all\'indirizzo host + NetPlay usa porte multigiocatore locali su TCP (giocatore 1 host / giocatore 2 client). L\'online PS2 usa invece Ethernet DEV9. + Porta + Memory Card %1$d + Screenshot + Usa salvataggio su cloud + LAN (IP diretto) + Connessione in corso… + Connessione + Online (codice host) + Ignora + Il NetPlay GameCube/Wii usa il motore di Dolphin. Ospita = Giocatore 1, Unisciti = Giocatore 2. Scegli Ospita o Unisciti e un tipo di connessione prima dell\'avvio; entrambi i dispositivi avviano insieme lo stesso gioco. + Condividi l\'IP Wi‑Fi del tuo dispositivo e questa porta con il Giocatore 2. Il gioco si avvia automaticamente quando si connette. + Un codice host viene mostrato all\'avvio del gioco — condividilo con il Giocatore 2. Il gioco si avvia automaticamente quando si connette. + Inserisci l\'IP Wi‑Fi e la porta dell\'host, poi avvia per connetterti. + Inserisci il codice host del Giocatore 1, poi avvia per connetterti. + Abilita NetPlay nelle impostazioni di gioco e scegli Ospita o Unisciti prima dell\'avvio + Trova stanze su Wi‑Fi + Game Link · ogni schermo è la propria console portatile + Il multigiocatore GBA usa gpSP + Wireless Adapter. Assicurati che libgpsp sia installato. + Multigiocatore a schermo condiviso su Wi‑Fi (come RetroArch).\nOspita = Giocatore 1, Unisciti = Giocatore 2. Entrambi i dispositivi mostrano lo stesso gioco. + Game Link su Wi‑Fi — ogni dispositivo esegue il proprio gioco.\nGB/GBC: collegamento seriale Gambatte (Pokémon Gen 1–2).\nGBA: gpSP Wireless Adapter (battaglie Pokémon FR/LG/Emerald). + Ospita stanza + Codice host + Codice host di traversal dall\'host + Ospitando stanza + Tocca Ospita per aprire una stanza per questa sessione di gioco, poi avvia il gioco. NetPlay si disattiva quando esci. + Nella stanza + Unisciti tramite IP + Unito + Unisciti + All\'avvio + Esci + Ospita = G1 · Unisciti = G2 · stesso gioco su entrambi gli schermi + Ospita + Unisciti + Manuale + Nessuna stanza trovata. Assicurati che l\'host sia sulla stessa rete Wi‑Fi e stia ospitando una stanza. + Nome visualizzato + Mostrato agli altri giocatori + %1$d connessi + La stanza è aperta solo per questa sessione. Avvia quando sei pronto. Uscire dal gioco disattiva NetPlay. + Giocatori + Scansiona Wi‑Fi + Scansiona di nuovo + Scansiona la stessa rete Wi‑Fi per stanze aperte, oppure unisciti tramite indirizzo IP. + Scansione Wi‑Fi… + Risultati scansione + Tocca una stanza per unirti ora (non salva l\'IP per il prossimo avvio). + Ferma scansione + NetPlay + %1$s connesso + %1$s disconnesso + In attesa di giocatori… + Il supporto per PlayStation 2 è in arrivo + Mostra pulsanti L3 / R3 + Quando disattivato, tocca due volte uno stick per premere L3 / R3 + FLAG DRIVER TURNIP + Applicati solo quando è selezionato un driver GPU personalizzato qui sopra. + File di gioco non trovato + Elimina + Importa da file… + Caricamento… + NetPlay + Wii Home + Cambia console + Identifica come console + Ora identificato come %1$s ReShade Applica un effetto ReShade (.fx) ai giochi DXVK/VKD3D (Vulkan) tramite il livello vkBasalt integrato. Metti ogni effetto in una propria cartella in Android/data/<package>/files/ReShade/. La regolazione dei parametri in tempo reale e l\'interruttore in gioco arriveranno con l\'aggiornamento del livello a ricaricamento immediato. @@ -1657,5 +2430,28 @@ Percorso installato: Abilita ReShade Nessun effetto ReShade in questa configurazione. Aggiungi effetti nelle impostazioni di questo gioco (o del contenitore) per cambiarli e regolarli qui. Questo effetto non espone parametri regolabili. + Eliminazione salvataggio… + Elimina + Eliminare definitivamente il salvataggio cloud da %1$s? L\'operazione non può essere annullata. + Elimina salvataggio cloud + Impossibile eliminare il salvataggio cloud + Salvataggio cloud eliminato + Scarica prima i core delle console — Impostazioni › Retro + Questo dispositivo non può eseguire l\'emulazione PS2: richiede OpenGL ES 3.1 o successivo. + Cerca aggiornamenti + Ricerca aggiornamenti… + Scarica i core delle console + Download… %1$d / %2$d MB + Core delle console + Installato — build %1$s + Installato — build %1$s (controllo aggiornamenti non riuscito) + Installazione… + Non installato — scaricalo per giocare ai giochi retro + Stato + Aggiorna i core delle console + Aggiornamento disponibile — build %1$s (%2$d MB) + Verifica del download… + Operazione in corso… + Sistema diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index f444592f9..c64ba1d35 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -1621,6 +1621,779 @@ フォルダの作成に失敗しました 更新 + レトロ + セーブの転送 + このゲームにローカルのセーブをインポートするか、現在のセーブをエクスポートします。 + セーブをインポート + セーブをエクスポート + セーブをインポートしました + セーブをインポートできませんでした + セーブをエクスポートしました + セーブをエクスポートできませんでした + このゲームのセーブはまだありません + チート + ハードコアモードではチートは無効です + + + 保存 + キャンセル + ステートセーブ + ステートロード + 実績 + チート + メモリーカード + 早送り + リセット + ディスク交換 + スロット %1$d + タップでロード + 空き + タップで上書き + 空き — タップで保存 + スロット %1$d は空です + スロット %1$d をロードしました + スロット %1$d をロードできませんでした + スロット %1$d に保存しました + 保存に失敗しました + • スロット 1 + • スロット 2 + • タップで使用 + 新規メモリーカード + カードをインポート + オンラインを有効化 (DEV9) + PS2 ネットワークアダプター — ゲームを再起動して接続します + イーサネットデバイス + DNS モード + プライマリ DNS + セカンダリ DNS + 任意 + 自動 IP (DHCP) + サーバー: %1$s + タップで IP を設定 (空欄で削除) + %1$s → IP + サーバーホストを追加 + 新規サーバーホスト名 + 例: bf2.playbattlefront.com + 画面上のコントロール + レイアウトを編集 + レイアウトをリセット + レイアウトをリセットしました + 左スティック: X 軸反転 + 左スティック: Y 軸反転 + 右スティック: X 軸反転 + 右スティック: Y 軸反転 + ボタンの色 + 文字の色 + 影の色 + 背景の色 + 色をリセット + レンダラー + Vulkan + OpenGL + Software + 解像度スケール + 1x (ネイティブ) + 1.5x + 2x + 3x + 4x + アスペクト比 + ストレッチ + 自動 (標準) + 4:3 + 16:9 + 表示フィルター + ニアレスト + バイリニア (スムーズ) + バイリニア (シャープ) + テクスチャフィルター + バイリニア (強制) + バイリニア (PS2) + バイリニア (スプライト) + ブレンド精度 + 最小 + 基本 + + + フル + 最大 + CRT / TV シェーダー + オフ + スキャンライン + ダイアゴナル + トライアンギュラー + ウェーブ + Lottes + 4xRGSS + NxAGSS + フレームスキップ + オフ + 1 スキップ + 2 スキップ + 3 スキップ + ミップマッピング + 音量 + %1$d%% + ミュート + ステレオチャンネルを入れ替え + EE サイクルレート + 50% + 60% + 75% + 100% (デフォルト) + 130% + 180% + 300% + EE サイクルスキップ + オフ + 1 + 2 + 3 + Instant VU1 + マルチスレッド VU (MTVU) + Fast CDVD + FPS + エミュレーション速度 + CPU 使用率 + GPU 使用率 + 内部解像度 + インターレース解除モード + 自動 + オフ + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + FMVアスペクト比 + アンチブラー + ワイドスクリーンパッチ + インターレース解除パッチ + VU Flag Hack + INTCスピン検出 + 待機ループ検出 + オーディオタイムストレッチ + オーディオバッファ + 出力レイテンシ + %1$d ms + フレームタイム + GS統計 + ハードウェア情報 + バージョン + 入力表示 + メニュー + 表示 + パフォーマンス + HUD + サウンド + オンライン + コントロール + 再開 + 一時停止 + 終了 + BIOS をインポートしました: %1$s + 無効な BIOS ファイル + 無効なレトロゲーム + ROM が見つかりません: %1$s + このアーカイブ内の ROM を読み込めませんでした + コアがインストールされていません: %1$s + チート有効 — このセッションでは実績が無効になります + クラウドセーブを復元しました + 復元に失敗しました + %1$s のより新しいクラウドセーブが存在します。同期しますか、またどのクラウドセーブを保持しますか? + クラウドセーブ + レトロ + エミュレータコアの読み込みに失敗しました + ROM の読み込みに失敗しました + このコアではグラフィックスがサポートされていません + エミュレータエラー + デフォルト + CRT + LCD + シャープ + SGSR + SGSR アップスケール + ネイティブ + サウンド + 左スティック: X 軸反転 + 左スティック: Y 軸反転 + 右スティック: X 軸反転 + 右スティック: Y 軸反転 + 画面上のコントロール + 触覚フィードバック + 縦向き + 横向き + レイアウトを編集 (%1$s) + %1$s レイアウトをリセット + %1$s レイアウトをリセットしました + ボタンの色 + 文字の色 + 影の色 + 背景の色 + 色をリセット + 色をリセットしました + パフォーマンス HUD + アルファ + 背景アルファ + 背景 + スケール + 数値フレームタイム + デュアルシリーズバッテリー + HUD 要素 + FPS + コンソール + GPU + CPU + RAM + バッテリー + 温度 + グラフ + CPU 温度 + ステートセーブ + ステートロード + ハードコアモードではステートのロードが無効です + 実績 + チート + ハードコアモードではチートが無効です + リセット + 早送り + ハードコアモードでは早送りが無効です + HUD + ディスク %1$d/%2$d + 再開 + 一時停止 + 終了 + スロット %1$d に保存しました + ステートを保存できませんでした + %1$s BIOS が必要です + PlayStation のゲームには、ユーザーが用意する必要のある実機の BIOS ファイルが必要です。続行するには BIOS (scph5501.bin、scph5500.bin、scph5502.bin、scph1001.bin または scph7001.bin) をインポートしてください。 + BIOS をインポート… + キャンセル + スロット %1$d は空です + スロット %1$d をロードしました + ステートをロードできませんでした + スロット %1$d + スロット %1$d の名前を変更 + 一般 + グラフィックス + パフォーマンス + HUD + 入力 + オーディオ + オンライン + キャンセル + 保存 + デフォルト + CRT + LCD + シャープ + 2x + 4x + ネイティブ + ゲーム + 名前 + システム + エミュレータコア + ROM パス + %1$s BIOS + インストール済み + なし — %1$s のゲームを実行するには必要です + BIOS をインポート… + BIOS を削除 + ライブラリアートワーク + ゲームカード画像 + グリッド画像 + カルーセル画像 + リスト画像 + カスタム画像を設定済み + 画像を設定 + 削除 + 映像 + 映像フィルター + SGSR + SGSR アップスケール + パフォーマンス HUD + コア + レンダラー + Vulkan + OpenGL + Software + 解像度スケール + 1x (ネイティブ) + 1.5x + 2x + 3x + 4x + アスペクト比 + ストレッチ + 自動 (標準) + 4:3 + 16:9 + 表示フィルター + ニアレスト + バイリニア (スムーズ) + バイリニア (シャープ) + テクスチャフィルター + バイリニア (強制) + バイリニア (PS2) + バイリニア (スプライト) + ブレンド精度 + 最小 + 基本 + + + フル + 最大 + CRT / TV シェーダー + オフ + スキャンライン + ダイアゴナル + トライアンギュラー + ウェーブ + Lottes + 4xRGSS + NxAGSS + フレームスキップ + 1 スキップ + 2 スキップ + 3 スキップ + ミップマッピング + パフォーマンス + EE サイクルレート + 50% + 60% + 75% + 100% (デフォルト) + 130% + 180% + 300% + EE サイクルスキップ + 1 + 2 + 3 + Instant VU1 + マルチスレッド VU (MTVU) + Fast CDVD + パフォーマンス HUD + FPS + エミュレーション速度 + CPU 使用率 + GPU 使用率 + 内部解像度 + インターレース解除モード + 自動 + オフ + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + FMVアスペクト比 + アンチブラー + ワイドスクリーンパッチ + インターレース解除パッチ + VU Flag Hack + INTCスピン検出 + 待機ループ検出 + オーディオタイムストレッチ + オーディオバッファ + 出力レイテンシ + %1$d ms + フレームタイム + GS統計 + ハードウェア情報 + バージョン + 入力表示 + 高速起動 + オンライン (DEV9) + オンラインを有効化 + イーサネットデバイス + 自動 + Wi-Fi + DNS モード + 手動 + 内部 + プライマリ DNS + セカンダリ DNS + 任意 + 自動 IP (DHCP) + 入力 + 画面上のコントロール + 触覚フィードバック + オーディオ + 音量 + ミュート + ステレオチャンネルを入れ替え + サウンド + レトロデフォルト + 各ゲーム独自の設定で上書きされない限り、各コンソールのゲームに適用されるデフォルト設定です。 + RETROACHIEVEMENTS + アカウント + サインイン済み + サインインしていません — ゲームの実績を開いてサインインしてください + 実績を有効化 + デフォルトでハードコアモード (ステートセーブなし) + サインアウト + PLAYSTATION BIOS + インストール済み + なし — PS1 のゲームには BIOS が必要です + PS1 BIOS をインポート… + PS1 BIOS を削除しました + 削除する BIOS がありません + PS1 BIOS を削除 + PLAYSTATION 2 BIOS + なし — PS2 のゲームには BIOS が必要です + 形式 + 単一ファイルに統合されたダンプ (地域タグ付き .bin、約 4MB)。分割された ROM0/MEC/NVM セットは使用できません。 + PS2 BIOS をインポート… + PS2 BIOS を削除しました + PS2 BIOS を削除 + ライブラリアートワーク + レトロケースアート (カートリッジ / CD ケース) + ボックスアート + インポート時に thumbnails.libretro.com から自動的に取得されます。カスタム画像は常にこれを上書きします。 + ROMS フォルダー + フォルダー + 未設定 — フォルダーを選択してゲームを自動インポート + 自動インポート + このフォルダー内の新しいゲームは、適切なコンソールが検出された状態で自動的にライブラリに追加されます。 + ROMs フォルダーを選択 + ROMs フォルダーを選択… + ROMs フォルダーを変更… + 今すぐスキャン + コンソールデフォルト + コンソールをタップしてデフォルト設定を行います。 + レンダラー + 解像度をアップスケール + アスペクト比 + ストレッチ + 自動 (標準) + 4:3 + 16:9 + 表示フィルター + ニアレスト + バイリニア (スムーズ) + バイリニア (シャープ) + テクスチャフィルター + バイリニア (強制) + バイリニア (PS2) + バイリニア (スプライト) + ブレンド精度 + 最小 + 基本 + + + フル + 最大 + CRT / TV シェーダー + オフ + スキャンライン + ダイアゴナル + トライアンギュラー + ウェーブ + Lottes + 4xRGSS + NxAGSS + フレームスキップ + 1 スキップ + 2 スキップ + 3 スキップ + ミップマッピング + EE サイクルレート + 50% + 60% + 75% + 100% (デフォルト) + 130% + 180% + 300% + EE サイクルスキップ + オフ + 1 + 2 + 3 + Instant VU1 + マルチスレッド VU (MTVU) + Fast CDVD + 画面上のタッチコントロール + サウンド + ステレオチャンネルを入れ替え + HUD: FPS + HUD: エミュレーション速度 + HUD: CPU 使用率 + HUD: GPU 使用率 + HUD: 内部解像度 + オンラインを有効化 (DEV9) + イーサネットデバイス + 自動 + Wi-Fi + DNS モード + 手動 + 内部 + プライマリ DNS + セカンダリ DNS + 任意 + 自動 IP (DHCP) + シェーダー + SGSR アップスケーリング + パフォーマンス HUD + クレジット & ライセンス + WinNative の一部の機能はこれらのオープンソースプロジェクトを基盤としています。タップして各ソースを表示します。 + デフォルト + クレジット + ハードコアモードを有効にしますか? + ハードコアモードは今すぐゲームをリセットし、ステートセーブのロード、早送り、チートを無効にします。保存していない進行状況は失われます。続行しますか? + キャンセル + 有効化 + BIOS をインポートしました: %1$s + 無効な BIOS ファイル + PS2 BIOS をインポートしました: %1$s + 無効な PS2 BIOS ファイル + チートを検索するゲームシリアルがありません。 + %1$d 件のチートを適用しました。 + チートを適用できませんでした。 + チート + 適用 + このゲームのチートが見つかりません。 + 実績 + RetroAchievements にサインイン + ユーザー名 + パスワード + ログインに失敗しました + サインインしています… + サインイン + %1$d/%2$d • %3$d pts + このゲームの実績はありません。 + 戻る + 有効 + 無効 + 名前を変更 + 保存 + クラウドセーブの競合 + ローカルセーブを保持 + A + メニュー + 表示 + HUD + サウンド + コントロール + ライブラリは最新です + ROM: %1$s + %1$d 件追加 + %1$d 件削除 + デフォルト + CRT + LCD + シャープ + ネイティブ + アスペクト比 + NTSC フィルター + カラー化 + 色補正 + スプライト制限を解除 + 解像度 + フレームバッファエミュレーション + ディザリング + ワイドスクリーンハック + 8:7 (ネイティブ) + 4:3 (TV) + オフ + RF + コンポジット + S-Video + RGB + 自動 + GBA スクリーン + GBC スクリーン + オン + 320x240 (ネイティブ) + 640x480 + 960x720 + 1280x960 + 4:3 + 16:9 + 16:9 調整済み + ネイティブ + 内部 + オン (16:9) + RETROACHIEVEMENTS + RetroAchievements アカウントでサインインして、レトロゲームの実績を獲得・追跡しましょう。 + ユーザー名 + パスワード + ユーザー名とパスワードを入力してください + ログインに失敗しました + サインイン + パスワードはログイントークンの取得に一度だけ使用され、デバイス上に安全に保存されます。 + 実績を有効化 + ハードコアモード (ステートセーブなし) + %1$d / %2$d ポイント + このゲームの実績が見つかりません。 + サインアウト + チート + 名前 + コード + キャンセル + 保存 + チート %1$d + チートはまだありません。このゲームのチートコードを追加してください。 + チートを追加 + + GPUドライバー + システム(デフォルト) + Turnipドライバーは設定 \u2192 ドライバーからインストールします。同じドライバーがPCとPS2の両方のゲームで動作します。 + + PS2 HDD (DEV9) + Final Fantasy XI などの HDD ベースのゲーム用の仮想内蔵ドライブ。ゲームを再起動します。 + Final Fantasy XI などの HDD ベースのゲーム用の仮想内蔵ドライブ。 + カスタムサーバーホストを有効にするため、DNS モードを Internal に設定しました。 + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + Add Cheat + Cheat name + Codes (one per line, e.g. 2021A268 00000000) + Custom + Enter a name and at least one valid code + Add + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + PS2 HDD Images + A .raw HDD image, or a .zip containing one (e.g. a game’s downloaded HDD with maps/DLC) + Import HDD Image + Importing… + Imported %1$s + Could not import HDD image + Removed %1$s + Remove %1$s + HDD Image + None + Cheats + Patches + PATCH + Custom + Applied %1$d cheat(s), %2$d patch(es). + No cheats or patches found for this game. + Cheat + Patch + Add + CPU コア + デュアルコア + 内部チート + 内部解像度 + レンダラー + センサーバーの位置 + BIOS イントロをスキップ + + + + + + + + キャッシュ付きインタプリタ + ハードウェア + インタプリタ + JIT + マウス / タッチ + 右スティック (絶対) + 右スティック (相対) + ソフトウェア + 引き伸ばし + + VBI スキップ (自動フレームスキップ) + ワイドスクリーン + Wiimote ポインター + 変更は次回このゲームを起動したときに適用されます。 + このゲームを一度起動するとディスクのシリアルが検出され、チートとパッチがここに表示されます。 + DNAS 認証バイパス — オンラインプレイに必要 + 自動適用 (オンライン) + チート & パッチ + サイズ: %1$s + HDD イメージをインポート + 削除 + NetPlay を有効化 + デフォルトはオフです。有効にしてから、起動前にホストまたは参加を選択してください。\nゲームを終了すると再びオフになります。 + ホストアドレス + IP またはホスト名 + ホストセッション + オン = プレイヤーを待つ。オフ = ホストアドレスに参加 + NetPlay は TCP 経由のローカルマルチプレイヤーポートを使用します (プレイヤー 1 がホスト / プレイヤー 2 がクライアント)。PS2 オンラインは代わりに DEV9 イーサネットを使用します。 + ポート + メモリーカード %1$d + スクリーンショット + クラウドセーブを使用 + LAN (直接 IP) + 接続中… + 接続 + オンライン (ホストコード) + 閉じる + GameCube/Wii の NetPlay は Dolphin 独自のエンジンを使用します。ホスト = プレイヤー 1、参加 = プレイヤー 2。起動前にホストまたは参加と接続タイプを選択してください。両方のデバイスが同じゲームを一緒に起動します。 + デバイスの Wi‑Fi IP とこのポートをプレイヤー 2 と共有してください。相手が接続すると自動的にゲームが開始します。 + ゲーム起動時にホストコードが表示されます — プレイヤー 2 と共有してください。相手が接続すると自動的にゲームが開始します。 + ホストの Wi‑Fi IP とポートを入力してから、起動して接続してください。 + プレイヤー 1 のホストコードを入力してから、起動して接続してください。 + ゲーム設定で NetPlay を有効にし、起動前にホストまたは参加を選択してください + Wi‑Fi 上のルームを探す + Game Link · 各画面がそれぞれの携帯機です + GBA マルチプレイヤーは gpSP + ワイヤレスアダプターを使用します。libgpsp がインストールされていることを確認してください。 + Wi‑Fi 経由の画面共有マルチプレイヤー (RetroArch と同様)。\nホスト = プレイヤー 1、参加 = プレイヤー 2。両方のデバイスに同じゲームが表示されます。 + Wi‑Fi 経由の Game Link — 各デバイスがそれぞれのゲームを実行します。\nGB/GBC: Gambatte シリアルリンク (Pokémon 第 1〜2 世代)。\nGBA: gpSP ワイヤレスアダプター (Pokémon FR/LG/エメラルドのバトル)。 + ルームをホスト + ホストコード + ホストからのトラバーサルホストコード + ルームをホスト中 + ホストをタップしてこのプレイセッション用のルームを開き、ゲームを起動してください。NetPlay は終了時にオフになります。 + ルーム内 + IP で参加 + 参加しました + 参加 + 起動時 + 退出 + ホスト = P1 · 参加 = P2 · 両方の画面に同じゲーム + ホスト + 参加 + 手動 + ルームが見つかりません。ホストが同じ Wi‑Fi に接続しており、ルームをホストしていることを確認してください。 + 表示名 + 他のプレイヤーに表示されます + %1$d 人接続中 + ルームはこのセッションのみ有効です。準備ができたら起動してください。ゲームを終了すると NetPlay がオフになります。 + プレイヤー + Wi‑Fi をスキャン + 再スキャン + 同じ Wi‑Fi で開いているルームをスキャンするか、IP アドレスで参加してください。 + Wi‑Fi をスキャン中… + スキャン結果 + ルームをタップすると今すぐ参加できます (次回起動用に IP は保存されません)。 + スキャンを停止 + NetPlay + %1$s が接続しました + %1$s が切断しました + プレイヤーを待っています… + PlayStation 2 のサポートは近日公開予定です + L3 / R3 ボタンを表示 + オフの場合、スティックをダブルタップすると L3 / R3 をクリックできます + TURNIP ドライバーフラグ + 上で選択したカスタム GPU ドライバーが選択されている場合にのみ適用されます。 + ゲームファイルが見つかりません + 削除 + ファイルからインポート… + 読み込み中… + NetPlay + Wii Home + コンソールを変更 + コンソールとして識別 + 現在 %1$s として識別されています ReShade 内蔵の vkBasalt レイヤーを介して DXVK/VKD3D(Vulkan)ゲームに ReShade エフェクト(.fx)を適用します。各エフェクトを Android/data/<package>/files/ReShade/ 以下の専用フォルダーに配置してください。ライブパラメーター調整とゲーム内トグルは、ライブリロードレイヤーの更新で提供されます。 @@ -1656,4 +2429,27 @@ ReShade を有効にする このロードアウトには ReShade エフェクトがありません。ここで切り替えたり調整したりするには、このゲームの設定(またはコンテナの設定)でエフェクトを追加してください。 このエフェクトには調整可能なパラメーターがありません。 + セーブデータを削除中… + 削除 + %1$s のクラウドセーブを完全に削除しますか?この操作は取り消せません。 + クラウドセーブを削除 + クラウドセーブを削除できませんでした + クラウドセーブを削除しました + 先にコンソールコアをダウンロードしてください — 設定 › レトロ + このデバイスでは PS2 エミュレーションを実行できません。OpenGL ES 3.1 以降が必要です。 + 更新を確認 + 更新を確認中… + コンソールコアをダウンロード + ダウンロード中… %1$d / %2$d MB + コンソールコア + インストール済み — ビルド %1$s + インストール済み — ビルド %1$s(更新の確認に失敗) + インストール中… + 未インストール — ダウンロードするとレトロゲームをプレイできます + 状態 + コンソールコアを更新 + 更新があります — ビルド %1$s(%2$d MB) + ダウンロードを検証中… + 処理中… + システム diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 3d9dd0d1c..3d8bd4e16 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -1623,6 +1623,779 @@ 백그라운드에서 실행 WinNative를 종료한 후에도 채팅 유지 새로고침 + 레트로 + 세이브 전송 + 이 게임에 로컬 세이브 파일을 가져오거나 현재 세이브를 내보냅니다. + 세이브 가져오기 + 세이브 내보내기 + 세이브를 가져왔습니다 + 세이브를 가져올 수 없습니다 + 세이브를 내보냈습니다 + 세이브를 내보낼 수 없습니다 + 이 게임에는 아직 세이브가 없습니다 + 치트 + 하드코어 모드에서는 치트를 사용할 수 없습니다 + + + 저장 + 취소 + 상태 저장 + 상태 불러오기 + 도전 과제 + 치트 + 메모리 카드 + 빨리 감기 + 재설정 + 디스크 교체 + 슬롯 %1$d + 탭하여 불러오기 + 비어 있음 + 탭하여 덮어쓰기 + 비어 있음 — 탭하여 저장 + 슬롯 %1$d 이(가) 비어 있습니다 + 슬롯 %1$d 을(를) 불러왔습니다 + 슬롯 %1$d 을(를) 불러올 수 없습니다 + 슬롯 %1$d 에 저장했습니다 + 저장에 실패했습니다 + • 슬롯 1 + • 슬롯 2 + • 탭하여 사용 + 새 메모리 카드 + 카드 가져오기 + 온라인 사용 (DEV9) + PS2 네트워크 어댑터 — 게임을 다시 시작하여 연결합니다 + 이더넷 장치 + DNS 모드 + 기본 DNS + 보조 DNS + 선택 사항 + 자동 IP (DHCP) + 서버: %1$s + 탭하여 IP 설정 (비우면 삭제) + %1$s → IP + 서버 호스트 추가 + 새 서버 호스트 이름 + 예: bf2.playbattlefront.com + 화면 컨트롤 + 레이아웃 편집 + 레이아웃 재설정 + 레이아웃을 재설정했습니다 + 왼쪽 스틱: X축 반전 + 왼쪽 스틱: Y축 반전 + 오른쪽 스틱: X축 반전 + 오른쪽 스틱: Y축 반전 + 버튼 색상 + 글자 색상 + 그림자 색상 + 배경 색상 + 색상 재설정 + 렌더러 + Vulkan + OpenGL + Software + 해상도 스케일 + 1x (네이티브) + 1.5x + 2x + 3x + 4x + 화면 비율 + 늘이기 + 자동 (표준) + 4:3 + 16:9 + 디스플레이 필터 + 니어리스트 + 바이리니어 (부드럽게) + 바이리니어 (선명하게) + 텍스처 필터 + 바이리니어 (강제) + 바이리니어 (PS2) + 바이리니어 (스프라이트) + 블렌딩 정확도 + 최소 + 기본 + 중간 + 높음 + 전체 + 최대 + CRT / TV 셰이더 + + 스캔라인 + 대각선 + 삼각형 + 웨이브 + Lottes + 4xRGSS + NxAGSS + 프레임 스킵 + + 1 스킵 + 2 스킵 + 3 스킵 + 밉매핑 + 볼륨 + %1$d%% + 음소거 + 스테레오 채널 교체 + EE 사이클 레이트 + 50% + 60% + 75% + 100% (기본값) + 130% + 180% + 300% + EE 사이클 스킵 + + 1 + 2 + 3 + Instant VU1 + 멀티 스레드 VU (MTVU) + Fast CDVD + FPS + 에뮬레이션 속도 + CPU 사용량 + GPU 사용량 + 내부 해상도 + 디인터레이스 모드 + 자동 + + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + FMV 화면비 + 안티 블러 + 와이드스크린 패치 + 노 인터레이스 패치 + VU Flag Hack + INTC 스핀 감지 + 대기 루프 감지 + 오디오 타임 스트레치 + 오디오 버퍼 + 출력 지연 시간 + %1$d ms + 프레임 시간 + GS 통계 + 하드웨어 정보 + 버전 + 입력 표시 + 메뉴 + 디스플레이 + 성능 + HUD + 사운드 + 온라인 + 컨트롤 + 계속하기 + 일시정지 + 종료 + BIOS 가져옴: %1$s + 잘못된 BIOS 파일 + 잘못된 레트로 게임 + ROM 을 찾을 수 없음: %1$s + 이 아카이브 안의 ROM 을 읽을 수 없습니다 + 코어가 설치되지 않음: %1$s + 치트 사용 — 이 세션에서는 도전 과제가 비활성화됩니다 + 클라우드 저장을 복원했습니다 + 복원에 실패했습니다 + %1$s 에 더 최신 클라우드 저장이 있습니다. 동기화하시겠습니까? 어느 클라우드 저장을 유지하시겠습니까? + 클라우드 저장 + 레트로 + 에뮬레이터 코어를 불러오지 못했습니다 + ROM 을 불러오지 못했습니다 + 이 코어에서는 그래픽이 지원되지 않습니다 + 에뮬레이터 오류 + 기본값 + CRT + LCD + 선명하게 + SGSR + SGSR 업스케일 + 네이티브 + 사운드 + 왼쪽 스틱: X축 반전 + 왼쪽 스틱: Y축 반전 + 오른쪽 스틱: X축 반전 + 오른쪽 스틱: Y축 반전 + 화면 컨트롤 + 햅틱 피드백 + 세로 모드 + 가로 모드 + 레이아웃 편집 (%1$s) + %1$s 레이아웃 재설정 + %1$s 레이아웃을 재설정했습니다 + 버튼 색상 + 글자 색상 + 그림자 색상 + 배경 색상 + 색상 재설정 + 색상을 재설정했습니다 + 성능 HUD + 알파 + 배경 알파 + 배경 + 스케일 + 숫자 프레임타임 + 듀얼 시리즈 배터리 + HUD 요소 + FPS + 콘솔 + GPU + CPU + RAM + 배터리 + 온도 + 그래프 + CPU 온도 + 상태 저장 + 상태 불러오기 + 하드코어 모드에서는 상태 불러오기가 비활성화됩니다 + 도전 과제 + 치트 + 하드코어 모드에서는 치트가 비활성화됩니다 + 재설정 + 빨리 감기 + 하드코어 모드에서는 빨리 감기가 비활성화됩니다 + HUD + 디스크 %1$d/%2$d + 계속하기 + 일시정지 + 종료 + 슬롯 %1$d 에 저장했습니다 + 상태를 저장할 수 없습니다 + %1$s BIOS 필요 + PlayStation 게임에는 사용자가 직접 준비해야 하는 실제 콘솔 BIOS 파일이 필요합니다. 계속하려면 BIOS (scph5501.bin, scph5500.bin, scph5502.bin, scph1001.bin 또는 scph7001.bin) 를 가져오세요. + BIOS 가져오기… + 취소 + 슬롯 %1$d 이(가) 비어 있습니다 + 슬롯 %1$d 을(를) 불러왔습니다 + 상태를 불러올 수 없습니다 + 슬롯 %1$d + 슬롯 %1$d 이름 변경 + 일반 + 그래픽 + 성능 + HUD + 입력 + 오디오 + 온라인 + 취소 + 저장 + 기본값 + CRT + LCD + 선명하게 + 2x + 4x + 네이티브 + 게임 + 이름 + 시스템 + 에뮬레이터 코어 + ROM 경로 + %1$s BIOS + 설치됨 + 없음 — %1$s 게임을 실행하려면 필요합니다 + BIOS 가져오기… + BIOS 제거 + 라이브러리 아트워크 + 게임 카드 이미지 + 그리드 이미지 + 캐러셀 이미지 + 목록 이미지 + 사용자 지정 이미지 설정됨 + 이미지 설정 + 제거 + 비디오 + 비디오 필터 + SGSR + SGSR 업스케일 + 성능 HUD + 코어 + 렌더러 + Vulkan + OpenGL + Software + 해상도 스케일 + 1x (네이티브) + 1.5x + 2x + 3x + 4x + 화면 비율 + 늘이기 + 자동 (표준) + 4:3 + 16:9 + 디스플레이 필터 + 니어리스트 + 바이리니어 (부드럽게) + 바이리니어 (선명하게) + 텍스처 필터 + 바이리니어 (강제) + 바이리니어 (PS2) + 바이리니어 (스프라이트) + 블렌딩 정확도 + 최소 + 기본 + 중간 + 높음 + 전체 + 최대 + CRT / TV 셰이더 + + 스캔라인 + 대각선 + 삼각형 + 웨이브 + Lottes + 4xRGSS + NxAGSS + 프레임 스킵 + 1 스킵 + 2 스킵 + 3 스킵 + 밉매핑 + 성능 + EE 사이클 레이트 + 50% + 60% + 75% + 100% (기본값) + 130% + 180% + 300% + EE 사이클 스킵 + 1 + 2 + 3 + Instant VU1 + 멀티 스레드 VU (MTVU) + Fast CDVD + 성능 HUD + FPS + 에뮬레이션 속도 + CPU 사용량 + GPU 사용량 + 내부 해상도 + 디인터레이스 모드 + 자동 + + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + FMV 화면비 + 안티 블러 + 와이드스크린 패치 + 노 인터레이스 패치 + VU Flag Hack + INTC 스핀 감지 + 대기 루프 감지 + 오디오 타임 스트레치 + 오디오 버퍼 + 출력 지연 시간 + %1$d ms + 프레임 시간 + GS 통계 + 하드웨어 정보 + 버전 + 입력 표시 + 빠른 부팅 + 온라인 (DEV9) + 온라인 사용 + 이더넷 장치 + 자동 + Wi-Fi + DNS 모드 + 수동 + 내부 + 기본 DNS + 보조 DNS + 선택 사항 + 자동 IP (DHCP) + 입력 + 화면 컨트롤 + 햅틱 피드백 + 오디오 + 볼륨 + 음소거 + 스테레오 채널 교체 + 사운드 + 레트로 기본값 + 게임 자체 설정에서 재정의하지 않는 한 각 콘솔의 게임에 적용되는 기본값입니다. + RETROACHIEVEMENTS + 계정 + 로그인됨 + 로그인하지 않음 — 게임의 도전 과제를 열어 로그인하세요 + 도전 과제 사용 + 기본적으로 하드코어 모드 (상태 저장 없음) + 로그아웃 + PLAYSTATION BIOS + 설치됨 + 없음 — PS1 게임에는 BIOS 가 필요합니다 + PS1 BIOS 가져오기… + PS1 BIOS 를 제거했습니다 + 제거할 BIOS 가 없습니다 + PS1 BIOS 제거 + PLAYSTATION 2 BIOS + 없음 — PS2 게임에는 BIOS 가 필요합니다 + 형식 + 단일 파일로 병합된 덤프 (지역 태그가 있는 .bin, 약 4MB). 분할된 ROM0/MEC/NVM 세트는 허용되지 않습니다. + PS2 BIOS 가져오기… + PS2 BIOS 를 제거했습니다 + PS2 BIOS 제거 + 라이브러리 아트워크 + 레트로 케이스 아트 (카트리지 / CD 케이스) + 박스 아트 + 가져올 때 thumbnails.libretro.com 에서 자동으로 가져옵니다. 사용자 지정 이미지는 항상 이를 재정의합니다. + ROMS 폴더 + 폴더 + 설정되지 않음 — 폴더를 선택하여 게임을 자동으로 가져오기 + 자동 가져오기 + 이 폴더의 새 게임은 올바른 콘솔이 감지된 상태로 라이브러리에 자동으로 추가됩니다. + ROMs 폴더 선택 + ROMs 폴더 선택… + ROMs 폴더 변경… + 지금 스캔 + 콘솔 기본값 + 콘솔을 탭하여 기본 설정을 지정하세요. + 렌더러 + 해상도 업스케일 + 화면 비율 + 늘이기 + 자동 (표준) + 4:3 + 16:9 + 디스플레이 필터 + 니어리스트 + 바이리니어 (부드럽게) + 바이리니어 (선명하게) + 텍스처 필터 + 바이리니어 (강제) + 바이리니어 (PS2) + 바이리니어 (스프라이트) + 블렌딩 정확도 + 최소 + 기본 + 중간 + 높음 + 전체 + 최대 + CRT / TV 셰이더 + + 스캔라인 + 대각선 + 삼각형 + 웨이브 + Lottes + 4xRGSS + NxAGSS + 프레임 스킵 + 1 스킵 + 2 스킵 + 3 스킵 + 밉매핑 + EE 사이클 레이트 + 50% + 60% + 75% + 100% (기본값) + 130% + 180% + 300% + EE 사이클 스킵 + + 1 + 2 + 3 + Instant VU1 + 멀티 스레드 VU (MTVU) + Fast CDVD + 화면 터치 컨트롤 + 사운드 + 스테레오 채널 교체 + HUD: FPS + HUD: 에뮬레이션 속도 + HUD: CPU 사용량 + HUD: GPU 사용량 + HUD: 내부 해상도 + 온라인 사용 (DEV9) + 이더넷 장치 + 자동 + Wi-Fi + DNS 모드 + 수동 + 내부 + 기본 DNS + 보조 DNS + 선택 사항 + 자동 IP (DHCP) + 셰이더 + SGSR 업스케일링 + 성능 HUD + 크레딧 & 라이선스 + WinNative의 일부 기능은 이러한 오픈 소스 프로젝트를 기반으로 합니다. 탭하여 각 소스를 확인하세요. + 기본값 + 크레딧 + 하드코어 모드를 사용하시겠습니까? + 하드코어 모드는 지금 게임을 재설정하고 상태 저장 불러오기, 빨리 감기, 치트를 비활성화합니다. 저장하지 않은 진행 상황은 손실됩니다. 계속하시겠습니까? + 취소 + 사용 + BIOS 가져옴: %1$s + 잘못된 BIOS 파일 + PS2 BIOS 가져옴: %1$s + 잘못된 PS2 BIOS 파일 + 치트를 검색할 게임 시리얼이 없습니다. + 치트 %1$d 개를 적용했습니다. + 치트를 적용할 수 없습니다. + 치트 + 적용 + 이 게임의 치트를 찾을 수 없습니다. + 도전 과제 + RetroAchievements 에 로그인 + 사용자 이름 + 비밀번호 + 로그인에 실패했습니다 + 로그인 중… + 로그인 + %1$d/%2$d • %3$d pts + 이 게임의 도전 과제가 없습니다. + 뒤로 + 사용 + 사용 안 함 + 이름 변경 + 저장 + 클라우드 저장 충돌 + 로컬 저장 유지 + A + 메뉴 + 디스플레이 + HUD + 사운드 + 컨트롤 + 라이브러리가 최신 상태입니다 + ROM: %1$s + %1$d 개 추가됨 + %1$d 개 제거됨 + 기본값 + CRT + LCD + 선명하게 + 네이티브 + 화면 비율 + NTSC 필터 + 색상화 + 색 보정 + 스프라이트 제한 해제 + 해상도 + 프레임버퍼 에뮬레이션 + 디더링 + 와이드스크린 핵 + 8:7 (네이티브) + 4:3 (TV) + + RF + 컴포지트 + S-Video + RGB + 자동 + GBA 화면 + GBC 화면 + + 320x240 (네이티브) + 640x480 + 960x720 + 1280x960 + 4:3 + 16:9 + 16:9 조정됨 + 네이티브 + 내부 + 켬 (16:9) + RETROACHIEVEMENTS + RetroAchievements 계정으로 로그인하여 레트로 게임의 도전 과제를 획득하고 추적하세요. + 사용자 이름 + 비밀번호 + 사용자 이름과 비밀번호를 입력하세요 + 로그인에 실패했습니다 + 로그인 + 비밀번호는 로그인 토큰을 얻기 위해 한 번만 사용되며, 기기에 안전하게 저장됩니다. + 도전 과제 사용 + 하드코어 모드 (상태 저장 없음) + %1$d / %2$d 포인트 + 이 게임의 도전 과제를 찾을 수 없습니다. + 로그아웃 + 치트 + 이름 + 코드 + 취소 + 저장 + 치트 %1$d + 아직 치트가 없습니다. 이 게임의 치트 코드를 추가하세요. + 치트 추가 + + GPU 드라이버 + 시스템(기본값) + 설정 \u2192 드라이버에서 Turnip 드라이버를 설치하세요. 동일한 드라이버가 PC와 PS2 게임 모두에서 작동합니다. + + PS2 HDD (DEV9) + Final Fantasy XI 같은 HDD 기반 게임용 가상 내장 드라이브. 게임을 다시 시작합니다. + Final Fantasy XI 같은 HDD 기반 게임용 가상 내장 드라이브. + 사용자 지정 서버 호스트가 적용되도록 DNS 모드를 Internal로 설정했습니다. + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + Add Cheat + Cheat name + Codes (one per line, e.g. 2021A268 00000000) + Custom + Enter a name and at least one valid code + Add + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + PS2 HDD Images + A .raw HDD image, or a .zip containing one (e.g. a game’s downloaded HDD with maps/DLC) + Import HDD Image + Importing… + Imported %1$s + Could not import HDD image + Removed %1$s + Remove %1$s + HDD Image + None + Cheats + Patches + PATCH + Custom + Applied %1$d cheat(s), %2$d patch(es). + No cheats or patches found for this game. + Cheat + Patch + Add + CPU 코어 + 듀얼 코어 + 내장 치트 + 내부 해상도 + 렌더러 + 센서 바 위치 + BIOS 인트로 건너뛰기 + + + + + + + 아래 + 캐시된 인터프리터 + 하드웨어 + 인터프리터 + JIT + 마우스 / 터치 + 오른쪽 스틱 (절대) + 오른쪽 스틱 (상대) + 소프트웨어 + 늘이기 + + VBI 건너뛰기 (자동 프레임 스킵) + 와이드스크린 + Wiimote 포인터 + 변경 사항은 다음에 이 게임을 실행할 때 적용됩니다. + 이 게임을 한 번 실행하면 디스크 시리얼이 감지되며, 그 후 치트와 패치가 여기에 표시됩니다. + DNAS 인증 우회 — 온라인 플레이에 필요 + 자동 적용 (온라인) + 치트 & 패치 + 크기: %1$s + HDD 이미지 가져오기 + 제거 + NetPlay 사용 + 기본적으로 꺼져 있습니다. 사용을 켠 다음 실행 전에 Host 또는 Join을 선택하세요.\n게임을 종료하면 다시 꺼집니다. + Host 주소 + IP 또는 호스트 이름 + Host 세션 + 켜짐 = 플레이어 대기. 꺼짐 = host 주소로 접속 + NetPlay는 TCP를 통해 로컬 멀티플레이 포트를 사용합니다 (플레이어 1 host / 플레이어 2 클라이언트). PS2 온라인은 대신 DEV9 이더넷을 사용합니다. + Port + 메모리 카드 %1$d + 스크린샷 + 클라우드 저장 사용 + LAN (직접 IP) + 연결 중… + 연결 + 온라인 (host 코드) + 닫기 + GameCube/Wii NetPlay는 Dolphin 자체 엔진을 사용합니다. Host = 플레이어 1, Join = 플레이어 2. 실행 전에 Host 또는 Join과 연결 유형을 선택하세요. 두 기기가 함께 같은 게임을 부팅합니다. + 기기의 Wi‑Fi IP와 이 port를 플레이어 2와 공유하세요. 상대가 연결하면 게임이 자동으로 시작됩니다. + 게임이 부팅되면 host 코드가 표시됩니다 — 플레이어 2와 공유하세요. 상대가 연결하면 게임이 자동으로 시작됩니다. + host의 Wi‑Fi IP와 port를 입력한 다음 실행하여 연결하세요. + 플레이어 1의 host 코드를 입력한 다음 실행하여 연결하세요. + 게임 설정에서 NetPlay를 사용으로 설정하고 실행 전에 Host 또는 Join을 선택하세요 + Wi‑Fi에서 방 찾기 + Game Link · 각 화면은 독립된 휴대용 기기입니다 + GBA 멀티플레이는 gpSP + Wireless Adapter를 사용합니다. libgpsp가 설치되어 있는지 확인하세요. + Wi‑Fi를 통한 화면 공유 멀티플레이 (RetroArch와 유사).\nHost = 플레이어 1, Join = 플레이어 2. 두 기기가 같은 게임을 표시합니다. + Wi‑Fi를 통한 Game Link — 각 기기가 자체 게임을 실행합니다.\nGB/GBC: Gambatte 시리얼 링크 (Pokémon 1–2세대).\nGBA: gpSP Wireless Adapter (Pokémon FR/LG/Emerald 배틀). + 방 호스팅 + Host 코드 + host의 트래버설 host 코드 + 방 호스팅 중 + Host를 눌러 이 플레이 세션용 방을 연 다음 게임을 실행하세요. 종료하면 NetPlay가 꺼집니다. + 방에 있음 + IP로 참가 + 참가함 + Join + 실행 시 + 나가기 + Host = P1 · Join = P2 · 두 화면에 같은 게임 + Host + Join + 수동 + 방을 찾을 수 없습니다. host가 같은 Wi‑Fi에 있고 방을 호스팅 중인지 확인하세요. + 표시 이름 + 다른 플레이어에게 표시됨 + %1$d명 연결됨 + 방은 이 세션 동안에만 열려 있습니다. 준비되면 실행하세요. 게임을 종료하면 NetPlay가 꺼집니다. + 플레이어 + Wi‑Fi 스캔 + 다시 스캔 + 같은 Wi‑Fi에서 열린 방을 스캔하거나 IP 주소로 참가하세요. + Wi‑Fi 스캔 중… + 스캔 결과 + 방을 눌러 지금 참가하세요 (다음 실행을 위해 IP를 저장하지 않습니다). + 스캔 중지 + NetPlay + %1$s 연결됨 + %1$s 연결 끊김 + 플레이어 대기 중… + PlayStation 2 지원이 곧 제공됩니다 + L3 / R3 버튼 표시 + 꺼져 있으면 스틱을 두 번 눌러 L3 / R3를 클릭합니다 + TURNIP 드라이버 플래그 + 위에서 사용자 지정 GPU 드라이버를 선택한 경우에만 적용됩니다. + 게임 파일을 찾을 수 없음 + 삭제 + 파일에서 가져오기… + 로딩 중… + NetPlay + Wii Home + 콘솔 변경 + 콘솔로 인식 + 이제 %1$s(으)로 인식됨 ReShade 내장된 vkBasalt 레이어를 통해 DXVK/VKD3D(Vulkan) 게임에 ReShade 효과(.fx)를 적용합니다. 각 효과를 Android/data/<package>/files/ReShade/ 아래의 자체 폴더에 넣으세요. 실시간 매개변수 조정 및 게임 내 토글은 라이브 리로드 레이어 업데이트와 함께 제공됩니다. @@ -1658,5 +2431,28 @@ ReShade 사용 이 로드아웃에 ReShade 효과가 없습니다. 여기에서 전환하고 조정하려면 이 게임의 설정(또는 컨테이너 설정)에서 효과를 추가하세요. 이 효과에는 조정 가능한 매개변수가 없습니다. + 저장 데이터 삭제 중… + 삭제 + %1$s의 클라우드 저장 데이터를 영구적으로 삭제할까요? 되돌릴 수 없습니다. + 클라우드 저장 삭제 + 클라우드 저장을 삭제할 수 없습니다 + 클라우드 저장이 삭제되었습니다 + 먼저 콘솔 코어를 다운로드하세요 — 설정 › 레트로 + 이 기기에서는 PS2 에뮬레이션을 실행할 수 없습니다. OpenGL ES 3.1 이상이 필요합니다. + 업데이트 확인 + 업데이트 확인 중… + 콘솔 코어 다운로드 + 다운로드 중… %1$d / %2$d MB + 콘솔 코어 + 설치됨 — 빌드 %1$s + 설치됨 — 빌드 %1$s (업데이트 확인 실패) + 설치 중… + 설치되지 않음 — 다운로드하면 레트로 게임을 즐길 수 있습니다 + 상태 + 콘솔 코어 업데이트 + 업데이트 있음 — 빌드 %1$s (%2$d MB) + 다운로드 확인 중… + 처리 중… + 시스템 diff --git a/app/src/main/res/values-no/strings.xml b/app/src/main/res/values-no/strings.xml index 144ab9a8e..f179a4374 100644 --- a/app/src/main/res/values-no/strings.xml +++ b/app/src/main/res/values-no/strings.xml @@ -1621,6 +1621,779 @@ Installert bane: Oppretting av mappe mislyktes Oppdater + Retro + Overfør lagret spill + Importer et lokalt lagret spill til dette spillet, eller eksporter det gjeldende lagrede spillet. + Importer lagret spill + Eksporter lagret spill + Lagret spill importert + Kunne ikke importere lagret spill + Lagret spill eksportert + Kunne ikke eksportere lagret spill + Det finnes ennå ingen lagring for dette spillet + Juksekoder + Juksekoder er deaktivert i Hardcore-modus + + + Lagre + Avbryt + Lagre tilstand + Last inn lagret tilstand + Prestasjoner + Juksekoder + Memory Cards + Spol fremover + Tilbakestill + Bytt disk + Slot %1$d + Trykk for å laste inn + Tom + Trykk for å overskrive + Tom – trykk for å lagre + Slot %1$d er tom + Lastet inn slot %1$d + Kunne ikke laste inn slot %1$d + Lagret i slot %1$d + Lagring mislyktes + • Slot 1 + • Slot 2 + • Trykk for å bruke + Nytt Memory Card + Importer kort + Aktiver online (DEV9) + PS2-nettverksadapter – starter spillet på nytt for å koble den til + Ethernet-enhet + DNS-modus + Primær DNS + Sekundær DNS + valgfritt + Auto-IP (DHCP) + Server: %1$s + trykk for å angi IP (tom fjerner) + %1$s → IP + Legg til serververt + Nytt serververtsnavn + f.eks. bf2.playbattlefront.com + Skjermkontroller + Rediger oppsett + Tilbakestill oppsett + Oppsett tilbakestilt + Venstre spak: Inverter X + Venstre spak: Inverter Y + Høyre spak: Inverter X + Høyre spak: Inverter Y + Knappfarge + Bokstavfarge + Skyggefarge + Bakgrunnsfarge + Tilbakestill farger + Renderer + Vulkan + OpenGL + Software + Oppløsningsskala + 1x (Native) + 1.5x + 2x + 3x + 4x + Bildeformat + Strekk + Auto (Standard) + 4:3 + 16:9 + Skjermfilter + Nærmeste + Bilineær (Myk) + Bilineær (Skarp) + Teksturfilter + Bilineær (Tvunget) + Bilineær (PS2) + Bilineær (Sprites) + Blandingsnøyaktighet + Minimum + Grunnleggende + Middels + Høy + Full + Maksimum + CRT-/TV-shader + Av + Scanline + Diagonal + Triangular + Wave + Lottes + 4xRGSS + NxAGSS + Frame Skip + Av + Hopp over 1 + Hopp over 2 + Hopp over 3 + Mipmapping + Volum + %1$d%% + Demp + Bytt stereokanaler + EE-syklusrate + 50% + 60% + 75% + 100% (Standard) + 130% + 180% + 300% + EE-syklushopp + Av + 1 + 2 + 3 + Instant VU1 + Multi-Threaded VU (MTVU) + Rask CDVD + FPS + Emuleringshastighet + CPU-bruk + GPU-bruk + Intern oppløsning + Deinterlace-modus + Auto + Av + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + FMV-bildeformat + Anti-uskarphet + Widescreen-patcher + No-interlace-patcher + VU Flag Hack + INTC-spinngjenkjenning + Venteløkke-gjenkjenning + Lyd-timestretch + Lydbuffer + Utgangslatens + %1$d ms + Frametider + GS-statistikk + Maskinvareinfo + Versjon + Inndatavisning + Meny + Skjerm + Ytelse + HUD + Lyd + Online + Kontroller + Fortsett + Pause + Avslutt + BIOS importert: %1$s + Ugyldig BIOS-fil + Ugyldig retrospill + ROM ikke funnet: %1$s + Kunne ikke lese ROM-en i dette arkivet + Kjerne ikke installert: %1$s + Juksekoder aktivert – prestasjoner er deaktivert for denne økten + Sky-lagring gjenopprettet + Gjenoppretting mislyktes + Det finnes en nyere sky-lagring for %1$s. Vil du synkronisere, og hvilken sky-lagring foretrekker du å beholde? + Sky-lagring + Retro + Kunne ikke laste inn emulatorkjernen + Kunne ikke laste inn ROM + Grafikk støttes ikke for denne kjernen + Emulatorfeil + Standard + CRT + LCD + Skarp + SGSR + SGSR-oppskalering + Native + Lyd + Venstre spak: Inverter X + Venstre spak: Inverter Y + Høyre spak: Inverter X + Høyre spak: Inverter Y + Skjermkontroller + Haptisk tilbakemelding + Stående + Liggende + Rediger oppsett (%1$s) + Tilbakestill %1$s-oppsett + %1$s-oppsett tilbakestilt + Knappfarge + Bokstavfarge + Skyggefarge + Bakgrunnsfarge + Tilbakestill farger + Farger tilbakestilt + Ytelse-HUD + Alfa + Bakgrunnsalfa + Bakgrunn + Skala + Numerisk frametid + Dual-serie batteri + HUD-ELEMENTER + FPS + Konsoll + GPU + CPU + RAM + Batteri + Temp. + Graf + CPU-temp. + Lagre tilstand + Last inn lagret tilstand + Innlasting av tilstander er deaktivert i Hardcore-modus + Prestasjoner + Juksekoder + Juksekoder er deaktivert i Hardcore-modus + Tilbakestill + Spol fremover + Spoling fremover er deaktivert i Hardcore-modus + HUD + Disk %1$d/%2$d + Fortsett + Pause + Avslutt + Lagret i slot %1$d + Kunne ikke lagre tilstand + %1$s BIOS kreves + PlayStation-spill trenger en ekte konsoll-BIOS-fil som du selv må oppgi. Importer en BIOS (scph5501.bin, scph5500.bin, scph5502.bin, scph1001.bin eller scph7001.bin) for å fortsette. + Importer BIOS… + Avbryt + Slot %1$d er tom + Lastet inn slot %1$d + Kunne ikke laste inn tilstand + Slot %1$d + Gi nytt navn til slot %1$d + Generelt + Grafikk + Ytelse + HUD + Inndata + Lyd + Online + Avbryt + Lagre + Standard + CRT + LCD + Skarp + 2x + 4x + Native + SPILL + Navn + System + Emulatorkjerne + ROM-bane + %1$s BIOS + Installert + Ingen – kreves for å kjøre %1$s-spill + Importer BIOS… + Fjern BIOS + BIBLIOTEKSGRAFIKK + Spillkortbilde + Rutenettbilde + Karusellbilde + Listebilde + Egendefinert bilde angitt + Angi bilde + Fjern + VIDEO + Videofilter + SGSR + SGSR-oppskalering + Ytelse-HUD + KJERNE + Renderer + Vulkan + OpenGL + Software + Oppløsningsskala + 1x (Native) + 1.5x + 2x + 3x + 4x + Bildeformat + Strekk + Auto (Standard) + 4:3 + 16:9 + Skjermfilter + Nærmeste + Bilineær (Myk) + Bilineær (Skarp) + Teksturfilter + Bilineær (Tvunget) + Bilineær (PS2) + Bilineær (Sprites) + Blandingsnøyaktighet + Minimum + Grunnleggende + Middels + Høy + Full + Maksimum + CRT-/TV-shader + Av + Scanline + Diagonal + Triangular + Wave + Lottes + 4xRGSS + NxAGSS + Frame Skip + Hopp over 1 + Hopp over 2 + Hopp over 3 + Mipmapping + YTELSE + EE-syklusrate + 50% + 60% + 75% + 100% (Standard) + 130% + 180% + 300% + EE-syklushopp + 1 + 2 + 3 + Instant VU1 + Multi-Threaded VU (MTVU) + Rask CDVD + YTELSE-HUD + FPS + Emuleringshastighet + CPU-bruk + GPU-bruk + Intern oppløsning + Deinterlace-modus + Auto + Av + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + FMV-bildeformat + Anti-uskarphet + Widescreen-patcher + No-interlace-patcher + VU Flag Hack + INTC-spinngjenkjenning + Venteløkke-gjenkjenning + Lyd-timestretch + Lydbuffer + Utgangslatens + %1$d ms + Frametider + GS-statistikk + Maskinvareinfo + Versjon + Inndatavisning + Hurtigoppstart + ONLINE (DEV9) + Aktiver online + Ethernet-enhet + Auto + Wi-Fi + DNS-modus + Manuell + Intern + Primær DNS + Sekundær DNS + valgfritt + Auto-IP (DHCP) + INNDATA + Skjermkontroller + Haptisk tilbakemelding + LYD + Volum + Demp + Bytt stereokanaler + Lyd + RETRO-STANDARDER + Standarder som brukes på hver konsolls spill med mindre de overstyres i et spills egne innstillinger. + RETROACHIEVEMENTS + Konto + Logget inn + Ikke logget inn – åpne et spills prestasjoner for å logge inn + Prestasjoner aktivert + Hardcore-modus som standard (ingen lagrede tilstander) + Logg ut + PLAYSTATION BIOS + Installert + Ingen – PS1-spill krever en BIOS + Importer PS1 BIOS… + PS1 BIOS fjernet + Ingen BIOS å fjerne + Fjern PS1 BIOS + PLAYSTATION 2 BIOS + Ingen – PS2-spill krever en BIOS + Format + Sammenslått enkeltfil-dump (regionsmerket .bin, ~4 MB). Delte ROM0/MEC/NVM-sett godtas ikke. + Importer PS2 BIOS… + PS2 BIOS fjernet + Fjern PS2 BIOS + BIBLIOTEKSGRAFIKK + Retro coverart (kassett / CD-cover) + Coverart + Hentes automatisk fra thumbnails.libretro.com ved import; et egendefinert bilde overstyrer det alltid. + ROMS-MAPPE + Mappe + Ikke angitt – velg en mappe for å importere spill automatisk + Auto-import + Nye spill i denne mappen legges automatisk til i biblioteket ditt med riktig konsoll gjenkjent. + Velg ROM-mappe + Velg ROM-mappe… + Endre ROM-mappe… + Skann nå + KONSOLL-STANDARDER + Trykk på en konsoll for å angi standardinnstillingene. + Renderer + Oppskaler oppløsning + Bildeformat + Strekk + Auto (Standard) + 4:3 + 16:9 + Skjermfilter + Nærmeste + Bilineær (Myk) + Bilineær (Skarp) + Teksturfilter + Bilineær (Tvunget) + Bilineær (PS2) + Bilineær (Sprites) + Blandingsnøyaktighet + Minimum + Grunnleggende + Middels + Høy + Full + Maksimum + CRT-/TV-shader + Av + Scanline + Diagonal + Triangular + Wave + Lottes + 4xRGSS + NxAGSS + Frame Skip + Hopp over 1 + Hopp over 2 + Hopp over 3 + Mipmapping + EE-syklusrate + 50% + 60% + 75% + 100% (Standard) + 130% + 180% + 300% + EE-syklushopp + Av + 1 + 2 + 3 + Instant VU1 + Multi-Threaded VU (MTVU) + Rask CDVD + Berøringskontroller på skjermen + Lyd + Bytt stereokanaler + HUD: FPS + HUD: Emuleringshastighet + HUD: CPU-bruk + HUD: GPU-bruk + HUD: Intern oppløsning + Aktiver online (DEV9) + Ethernet-enhet + Auto + Wi-Fi + DNS-modus + Manuell + Intern + Primær DNS + Sekundær DNS + valgfritt + Auto-IP (DHCP) + Shader + SGSR-oppskalering + Ytelse-HUD + BIDRAGSYTERE & LISENSER + Noen av WinNatives funksjoner er bygget på disse åpen kildekode-prosjektene. Trykk for å se hver kilde. + Standarder + Bidragsytere + Aktivere Hardcore-modus? + Hardcore-modus tilbakestiller spillet nå og deaktiverer innlasting av lagrede tilstander, spoling fremover og juksekoder. Ulagret fremdrift går tapt. Fortsette? + Avbryt + Aktiver + BIOS importert: %1$s + Ugyldig BIOS-fil + PS2 BIOS importert: %1$s + Ugyldig PS2 BIOS-fil + Ingen spillserie å slå opp juksekoder for. + Brukte %1$d juksekode(r). + Kunne ikke bruke juksekoder. + Juksekoder + Bruk + Ingen juksekoder funnet for dette spillet. + Prestasjoner + Logg inn på RetroAchievements + Brukernavn + Passord + Innlogging mislyktes + Logger inn… + Logg inn + %1$d/%2$d • %3$d p. + Ingen prestasjoner for dette spillet. + Tilbake + Aktivert + Deaktivert + Gi nytt navn + Lagre + Sky-lagringskonflikt + Behold lokal lagring + A + Meny + Skjerm + HUD + Lyd + Kontroller + Biblioteket er oppdatert + ROM-er: %1$s + lagt til %1$d + fjernet %1$d + Standard + CRT + LCD + Skarp + Native + Bildeformat + NTSC-filter + Fargelegging + Fargekorrigering + Fjern sprite-grense + Oppløsning + Framebuffer-emulering + Dithering + Widescreen-hack + 8:7 (Native) + 4:3 (TV) + Av + RF + Composite + S-Video + RGB + Auto + GBA-skjerm + GBC-skjerm + + 320x240 (Native) + 640x480 + 960x720 + 1280x960 + 4:3 + 16:9 + 16:9 justert + Native + Intern + På (16:9) + RETROACHIEVEMENTS + Logg inn med RetroAchievements-kontoen din for å tjene og spore prestasjoner for retrospill. + Brukernavn + Passord + Skriv inn brukernavn og passord + Innlogging mislyktes + Logg inn + Passordet ditt brukes bare én gang for å hente et innloggingstoken, som lagres sikkert på enheten. + Prestasjoner aktivert + Hardcore-modus (ingen lagrede tilstander) + %1$d / %2$d poeng + Ingen prestasjoner funnet for dette spillet. + Logg ut + JUKSEKODER + Navn + Kode + Avbryt + Lagre + Juksekode %1$d + Ingen juksekoder ennå. Legg til en juksekode for dette spillet. + Legg til juksekode + + GPU-driver + System (Standard) + Installer Turnip-drivere under Innstillinger \u2192 Drivere. De samme driverne fungerer for både PC- og PS2-spill. + + PS2 HDD (DEV9) + Virtuell intern stasjon for HDD-baserte spill som Final Fantasy XI. Starter spillet på nytt. + Virtuell intern stasjon for HDD-baserte spill som Final Fantasy XI. + DNS-modus satt til Internal, slik at dine egendefinerte serververtar trer i kraft. + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + Add Cheat + Cheat name + Codes (one per line, e.g. 2021A268 00000000) + Custom + Enter a name and at least one valid code + Add + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + PS2 HDD Images + A .raw HDD image, or a .zip containing one (e.g. a game’s downloaded HDD with maps/DLC) + Import HDD Image + Importing… + Imported %1$s + Could not import HDD image + Removed %1$s + Remove %1$s + HDD Image + None + Cheats + Patches + PATCH + Custom + Applied %1$d cheat(s), %2$d patch(es). + No cheats or patches found for this game. + Cheat + Patch + Add + CPU-kjerne + Dobbeltkjerne + Interne juksekoder + Intern oppløsning + Gjengiver + Plassering av sensorlinje + Hopp over BIOS-intro + + + + + + + Nederst + Bufret tolker + Maskinvare + Tolker + JIT + Mus / berøring + Høyre spak (absolutt) + Høyre spak (relativ) + Programvare + Strekk + Øverst + VBI-hopp (auto-bildehopp) + Bredskjerm + Wiimote-peker + Endringene trer i kraft neste gang du starter dette spillet. + Start dette spillet én gang slik at plateserienummeret kan oppdages, så vil juksekoder og oppdateringer vises her. + Omgåelse av DNAS-autentisering — kreves for nettspill + Automatisk anvendt (på nett) + Juksekoder & oppdateringer + Størrelse: %1$s + Importer HDD-avbildning + Fjern + Aktiver NetPlay + Av som standard. Aktiver, og velg deretter Vert eller Bli med før oppstart.\nSlås av igjen når du avslutter spillet. + Vertsadresse + IP eller vertsnavn + Vertsøkt + På = vent på en spiller. Av = koble til vertsadresse + NetPlay bruker lokale flerspillerporter over TCP (spiller 1 vert / spiller 2 klient). PS2-nettspill bruker DEV9 Ethernet i stedet. + Port + Minnekort %1$d + Skjermbilde + Bruk skylagring + LAN (direkte IP) + Kobler til… + Tilkobling + På nett (vertskode) + Lukk + GameCube/Wii-NetPlay bruker Dolphins egen motor. Vert = spiller 1, Bli med = spiller 2. Velg Vert eller Bli med og en tilkoblingstype før oppstart; begge enhetene starter det samme spillet sammen. + Del enhetens Wi‑Fi-IP og denne porten med spiller 2. Spillet starter automatisk så snart de kobler til. + En vertskode vises når spillet starter — del den med spiller 2. Spillet starter automatisk så snart de kobler til. + Skriv inn vertens Wi‑Fi-IP og port, og start deretter for å koble til. + Skriv inn vertskoden fra spiller 1, og start deretter for å koble til. + Aktiver NetPlay i spillinnstillingene og velg Vert eller Bli med før oppstart + Finn rom på Wi‑Fi + Game Link · hver skjerm er sin egen håndholdte konsoll + GBA-flerspiller bruker gpSP + trådløs adapter. Sørg for at libgpsp er installert. + Flerspiller med delt skjerm over Wi‑Fi (som RetroArch).\nVert = spiller 1, Bli med = spiller 2. Begge enhetene viser det samme spillet. + Game Link over Wi‑Fi — hver enhet kjører sitt eget spill.\nGB/GBC: Gambatte seriell tilkobling (Pokémon Gen 1–2).\nGBA: gpSP trådløs adapter (Pokémon FR/LG/Emerald-kamper). + Vær vert for rom + Vertskode + Traverserings-vertskode fra verten + Er vert for rom + Trykk på Vert for å åpne et rom for denne spilløkten, og start deretter spillet. NetPlay slås av når du avslutter. + I rom + Bli med via IP + Ble med + Bli med + Ved oppstart + Forlat + Vert = S1 · Bli med = S2 · samme spill på begge skjermer + Vert + Bli med + Manuell + Fant ingen rom. Sørg for at verten er på samme Wi‑Fi og er vert for et rom. + Visningsnavn + Vises til andre spillere + %1$d tilkoblet + Rommet er åpent kun for denne økten. Start når du er klar. Å avslutte spillet slår av NetPlay. + Spillere + Skann Wi‑Fi + Skann på nytt + Skann samme Wi‑Fi etter åpne rom, eller bli med via IP-adresse. + Skanner Wi‑Fi… + Skanneresultater + Trykk på et rom for å bli med nå (lagrer ikke IP-en til neste oppstart). + Stopp skanning + NetPlay + %1$s koblet til + %1$s koblet fra + Venter på spillere… + Støtte for PlayStation 2 kommer snart + Vis L3- / R3-knapper + Når av, dobbelttrykk en spak for å klikke L3 / R3 + TURNIP-DRIVERFLAGG + Brukes kun når en egendefinert GPU-driver er valgt ovenfor. + Fant ikke spillfilen + Slett + Importer fra fil… + Laster inn… + NetPlay + Wii Home + Bytt konsoll + Identifiser som konsoll + Nå identifisert som %1$s ReShade Bruk en ReShade-effekt (.fx) på DXVK/VKD3D-spill (Vulkan) via det innebygde vkBasalt-laget. Legg hver effekt i sin egen mappe under Android/data/<package>/files/ReShade/. Justering av parametere i sanntid og bryteren i spillet kommer med oppdateringen av live-reload-laget. @@ -1656,4 +2429,27 @@ Installert bane: Aktiver ReShade Ingen ReShade-effekter i dette settet. Legg til effekter i dette spillets innstillinger (eller containerens) for å bytte og justere dem her. Denne effekten har ingen justerbare parametere. + Sletter lagring… + Slett + Vil du slette skylagringen fra %1$s permanent? Dette kan ikke angres. + Slett skylagring + Kunne ikke slette skylagringen + Skylagring slettet + Last ned konsollkjernene først — Innstillinger › Retro + Denne enheten kan ikke kjøre PS2-emulering — den krever OpenGL ES 3.1 eller nyere. + Se etter oppdateringer + Ser etter oppdateringer… + Last ned konsollkjerner + Laster ned… %1$d / %2$d MB + Konsollkjerner + Installert — build %1$s + Installert — build %1$s (kunne ikke se etter oppdateringer) + Installerer… + Ikke installert — last ned for å spille retrospill + Status + Oppdater konsollkjerner + Oppdatering tilgjengelig — build %1$s (%2$d MB) + Verifiserer nedlastingen… + Arbeider… + System diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 33f7e49df..0ab4e4a97 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1628,6 +1628,779 @@ Zainstalowana ścieżka: Uruchom w tle Pozostaw czat aktywny po zamknięciu WinNative Odśwież + Retro + Przenieś zapis + Zaimportuj lokalny zapis do tej gry lub wyeksportuj bieżący zapis. + Importuj zapis + Eksportuj zapis + Zaimportowano zapis + Nie udało się zaimportować zapisu + Wyeksportowano zapis + Nie udało się wyeksportować zapisu + Dla tej gry nie ma jeszcze zapisu + Kody + Kody są wyłączone w trybie Hardcore + + + Zapisz + Anuluj + Zapisz stan + Wczytaj stan + Osiągnięcia + Kody + Karty pamięci + Przewijanie + Resetuj + Zmień płytę + Slot %1$d + Dotknij, aby wczytać + Pusty + Dotknij, aby nadpisać + Pusty — dotknij, aby zapisać + Slot %1$d jest pusty + Wczytano slot %1$d + Nie udało się wczytać slotu %1$d + Zapisano w slocie %1$d + Zapis nie powiódł się + • Slot 1 + • Slot 2 + • Dotknij, aby użyć + Nowa karta pamięci + Importuj kartę + Włącz sieć (DEV9) + Karta sieciowa PS2 — uruchamia grę ponownie, aby ją podłączyć + Urządzenie Ethernet + Tryb DNS + Podstawowy DNS + Zapasowy DNS + opcjonalne + Auto IP (DHCP) + Serwer: %1$s + dotknij, aby ustawić IP (puste usuwa) + %1$s → IP + Dodaj host serwera + Nowa nazwa hosta serwera + np. bf2.playbattlefront.com + Sterowanie ekranowe + Edytuj układ + Resetuj układ + Zresetowano układ + Lewa gałka: odwróć X + Lewa gałka: odwróć Y + Prawa gałka: odwróć X + Prawa gałka: odwróć Y + Kolor przycisku + Kolor litery + Kolor cienia + Kolor tła + Resetuj kolory + Renderer + Vulkan + OpenGL + Software + Skala rozdzielczości + 1x (natywna) + 1.5x + 2x + 3x + 4x + Proporcje obrazu + Rozciągnij + Auto (standard) + 4:3 + 16:9 + Filtr wyświetlania + Najbliższy + Dwuliniowy (gładki) + Dwuliniowy (ostry) + Filtr tekstur + Dwuliniowy (wymuszony) + Dwuliniowy (PS2) + Dwuliniowy (sprite\'y) + Dokładność mieszania + Minimalna + Podstawowa + Średnia + Wysoka + Pełna + Maksymalna + Shader CRT / TV + Wył. + Linie skanowania + Ukośny + Trójkątny + Fala + Lottes + 4xRGSS + NxAGSS + Pomijanie klatek + Wył. + Pomiń 1 + Pomiń 2 + Pomiń 3 + Mipmapping + Głośność + %1$d%% + Wycisz + Zamień kanały stereo + Szybkość cykli EE + 50% + 60% + 75% + 100% (domyślnie) + 130% + 180% + 300% + Pomijanie cykli EE + Wył. + 1 + 2 + 3 + Natychmiastowy VU1 + Wielowątkowy VU (MTVU) + Szybki CDVD + FPS + Szybkość emulacji + Użycie CPU + Użycie GPU + Rozdzielczość wewnętrzna + Tryb usuwania przeplotu + Auto + Wył. + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + Proporcje obrazu FMV + Antyrozmycie + Łatki szerokoekranowe + Łatki bez przeplotu + VU Flag Hack + Wykrywanie pętli INTC + Wykrywanie pętli oczekiwania + Rozciąganie czasu dźwięku + Bufor dźwięku + Opóźnienie wyjścia + %1$d ms + Czasy klatek + Statystyki GS + Informacje o sprzęcie + Wersja + Wyświetlanie wejścia + Menu + Ekran + Wydajność + HUD + Dźwięk + Sieć + Sterowanie + Wznów + Pauza + Wyjdź + Zaimportowano BIOS: %1$s + Nieprawidłowy plik BIOS + Nieprawidłowa gra retro + Nie znaleziono ROM: %1$s + Nie udało się odczytać ROM z tego archiwum + Rdzeń nie zainstalowany: %1$s + Kody włączone — osiągnięcia są wyłączone w tej sesji + Przywrócono zapis w chmurze + Przywracanie nie powiodło się + Istnieje nowszy zapis w chmurze dla %1$s. Czy chcesz zsynchronizować i który zapis w chmurze zachować? + Zapis w chmurze + Retro + Nie udało się wczytać rdzenia emulatora + Nie udało się wczytać ROM + Grafika nieobsługiwana dla tego rdzenia + Błąd emulatora + Domyślny + CRT + LCD + Ostry + SGSR + Skalowanie SGSR + Natywna + Dźwięk + Lewa gałka: odwróć X + Lewa gałka: odwróć Y + Prawa gałka: odwróć X + Prawa gałka: odwróć Y + Sterowanie ekranowe + Wibracje dotykowe + Pionowo + Poziomo + Edytuj układ (%1$s) + Resetuj układ %1$s + Zresetowano układ %1$s + Kolor przycisku + Kolor litery + Kolor cienia + Kolor tła + Resetuj kolory + Zresetowano kolory + HUD wydajności + Alfa + Alfa tła + Tło + Skala + Numeryczny czas klatki + Bateria dwuszeregowa + ELEMENTY HUD + FPS + Konsola + GPU + CPU + RAM + Bateria + Temp. + Wykres + Temp. CPU + Zapisz stan + Wczytaj stan + Wczytywanie stanów jest wyłączone w trybie Hardcore + Osiągnięcia + Kody + Kody są wyłączone w trybie Hardcore + Resetuj + Przewijanie + Przewijanie jest wyłączone w trybie Hardcore + HUD + Płyta %1$d/%2$d + Wznów + Pauza + Wyjdź + Zapisano w slocie %1$d + Nie udało się zapisać stanu + Wymagany BIOS %1$s + Gry PlayStation wymagają prawdziwego pliku BIOS konsoli, który musisz dostarczyć. Zaimportuj BIOS (scph5501.bin, scph5500.bin, scph5502.bin, scph1001.bin lub scph7001.bin), aby kontynuować. + Importuj BIOS… + Anuluj + Slot %1$d jest pusty + Wczytano slot %1$d + Nie udało się wczytać stanu + Slot %1$d + Zmień nazwę slotu %1$d + Ogólne + Grafika + Wydajność + HUD + Wejście + Dźwięk + Sieć + Anuluj + Zapisz + Domyślny + CRT + LCD + Ostry + 2x + 4x + Natywna + GRA + Nazwa + System + Rdzeń emulatora + Ścieżka ROM + BIOS %1$s + Zainstalowany + Brak — wymagany do uruchamiania gier %1$s + Importuj BIOS… + Usuń BIOS + GRAFIKA BIBLIOTEKI + Obraz karty gry + Obraz siatki + Obraz karuzeli + Obraz listy + Ustawiono obraz niestandardowy + Ustaw obraz + Usuń + WIDEO + Filtr wideo + SGSR + Skalowanie SGSR + HUD wydajności + RDZEŃ + Renderer + Vulkan + OpenGL + Software + Skala rozdzielczości + 1x (natywna) + 1.5x + 2x + 3x + 4x + Proporcje obrazu + Rozciągnij + Auto (standard) + 4:3 + 16:9 + Filtr wyświetlania + Najbliższy + Dwuliniowy (gładki) + Dwuliniowy (ostry) + Filtr tekstur + Dwuliniowy (wymuszony) + Dwuliniowy (PS2) + Dwuliniowy (sprite\'y) + Dokładność mieszania + Minimalna + Podstawowa + Średnia + Wysoka + Pełna + Maksymalna + Shader CRT / TV + Wył. + Linie skanowania + Ukośny + Trójkątny + Fala + Lottes + 4xRGSS + NxAGSS + Pomijanie klatek + Pomiń 1 + Pomiń 2 + Pomiń 3 + Mipmapping + WYDAJNOŚĆ + Szybkość cykli EE + 50% + 60% + 75% + 100% (domyślnie) + 130% + 180% + 300% + Pomijanie cykli EE + 1 + 2 + 3 + Natychmiastowy VU1 + Wielowątkowy VU (MTVU) + Szybki CDVD + HUD WYDAJNOŚCI + FPS + Szybkość emulacji + Użycie CPU + Użycie GPU + Rozdzielczość wewnętrzna + Tryb usuwania przeplotu + Auto + Wył. + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + Proporcje obrazu FMV + Antyrozmycie + Łatki szerokoekranowe + Łatki bez przeplotu + VU Flag Hack + Wykrywanie pętli INTC + Wykrywanie pętli oczekiwania + Rozciąganie czasu dźwięku + Bufor dźwięku + Opóźnienie wyjścia + %1$d ms + Czasy klatek + Statystyki GS + Informacje o sprzęcie + Wersja + Wyświetlanie wejścia + Szybki rozruch + SIEĆ (DEV9) + Włącz sieć + Urządzenie Ethernet + Auto + Wi-Fi + Tryb DNS + Ręczny + Wewnętrzny + Podstawowy DNS + Zapasowy DNS + opcjonalne + Auto IP (DHCP) + WEJŚCIE + Sterowanie ekranowe + Wibracje dotykowe + DŹWIĘK + Głośność + Wycisz + Zamień kanały stereo + Dźwięk + USTAWIENIA DOMYŚLNE RETRO + Ustawienia domyślne stosowane do gier każdej konsoli, chyba że zostaną zastąpione we własnych ustawieniach gry. + RETROACHIEVEMENTS + Konto + Zalogowano + Nie zalogowano — otwórz Osiągnięcia gry, aby się zalogować + Osiągnięcia włączone + Tryb Hardcore domyślnie (bez stanów zapisu) + Wyloguj + BIOS PLAYSTATION + Zainstalowany + Brak — gry PS1 wymagają BIOS + Importuj BIOS PS1… + Usunięto BIOS PS1 + Brak BIOS do usunięcia + Usuń BIOS PS1 + BIOS PLAYSTATION 2 + Brak — gry PS2 wymagają BIOS + Format + Scalony zrzut jednoplikowy (.bin z oznaczeniem regionu, ~4 MB). Podzielone zestawy ROM0/MEC/NVM nie są akceptowane. + Importuj BIOS PS2… + Usunięto BIOS PS2 + Usuń BIOS PS2 + GRAFIKA BIBLIOTEKI + Grafika pudełka retro (kartridż / etui CD) + Grafika pudełka + Pobierana automatycznie z thumbnails.libretro.com przy imporcie; niestandardowy obraz zawsze ją zastępuje. + FOLDER ROM + Folder + Nie ustawiono — wybierz folder do automatycznego importu gier + Automatyczny import + Nowe gry w tym folderze są automatycznie dodawane do biblioteki z wykryciem właściwej konsoli. + Wybierz folder ROM + Wybierz folder ROM… + Zmień folder ROM… + Skanuj teraz + USTAWIENIA DOMYŚLNE KONSOLI + Dotknij konsoli, aby ustawić jej ustawienia domyślne. + Renderer + Skaluj rozdzielczość + Proporcje obrazu + Rozciągnij + Auto (standard) + 4:3 + 16:9 + Filtr wyświetlania + Najbliższy + Dwuliniowy (gładki) + Dwuliniowy (ostry) + Filtr tekstur + Dwuliniowy (wymuszony) + Dwuliniowy (PS2) + Dwuliniowy (sprite\'y) + Dokładność mieszania + Minimalna + Podstawowa + Średnia + Wysoka + Pełna + Maksymalna + Shader CRT / TV + Wył. + Linie skanowania + Ukośny + Trójkątny + Fala + Lottes + 4xRGSS + NxAGSS + Pomijanie klatek + Pomiń 1 + Pomiń 2 + Pomiń 3 + Mipmapping + Szybkość cykli EE + 50% + 60% + 75% + 100% (domyślnie) + 130% + 180% + 300% + Pomijanie cykli EE + Wył. + 1 + 2 + 3 + Natychmiastowy VU1 + Wielowątkowy VU (MTVU) + Szybki CDVD + Sterowanie dotykowe na ekranie + Dźwięk + Zamień kanały stereo + HUD: FPS + HUD: szybkość emulacji + HUD: użycie CPU + HUD: użycie GPU + HUD: rozdzielczość wewnętrzna + Włącz sieć (DEV9) + Urządzenie Ethernet + Auto + Wi-Fi + Tryb DNS + Ręczny + Wewnętrzny + Podstawowy DNS + Zapasowy DNS + opcjonalne + Auto IP (DHCP) + Shader + Skalowanie SGSR + HUD wydajności + AUTORZY & LICENCJE + Niektóre funkcje WinNative są oparte na tych projektach open-source. Dotknij, aby zobaczyć każde źródło. + Domyślne + Autorzy + Włączyć tryb Hardcore? + Tryb Hardcore resetuje teraz grę i wyłącza wczytywanie stanów zapisu, przewijanie i kody. Wszelkie niezapisane postępy zostaną utracone. Kontynuować? + Anuluj + Włącz + Zaimportowano BIOS: %1$s + Nieprawidłowy plik BIOS + Zaimportowano BIOS PS2: %1$s + Nieprawidłowy plik BIOS PS2 + Brak numeru seryjnego gry do wyszukania kodów. + Zastosowano %1$d kod(ów). + Nie udało się zastosować kodów. + Kody + Zastosuj + Nie znaleziono kodów dla tej gry. + Osiągnięcia + Zaloguj się do RetroAchievements + Nazwa użytkownika + Hasło + Logowanie nie powiodło się + Logowanie… + Zaloguj + %1$d/%2$d • %3$d pkt + Brak osiągnięć dla tej gry. + Wstecz + Włączone + Wyłączone + Zmień nazwę + Zapisz + Konflikt zapisu w chmurze + Zachowaj zapis lokalny + A + Menu + Ekran + HUD + Dźwięk + Sterowanie + Biblioteka aktualna + ROM-y: %1$s + dodano %1$d + usunięto %1$d + Domyślny + CRT + LCD + Ostry + Natywna + Proporcje obrazu + Filtr NTSC + Koloryzacja + Korekcja kolorów + Usuń limit sprite\'ów + Rozdzielczość + Emulacja bufora ramki + Dithering + Hack panoramiczny + 8:7 (natywna) + 4:3 (TV) + Wył. + RF + Composite + S-Video + RGB + Auto + Ekran GBA + Ekran GBC + Wł. + 320x240 (natywna) + 640x480 + 960x720 + 1280x960 + 4:3 + 16:9 + 16:9 dopasowane + Natywna + Wewnętrzna + Wł. (16:9) + RETROACHIEVEMENTS + Zaloguj się swoim kontem RetroAchievements, aby zdobywać i śledzić osiągnięcia w grach retro. + Nazwa użytkownika + Hasło + Wprowadź nazwę użytkownika i hasło + Logowanie nie powiodło się + Zaloguj + Twoje hasło jest używane tylko raz do uzyskania tokenu logowania, który jest bezpiecznie przechowywany na urządzeniu. + Osiągnięcia włączone + Tryb Hardcore (bez stanów zapisu) + %1$d / %2$d punktów + Nie znaleziono osiągnięć dla tej gry. + Wyloguj + KODY + Nazwa + Kod + Anuluj + Zapisz + Kod %1$d + Brak kodów. Dodaj kod dla tej gry. + Dodaj kod + + Sterownik GPU + System (Domyślny) + Zainstaluj sterowniki Turnip w Ustawienia \u2192 Sterowniki. Te same sterowniki działają zarówno w grach PC, jak i PS2. + + HDD PS2 (DEV9) + Wirtualny dysk wewnętrzny dla gier opartych na HDD, takich jak Final Fantasy XI. Uruchamia grę ponownie. + Wirtualny dysk wewnętrzny dla gier opartych na HDD, takich jak Final Fantasy XI. + Tryb DNS ustawiony na Internal, aby Twoje niestandardowe hosty serwera zaczęły działać. + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + Add Cheat + Cheat name + Codes (one per line, e.g. 2021A268 00000000) + Custom + Enter a name and at least one valid code + Add + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + PS2 HDD Images + A .raw HDD image, or a .zip containing one (e.g. a game’s downloaded HDD with maps/DLC) + Import HDD Image + Importing… + Imported %1$s + Could not import HDD image + Removed %1$s + Remove %1$s + HDD Image + None + Cheats + Patches + PATCH + Custom + Applied %1$d cheat(s), %2$d patch(es). + No cheats or patches found for this game. + Cheat + Patch + Add +Rdzeń CPU +Dwa rdzenie +Wbudowane kody +Rozdzielczość wewnętrzna +Renderer +Pozycja listwy sensorów +Pomiń intro BIOS + + + + + + +Dół +Interpreter z buforowaniem +Sprzętowy +Interpreter +JIT +Mysz / dotyk +Prawy drążek (bezwzględny) +Prawy drążek (względny) +Programowy +Rozciągnij +Góra +Pomijanie VBI (automatyczne pomijanie klatek) +Panoramiczny +Wskaźnik Wiimote +Zmiany zostaną zastosowane przy następnym uruchomieniu tej gry. +Uruchom tę grę raz, aby można było wykryć numer seryjny płyty, a następnie pojawią się tutaj kody i łatki. +Obejście autoryzacji DNAS — wymagane do gry online +Stosowane automatycznie (online) +Kody i łatki +Rozmiar: %1$s +Importuj obraz HDD +Usuń +Włącz NetPlay +Domyślnie wyłączone. Włącz, a następnie przed uruchomieniem wybierz Hostuj lub Dołącz.\nWyłącza się ponownie po zamknięciu gry. +Adres hosta +IP lub nazwa hosta +Sesja hosta +Wł. = czekaj na gracza. Wył. = dołącz do adresu hosta +NetPlay używa lokalnych portów gry wieloosobowej przez TCP (gracz 1 host / gracz 2 klient). PS2 online używa zamiast tego Ethernetu DEV9. +Port +Karta pamięci %1$d +Zrzut ekranu +Użyj zapisu w chmurze +LAN (bezpośrednie IP) +Łączenie… +Połączenie +Online (kod hosta) +Odrzuć +NetPlay dla GameCube/Wii używa własnego silnika Dolphin. Host = Gracz 1, Dołącz = Gracz 2. Wybierz Hostuj lub Dołącz oraz typ połączenia przed uruchomieniem; oba urządzenia wspólnie uruchamiają tę samą grę. +Udostępnij adres IP Wi‑Fi swojego urządzenia oraz ten port graczowi 2. Gra uruchamia się automatycznie po jego połączeniu. +Kod hosta jest wyświetlany po uruchomieniu gry — udostępnij go graczowi 2. Gra uruchamia się automatycznie po jego połączeniu. +Wprowadź adres IP Wi‑Fi hosta oraz port, a następnie uruchom, aby się połączyć. +Wprowadź kod hosta od gracza 1, a następnie uruchom, aby się połączyć. +Włącz NetPlay w ustawieniach gry i wybierz Hostuj lub Dołącz przed uruchomieniem +Znajdź pokoje w sieci Wi‑Fi +Game Link · każdy ekran to osobna konsola przenośna +Gra wieloosobowa GBA używa gpSP + adaptera bezprzewodowego. Upewnij się, że zainstalowano libgpsp. +Gra wieloosobowa ze wspólnym ekranem przez Wi‑Fi (jak w RetroArch).\nHost = Gracz 1, Dołącz = Gracz 2. Oba urządzenia pokazują tę samą grę. +Game Link przez Wi‑Fi — każde urządzenie uruchamia własną grę.\nGB/GBC: łącze szeregowe Gambatte (Pokémon gen. 1–2).\nGBA: adapter bezprzewodowy gpSP (walki Pokémon FR/LG/Emerald). +Hostuj pokój +Kod hosta +Kod hosta traversal od hosta +Hostowanie pokoju +Naciśnij Hostuj, aby otworzyć pokój na tę sesję gry, a następnie uruchom grę. NetPlay wyłącza się po zamknięciu. +W pokoju +Dołącz przez IP +Dołączono +Dołącz +Przy uruchomieniu +Opuść +Host = G1 · Dołącz = G2 · ta sama gra na obu ekranach +Hostuj +Dołącz +Ręcznie +Nie znaleziono pokoi. Upewnij się, że host jest w tej samej sieci Wi‑Fi i hostuje pokój. +Wyświetlana nazwa +Widoczna dla innych graczy +Połączono: %1$d +Pokój jest otwarty tylko na tę sesję. Uruchom, gdy będziesz gotów. Zamknięcie gry wyłącza NetPlay. +Gracze +Skanuj Wi‑Fi +Skanuj ponownie +Przeskanuj tę samą sieć Wi‑Fi w poszukiwaniu otwartych pokoi lub dołącz przez adres IP. +Skanowanie Wi‑Fi… +Wyniki skanowania +Naciśnij pokój, aby dołączyć teraz (nie zapisuje adresu IP na następne uruchomienie). +Zatrzymaj skanowanie +NetPlay +%1$s połączony +%1$s rozłączony +Oczekiwanie na graczy… +Obsługa PlayStation 2 pojawi się wkrótce +Pokaż przyciski L3 / R3 +Gdy wyłączone, dwukrotnie naciśnij drążek, aby kliknąć L3 / R3 +FLAGI STEROWNIKA TURNIP +Stosowane tylko, gdy powyżej wybrano niestandardowy sterownik GPU. +Nie znaleziono pliku gry +Usuń +Importuj z pliku… +Ładowanie… +NetPlay + Wii Home + Zmień konsolę + Identyfikuj jako konsolę + Teraz zidentyfikowano jako %1$s ReShade Zastosuj efekt ReShade (.fx) do gier DXVK/VKD3D (Vulkan) za pomocą wbudowanej warstwy vkBasalt. Umieść każdy efekt w osobnym folderze w Android/data/<package>/files/ReShade/. Dostrajanie parametrów na żywo i przełącznik w grze pojawią się wraz z aktualizacją warstwy przeładowywanej na żywo. @@ -1663,5 +2436,28 @@ Zainstalowana ścieżka: Włącz ReShade Brak efektów ReShade w tym zestawie. Dodaj efekty w ustawieniach tej gry (lub kontenera), aby je tutaj przełączać i dostrajać. Ten efekt nie udostępnia żadnych regulowanych parametrów. + Usuwanie zapisu… + Usuń + Trwale usunąć zapis w chmurze z %1$s? Tej operacji nie można cofnąć. + Usuń zapis w chmurze + Nie udało się usunąć zapisu w chmurze + Zapis w chmurze usunięty + Najpierw pobierz rdzenie konsol — Ustawienia › Retro + To urządzenie nie obsługuje emulacji PS2 — wymaga OpenGL ES 3.1 lub nowszego. + Sprawdź aktualizacje + Sprawdzanie aktualizacji… + Pobierz rdzenie konsol + Pobieranie… %1$d / %2$d MB + Rdzenie konsol + Zainstalowano — kompilacja %1$s + Zainstalowano — kompilacja %1$s (nie udało się sprawdzić aktualizacji) + Instalowanie… + Nie zainstalowano — pobierz, aby grać w gry retro + Stan + Zaktualizuj rdzenie konsol + Dostępna aktualizacja — kompilacja %1$s (%2$d MB) + Weryfikowanie pobranego pliku… + Trwa praca… + System diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 144328d65..d764aa465 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -1622,6 +1622,779 @@ Caminho instalado: Executar em segundo plano Manter o chat ativo após sair do WinNative Atualizar + Retro + Transferir save + Importe um save local para este jogo ou exporte o save atual. + Importar save + Exportar save + Save importado + Não foi possível importar o save + Save exportado + Não foi possível exportar o save + Ainda não existe um save para este jogo + Cheats + Os cheats estão desativados no modo Hardcore + + + Salvar + Cancelar + Salvar estado + Carregar estado + Conquistas + Trapaças + Cartões de memória + Avanço rápido + Reiniciar + Trocar disco + Slot %1$d + Toque para carregar + Vazio + Toque para substituir + Vazio — toque para salvar + O slot %1$d está vazio + Slot %1$d carregado + Não foi possível carregar o slot %1$d + Salvo no slot %1$d + Falha ao salvar + • Slot 1 + • Slot 2 + • Toque para usar + Novo cartão de memória + Importar cartão + Ativar online (DEV9) + Adaptador de rede do PS2 — reinicia o jogo para conectá-lo + Dispositivo Ethernet + Modo DNS + DNS primário + DNS secundário + opcional + IP automático (DHCP) + Servidor: %1$s + toque para definir o IP (em branco remove) + %1$s → IP + Adicionar host do servidor + Novo nome de host do servidor + p. ex. bf2.playbattlefront.com + Controles na tela + Editar disposição + Repor disposição + Disposição reposta + Analógico esquerdo: inverter X + Analógico esquerdo: inverter Y + Analógico direito: inverter X + Analógico direito: inverter Y + Cor dos botões + Cor das letras + Cor da sombra + Cor de fundo + Repor cores + Renderizador + Vulkan + OpenGL + Software + Escala de resolução + 1x (nativa) + 1.5x + 2x + 3x + 4x + Proporção da tela + Esticar + Automática (padrão) + 4:3 + 16:9 + Filtro de tela + Mais próximo + Bilinear (suave) + Bilinear (nítido) + Filtro de texturas + Bilinear (forçado) + Bilinear (PS2) + Bilinear (sprites) + Precisão da mistura + Mínima + Básica + Média + Alta + Completa + Máxima + Shader CRT / TV + Desligado + Linhas de varredura + Diagonal + Triangular + Onda + Lottes + 4xRGSS + NxAGSS + Ignorar fotogramas + Desligado + Ignorar 1 + Ignorar 2 + Ignorar 3 + Mipmapping + Volume + %1$d%% + Sem som + Trocar canais estéreo + Taxa de ciclos EE + 50% + 60% + 75% + 100% (padrão) + 130% + 180% + 300% + Salto de ciclos EE + Desligado + 1 + 2 + 3 + VU1 instantâneo + VU multithread (MTVU) + CDVD rápido + FPS + Velocidade de emulação + Uso da CPU + Uso da GPU + Resolução interna + Modo de desentrelaçamento + Automático + Desligado + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + Proporção de FMV + Antidesfoque + Patches de widescreen + Patches sem entrelaçamento + VU Flag Hack + Detecção de loop INTC + Detecção de loop de espera + Esticamento de tempo do áudio + Buffer de áudio + Latência de saída + %1$d ms + Tempos de quadro + Estatísticas do GS + Informações de hardware + Versão + Exibição de entradas + Menu + Tela + Desempenho + HUD + Som + Online + Controles + Retomar + Pausar + Sair + BIOS importada: %1$s + Ficheiro de BIOS inválido + Jogo retro inválido + ROM não encontrada: %1$s + Não foi possível ler a ROM dentro deste arquivo + Núcleo não instalado: %1$s + Trapaças ativadas — as conquistas estão desativadas nesta sessão + Save na nuvem restaurado + Falha ao restaurar + Existe um save na nuvem mais recente para %1$s. Deseja sincronizar e qual save na nuvem prefere manter? + Save na nuvem + Retro + Falha ao carregar o núcleo do emulador + Falha ao carregar a ROM + Gráficos não suportados por este núcleo + Erro do emulador + Padrão + CRT + LCD + Nítido + SGSR + Upscaling SGSR + Nativa + Som + Analógico esquerdo: inverter X + Analógico esquerdo: inverter Y + Analógico direito: inverter X + Analógico direito: inverter Y + Controles na tela + Resposta tátil + Vertical + Horizontal + Editar disposição (%1$s) + Repor disposição %1$s + Disposição %1$s reposta + Cor dos botões + Cor das letras + Cor da sombra + Cor de fundo + Repor cores + Cores repostas + HUD de desempenho + Alfa + Alfa do fundo + Fundo + Escala + Tempo de fotograma numérico + Bateria de série dupla + ELEMENTOS DO HUD + FPS + Console + GPU + CPU + RAM + Bateria + Temp. + Gráfico + Temp. CPU + Salvar estado + Carregar estado + O carregamento de estados está desativado no modo Hardcore + Conquistas + Trapaças + As trapaças estão desativadas no modo Hardcore + Reiniciar + Avanço rápido + O avanço rápido está desativado no modo Hardcore + HUD + Disco %1$d/%2$d + Retomar + Pausar + Sair + Salvo no slot %1$d + Não foi possível salvar o estado + BIOS de %1$s necessária + Os jogos de PlayStation precisam de um arquivo de BIOS real do console que você deve fornecer. Importe uma BIOS (scph5501.bin, scph5500.bin, scph5502.bin, scph1001.bin ou scph7001.bin) para continuar. + Importar BIOS… + Cancelar + O slot %1$d está vazio + Slot %1$d carregado + Não foi possível carregar o estado + Slot %1$d + Renomear slot %1$d + Geral + Gráficos + Desempenho + HUD + Entrada + Áudio + Online + Cancelar + Guardar + Padrão + CRT + LCD + Nítido + 2x + 4x + Nativa + JOGO + Nome + Sistema + Núcleo do emulador + Caminho da ROM + BIOS do %1$s + Instalada + Nenhuma — necessária para executar jogos de %1$s + Importar BIOS… + Remover BIOS + IMAGENS DA BIBLIOTECA + Imagem do card do jogo + Imagem da grade + Imagem do carrossel + Imagem da lista + Imagem personalizada definida + Definir imagem + Remover + VÍDEO + Filtro de vídeo + SGSR + Upscaling SGSR + HUD de desempenho + NÚCLEO + Renderizador + Vulkan + OpenGL + Software + Escala de resolução + 1x (nativa) + 1.5x + 2x + 3x + 4x + Proporção da tela + Esticar + Automática (padrão) + 4:3 + 16:9 + Filtro de tela + Mais próximo + Bilinear (suave) + Bilinear (nítido) + Filtro de texturas + Bilinear (forçado) + Bilinear (PS2) + Bilinear (sprites) + Precisão da mistura + Mínima + Básica + Média + Alta + Completa + Máxima + Shader CRT / TV + Desligado + Linhas de varredura + Diagonal + Triangular + Onda + Lottes + 4xRGSS + NxAGSS + Ignorar fotogramas + Ignorar 1 + Ignorar 2 + Ignorar 3 + Mipmapping + DESEMPENHO + Taxa de ciclos EE + 50% + 60% + 75% + 100% (padrão) + 130% + 180% + 300% + Salto de ciclos EE + 1 + 2 + 3 + VU1 instantâneo + VU multithread (MTVU) + CDVD rápido + HUD DE DESEMPENHO + FPS + Velocidade de emulação + Uso da CPU + Uso da GPU + Resolução interna + Modo de desentrelaçamento + Automático + Desligado + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + Proporção de FMV + Antidesfoque + Patches de widescreen + Patches sem entrelaçamento + VU Flag Hack + Detecção de loop INTC + Detecção de loop de espera + Esticamento de tempo do áudio + Buffer de áudio + Latência de saída + %1$d ms + Tempos de quadro + Estatísticas do GS + Informações de hardware + Versão + Exibição de entradas + Inicialização rápida + ONLINE (DEV9) + Ativar online + Dispositivo Ethernet + Automático + Wi-Fi + Modo DNS + Manual + Interno + DNS primário + DNS secundário + opcional + IP automático (DHCP) + ENTRADA + Controles na tela + Resposta tátil + ÁUDIO + Volume + Sem som + Trocar canais estéreo + Som + PADRÕES RETRO + Padrões aplicados aos jogos de cada console, a menos que substituídos nas configurações do próprio jogo. + RETROACHIEVEMENTS + Conta + Sessão iniciada + Sem sessão iniciada — abra as Conquistas de um jogo para entrar + Conquistas ativadas + Modo Hardcore por padrão (sem estados salvos) + Sair + BIOS DO PLAYSTATION + Instalada + Nenhuma — os jogos de PS1 exigem uma BIOS + Importar BIOS do PS1… + BIOS do PS1 removida + Não há nenhuma BIOS para remover + Remover BIOS do PS1 + BIOS DO PLAYSTATION 2 + Nenhuma — os jogos de PS2 exigem uma BIOS + Formato + Cópia combinada em um único arquivo (.bin com região marcada, ~4MB). Conjuntos ROM0/MEC/NVM separados não são aceitos. + Importar BIOS do PS2… + BIOS do PS2 removida + Remover BIOS do PS2 + IMAGENS DA BIBLIOTECA + Imagem retro da caixa (cartucho / caixa de CD) + Imagem da caixa + Obtida automaticamente de thumbnails.libretro.com na importação; uma imagem personalizada sempre a substitui. + PASTA DE ROMS + Pasta + Não definida — escolha uma pasta para importar jogos automaticamente + Importação automática + Os novos jogos nesta pasta são adicionados automaticamente à sua biblioteca com o console correto detectado. + Selecionar pasta de ROMs + Selecionar pasta de ROMs… + Mudar pasta de ROMs… + Analisar agora + PADRÕES DO CONSOLE + Toque em um console para definir suas configurações padrão. + Renderizador + Escalonar resolução + Proporção da tela + Esticar + Automática (padrão) + 4:3 + 16:9 + Filtro de tela + Mais próximo + Bilinear (suave) + Bilinear (nítido) + Filtro de texturas + Bilinear (forçado) + Bilinear (PS2) + Bilinear (sprites) + Precisão da mistura + Mínima + Básica + Média + Alta + Completa + Máxima + Shader CRT / TV + Desligado + Linhas de varredura + Diagonal + Triangular + Onda + Lottes + 4xRGSS + NxAGSS + Ignorar fotogramas + Ignorar 1 + Ignorar 2 + Ignorar 3 + Mipmapping + Taxa de ciclos EE + 50% + 60% + 75% + 100% (padrão) + 130% + 180% + 300% + Salto de ciclos EE + Desligado + 1 + 2 + 3 + VU1 instantâneo + VU multithread (MTVU) + CDVD rápido + Controles de toque na tela + Som + Trocar canais estéreo + HUD: FPS + HUD: velocidade de emulação + HUD: uso da CPU + HUD: uso da GPU + HUD: resolução interna + Ativar online (DEV9) + Dispositivo Ethernet + Automático + Wi-Fi + Modo DNS + Manual + Interno + DNS primário + DNS secundário + opcional + IP automático (DHCP) + Shader + Upscaling SGSR + HUD de desempenho + CRÉDITOS & LICENÇAS + Alguns recursos do WinNative são baseados nestes projetos de código aberto. Toque para ver cada fonte. + Predefinições + Créditos + Ativar o modo Hardcore? + O modo Hardcore reinicia o jogo agora e desativa o carregamento de estados salvos, o avanço rápido e as trapaças. Qualquer progresso não salvo será perdido. Continuar? + Cancelar + Ativar + BIOS importada: %1$s + Ficheiro de BIOS inválido + BIOS da PS2 importada: %1$s + Ficheiro de BIOS da PS2 inválido + Não há número de série do jogo para procurar trapaças. + Foram aplicadas %1$d trapaça(s). + Não foi possível aplicar as trapaças. + Trapaças + Aplicar + Nenhuma trapaça encontrada para este jogo. + Conquistas + Entre no RetroAchievements + Nome de usuário + Senha + Falha ao entrar + Entrando… + Entrar + %1$d/%2$d • %3$d pts + Não há conquistas para este jogo. + Voltar + Ativado + Desativado + Renomear + Salvar + Conflito de save na nuvem + Manter save local + A + Menu + Tela + HUD + Som + Controles + Biblioteca atualizada + ROMs: %1$s + %1$d adicionados + %1$d removidos + Padrão + CRT + LCD + Nítido + Nativa + Proporção da tela + Filtro NTSC + Colorização + Correção de cor + Remover limite de sprites + Resolução + Emulação de framebuffer + Dithering + Hack widescreen + 8:7 (nativa) + 4:3 (TV) + Desligado + RF + Composto + S-Video + RGB + Automático + Tela GBA + Tela GBC + Ligado + 320x240 (nativa) + 640x480 + 960x720 + 1280x960 + 4:3 + 16:9 + 16:9 ajustado + Nativa + Interna + Ligado (16:9) + RETROACHIEVEMENTS + Entre com sua conta RetroAchievements para conquistar e acompanhar conquistas de jogos retro. + Nome de usuário + Senha + Digite seu nome de usuário e senha + Falha ao entrar + Entrar + Sua senha é usada apenas uma vez para obter um token de login, que é armazenado com segurança no dispositivo. + Conquistas ativadas + Modo Hardcore (sem estados salvos) + %1$d / %2$d pontos + Nenhuma conquista encontrada para este jogo. + Sair + TRAPAÇAS + Nome + Código + Cancelar + Guardar + Trapaça %1$d + Ainda não há trapaças. Adicione um código de trapaça para este jogo. + Adicionar trapaça + + Driver de GPU + Sistema (Padrão) + Instale os drivers Turnip em Configurações \u2192 Drivers. Os mesmos drivers funcionam para jogos de PC e de PS2. + + HDD do PS2 (DEV9) + Unidade interna virtual para jogos baseados em HDD como Final Fantasy XI. Reinicia o jogo. + Unidade interna virtual para jogos baseados em HDD como Final Fantasy XI. + Modo DNS definido como Internal para que seus hosts de servidor personalizados tenham efeito. + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + Add Cheat + Cheat name + Codes (one per line, e.g. 2021A268 00000000) + Custom + Enter a name and at least one valid code + Add + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + PS2 HDD Images + A .raw HDD image, or a .zip containing one (e.g. a game’s downloaded HDD with maps/DLC) + Import HDD Image + Importing… + Imported %1$s + Could not import HDD image + Removed %1$s + Remove %1$s + HDD Image + None + Cheats + Patches + PATCH + Custom + Applied %1$d cheat(s), %2$d patch(es). + No cheats or patches found for this game. + Cheat + Patch + Add + Núcleo da CPU + Núcleo Duplo + Trapaças Internas + Resolução Interna + Renderizador + Posição da Barra de Sensor + Pular Introdução do BIOS + + + + + + + Inferior + Interpretador em Cache + Hardware + Interpretador + JIT + Mouse / Toque + Analógico Direito (Absoluto) + Analógico Direito (Relativo) + Software + Esticar + Superior + Pulo de VBI (Salto de Quadros Automático) + Tela Panorâmica + Ponteiro do Wiimote + As alterações serão aplicadas na próxima vez que você iniciar este jogo. + Inicie este jogo uma vez para que o número de série do disco possa ser detectado; então as trapaças e correções aparecerão aqui. + Contorno de autenticação DNAS — necessário para jogar online + Aplicado Automaticamente (Online) + Trapaças & Correções + Tamanho: %1$s + Importar Imagem do HDD + Remover + Ativar NetPlay + Desativado por padrão. Ative e, em seguida, escolha Hospedar ou Entrar antes de iniciar.\nDesativa novamente ao sair do jogo. + Endereço do host + IP ou nome do host + Hospedar sessão + Ligado = aguardar um jogador. Desligado = entrar no endereço do host + O NetPlay usa portas de multijogador local via TCP (jogador 1 host / jogador 2 cliente). O online do PS2 usa Ethernet DEV9 em vez disso. + Porta + Cartão de Memória %1$d + Captura de Tela + Usar Salvamento na Nuvem + LAN (IP direto) + Conectando… + Conexão + Online (código do host) + Dispensar + O NetPlay de GameCube/Wii usa o próprio motor do Dolphin. Host = Jogador 1, Entrar = Jogador 2. Escolha Hospedar ou Entrar e um tipo de conexão antes de iniciar; ambos os dispositivos iniciam o mesmo jogo juntos. + Compartilhe o IP de Wi‑Fi do seu dispositivo e esta porta com o Jogador 2. O jogo começa automaticamente assim que ele se conectar. + Um código do host é exibido quando o jogo inicia — compartilhe-o com o Jogador 2. O jogo começa automaticamente assim que ele se conectar. + Insira o IP de Wi‑Fi e a porta do host, depois inicie para conectar. + Insira o código do host do Jogador 1, depois inicie para conectar. + Ative o NetPlay nas configurações do jogo e escolha Hospedar ou Entrar antes de iniciar + Encontrar salas no Wi‑Fi + Game Link · cada tela é seu próprio portátil + O multijogador de GBA usa gpSP + Adaptador Sem Fio. Certifique-se de que o libgpsp esteja instalado. + Multijogador de tela compartilhada via Wi‑Fi (como o RetroArch).\nHost = Jogador 1, Entrar = Jogador 2. Ambos os dispositivos mostram o mesmo jogo. + Game Link via Wi‑Fi — cada dispositivo roda seu próprio jogo.\nGB/GBC: link serial do Gambatte (Pokémon Ger. 1–2).\nGBA: Adaptador Sem Fio do gpSP (batalhas de Pokémon FR/LG/Emerald). + Hospedar sala + Código do host + Código do host de traversal fornecido pelo host + Hospedando sala + Toque em Hospedar para abrir uma sala para esta sessão de jogo, depois inicie o jogo. O NetPlay desativa ao sair. + Na sala + Entrar por IP + Entrou + Entrar + Ao iniciar + Sair + Host = J1 · Entrar = J2 · mesmo jogo em ambas as telas + Hospedar + Entrar + Manual + Nenhuma sala encontrada. Certifique-se de que o host esteja no mesmo Wi‑Fi e hospedando uma sala. + Nome de exibição + Mostrado a outros jogadores + %1$d conectado(s) + A sala fica aberta apenas para esta sessão. Inicie quando estiver pronto. Sair do jogo desativa o NetPlay. + Jogadores + Buscar no Wi‑Fi + Buscar novamente + Busque salas abertas no mesmo Wi‑Fi ou entre por endereço IP. + Buscando no Wi‑Fi… + Resultados da busca + Toque em uma sala para entrar agora (não salva o IP para a próxima inicialização). + Parar busca + NetPlay + %1$s conectou-se + %1$s desconectou-se + Aguardando jogadores… + O suporte a PlayStation 2 chegará em breve + Mostrar Botões L3 / R3 + Quando desativado, toque duas vezes em um analógico para clicar L3 / R3 + FLAGS DO DRIVER TURNIP + Aplicado apenas quando um driver de GPU personalizado é selecionado acima. + Arquivo do jogo não encontrado + Excluir + Importar de arquivo… + Carregando… + NetPlay + Wii Home + Mudar console + Identificar como console + Agora identificado como %1$s ReShade Aplique um efeito ReShade (.fx) a jogos DXVK/VKD3D (Vulkan) por meio da camada vkBasalt integrada. Coloque cada efeito em sua própria pasta em Android/data/<package>/files/ReShade/. O ajuste de parâmetros ao vivo e o botão no jogo chegarão com a atualização da camada de recarregamento ao vivo. @@ -1657,5 +2430,28 @@ Caminho instalado: Ativar ReShade Nenhum efeito ReShade neste conjunto. Adicione efeitos nas configurações deste jogo (ou do contêiner) para alterná-los e ajustá-los aqui. Este efeito não expõe parâmetros ajustáveis. + Excluindo save… + Excluir + Excluir permanentemente o save na nuvem de %1$s? Isso não pode ser desfeito. + Excluir save na nuvem + Não foi possível excluir o save na nuvem + Save na nuvem excluído + Baixe primeiro os núcleos de console — Configuracoes › Retro + Este dispositivo não pode executar a emulação de PS2 — ele precisa de OpenGL ES 3.1 ou mais recente. + Verificar atualizações + Verificando atualizações… + Baixar núcleos de console + Baixando… %1$d / %2$d MB + Núcleos de console + Instalado — build %1$s + Instalado — build %1$s (falha ao verificar atualizações) + Instalando… + Não instalado — baixe para jogar jogos retro + Status + Atualizar núcleos de console + Atualização disponível — build %1$s (%2$d MB) + Verificando o download… + Processando… + Sistema diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 36753863d..791d675c6 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1621,6 +1621,779 @@ Caminho instalado: A criação da pasta falhou Atualizar + Retro + Transferir save + Importe um save local para este jogo ou exporte o save atual. + Importar save + Exportar save + Save importado + Não foi possível importar o save + Save exportado + Não foi possível exportar o save + Ainda não existe um save para este jogo + Cheats + Os cheats estão desativados no modo Hardcore + + + Guardar + Cancelar + Guardar estado + Carregar estado + Proezas + Batotas + Cartões de memória + Avanço rápido + Reiniciar + Trocar disco + Ranhura %1$d + Toque para carregar + Vazia + Toque para substituir + Vazia — toque para guardar + A ranhura %1$d está vazia + Ranhura %1$d carregada + Não foi possível carregar a ranhura %1$d + Guardado na ranhura %1$d + Falha ao guardar + • Ranhura 1 + • Ranhura 2 + • Toque para usar + Novo cartão de memória + Importar cartão + Ativar online (DEV9) + Adaptador de rede da PS2 — reinicia o jogo para o ligar + Dispositivo Ethernet + Modo DNS + DNS primário + DNS secundário + opcional + IP automático (DHCP) + Servidor: %1$s + toque para definir o IP (em branco remove) + %1$s → IP + Adicionar anfitrião do servidor + Novo nome de anfitrião do servidor + p. ex. bf2.playbattlefront.com + Controlos no ecrã + Editar disposição + Repor disposição + Disposição reposta + Manípulo esquerdo: inverter X + Manípulo esquerdo: inverter Y + Manípulo direito: inverter X + Manípulo direito: inverter Y + Cor dos botões + Cor das letras + Cor da sombra + Cor de fundo + Repor cores + Renderizador + Vulkan + OpenGL + Software + Escala de resolução + 1x (nativa) + 1.5x + 2x + 3x + 4x + Proporção de imagem + Esticar + Automática (padrão) + 4:3 + 16:9 + Filtro de ecrã + Mais próximo + Bilinear (suave) + Bilinear (nítido) + Filtro de texturas + Bilinear (forçado) + Bilinear (PS2) + Bilinear (sprites) + Precisão da mistura + Mínima + Básica + Média + Alta + Completa + Máxima + Shader CRT / TV + Desligado + Linhas de varrimento + Diagonal + Triangular + Onda + Lottes + 4xRGSS + NxAGSS + Ignorar fotogramas + Desligado + Ignorar 1 + Ignorar 2 + Ignorar 3 + Mipmapping + Volume + %1$d%% + Sem som + Trocar canais estéreo + Taxa de ciclos EE + 50% + 60% + 75% + 100% (predefinição) + 130% + 180% + 300% + Salto de ciclos EE + Desligado + 1 + 2 + 3 + VU1 instantâneo + VU multitarefa (MTVU) + CDVD rápido + FPS + Velocidade de emulação + Utilização da CPU + Utilização da GPU + Resolução interna + Modo de desentrelaçamento + Automático + Desligado + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + Proporção de FMV + Antidesfoque + Patches de ecrã panorâmico + Patches sem entrelaçamento + VU Flag Hack + Deteção de ciclo INTC + Deteção de ciclo de espera + Esticamento de tempo do áudio + Buffer de áudio + Latência de saída + %1$d ms + Tempos de fotograma + Estatísticas do GS + Informações de hardware + Versão + Visualização de entradas + Menu + Ecrã + Desempenho + HUD + Som + Online + Controlos + Retomar + Pausar + Sair + BIOS importada: %1$s + Ficheiro de BIOS inválido + Jogo retro inválido + ROM não encontrada: %1$s + Não foi possível ler a ROM dentro deste arquivo + Núcleo não instalado: %1$s + Batotas ativadas — as proezas estão desativadas nesta sessão + Jogo guardado na nuvem restaurado + Falha ao restaurar + Existe um jogo guardado na nuvem mais recente para %1$s. Pretende sincronizar e qual jogo guardado na nuvem prefere manter? + Jogo guardado na nuvem + Retro + Falha ao carregar o núcleo do emulador + Falha ao carregar a ROM + Gráficos não suportados por este núcleo + Erro do emulador + Predefinição + CRT + LCD + Nítido + SGSR + Escalonamento SGSR + Nativa + Som + Manípulo esquerdo: inverter X + Manípulo esquerdo: inverter Y + Manípulo direito: inverter X + Manípulo direito: inverter Y + Controlos no ecrã + Retorno tátil + Vertical + Horizontal + Editar disposição (%1$s) + Repor disposição %1$s + Disposição %1$s reposta + Cor dos botões + Cor das letras + Cor da sombra + Cor de fundo + Repor cores + Cores repostas + HUD de desempenho + Alfa + Alfa do fundo + Fundo + Escala + Tempo de fotograma numérico + Bateria de série dupla + ELEMENTOS DO HUD + FPS + Consola + GPU + CPU + RAM + Bateria + Temp. + Gráfico + Temp. CPU + Guardar estado + Carregar estado + O carregamento de estados está desativado no modo Hardcore + Proezas + Batotas + As batotas estão desativadas no modo Hardcore + Reiniciar + Avanço rápido + O avanço rápido está desativado no modo Hardcore + HUD + Disco %1$d/%2$d + Retomar + Pausar + Sair + Guardado na ranhura %1$d + Não foi possível guardar o estado + BIOS de %1$s necessária + Os jogos da PlayStation precisam de um ficheiro de BIOS real da consola que tem de fornecer. Importe uma BIOS (scph5501.bin, scph5500.bin, scph5502.bin, scph1001.bin ou scph7001.bin) para continuar. + Importar BIOS… + Cancelar + A ranhura %1$d está vazia + Ranhura %1$d carregada + Não foi possível carregar o estado + Ranhura %1$d + Mudar o nome da ranhura %1$d + Geral + Gráficos + Desempenho + HUD + Entrada + Áudio + Online + Cancelar + Guardar + Predefinição + CRT + LCD + Nítido + 2x + 4x + Nativa + JOGO + Nome + Sistema + Núcleo do emulador + Caminho da ROM + BIOS de %1$s + Instalada + Nenhuma — necessária para executar jogos de %1$s + Importar BIOS… + Remover BIOS + IMAGENS DA BIBLIOTECA + Imagem do cartão do jogo + Imagem da grelha + Imagem do carrossel + Imagem da lista + Imagem personalizada definida + Definir imagem + Remover + VÍDEO + Filtro de vídeo + SGSR + Escalonamento SGSR + HUD de desempenho + NÚCLEO + Renderizador + Vulkan + OpenGL + Software + Escala de resolução + 1x (nativa) + 1.5x + 2x + 3x + 4x + Proporção de imagem + Esticar + Automática (padrão) + 4:3 + 16:9 + Filtro de ecrã + Mais próximo + Bilinear (suave) + Bilinear (nítido) + Filtro de texturas + Bilinear (forçado) + Bilinear (PS2) + Bilinear (sprites) + Precisão da mistura + Mínima + Básica + Média + Alta + Completa + Máxima + Shader CRT / TV + Desligado + Linhas de varrimento + Diagonal + Triangular + Onda + Lottes + 4xRGSS + NxAGSS + Ignorar fotogramas + Ignorar 1 + Ignorar 2 + Ignorar 3 + Mipmapping + DESEMPENHO + Taxa de ciclos EE + 50% + 60% + 75% + 100% (predefinição) + 130% + 180% + 300% + Salto de ciclos EE + 1 + 2 + 3 + VU1 instantâneo + VU multitarefa (MTVU) + CDVD rápido + HUD DE DESEMPENHO + FPS + Velocidade de emulação + Utilização da CPU + Utilização da GPU + Resolução interna + Modo de desentrelaçamento + Automático + Desligado + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + Proporção de FMV + Antidesfoque + Patches de ecrã panorâmico + Patches sem entrelaçamento + VU Flag Hack + Deteção de ciclo INTC + Deteção de ciclo de espera + Esticamento de tempo do áudio + Buffer de áudio + Latência de saída + %1$d ms + Tempos de fotograma + Estatísticas do GS + Informações de hardware + Versão + Visualização de entradas + Arranque rápido + ONLINE (DEV9) + Ativar online + Dispositivo Ethernet + Automático + Wi-Fi + Modo DNS + Manual + Interno + DNS primário + DNS secundário + opcional + IP automático (DHCP) + ENTRADA + Controlos no ecrã + Retorno tátil + ÁUDIO + Volume + Sem som + Trocar canais estéreo + Som + PREDEFINIÇÕES RETRO + Predefinições aplicadas aos jogos de cada consola, salvo se substituídas nas definições do próprio jogo. + RETROACHIEVEMENTS + Conta + Sessão iniciada + Sem sessão iniciada — abra as Proezas de um jogo para iniciar sessão + Proezas ativadas + Modo Hardcore por predefinição (sem estados guardados) + Terminar sessão + BIOS DA PLAYSTATION + Instalada + Nenhuma — os jogos da PS1 requerem uma BIOS + Importar BIOS da PS1… + BIOS da PS1 removida + Não há nenhuma BIOS para remover + Remover BIOS da PS1 + BIOS DA PLAYSTATION 2 + Nenhuma — os jogos da PS2 requerem uma BIOS + Formato + Cópia combinada num único ficheiro (.bin com região etiquetada, ~4MB). Conjuntos ROM0/MEC/NVM separados não são aceites. + Importar BIOS da PS2… + BIOS da PS2 removida + Remover BIOS da PS2 + IMAGENS DA BIBLIOTECA + Imagem retro da caixa (cartucho / caixa de CD) + Imagem da caixa + Obtida automaticamente de thumbnails.libretro.com na importação; uma imagem personalizada substitui-a sempre. + PASTA DE ROMS + Pasta + Não definida — escolha uma pasta para importar jogos automaticamente + Importação automática + Os novos jogos nesta pasta são adicionados automaticamente à sua biblioteca com a consola correta detetada. + Selecionar pasta de ROMs + Selecionar pasta de ROMs… + Mudar pasta de ROMs… + Analisar agora + PREDEFINIÇÕES DA CONSOLA + Toque numa consola para definir as suas predefinições. + Renderizador + Escalonar resolução + Proporção de imagem + Esticar + Automática (padrão) + 4:3 + 16:9 + Filtro de ecrã + Mais próximo + Bilinear (suave) + Bilinear (nítido) + Filtro de texturas + Bilinear (forçado) + Bilinear (PS2) + Bilinear (sprites) + Precisão da mistura + Mínima + Básica + Média + Alta + Completa + Máxima + Shader CRT / TV + Desligado + Linhas de varrimento + Diagonal + Triangular + Onda + Lottes + 4xRGSS + NxAGSS + Ignorar fotogramas + Ignorar 1 + Ignorar 2 + Ignorar 3 + Mipmapping + Taxa de ciclos EE + 50% + 60% + 75% + 100% (predefinição) + 130% + 180% + 300% + Salto de ciclos EE + Desligado + 1 + 2 + 3 + VU1 instantâneo + VU multitarefa (MTVU) + CDVD rápido + Controlos tácteis no ecrã + Som + Trocar canais estéreo + HUD: FPS + HUD: velocidade de emulação + HUD: utilização da CPU + HUD: utilização da GPU + HUD: resolução interna + Ativar online (DEV9) + Dispositivo Ethernet + Automático + Wi-Fi + Modo DNS + Manual + Interno + DNS primário + DNS secundário + opcional + IP automático (DHCP) + Shader + Escalonamento SGSR + HUD de desempenho + CRÉDITOS & LICENÇAS + Algumas funcionalidades do WinNative baseiam-se nestes projetos de código aberto. Toque para ver cada fonte. + Predefinições + Créditos + Ativar o modo Hardcore? + O modo Hardcore reinicia o jogo agora e desativa o carregamento de estados guardados, o avanço rápido e as batotas. Qualquer progresso não guardado será perdido. Continuar? + Cancelar + Ativar + BIOS importada: %1$s + Ficheiro de BIOS inválido + BIOS da PS2 importada: %1$s + Ficheiro de BIOS da PS2 inválido + Não há número de série do jogo para procurar batotas. + Foram aplicadas %1$d batota(s). + Não foi possível aplicar as batotas. + Batotas + Aplicar + Não foram encontradas batotas para este jogo. + Proezas + Inicie sessão no RetroAchievements + Nome de utilizador + Palavra-passe + Falha ao iniciar sessão + A iniciar sessão… + Iniciar sessão + %1$d/%2$d • %3$d pts + Não há proezas para este jogo. + Voltar + Ativado + Desativado + Mudar o nome + Guardar + Conflito de jogo guardado na nuvem + Manter jogo guardado local + A + Menu + Ecrã + HUD + Som + Controlos + Biblioteca atualizada + ROMs: %1$s + %1$d adicionados + %1$d removidos + Predefinição + CRT + LCD + Nítido + Nativa + Proporção de imagem + Filtro NTSC + Colorização + Correção de cor + Remover limite de sprites + Resolução + Emulação de framebuffer + Dithering + Hack panorâmico + 8:7 (nativa) + 4:3 (TV) + Desligado + RF + Composto + S-Video + RGB + Automático + Ecrã GBA + Ecrã GBC + Ligado + 320x240 (nativa) + 640x480 + 960x720 + 1280x960 + 4:3 + 16:9 + 16:9 ajustado + Nativa + Interna + Ligado (16:9) + RETROACHIEVEMENTS + Inicie sessão com a sua conta RetroAchievements para conquistar e acompanhar proezas de jogos retro. + Nome de utilizador + Palavra-passe + Introduza o seu nome de utilizador e palavra-passe + Falha ao iniciar sessão + Iniciar sessão + A sua palavra-passe é usada apenas uma vez para obter um token de início de sessão, que é armazenado em segurança no dispositivo. + Proezas ativadas + Modo Hardcore (sem estados guardados) + %1$d / %2$d pontos + Não foram encontradas proezas para este jogo. + Terminar sessão + BATOTAS + Nome + Código + Cancelar + Guardar + Batota %1$d + Ainda não há batotas. Adicione um código de batota para este jogo. + Adicionar batota + + Controlador de GPU + Sistema (Predefinição) + Instala os controladores Turnip em Definições \u2192 Controladores. Os mesmos controladores funcionam para jogos de PC e de PS2. + + HDD do PS2 (DEV9) + Unidade interna virtual para jogos baseados em HDD como Final Fantasy XI. Reinicia o jogo. + Unidade interna virtual para jogos baseados em HDD como Final Fantasy XI. + Modo DNS definido como Internal para que os teus hosts de servidor personalizados tenham efeito. + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + Add Cheat + Cheat name + Codes (one per line, e.g. 2021A268 00000000) + Custom + Enter a name and at least one valid code + Add + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + PS2 HDD Images + A .raw HDD image, or a .zip containing one (e.g. a game’s downloaded HDD with maps/DLC) + Import HDD Image + Importing… + Imported %1$s + Could not import HDD image + Removed %1$s + Remove %1$s + HDD Image + None + Cheats + Patches + PATCH + Custom + Applied %1$d cheat(s), %2$d patch(es). + No cheats or patches found for this game. + Cheat + Patch + Add + Núcleo do CPU + Núcleo Duplo + Cheats Internos + Resolução Interna + Renderizador + Posição da Barra de Sensor + Ignorar Introdução do BIOS + + + + + + + Inferior + Interpretador em Cache + Hardware + Interpretador + JIT + Rato / Toque + Stick Direito (Absoluto) + Stick Direito (Relativo) + Software + Esticar + Superior + Ignorar VBI (Salto Automático de Fotogramas) + Ecrã Panorâmico + Ponteiro do Wiimote + As alterações são aplicadas da próxima vez que iniciar este jogo. + Inicie este jogo uma vez para que o número de série do disco possa ser detetado; depois, os cheats e patches aparecerão aqui. + Contorno da autenticação DNAS — necessário para jogar online + Aplicado Automaticamente (Online) + Cheats & Patches + Tamanho: %1$s + Importar Imagem de HDD + Remover + Ativar NetPlay + Desativado por predefinição. Ative e, em seguida, escolha Alojar ou Juntar-se antes de iniciar.\nVolta a desativar-se quando sai do jogo. + Endereço do anfitrião + IP ou nome de anfitrião + Alojar sessão + Ligado = aguardar um jogador. Desligado = juntar-se ao endereço do anfitrião + O NetPlay utiliza portas de multijogador local através de TCP (jogador 1 anfitrião / jogador 2 cliente). O online da PS2 utiliza Ethernet DEV9 em vez disso. + Porta + Cartão de Memória %1$d + Captura de Ecrã + Utilizar Gravação na Nuvem + LAN (IP direto) + A ligar… + Ligação + Online (código de anfitrião) + Dispensar + O NetPlay de GameCube/Wii utiliza o motor próprio do Dolphin. Anfitrião = Jogador 1, Juntar-se = Jogador 2. Escolha Alojar ou Juntar-se e um tipo de ligação antes de iniciar; ambos os dispositivos arrancam o mesmo jogo em conjunto. + Partilhe o IP de Wi‑Fi do seu dispositivo e esta porta com o Jogador 2. O jogo inicia automaticamente assim que se ligarem. + É apresentado um código de anfitrião quando o jogo arranca — partilhe-o com o Jogador 2. O jogo inicia automaticamente assim que se ligarem. + Introduza o IP de Wi‑Fi e a porta do anfitrião e, em seguida, inicie para ligar. + Introduza o código de anfitrião do Jogador 1 e, em seguida, inicie para ligar. + Ative o NetPlay nas definições do jogo e escolha Alojar ou Juntar-se antes de iniciar + Procurar salas na Wi‑Fi + Game Link · cada ecrã é a sua própria consola portátil + O multijogador de GBA utiliza gpSP + Adaptador Sem Fios. Certifique-se de que o libgpsp está instalado. + Multijogador de ecrã partilhado através de Wi‑Fi (como o RetroArch).\nAnfitrião = Jogador 1, Juntar-se = Jogador 2. Ambos os dispositivos mostram o mesmo jogo. + Game Link através de Wi‑Fi — cada dispositivo executa o seu próprio jogo.\nGB/GBC: ligação série do Gambatte (Pokémon Gen 1–2).\nGBA: Adaptador Sem Fios do gpSP (combates de Pokémon FR/LG/Emerald). + Alojar sala + Código de anfitrião + Código de anfitrião de travessia fornecido pelo anfitrião + A alojar sala + Toque em Alojar para abrir uma sala para esta sessão de jogo e, em seguida, inicie o jogo. O NetPlay desativa-se quando sai. + Na sala + Juntar-se por IP + Juntou-se + Juntar-se + Ao iniciar + Sair + Anfitrião = P1 · Juntar-se = P2 · o mesmo jogo em ambos os ecrãs + Alojar + Juntar-se + Manual + Nenhuma sala encontrada. Certifique-se de que o anfitrião está na mesma Wi‑Fi e a alojar uma sala. + Nome de apresentação + Mostrado aos outros jogadores + %1$d ligado(s) + A sala está aberta apenas para esta sessão. Inicie quando estiver pronto. Sair do jogo desativa o NetPlay. + Jogadores + Procurar Wi‑Fi + Procurar novamente + Procure na mesma Wi‑Fi por salas abertas ou junte-se por endereço IP. + A procurar Wi‑Fi… + Resultados da procura + Toque numa sala para se juntar agora (não guarda o IP para o próximo início). + Parar procura + NetPlay + %1$s ligou-se + %1$s desligou-se + A aguardar jogadores… + O suporte para PlayStation 2 chegará em breve + Mostrar Botões L3 / R3 + Quando desligado, toque duas vezes num stick para clicar em L3 / R3 + FLAGS DO CONTROLADOR TURNIP + Aplicado apenas quando um controlador de GPU personalizado é selecionado acima. + Ficheiro do jogo não encontrado + Eliminar + Importar de ficheiro… + A carregar… + NetPlay + Wii Home + Mudar de consola + Identificar como consola + Agora identificado como %1$s ReShade Aplique um efeito ReShade (.fx) a jogos DXVK/VKD3D (Vulkan) através da camada vkBasalt integrada. Coloque cada efeito na sua própria pasta em Android/data/<package>/files/ReShade/. O ajuste de parâmetros em tempo real e o botão no jogo chegarão com a atualização da camada de recarregamento em tempo real. @@ -1656,4 +2429,27 @@ Caminho instalado: Ativar ReShade Não há efeitos ReShade neste conjunto. Adicione efeitos nas definições deste jogo (ou do contentor) para os alternar e ajustar aqui. Este efeito não expõe parâmetros ajustáveis. + A eliminar jogo guardado… + Eliminar + Eliminar permanentemente o jogo guardado na nuvem de %1$s? Esta ação não pode ser anulada. + Eliminar Jogo Guardado na Nuvem + Não foi possível eliminar o jogo guardado na nuvem + Jogo guardado na nuvem eliminado + Transfira primeiro os núcleos de consola — Definições › Retro + Este dispositivo não consegue executar a emulação de PS2 — necessita de OpenGL ES 3.1 ou mais recente. + Procurar atualizações + A procurar atualizações… + Transferir núcleos de consola + A transferir… %1$d / %2$d MB + Núcleos de Consola + Instalado — compilação %1$s + Instalado — compilação %1$s (falha ao procurar atualizações) + A instalar… + Não instalado — transfira para jogar jogos retro + Estado + Atualizar núcleos de consola + Atualização disponível — compilação %1$s (%2$d MB) + A verificar a transferência… + A processar… + Sistema diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index 2577a0474..1e8086a12 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -1621,6 +1621,779 @@ Cale instalata: Rulează în fundal Menține chatul activ după ce ieși din WinNative Reîmprospătează + Retro + Transferă salvarea + Importă o salvare locală în acest joc sau exportă salvarea curentă. + Importă salvarea + Exportă salvarea + Salvare importată + Salvarea nu a putut fi importată + Salvare exportată + Salvarea nu a putut fi exportată + Nu există încă o salvare pentru acest joc + Coduri + Codurile sunt dezactivate în modul Hardcore + + + Salvează + Anulează + Salvare de stare + Încarcă salvarea de stare + Realizări + Coduri + Carduri de memorie + Derulare rapidă + Resetează + Schimbă discul + Slot %1$d + Atinge pentru a încărca + Gol + Atinge pentru a suprascrie + Gol — atinge pentru a salva + Slotul %1$d este gol + Slotul %1$d încărcat + Nu s-a putut încărca slotul %1$d + Salvat în slotul %1$d + Salvarea a eșuat + • Slot 1 + • Slot 2 + • Atinge pentru a folosi + Card de memorie nou + Importă card + Activează modul online (DEV9) + Adaptor de rețea PS2 — repornește jocul pentru a-l atașa + Dispozitiv Ethernet + Mod DNS + DNS principal + DNS secundar + opțional + IP automat (DHCP) + Server: %1$s + atinge pentru a seta IP-ul (gol pentru a elimina) + %1$s → IP + Adaugă gazdă server + Nume nou de gazdă server + ex. bf2.playbattlefront.com + Comenzi pe ecran + Editează aspectul + Resetează aspectul + Aspect resetat + Stick stâng: inversează X + Stick stâng: inversează Y + Stick drept: inversează X + Stick drept: inversează Y + Culoare butoane + Culoare litere + Culoare umbră + Culoare fundal + Resetează culorile + Motor de randare + Vulkan + OpenGL + Software + Scală rezoluție + 1x (nativă) + 1.5x + 2x + 3x + 4x + Raport de aspect + Întinde + Auto (standard) + 4:3 + 16:9 + Filtru afișaj + Cel mai apropiat + Biliniar (fin) + Biliniar (clar) + Filtru textură + Biliniar (forțat) + Biliniar (PS2) + Biliniar (sprite-uri) + Precizie amestecare + Minimă + De bază + Medie + Ridicată + Completă + Maximă + Shader CRT / TV + Dezactivat + Linii de scanare + Diagonal + Triunghiular + Undă + Lottes + 4xRGSS + NxAGSS + Omitere cadre + Dezactivat + Omite 1 + Omite 2 + Omite 3 + Mipmapping + Volum + %1$d%% + Fără sunet + Inversează canalele stereo + Frecvență cicluri EE + 50% + 60% + 75% + 100% (implicit) + 130% + 180% + 300% + Omitere cicluri EE + Dezactivat + 1 + 2 + 3 + VU1 instant + VU multi-thread (MTVU) + CDVD rapid + FPS + Viteză emulare + Utilizare CPU + Utilizare GPU + Rezoluție internă + Mod deîntrețesere + Auto + Dezactivat + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + Raport de aspect FMV + Anti-neclaritate + Patch-uri widescreen + Patch-uri fără întrețesere + VU Flag Hack + Detectare buclă INTC + Detectare buclă de așteptare + Întindere temporală audio + Buffer audio + Latență de ieșire + %1$d ms + Timpi de cadru + Statistici GS + Informații hardware + Versiune + Afișare intrări + Meniu + Afișaj + Performanță + HUD + Sunet + Online + Comenzi + Reia + Pauză + Ieșire + BIOS importat: %1$s + Fișier BIOS nevalid + Joc retro nevalid + ROM negăsit: %1$s + Nu s-a putut citi ROM-ul din această arhivă + Core neinstalat: %1$s + Coduri activate — realizările sunt dezactivate pentru această sesiune + Salvare din cloud restaurată + Restaurarea a eșuat + Există o salvare din cloud mai recentă pentru %1$s. Dorești să sincronizezi și pe care salvare din cloud preferi să o păstrezi? + Salvare din cloud + Retro + Încărcarea core-ului de emulare a eșuat + Încărcarea ROM-ului a eșuat + Grafica nu este acceptată pentru acest core + Eroare de emulator + Implicit + CRT + LCD + Clar + SGSR + Mărire SGSR + Nativă + Sunet + Stick stâng: inversează X + Stick stâng: inversează Y + Stick drept: inversează X + Stick drept: inversează Y + Comenzi pe ecran + Feedback haptic + Portret + Peisaj + Editează aspectul (%1$s) + Resetează aspectul %1$s + Aspect %1$s resetat + Culoare butoane + Culoare litere + Culoare umbră + Culoare fundal + Resetează culorile + Culori resetate + HUD performanță + Alfa + Alfa fundal + Fundal + Scală + Timp de cadru numeric + Baterie dublă serie + ELEMENTE HUD + FPS + Consolă + GPU + CPU + RAM + Baterie + Temp. + Grafic + Temp. CPU + Salvare de stare + Încarcă salvarea de stare + Încărcarea salvărilor este dezactivată în modul Hardcore + Realizări + Coduri + Codurile sunt dezactivate în modul Hardcore + Resetează + Derulare rapidă + Derularea rapidă este dezactivată în modul Hardcore + HUD + Disc %1$d/%2$d + Reia + Pauză + Ieșire + Salvat în slotul %1$d + Nu s-a putut salva starea + BIOS %1$s necesar + Jocurile PlayStation au nevoie de un fișier BIOS real de consolă pe care trebuie să îl furnizezi. Importă un BIOS (scph5501.bin, scph5500.bin, scph5502.bin, scph1001.bin sau scph7001.bin) pentru a continua. + Importă BIOS… + Anulează + Slotul %1$d este gol + Slotul %1$d încărcat + Nu s-a putut încărca starea + Slot %1$d + Redenumește slotul %1$d + General + Grafică + Performanță + HUD + Intrare + Audio + Online + Anulează + Salvează + Implicit + CRT + LCD + Clar + 2x + 4x + Nativă + JOC + Nume + Sistem + Core emulator + Cale ROM + BIOS %1$s + Instalat + Niciunul — necesar pentru a rula jocurile %1$s + Importă BIOS… + Elimină BIOS + GRAFICĂ BIBLIOTECĂ + Imagine fișă joc + Imagine grilă + Imagine carusel + Imagine listă + Imagine personalizată setată + Setează imaginea + Elimină + VIDEO + Filtru video + SGSR + Mărire SGSR + HUD performanță + CORE + Motor de randare + Vulkan + OpenGL + Software + Scală rezoluție + 1x (nativă) + 1.5x + 2x + 3x + 4x + Raport de aspect + Întinde + Auto (standard) + 4:3 + 16:9 + Filtru afișaj + Cel mai apropiat + Biliniar (fin) + Biliniar (clar) + Filtru textură + Biliniar (forțat) + Biliniar (PS2) + Biliniar (sprite-uri) + Precizie amestecare + Minimă + De bază + Medie + Ridicată + Completă + Maximă + Shader CRT / TV + Dezactivat + Linii de scanare + Diagonal + Triunghiular + Undă + Lottes + 4xRGSS + NxAGSS + Omitere cadre + Omite 1 + Omite 2 + Omite 3 + Mipmapping + PERFORMANȚĂ + Frecvență cicluri EE + 50% + 60% + 75% + 100% (implicit) + 130% + 180% + 300% + Omitere cicluri EE + 1 + 2 + 3 + VU1 instant + VU multi-thread (MTVU) + CDVD rapid + HUD PERFORMANȚĂ + FPS + Viteză emulare + Utilizare CPU + Utilizare GPU + Rezoluție internă + Mod deîntrețesere + Auto + Dezactivat + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + Raport de aspect FMV + Anti-neclaritate + Patch-uri widescreen + Patch-uri fără întrețesere + VU Flag Hack + Detectare buclă INTC + Detectare buclă de așteptare + Întindere temporală audio + Buffer audio + Latență de ieșire + %1$d ms + Timpi de cadru + Statistici GS + Informații hardware + Versiune + Afișare intrări + Pornire rapidă + ONLINE (DEV9) + Activează modul online + Dispozitiv Ethernet + Auto + Wi-Fi + Mod DNS + Manual + Intern + DNS principal + DNS secundar + opțional + IP automat (DHCP) + INTRARE + Comenzi pe ecran + Feedback haptic + AUDIO + Volum + Fără sunet + Inversează canalele stereo + Sunet + SETĂRI RETRO IMPLICITE + Setări implicite aplicate jocurilor fiecărei console, cu excepția celor modificate în setările proprii ale unui joc. + RETROACHIEVEMENTS + Cont + Conectat + Neconectat — deschide Realizările unui joc pentru a te conecta + Realizări activate + Mod Hardcore implicit (fără salvări de stare) + Deconectează-te + BIOS PLAYSTATION + Instalat + Niciunul — jocurile PS1 necesită un BIOS + Importă BIOS PS1… + BIOS PS1 eliminat + Niciun BIOS de eliminat + Elimină BIOS PS1 + BIOS PLAYSTATION 2 + Niciunul — jocurile PS2 necesită un BIOS + Format + Dump unificat într-un singur fișier (.bin etichetat cu regiunea, ~4 MB). Seturile ROM0/MEC/NVM separate nu sunt acceptate. + Importă BIOS PS2… + BIOS PS2 eliminat + Elimină BIOS PS2 + GRAFICĂ BIBLIOTECĂ + Grafică retro (cartuș / cutie CD) + Copertă + Preluată automat de pe thumbnails.libretro.com la import; o imagine personalizată o înlocuiește întotdeauna. + DOSAR ROM-URI + Dosar + Nesetat — alege un dosar pentru a importa automat jocuri + Import automat + Jocurile noi din acest dosar sunt adăugate automat în bibliotecă, cu consola corectă detectată. + Selectează dosarul ROM-urilor + Selectează dosarul ROM-urilor… + Schimbă dosarul ROM-urilor… + Scanează acum + SETĂRI CONSOLĂ IMPLICITE + Atinge o consolă pentru a-i seta setările implicite. + Motor de randare + Rezoluție mărire + Raport de aspect + Întinde + Auto (standard) + 4:3 + 16:9 + Filtru afișaj + Cel mai apropiat + Biliniar (fin) + Biliniar (clar) + Filtru textură + Biliniar (forțat) + Biliniar (PS2) + Biliniar (sprite-uri) + Precizie amestecare + Minimă + De bază + Medie + Ridicată + Completă + Maximă + Shader CRT / TV + Dezactivat + Linii de scanare + Diagonal + Triunghiular + Undă + Lottes + 4xRGSS + NxAGSS + Omitere cadre + Omite 1 + Omite 2 + Omite 3 + Mipmapping + Frecvență cicluri EE + 50% + 60% + 75% + 100% (implicit) + 130% + 180% + 300% + Omitere cicluri EE + Dezactivat + 1 + 2 + 3 + VU1 instant + VU multi-thread (MTVU) + CDVD rapid + Comenzi tactile pe ecran + Sunet + Inversează canalele stereo + HUD: FPS + HUD: viteză emulare + HUD: utilizare CPU + HUD: utilizare GPU + HUD: rezoluție internă + Activează modul online (DEV9) + Dispozitiv Ethernet + Auto + Wi-Fi + Mod DNS + Manual + Intern + DNS principal + DNS secundar + opțional + IP automat (DHCP) + Shader + Mărire SGSR + HUD performanță + CREDITE & LICENȚE + Unele funcții ale WinNative sunt construite pe aceste proiecte open-source. Atinge pentru a vedea fiecare sursă. + Implicite + Credite + Activezi modul Hardcore? + Modul Hardcore resetează jocul acum și dezactivează încărcarea salvărilor de stare, derularea rapidă și codurile. Orice progres nesalvat va fi pierdut. Continui? + Anulează + Activează + BIOS importat: %1$s + Fișier BIOS nevalid + BIOS PS2 importat: %1$s + Fișier BIOS PS2 nevalid + Niciun număr de serie al jocului pentru a căuta coduri. + S-au aplicat %1$d cod(uri). + Nu s-au putut aplica codurile. + Coduri + Aplică + Niciun cod găsit pentru acest joc. + Realizări + Conectează-te la RetroAchievements + Nume de utilizator + Parolă + Conectarea a eșuat + Conectare în curs… + Conectează-te + %1$d/%2$d • %3$d pct + Nicio realizare pentru acest joc. + Înapoi + Activat + Dezactivat + Redenumește + Salvează + Conflict de salvare din cloud + Păstrează salvarea locală + A + Meniu + Afișaj + HUD + Sunet + Comenzi + Bibliotecă actualizată + ROM-uri: %1$s + %1$d adăugate + %1$d eliminate + Implicit + CRT + LCD + Clar + Nativă + Raport de aspect + Filtru NTSC + Colorare + Corecție de culoare + Elimină limita de sprite-uri + Rezoluție + Emulare framebuffer + Dithering + Hack ecran lat + 8:7 (nativă) + 4:3 (TV) + Dezactivat + RF + Compozit + S-Video + RGB + Auto + Ecran GBA + Ecran GBC + Activat + 320x240 (nativă) + 640x480 + 960x720 + 1280x960 + 4:3 + 16:9 + 16:9 ajustat + Nativă + Internă + Activat (16:9) + RETROACHIEVEMENTS + Conectează-te cu contul tău RetroAchievements pentru a câștiga și urmări realizări pentru jocuri retro. + Nume de utilizator + Parolă + Introdu numele de utilizator și parola + Conectarea a eșuat + Conectează-te + Parola ta este folosită o singură dată pentru a obține un token de conectare, stocat în siguranță pe dispozitiv. + Realizări activate + Mod Hardcore (fără salvări de stare) + %1$d / %2$d puncte + Nicio realizare găsită pentru acest joc. + Deconectează-te + CODURI + Nume + Cod + Anulează + Salvează + Cod %1$d + Niciun cod încă. Adaugă un cod pentru acest joc. + Adaugă cod + + Driver GPU + Sistem (Implicit) + Instalează driverele Turnip din Setări \u2192 Drivere. Aceleași drivere funcționează atât pentru jocurile PC, cât și PS2. + + HDD PS2 (DEV9) + Unitate internă virtuală pentru jocuri bazate pe HDD precum Final Fantasy XI. Repornește jocul. + Unitate internă virtuală pentru jocuri bazate pe HDD precum Final Fantasy XI. + Mod DNS setat pe Internal pentru ca gazdele tale de server personalizate să aibă efect. + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + Add Cheat + Cheat name + Codes (one per line, e.g. 2021A268 00000000) + Custom + Enter a name and at least one valid code + Add + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + PS2 HDD Images + A .raw HDD image, or a .zip containing one (e.g. a game’s downloaded HDD with maps/DLC) + Import HDD Image + Importing… + Imported %1$s + Could not import HDD image + Removed %1$s + Remove %1$s + HDD Image + None + Cheats + Patches + PATCH + Custom + Applied %1$d cheat(s), %2$d patch(es). + No cheats or patches found for this game. + Cheat + Patch + Add + Nucleu CPU + Dublu nucleu + Coduri interne + Rezoluție internă + Randator + Poziția barei de senzori + Omite introducerea BIOS + + + + + + + Jos + Interpretor în cache + Hardware + Interpretor + JIT + Mouse / Atingere + Stick dreapta (Absolut) + Stick dreapta (Relativ) + Software + Întindere + Sus + Omitere VBI (Săritură automată de cadre) + Ecran lat + Indicator Wiimote + Modificările se aplică data viitoare când pornești acest joc. + Pornește acest joc o dată pentru ca seria discului să poată fi detectată, apoi codurile și patch-urile vor apărea aici. + Ocolire autentificare DNAS — necesară pentru jocul online + Aplicat automat (Online) + Coduri & Patch-uri + Dimensiune: %1$s + Importă imagine HDD + Elimină + Activează NetPlay + Dezactivat implicit. Activează, apoi alege Găzduire sau Alăturare înainte de pornire.\nSe dezactivează din nou când ieși din joc. + Adresă gazdă + IP sau nume de gazdă + Sesiune de găzduire + Pornit = așteaptă un jucător. Oprit = alătură-te adresei gazdei + NetPlay folosește porturi de multiplayer local prin TCP (jucătorul 1 gazdă / jucătorul 2 client). Online-ul PS2 folosește în schimb Ethernet DEV9. + Port + Card de memorie %1$d + Captură de ecran + Folosește salvarea în cloud + LAN (IP direct) + Se conectează… + Conexiune + Online (cod gazdă) + Închide + NetPlay pentru GameCube/Wii folosește propriul motor Dolphin. Gazdă = Jucătorul 1, Alăturare = Jucătorul 2. Alege Găzduire sau Alăturare și un tip de conexiune înainte de pornire; ambele dispozitive pornesc împreună același joc. + Partajează IP-ul Wi‑Fi al dispozitivului tău și acest port cu Jucătorul 2. Jocul pornește automat odată ce se conectează. + Un cod gazdă este afișat când pornește jocul — partajează-l cu Jucătorul 2. Jocul pornește automat odată ce se conectează. + Introdu IP-ul Wi‑Fi al gazdei și portul, apoi pornește pentru a te conecta. + Introdu codul gazdă de la Jucătorul 1, apoi pornește pentru a te conecta. + Activează NetPlay în setările jocului și alege Găzduire sau Alăturare înainte de pornire + Găsește camere pe Wi‑Fi + Game Link · fiecare ecran este propria consolă portabilă + Multiplayer-ul GBA folosește gpSP + Adaptor wireless. Asigură-te că libgpsp este instalat. + Multiplayer cu ecran partajat prin Wi‑Fi (ca RetroArch).\nGazdă = Jucătorul 1, Alăturare = Jucătorul 2. Ambele dispozitive afișează același joc. + Game Link prin Wi‑Fi — fiecare dispozitiv rulează propriul joc.\nGB/GBC: legătură serială Gambatte (Pokémon Gen 1–2).\nGBA: Adaptor wireless gpSP (lupte Pokémon FR/LG/Emerald). + Găzduiește cameră + Cod gazdă + Cod gazdă de traversare de la gazdă + Se găzduiește camera + Atinge Găzduire pentru a deschide o cameră pentru această sesiune de joc, apoi pornește jocul. NetPlay se dezactivează când ieși. + În cameră + Alătură-te prin IP + Alăturat + Alăturare + La pornire + Părăsește + Gazdă = P1 · Alăturare = P2 · același joc pe ambele ecrane + Găzduire + Alăturare + Manual + Nu s-au găsit camere. Asigură-te că gazda este pe același Wi‑Fi și găzduiește o cameră. + Nume afișat + Afișat celorlalți jucători + %1$d conectat(i) + Camera este deschisă doar pentru această sesiune. Pornește când ești gata. Ieșirea din joc dezactivează NetPlay. + Jucători + Scanează Wi‑Fi + Scanează din nou + Scanează același Wi‑Fi pentru camere deschise, sau alătură-te prin adresă IP. + Se scanează Wi‑Fi… + Rezultatele scanării + Atinge o cameră pentru a te alătura acum (nu salvează IP-ul pentru următoarea pornire). + Oprește scanarea + NetPlay + %1$s conectat + %1$s deconectat + Se așteaptă jucători… + Suportul pentru PlayStation 2 va fi disponibil în curând + Afișează butoanele L3 / R3 + Când este oprit, atinge de două ori un stick pentru a apăsa L3 / R3 + INDICATOARE DRIVER TURNIP + Aplicate doar când un driver GPU personalizat este selectat mai sus. + Fișierul jocului nu a fost găsit + Șterge + Importă din fișier… + Se încarcă… + NetPlay + Wii Home + Schimbă consola + Identifică drept consolă + Identificat acum ca %1$s ReShade Aplică un efect ReShade (.fx) jocurilor DXVK/VKD3D (Vulkan) prin stratul vkBasalt integrat. Pune fiecare efect în propriul folder în Android/data/<package>/files/ReShade/. Reglarea parametrilor în timp real și comutatorul din joc vor sosi odată cu actualizarea stratului cu reîncărcare în timp real. @@ -1656,5 +2429,28 @@ Cale instalata: Activează ReShade Niciun efect ReShade în această configurație. Adaugă efecte în setările acestui joc (sau ale containerului) pentru a le comuta și ajusta aici. Acest efect nu expune parametri ajustabili. + Se șterge salvarea… + Șterge + Ștergi definitiv salvarea din cloud de la %1$s? Această acțiune nu poate fi anulată. + Șterge salvarea din cloud + Salvarea din cloud nu a putut fi ștearsă + Salvare din cloud ștearsă + Descarcă mai întâi nucleele consolelor — Setari › Retro + Acest dispozitiv nu poate rula emularea PS2 — necesită OpenGL ES 3.1 sau mai nou. + Caută actualizări + Se caută actualizări… + Descarcă nucleele consolelor + Se descarcă… %1$d / %2$d MB + Nucleele consolelor + Instalat — versiunea %1$s + Instalat — versiunea %1$s (verificarea actualizărilor a eșuat) + Se instalează… + Neinstalat — descarcă pentru a juca jocuri retro + Stare + Actualizează nucleele consolelor + Actualizare disponibilă — versiunea %1$s (%2$d MB) + Se verifică descărcarea… + Se lucrează… + Sistem diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index d63098f20..405cbca18 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1528,6 +1528,779 @@ Работать в фоне Оставлять чат активным после выхода из WinNative Обновить + Ретро + Перенос сохранения + Импортируйте локальное сохранение для этой игры или экспортируйте текущее сохранение. + Импорт сохранения + Экспорт сохранения + Сохранение импортировано + Не удалось импортировать сохранение + Сохранение экспортировано + Не удалось экспортировать сохранение + Для этой игры ещё нет сохранения + Читы + Читы отключены в режиме Hardcore + + + Сохранить + Отмена + Сохранить состояние + Загрузить состояние + Достижения + Читы + Карты памяти + Ускорение + Сброс + Сменить диск + Слот %1$d + Нажмите для загрузки + Пусто + Нажмите для перезаписи + Пусто — нажмите для сохранения + Слот %1$d пуст + Загружен слот %1$d + Не удалось загрузить слот %1$d + Сохранено в слот %1$d + Не удалось сохранить + • Слот 1 + • Слот 2 + • Нажмите для использования + Новая карта памяти + Импорт карты + Включить сеть (DEV9) + Сетевой адаптер PS2 — перезапускает игру для подключения + Устройство Ethernet + Режим DNS + Основной DNS + Дополнительный DNS + необязательно + Авто IP (DHCP) + Сервер: %1$s + нажмите для указания IP (пусто — удаляет) + %1$s → IP + Добавить хост сервера + Новое имя хоста сервера + напр. bf2.playbattlefront.com + Экранные кнопки + Изменить раскладку + Сбросить раскладку + Раскладка сброшена + Левый стик: инверт. X + Левый стик: инверт. Y + Правый стик: инверт. X + Правый стик: инверт. Y + Цвет кнопок + Цвет букв + Цвет тени + Цвет фона + Сбросить цвета + Рендерер + Vulkan + OpenGL + Software + Масштаб разрешения + 1x (родное) + 1.5x + 2x + 3x + 4x + Соотношение сторон + Растянуть + Авто (стандарт) + 4:3 + 16:9 + Фильтр экрана + Ближайший + Билинейный (мягкий) + Билинейный (резкий) + Фильтр текстур + Билинейный (принуд.) + Билинейный (PS2) + Билинейный (спрайты) + Точность смешивания + Минимальная + Базовая + Средняя + Высокая + Полная + Максимальная + CRT / ТВ-шейдер + Выкл. + Строчный + Диагональный + Треугольный + Волна + Lottes + 4xRGSS + NxAGSS + Пропуск кадров + Выкл. + Пропуск 1 + Пропуск 2 + Пропуск 3 + Мип-текстурирование + Громкость + %1$d%% + Без звука + Поменять стереоканалы + Частота циклов EE + 50% + 60% + 75% + 100% (по умолч.) + 130% + 180% + 300% + Пропуск циклов EE + Выкл. + 1 + 2 + 3 + Мгновенный VU1 + Многопоточный VU (MTVU) + Быстрый CDVD + FPS + Скорость эмуляции + Загрузка CPU + Загрузка GPU + Внутреннее разрешение + Режим деинтерлейсинга + Авто + Выкл. + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + Соотношение сторон FMV + Антиразмытие + Широкоэкранные патчи + Патчи без чересстрочности + VU Flag Hack + Обнаружение цикла INTC + Обнаружение цикла ожидания + Растяжение звука по времени + Аудиобуфер + Задержка вывода + %1$d мс + Время кадров + Статистика GS + Информация об оборудовании + Версия + Отображение ввода + Меню + Экран + Производительность + HUD + Звук + Сеть + Управление + Продолжить + Пауза + Выход + BIOS импортирован: %1$s + Недопустимый файл BIOS + Недопустимая ретро-игра + ROM не найден: %1$s + Не удалось прочитать ROM в этом архиве + Ядро не установлено: %1$s + Читы включены — достижения отключены для этой сессии + Облачное сохранение восстановлено + Не удалось восстановить + Для %1$s существует более новое облачное сохранение. Хотите синхронизировать, и какое облачное сохранение оставить? + Облачное сохранение + Retro + Не удалось загрузить ядро эмулятора + Не удалось загрузить ROM + Графика не поддерживается этим ядром + Ошибка эмулятора + По умолчанию + CRT + LCD + Резкий + SGSR + Апскейл SGSR + Родное + Звук + Левый стик: инверт. X + Левый стик: инверт. Y + Правый стик: инверт. X + Правый стик: инверт. Y + Экранные кнопки + Виброотклик + Портретная + Альбомная + Изменить раскладку (%1$s) + Сбросить раскладку %1$s + Раскладка %1$s сброшена + Цвет кнопок + Цвет букв + Цвет тени + Цвет фона + Сбросить цвета + Цвета сброшены + HUD производительности + Прозрачность + Прозрачность фона + Фон + Масштаб + Числовое время кадра + Двойной график батареи + ЭЛЕМЕНТЫ HUD + FPS + Консоль + GPU + CPU + RAM + Батарея + Темп. + График + Темп. CPU + Сохранить состояние + Загрузить состояние + Загрузка состояний отключена в режиме Hardcore + Достижения + Читы + Читы отключены в режиме Hardcore + Сброс + Ускорение + Ускорение отключено в режиме Hardcore + HUD + Диск %1$d/%2$d + Продолжить + Пауза + Выход + Сохранено в слот %1$d + Не удалось сохранить состояние + Требуется BIOS %1$s + Играм PlayStation нужен настоящий файл BIOS консоли, который вы должны предоставить. Импортируйте BIOS (scph5501.bin, scph5500.bin, scph5502.bin, scph1001.bin или scph7001.bin), чтобы продолжить. + Импорт BIOS… + Отмена + Слот %1$d пуст + Загружен слот %1$d + Не удалось загрузить состояние + Слот %1$d + Переименовать слот %1$d + Общие + Графика + Производительность + HUD + Ввод + Звук + Сеть + Отмена + Сохранить + По умолчанию + CRT + LCD + Резкий + 2x + 4x + Родное + ИГРА + Название + Система + Ядро эмулятора + Путь к ROM + BIOS %1$s + Установлен + Нет — требуется для запуска игр %1$s + Импорт BIOS… + Удалить BIOS + ОФОРМЛЕНИЕ БИБЛИОТЕКИ + Изображение карточки игры + Изображение сетки + Изображение карусели + Изображение списка + Задано своё изображение + Задать изображение + Удалить + ВИДЕО + Видеофильтр + SGSR + Апскейл SGSR + HUD производительности + ЯДРО + Рендерер + Vulkan + OpenGL + Software + Масштаб разрешения + 1x (родное) + 1.5x + 2x + 3x + 4x + Соотношение сторон + Растянуть + Авто (стандарт) + 4:3 + 16:9 + Фильтр экрана + Ближайший + Билинейный (мягкий) + Билинейный (резкий) + Фильтр текстур + Билинейный (принуд.) + Билинейный (PS2) + Билинейный (спрайты) + Точность смешивания + Минимальная + Базовая + Средняя + Высокая + Полная + Максимальная + CRT / ТВ-шейдер + Выкл. + Строчный + Диагональный + Треугольный + Волна + Lottes + 4xRGSS + NxAGSS + Пропуск кадров + Пропуск 1 + Пропуск 2 + Пропуск 3 + Мип-текстурирование + ПРОИЗВОДИТЕЛЬНОСТЬ + Частота циклов EE + 50% + 60% + 75% + 100% (по умолч.) + 130% + 180% + 300% + Пропуск циклов EE + 1 + 2 + 3 + Мгновенный VU1 + Многопоточный VU (MTVU) + Быстрый CDVD + HUD ПРОИЗВОДИТЕЛЬНОСТИ + FPS + Скорость эмуляции + Загрузка CPU + Загрузка GPU + Внутреннее разрешение + Режим деинтерлейсинга + Авто + Выкл. + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + Соотношение сторон FMV + Антиразмытие + Широкоэкранные патчи + Патчи без чересстрочности + VU Flag Hack + Обнаружение цикла INTC + Обнаружение цикла ожидания + Растяжение звука по времени + Аудиобуфер + Задержка вывода + %1$d мс + Время кадров + Статистика GS + Информация об оборудовании + Версия + Отображение ввода + Быстрая загрузка + СЕТЬ (DEV9) + Включить сеть + Устройство Ethernet + Авто + Wi-Fi + Режим DNS + Вручную + Внутренний + Основной DNS + Дополнительный DNS + необязательно + Авто IP (DHCP) + ВВОД + Экранные кнопки + Виброотклик + ЗВУК + Громкость + Без звука + Поменять стереоканалы + Звук + РЕТРО-НАСТРОЙКИ ПО УМОЛЧАНИЮ + Настройки по умолчанию применяются к играм каждой консоли, если не переопределены в настройках самой игры. + RETROACHIEVEMENTS + Аккаунт + Выполнен вход + Вход не выполнен — откройте Достижения игры для входа + Достижения включены + Режим Hardcore по умолчанию (без сохранений состояний) + Выйти + BIOS PLAYSTATION + Установлен + Нет — играм PS1 требуется BIOS + Импорт BIOS PS1… + BIOS PS1 удалён + Нет BIOS для удаления + Удалить BIOS PS1 + BIOS PLAYSTATION 2 + Нет — играм PS2 требуется BIOS + Формат + Объединённый однофайловый дамп (с меткой региона .bin, ~4МБ). Раздельные наборы ROM0/MEC/NVM не принимаются. + Импорт BIOS PS2… + BIOS PS2 удалён + Удалить BIOS PS2 + ОФОРМЛЕНИЕ БИБЛИОТЕКИ + Ретро-обложка (картридж / коробка CD) + Обложка + Загружается автоматически с thumbnails.libretro.com при импорте; своё изображение всегда имеет приоритет. + ПАПКА ROM + Папка + Не задана — выберите папку для авто-импорта игр + Авто-импорт + Новые игры в этой папке добавляются в библиотеку автоматически с определением нужной консоли. + Выбрать папку ROM + Выбрать папку ROM… + Сменить папку ROM… + Сканировать + НАСТРОЙКИ КОНСОЛИ ПО УМОЛЧАНИЮ + Нажмите на консоль, чтобы задать её настройки по умолчанию. + Рендерер + Апскейл разрешения + Соотношение сторон + Растянуть + Авто (стандарт) + 4:3 + 16:9 + Фильтр экрана + Ближайший + Билинейный (мягкий) + Билинейный (резкий) + Фильтр текстур + Билинейный (принуд.) + Билинейный (PS2) + Билинейный (спрайты) + Точность смешивания + Минимальная + Базовая + Средняя + Высокая + Полная + Максимальная + CRT / ТВ-шейдер + Выкл. + Строчный + Диагональный + Треугольный + Волна + Lottes + 4xRGSS + NxAGSS + Пропуск кадров + Пропуск 1 + Пропуск 2 + Пропуск 3 + Мип-текстурирование + Частота циклов EE + 50% + 60% + 75% + 100% (по умолч.) + 130% + 180% + 300% + Пропуск циклов EE + Выкл. + 1 + 2 + 3 + Мгновенный VU1 + Многопоточный VU (MTVU) + Быстрый CDVD + Экранное сенсорное управление + Звук + Поменять стереоканалы + HUD: FPS + HUD: скорость эмуляции + HUD: загрузка CPU + HUD: загрузка GPU + HUD: внутреннее разрешение + Включить сеть (DEV9) + Устройство Ethernet + Авто + Wi-Fi + Режим DNS + Вручную + Внутренний + Основной DNS + Дополнительный DNS + необязательно + Авто IP (DHCP) + Шейдер + Апскейл SGSR + HUD производительности + БЛАГОДАРНОСТИ & ЛИЦЕНЗИИ + Некоторые функции WinNative построены на этих проектах с открытым исходным кодом. Нажмите, чтобы посмотреть каждый источник. + По умолчанию + Благодарности + Включить режим Hardcore? + Режим Hardcore сбрасывает игру сейчас и отключает загрузку сохранений состояний, ускорение и читы. Любой несохранённый прогресс будет потерян. Продолжить? + Отмена + Включить + BIOS импортирован: %1$s + Недопустимый файл BIOS + BIOS PS2 импортирован: %1$s + Недопустимый файл BIOS PS2 + Нет серийного номера игры для поиска читов. + Применено читов: %1$d. + Не удалось применить читы. + Читы + Применить + Читы для этой игры не найдены. + Достижения + Войти в RetroAchievements + Имя пользователя + Пароль + Ошибка входа + Выполняется вход… + Войти + %1$d/%2$d • %3$d очк. + Для этой игры нет достижений. + Назад + Включено + Отключено + Переименовать + Сохранить + Конфликт облачного сохранения + Оставить локальное сохранение + A + Меню + Экран + HUD + Звук + Управление + Библиотека актуальна + ROM: %1$s + добавлено %1$d + удалено %1$d + По умолчанию + CRT + LCD + Резкий + Родное + Соотношение сторон + Фильтр NTSC + Раскрашивание + Коррекция цвета + Снять лимит спрайтов + Разрешение + Эмуляция кадрового буфера + Дизеринг + Широкоэкранный хак + 8:7 (родное) + 4:3 (ТВ) + Выкл. + RF + Композитный + S-Video + RGB + Авто + Экран GBA + Экран GBC + Вкл. + 320x240 (родное) + 640x480 + 960x720 + 1280x960 + 4:3 + 16:9 + 16:9 с коррекцией + Родное + Внутреннее + Вкл. (16:9) + RETROACHIEVEMENTS + Войдите с аккаунтом RetroAchievements, чтобы получать и отслеживать достижения в ретро-играх. + Имя пользователя + Пароль + Введите имя пользователя и пароль + Ошибка входа + Войти + Ваш пароль используется только один раз для получения токена входа, который надёжно хранится на устройстве. + Достижения включены + Режим Hardcore (без сохранений состояний) + %1$d / %2$d очков + Достижения для этой игры не найдены. + Выйти + ЧИТЫ + Название + Код + Отмена + Сохранить + Чит %1$d + Читов пока нет. Добавьте чит-код для этой игры. + Добавить чит + + Драйвер GPU + Системный (По умолчанию) + Установите драйверы Turnip в разделе Настройки \u2192 Драйверы. Одни и те же драйверы работают для игр PC и PS2. + + HDD PS2 (DEV9) + Виртуальный внутренний диск для игр на HDD, таких как Final Fantasy XI. Перезапускает игру. + Виртуальный внутренний диск для игр на HDD, таких как Final Fantasy XI. + Режим DNS установлен на Internal, чтобы ваши пользовательские хосты сервера вступили в силу. + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + Add Cheat + Cheat name + Codes (one per line, e.g. 2021A268 00000000) + Custom + Enter a name and at least one valid code + Add + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + PS2 HDD Images + A .raw HDD image, or a .zip containing one (e.g. a game’s downloaded HDD with maps/DLC) + Import HDD Image + Importing… + Imported %1$s + Could not import HDD image + Removed %1$s + Remove %1$s + HDD Image + None + Cheats + Patches + PATCH + Custom + Applied %1$d cheat(s), %2$d patch(es). + No cheats or patches found for this game. + Cheat + Patch + Add +Ядро CPU +Два ядра +Встроенные читы +Внутреннее разрешение +Рендерер +Положение сенсорной панели +Пропустить заставку BIOS + + + + + + +Снизу +Кэширующий интерпретатор +Аппаратный +Интерпретатор +JIT +Мышь / Касание +Правый стик (абсолютный) +Правый стик (относительный) +Программный +Растянуть +Сверху +Пропуск VBI (авто пропуск кадров) +Широкий экран +Указатель Wiimote +Изменения применятся при следующем запуске этой игры. +Запустите эту игру один раз, чтобы определить серийный номер диска, после чего здесь появятся читы и патчи. +Обход авторизации DNAS — необходим для игры онлайн +Применяется автоматически (онлайн) +Читы & патчи +Размер: %1$s +Импорт образа HDD +Удалить +Включить NetPlay +По умолчанию выключено. Включите, затем выберите «Хост» или «Присоединиться» перед запуском.\nСнова выключается при выходе из игры. +Адрес хоста +IP или имя хоста +Сессия хоста +Вкл = ждать игрока. Выкл = присоединиться к адресу хоста +NetPlay использует локальные порты для нескольких игроков по TCP (игрок 1 — хост / игрок 2 — клиент). Онлайн-игра PS2 вместо этого использует Ethernet DEV9. +Порт +Карта памяти %1$d +Снимок экрана +Использовать облачное сохранение +LAN (прямой IP) +Подключение… +Подключение +Онлайн (код хоста) +Закрыть +NetPlay для GameCube/Wii использует собственный движок Dolphin. Хост = игрок 1, «Присоединиться» = игрок 2. Выберите «Хост» или «Присоединиться» и тип подключения перед запуском; оба устройства запускают одну и ту же игру вместе. +Сообщите игроку 2 IP-адрес вашего устройства в сети Wi‑Fi и этот порт. Игра запустится автоматически, как только он подключится. +При загрузке игры отображается код хоста — сообщите его игроку 2. Игра запустится автоматически, как только он подключится. +Введите IP-адрес хоста в сети Wi‑Fi и порт, затем запустите для подключения. +Введите код хоста от игрока 1, затем запустите для подключения. +Включите NetPlay в настройках игры и выберите «Хост» или «Присоединиться» перед запуском +Найти комнаты в Wi‑Fi +Game Link · каждый экран — своя консоль +Мультиплеер GBA использует gpSP + беспроводной адаптер. Убедитесь, что libgpsp установлен. +Мультиплеер с общим экраном по Wi‑Fi (как в RetroArch).\nХост = игрок 1, «Присоединиться» = игрок 2. Оба устройства показывают одну и ту же игру. +Game Link по Wi‑Fi — каждое устройство запускает свою игру.\nGB/GBC: последовательное соединение Gambatte (Pokémon 1–2 поколения).\nGBA: беспроводной адаптер gpSP (сражения Pokémon FR/LG/Emerald). +Создать комнату +Код хоста +Код хоста для сквозного подключения от хоста +Размещение комнаты +Нажмите «Хост», чтобы открыть комнату для этой игровой сессии, затем запустите игру. NetPlay выключается при выходе. +В комнате +Присоединиться по IP +Присоединился +Присоединиться +При запуске +Покинуть +Хост = И1 · Присоединиться = И2 · одна игра на обоих экранах +Хост +Присоединиться +Вручную +Комнаты не найдены. Убедитесь, что хост находится в той же сети Wi‑Fi и разместил комнату. +Отображаемое имя +Показывается другим игрокам +%1$d подключено +Комната открыта только для этой сессии. Запустите, когда будете готовы. Выход из игры выключает NetPlay. +Игроки +Сканировать Wi‑Fi +Сканировать снова +Сканируйте ту же сеть Wi‑Fi на наличие открытых комнат или присоединяйтесь по IP-адресу. +Сканирование Wi‑Fi… +Результаты сканирования +Нажмите на комнату, чтобы присоединиться сейчас (IP не сохраняется для следующего запуска). +Остановить сканирование +NetPlay +%1$s подключился +%1$s отключился +Ожидание игроков… +Поддержка PlayStation 2 скоро появится +Показать кнопки L3 / R3 +Когда выключено, дважды нажмите на стик для клика L3 / R3 +ФЛАГИ ДРАЙВЕРА TURNIP +Применяется только когда выше выбран пользовательский драйвер GPU. +Файл игры не найден +Удалить +Импорт из файла… +Загрузка… +NetPlay + Wii Home + Сменить консоль + Определять как консоль + Теперь определяется как %1$s ReShade Применяйте эффект ReShade (.fx) к играм DXVK/VKD3D (Vulkan) через встроенный слой vkBasalt. Поместите каждый эффект в отдельную папку в Android/data/<package>/files/ReShade/. Настройка параметров в реальном времени и переключатель в игре появятся с обновлением слоя с горячей перезагрузкой. @@ -1563,4 +2336,27 @@ Включить ReShade В этом наборе нет эффектов ReShade. Добавьте эффекты в настройках этой игры (или контейнера), чтобы переключать и настраивать их здесь. У этого эффекта нет настраиваемых параметров. + Удаление сохранения… + Удалить + Удалить облачное сохранение из %1$s навсегда? Это действие нельзя отменить. + Удалить облачное сохранение + Не удалось удалить облачное сохранение + Облачное сохранение удалено + Сначала загрузите ядра консолей — Настройки › Ретро + Это устройство не может запустить эмуляцию PS2 — требуется OpenGL ES 3.1 или новее. + Проверить обновления + Проверка обновлений… + Загрузить ядра консолей + Загрузка… %1$d / %2$d МБ + Ядра консолей + Установлено — сборка %1$s + Установлено — сборка %1$s (не удалось проверить обновления) + Установка… + Не установлено — загрузите, чтобы играть в ретро-игры + Состояние + Обновить ядра консолей + Доступно обновление — сборка %1$s (%2$d МБ) + Проверка загрузки… + Выполняется… + Система diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 5a9dfd660..f814d7771 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -1621,6 +1621,779 @@ Installerad sökväg: Det gick inte att skapa mappen Uppdatera + Retro + Överför sparfil + Importera en lokal sparfil till det här spelet eller exportera spelets nuvarande sparfil. + Importera sparfil + Exportera sparfil + Sparfil importerad + Det gick inte att importera sparfilen + Sparfil exporterad + Det gick inte att exportera sparfilen + Det finns ännu ingen sparfil för det här spelet + Fusk + Fusk är inaktiverat i Hardcore-läge + + + Spara + Avbryt + Spara tillstånd + Läs in sparat tillstånd + Prestationer + Fusk + Memory Cards + Snabbspola + Återställ + Byt skiva + Slot %1$d + Tryck för att läsa in + Tom + Tryck för att skriva över + Tom – tryck för att spara + Slot %1$d är tom + Läste in slot %1$d + Kunde inte läsa in slot %1$d + Sparat i slot %1$d + Sparandet misslyckades + • Slot 1 + • Slot 2 + • Tryck för att använda + Nytt Memory Card + Importera kort + Aktivera online (DEV9) + PS2-nätverksadapter – startar om spelet för att ansluta den + Ethernet-enhet + DNS-läge + Primär DNS + Sekundär DNS + valfritt + Auto-IP (DHCP) + Server: %1$s + tryck för att ange IP (tom tar bort) + %1$s → IP + Lägg till servervärd + Nytt servervärdnamn + t.ex. bf2.playbattlefront.com + Skärmkontroller + Redigera layout + Återställ layout + Layout återställd + Vänster spak: Invertera X + Vänster spak: Invertera Y + Höger spak: Invertera X + Höger spak: Invertera Y + Knappfärg + Bokstavsfärg + Skuggfärg + Bakgrundsfärg + Återställ färger + Renderare + Vulkan + OpenGL + Software + Upplösningsskala + 1x (Native) + 1.5x + 2x + 3x + 4x + Bildförhållande + Sträck ut + Auto (Standard) + 4:3 + 16:9 + Skärmfilter + Närmaste + Bilinjär (Mjuk) + Bilinjär (Skarp) + Texturfilter + Bilinjär (Tvingad) + Bilinjär (PS2) + Bilinjär (Sprites) + Blandningsnoggrannhet + Minimum + Grundläggande + Medel + Hög + Full + Maximum + CRT-/TV-shader + Av + Scanline + Diagonal + Triangular + Wave + Lottes + 4xRGSS + NxAGSS + Frame Skip + Av + Hoppa över 1 + Hoppa över 2 + Hoppa över 3 + Mipmapping + Volym + %1$d%% + Tyst + Byt stereokanaler + EE-cykelfrekvens + 50% + 60% + 75% + 100% (Standard) + 130% + 180% + 300% + EE-cykelhopp + Av + 1 + 2 + 3 + Instant VU1 + Multi-Threaded VU (MTVU) + Snabb CDVD + FPS + Emuleringshastighet + CPU-användning + GPU-användning + Intern upplösning + Deinterlace-läge + Auto + Av + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + FMV-bildförhållande + Anti-oskärpa + Widescreen-patchar + No-interlace-patchar + VU Flag Hack + INTC-spinndetektering + Vänteloopsdetektering + Ljud-timestretch + Ljudbuffert + Utgångslatens + %1$d ms + Bildrutetider + GS-statistik + Hårdvaruinfo + Version + Inmatningsvisning + Meny + Skärm + Prestanda + HUD + Ljud + Online + Kontroller + Fortsätt + Pausa + Avsluta + BIOS importerat: %1$s + Ogiltig BIOS-fil + Ogiltigt retrospel + ROM hittades inte: %1$s + Kunde inte läsa ROM:en i detta arkiv + Kärna ej installerad: %1$s + Fusk aktiverat – prestationer är inaktiverade för denna session + Molnsparning återställd + Återställning misslyckades + En nyare molnsparning finns för %1$s. Vill du synkronisera, och vilken molnsparning föredrar du att behålla? + Molnsparning + Retro + Det gick inte att läsa in emulatorkärnan + Det gick inte att läsa in ROM + Grafik stöds inte för denna kärna + Emulatorfel + Standard + CRT + LCD + Skarp + SGSR + SGSR-uppskalning + Native + Ljud + Vänster spak: Invertera X + Vänster spak: Invertera Y + Höger spak: Invertera X + Höger spak: Invertera Y + Skärmkontroller + Haptisk återkoppling + Stående + Liggande + Redigera layout (%1$s) + Återställ %1$s-layout + %1$s-layout återställd + Knappfärg + Bokstavsfärg + Skuggfärg + Bakgrundsfärg + Återställ färger + Färger återställda + Prestanda-HUD + Alfa + Bakgrundsalfa + Bakgrund + Skala + Numerisk bildtid + Dubbelserie-batteri + HUD-ELEMENT + FPS + Konsol + GPU + CPU + RAM + Batteri + Temp. + Graf + CPU-temp. + Spara tillstånd + Läs in sparat tillstånd + Inläsning av tillstånd är inaktiverad i Hardcore-läge + Prestationer + Fusk + Fusk är inaktiverat i Hardcore-läge + Återställ + Snabbspola + Snabbspolning är inaktiverad i Hardcore-läge + HUD + Skiva %1$d/%2$d + Fortsätt + Pausa + Avsluta + Sparat i slot %1$d + Kunde inte spara tillstånd + %1$s BIOS krävs + PlayStation-spel kräver en riktig konsol-BIOS-fil som du måste tillhandahålla själv. Importera en BIOS (scph5501.bin, scph5500.bin, scph5502.bin, scph1001.bin eller scph7001.bin) för att fortsätta. + Importera BIOS… + Avbryt + Slot %1$d är tom + Läste in slot %1$d + Kunde inte läsa in tillstånd + Slot %1$d + Byt namn på slot %1$d + Allmänt + Grafik + Prestanda + HUD + Inmatning + Ljud + Online + Avbryt + Spara + Standard + CRT + LCD + Skarp + 2x + 4x + Native + SPEL + Namn + System + Emulatorkärna + ROM-sökväg + %1$s BIOS + Installerat + Inget – krävs för att köra %1$s-spel + Importera BIOS… + Ta bort BIOS + BIBLIOTEKSGRAFIK + Spelkortsbild + Rutnätsbild + Karusellbild + Listbild + Anpassad bild inställd + Ställ in bild + Ta bort + VIDEO + Videofilter + SGSR + SGSR-uppskalning + Prestanda-HUD + KÄRNA + Renderare + Vulkan + OpenGL + Software + Upplösningsskala + 1x (Native) + 1.5x + 2x + 3x + 4x + Bildförhållande + Sträck ut + Auto (Standard) + 4:3 + 16:9 + Skärmfilter + Närmaste + Bilinjär (Mjuk) + Bilinjär (Skarp) + Texturfilter + Bilinjär (Tvingad) + Bilinjär (PS2) + Bilinjär (Sprites) + Blandningsnoggrannhet + Minimum + Grundläggande + Medel + Hög + Full + Maximum + CRT-/TV-shader + Av + Scanline + Diagonal + Triangular + Wave + Lottes + 4xRGSS + NxAGSS + Frame Skip + Hoppa över 1 + Hoppa över 2 + Hoppa över 3 + Mipmapping + PRESTANDA + EE-cykelfrekvens + 50% + 60% + 75% + 100% (Standard) + 130% + 180% + 300% + EE-cykelhopp + 1 + 2 + 3 + Instant VU1 + Multi-Threaded VU (MTVU) + Snabb CDVD + PRESTANDA-HUD + FPS + Emuleringshastighet + CPU-användning + GPU-användning + Intern upplösning + Deinterlace-läge + Auto + Av + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + FMV-bildförhållande + Anti-oskärpa + Widescreen-patchar + No-interlace-patchar + VU Flag Hack + INTC-spinndetektering + Vänteloopsdetektering + Ljud-timestretch + Ljudbuffert + Utgångslatens + %1$d ms + Bildrutetider + GS-statistik + Hårdvaruinfo + Version + Inmatningsvisning + Snabbstart + ONLINE (DEV9) + Aktivera online + Ethernet-enhet + Auto + Wi-Fi + DNS-läge + Manuell + Intern + Primär DNS + Sekundär DNS + valfritt + Auto-IP (DHCP) + INMATNING + Skärmkontroller + Haptisk återkoppling + LJUD + Volym + Tyst + Byt stereokanaler + Ljud + RETRO-STANDARDER + Standarder som tillämpas på varje konsols spel om de inte åsidosätts i ett spels egna inställningar. + RETROACHIEVEMENTS + Konto + Inloggad + Inte inloggad – öppna ett spels prestationer för att logga in + Prestationer aktiverade + Hardcore-läge som standard (inga sparade tillstånd) + Logga ut + PLAYSTATION BIOS + Installerat + Inget – PS1-spel kräver en BIOS + Importera PS1 BIOS… + PS1 BIOS borttaget + Ingen BIOS att ta bort + Ta bort PS1 BIOS + PLAYSTATION 2 BIOS + Inget – PS2-spel kräver en BIOS + Format + Sammanslagen enkelfilsdump (regionsmärkt .bin, ~4 MB). Uppdelade ROM0/MEC/NVM-uppsättningar accepteras inte. + Importera PS2 BIOS… + PS2 BIOS borttaget + Ta bort PS2 BIOS + BIBLIOTEKSGRAFIK + Retro fodralbild (kassett / CD-fodral) + Omslagsbild + Hämtas automatiskt från thumbnails.libretro.com vid import; en anpassad bild åsidosätter den alltid. + ROMS-MAPP + Mapp + Inte inställd – välj en mapp för att importera spel automatiskt + Auto-import + Nya spel i denna mapp läggs automatiskt till i ditt bibliotek med rätt konsol identifierad. + Välj ROM-mapp + Välj ROM-mapp… + Ändra ROM-mapp… + Sök nu + KONSOL-STANDARDER + Tryck på en konsol för att ange dess standardinställningar. + Renderare + Uppskala upplösning + Bildförhållande + Sträck ut + Auto (Standard) + 4:3 + 16:9 + Skärmfilter + Närmaste + Bilinjär (Mjuk) + Bilinjär (Skarp) + Texturfilter + Bilinjär (Tvingad) + Bilinjär (PS2) + Bilinjär (Sprites) + Blandningsnoggrannhet + Minimum + Grundläggande + Medel + Hög + Full + Maximum + CRT-/TV-shader + Av + Scanline + Diagonal + Triangular + Wave + Lottes + 4xRGSS + NxAGSS + Frame Skip + Hoppa över 1 + Hoppa över 2 + Hoppa över 3 + Mipmapping + EE-cykelfrekvens + 50% + 60% + 75% + 100% (Standard) + 130% + 180% + 300% + EE-cykelhopp + Av + 1 + 2 + 3 + Instant VU1 + Multi-Threaded VU (MTVU) + Snabb CDVD + Pekkontroller på skärmen + Ljud + Byt stereokanaler + HUD: FPS + HUD: Emuleringshastighet + HUD: CPU-användning + HUD: GPU-användning + HUD: Intern upplösning + Aktivera online (DEV9) + Ethernet-enhet + Auto + Wi-Fi + DNS-läge + Manuell + Intern + Primär DNS + Sekundär DNS + valfritt + Auto-IP (DHCP) + Shader + SGSR-uppskalning + Prestanda-HUD + MEDVERKANDE & LICENSER + Vissa av WinNatives funktioner bygger på dessa projekt med öppen källkod. Tryck för att visa varje källa. + Standarder + Medverkande + Aktivera Hardcore-läge? + Hardcore-läge återställer spelet nu och inaktiverar inläsning av sparade tillstånd, snabbspolning och fusk. Osparade framsteg går förlorade. Fortsätta? + Avbryt + Aktivera + BIOS importerat: %1$s + Ogiltig BIOS-fil + PS2 BIOS importerat: %1$s + Ogiltig PS2 BIOS-fil + Inget spelserienummer att slå upp fusk för. + Tillämpade %1$d fusk. + Kunde inte tillämpa fusk. + Fusk + Tillämpa + Inget fusk hittades för detta spel. + Prestationer + Logga in på RetroAchievements + Användarnamn + Lösenord + Inloggningen misslyckades + Loggar in… + Logga in + %1$d/%2$d • %3$d p + Inga prestationer för detta spel. + Tillbaka + Aktiverat + Inaktiverat + Byt namn + Spara + Molnsparningskonflikt + Behåll lokal sparning + A + Meny + Skärm + HUD + Ljud + Kontroller + Biblioteket är uppdaterat + ROM:ar: %1$s + lade till %1$d + tog bort %1$d + Standard + CRT + LCD + Skarp + Native + Bildförhållande + NTSC-filter + Färgläggning + Färgkorrigering + Ta bort sprite-gräns + Upplösning + Framebuffer-emulering + Dithering + Widescreen-hack + 8:7 (Native) + 4:3 (TV) + Av + RF + Composite + S-Video + RGB + Auto + GBA-skärm + GBC-skärm + + 320x240 (Native) + 640x480 + 960x720 + 1280x960 + 4:3 + 16:9 + 16:9 justerad + Native + Intern + På (16:9) + RETROACHIEVEMENTS + Logga in med ditt RetroAchievements-konto för att tjäna och spåra prestationer för retrospel. + Användarnamn + Lösenord + Ange ditt användarnamn och lösenord + Inloggningen misslyckades + Logga in + Ditt lösenord används bara en gång för att hämta en inloggningstoken, som lagras säkert på enheten. + Prestationer aktiverade + Hardcore-läge (inga sparade tillstånd) + %1$d / %2$d poäng + Inga prestationer hittades för detta spel. + Logga ut + FUSK + Namn + Kod + Avbryt + Spara + Fusk %1$d + Inget fusk ännu. Lägg till en fuskkod för detta spel. + Lägg till fusk + + GPU-drivrutin + System (Standard) + Installera Turnip-drivrutiner under Inställningar \u2192 Drivrutiner. Samma drivrutiner fungerar för både PC- och PS2-spel. + + PS2 HDD (DEV9) + Virtuell intern enhet för HDD-baserade spel som Final Fantasy XI. Startar om spelet. + Virtuell intern enhet för HDD-baserade spel som Final Fantasy XI. + DNS-läge inställt på Internal så att dina anpassade servervärdar träder i kraft. + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + Add Cheat + Cheat name + Codes (one per line, e.g. 2021A268 00000000) + Custom + Enter a name and at least one valid code + Add + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + PS2 HDD Images + A .raw HDD image, or a .zip containing one (e.g. a game’s downloaded HDD with maps/DLC) + Import HDD Image + Importing… + Imported %1$s + Could not import HDD image + Removed %1$s + Remove %1$s + HDD Image + None + Cheats + Patches + PATCH + Custom + Applied %1$d cheat(s), %2$d patch(es). + No cheats or patches found for this game. + Cheat + Patch + Add +CPU-kärna +Dubbelkärna +Interna fusk +Intern upplösning +Renderare +Sensorstavens position +Hoppa över BIOS-intro + + + + + + +Nederkant +Cachad tolk +Hårdvara +Tolk +JIT +Mus / pekskärm +Höger spak (absolut) +Höger spak (relativ) +Programvara +Sträck +Överkant +VBI-hopp (auto-bildhopp) +Bredbild +Wiimote-pekare +Ändringarna gäller nästa gång du startar spelet. +Starta spelet en gång så att dess skivserienummer kan identifieras, sedan visas fusk och patchar här. +DNAS-autentiseringsförbikoppling — krävs för onlinespel +Tillämpas automatiskt (online) +Fusk & patchar +Storlek: %1$s +Importera HDD-avbild +Ta bort +Aktivera NetPlay +Av som standard. Aktivera och välj sedan Värd eller Anslut före start.\nStängs av igen när du avslutar spelet. +Värdadress +IP eller värdnamn +Värdsession +På = vänta på en spelare. Av = anslut till värdadress +NetPlay använder lokala flerspelarportar över TCP (spelare 1 värd / spelare 2 klient). PS2-online använder DEV9 Ethernet i stället. +Port +Minneskort %1$d +Skärmbild +Använd molnsparning +LAN (direkt IP) +Ansluter… +Anslutning +Online (värdkod) +Avfärda +GameCube/Wii-NetPlay använder Dolphins egen motor. Värd = spelare 1, Anslut = spelare 2. Välj Värd eller Anslut och en anslutningstyp före start; båda enheterna startar samma spel tillsammans. +Dela enhetens Wi‑Fi-IP och den här porten med spelare 2. Spelet startar automatiskt när de ansluter. +En värdkod visas när spelet startar — dela den med spelare 2. Spelet startar automatiskt när de ansluter. +Ange värdens Wi‑Fi-IP och port, starta sedan för att ansluta. +Ange värdkoden från spelare 1, starta sedan för att ansluta. +Aktivera NetPlay i spelinställningarna och välj Värd eller Anslut före start +Hitta rum på Wi‑Fi +Game Link · varje skärm är sin egen handhållna enhet +GBA-flerspelarläge använder gpSP + trådlös adapter. Se till att libgpsp är installerat. +Flerspelarläge med delad skärm över Wi‑Fi (som RetroArch).\nVärd = spelare 1, Anslut = spelare 2. Båda enheterna visar samma spel. +Game Link över Wi‑Fi — varje enhet kör sitt eget spel.\nGB/GBC: Gambatte seriell länk (Pokémon Gen 1–2).\nGBA: gpSP trådlös adapter (Pokémon FR/LG/Emerald-strider). +Var värd för rum +Värdkod +Traversal-värdkod från värden +Är värd för rum +Tryck på Värd för att öppna ett rum för den här spelsessionen, starta sedan spelet. NetPlay stängs av när du avslutar. +I rum +Anslut via IP +Ansluten +Anslut +Vid start +Lämna +Värd = S1 · Anslut = S2 · samma spel på båda skärmarna +Värd +Anslut +Manuell +Inga rum hittades. Se till att värden är på samma Wi‑Fi och är värd för ett rum. +Visningsnamn +Visas för andra spelare +%1$d anslutna +Rummet är endast öppet för den här sessionen. Starta när du är redo. Att avsluta spelet stänger av NetPlay. +Spelare +Sök Wi‑Fi +Sök igen +Sök på samma Wi‑Fi efter öppna rum, eller anslut via IP-adress. +Söker Wi‑Fi… +Sökresultat +Tryck på ett rum för att ansluta nu (sparar inte IP-adressen till nästa start). +Stoppa sökning +NetPlay +%1$s anslöt +%1$s kopplade från +Väntar på spelare… +Stöd för PlayStation 2 kommer snart +Visa L3-/R3-knappar +När av, dubbeltryck på en spak för att klicka L3 / R3 +TURNIP-DRIVRUTINSFLAGGOR +Tillämpas endast när en anpassad GPU-drivrutin är vald ovan. +Spelfilen hittades inte +Ta bort +Importera från fil… +Läser in… +NetPlay + Wii Home + Byt konsol + Identifiera som konsol + Identifieras nu som %1$s ReShade Använd en ReShade-effekt (.fx) på DXVK/VKD3D-spel (Vulkan) via det inbyggda vkBasalt-lagret. Lägg varje effekt i sin egen mapp under Android/data/<package>/files/ReShade/. Justering av parametrar i realtid och växeln i spelet kommer med uppdateringen av live-reload-lagret. @@ -1656,4 +2429,27 @@ Installerad sökväg: Aktivera ReShade Inga ReShade-effekter i den här uppsättningen. Lägg till effekter i det här spelets inställningar (eller containerns) för att växla och justera dem här. Den här effekten har inga justerbara parametrar. + Tar bort sparfil… + Ta bort + Vill du ta bort molnsparningen från %1$s permanent? Det går inte att ångra. + Ta bort molnsparning + Det gick inte att ta bort molnsparningen + Molnsparning borttagen + Ladda ner konsolkärnorna först — Inställningar › Retro + Den här enheten kan inte köra PS2-emulering — den kräver OpenGL ES 3.1 eller senare. + Sök efter uppdateringar + Söker efter uppdateringar… + Ladda ner konsolkärnor + Laddar ner… %1$d / %2$d MB + Konsolkärnor + Installerad — build %1$s + Installerad — build %1$s (kunde inte söka efter uppdateringar) + Installerar… + Inte installerad — ladda ner för att spela retrospel + Status + Uppdatera konsolkärnor + Uppdatering tillgänglig — build %1$s (%2$d MB) + Verifierar nedladdningen… + Arbetar… + System diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 048f4e759..c1f0e436f 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -1621,6 +1621,779 @@ สร้างโฟลเดอร์ล้มเหลว รีเฟรช + เรโทร + ถ่ายโอนเซฟ + นำเข้าไฟล์เซฟในเครื่องสำหรับเกมนี้ หรือส่งออกเซฟปัจจุบันของเกม + นำเข้าเซฟ + ส่งออกเซฟ + นำเข้าเซฟแล้ว + ไม่สามารถนำเข้าเซฟได้ + ส่งออกเซฟแล้ว + ไม่สามารถส่งออกเซฟได้ + ยังไม่มีเซฟสำหรับเกมนี้ + สูตรโกง + สูตรโกงถูกปิดใช้งานในโหมดฮาร์ดคอร์ + + + บันทึก + ยกเลิก + บันทึกสเตต + โหลดสเตตที่บันทึก + ความสำเร็จ + สูตรโกง + การ์ดหน่วยความจำ + กรอไปข้างหน้า + รีเซ็ต + สลับแผ่น + ช่อง %1$d + แตะเพื่อโหลด + ว่าง + แตะเพื่อเขียนทับ + ว่าง — แตะเพื่อบันทึก + ช่อง %1$d ว่าง + โหลดช่อง %1$d แล้ว + ไม่สามารถโหลดช่อง %1$d + บันทึกไปยังช่อง %1$d + บันทึกไม่สำเร็จ + • ช่อง 1 + • ช่อง 2 + • แตะเพื่อใช้ + การ์ดหน่วยความจำใหม่ + นำเข้าการ์ด + เปิดใช้งานออนไลน์ (DEV9) + อะแดปเตอร์เครือข่าย PS2 — รีสตาร์ตเกมเพื่อเชื่อมต่อ + อุปกรณ์อีเทอร์เน็ต + โหมด DNS + DNS หลัก + DNS รอง + ไม่บังคับ + IP อัตโนมัติ (DHCP) + เซิร์ฟเวอร์: %1$s + แตะเพื่อตั้ง IP (เว้นว่างเพื่อลบ) + %1$s → IP + เพิ่มโฮสต์เซิร์ฟเวอร์ + ชื่อโฮสต์เซิร์ฟเวอร์ใหม่ + เช่น bf2.playbattlefront.com + ปุ่มควบคุมบนหน้าจอ + แก้ไขเลย์เอาต์ + รีเซ็ตเลย์เอาต์ + รีเซ็ตเลย์เอาต์แล้ว + สติกซ้าย: กลับด้าน X + สติกซ้าย: กลับด้าน Y + สติกขวา: กลับด้าน X + สติกขวา: กลับด้าน Y + สีปุ่ม + สีตัวอักษร + สีเงา + สีพื้นหลัง + รีเซ็ตสี + ตัวเรนเดอร์ + Vulkan + OpenGL + Software + สเกลความละเอียด + 1x (เนทีฟ) + 1.5x + 2x + 3x + 4x + อัตราส่วนภาพ + ยืด + อัตโนมัติ (มาตรฐาน) + 4:3 + 16:9 + ฟิลเตอร์การแสดงผล + ใกล้สุด + Bilinear (เนียน) + Bilinear (คม) + ฟิลเตอร์พื้นผิว + Bilinear (บังคับ) + Bilinear (PS2) + Bilinear (สไปรต์) + ความแม่นยำการผสม + ต่ำสุด + พื้นฐาน + ปานกลาง + สูง + เต็ม + สูงสุด + เชดเดอร์ CRT / TV + ปิด + สแกนไลน์ + แนวทแยง + สามเหลี่ยม + คลื่น + Lottes + 4xRGSS + NxAGSS + ข้ามเฟรม + ปิด + ข้าม 1 + ข้าม 2 + ข้าม 3 + มิปแมปปิง + ระดับเสียง + %1$d%% + ปิดเสียง + สลับช่องสเตอริโอ + อัตรารอบ EE + 50% + 60% + 75% + 100% (ค่าเริ่มต้น) + 130% + 180% + 300% + ข้ามรอบ EE + ปิด + 1 + 2 + 3 + VU1 ทันที + VU หลายเธรด (MTVU) + CDVD เร็ว + FPS + ความเร็วการจำลอง + การใช้ CPU + การใช้ GPU + ความละเอียดภายใน + โหมดดีอินเตอร์เลซ + อัตโนมัติ + ปิด + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + อัตราส่วนภาพ FMV + ป้องกันภาพเบลอ + แพตช์จอกว้าง + แพตช์ไม่อินเตอร์เลซ + VU Flag Hack + การตรวจจับ INTC Spin + การตรวจจับลูปรอ + การยืดเวลาเสียง + บัฟเฟอร์เสียง + ความหน่วงเอาต์พุต + %1$d ms + เวลาต่อเฟรม + สถิติ GS + ข้อมูลฮาร์ดแวร์ + เวอร์ชัน + การแสดงอินพุต + เมนู + การแสดงผล + ประสิทธิภาพ + HUD + เสียง + ออนไลน์ + การควบคุม + เล่นต่อ + หยุดชั่วคราว + ออก + นำเข้า BIOS แล้ว: %1$s + ไฟล์ BIOS ไม่ถูกต้อง + เกมเรโทรไม่ถูกต้อง + ไม่พบ ROM: %1$s + ไม่สามารถอ่าน ROM ภายในไฟล์เก็บถาวรนี้ + ยังไม่ได้ติดตั้งคอร์: %1$s + เปิดสูตรโกง — ความสำเร็จถูกปิดในเซสชันนี้ + กู้คืนการบันทึกบนคลาวด์แล้ว + กู้คืนไม่สำเร็จ + มีการบันทึกบนคลาวด์ที่ใหม่กว่าสำหรับ %1$s คุณต้องการซิงค์หรือไม่ และต้องการเก็บการบันทึกบนคลาวด์ใด? + การบันทึกบนคลาวด์ + เรโทร + โหลดคอร์อีมูเลเตอร์ไม่สำเร็จ + โหลด ROM ไม่สำเร็จ + คอร์นี้ไม่รองรับกราฟิก + ข้อผิดพลาดอีมูเลเตอร์ + ค่าเริ่มต้น + CRT + LCD + คม + SGSR + SGSR อัปสเกล + เนทีฟ + เสียง + สติกซ้าย: กลับด้าน X + สติกซ้าย: กลับด้าน Y + สติกขวา: กลับด้าน X + สติกขวา: กลับด้าน Y + ปุ่มควบคุมบนหน้าจอ + การสั่นตอบสนอง + แนวตั้ง + แนวนอน + แก้ไขเลย์เอาต์ (%1$s) + รีเซ็ตเลย์เอาต์ %1$s + รีเซ็ตเลย์เอาต์ %1$s แล้ว + สีปุ่ม + สีตัวอักษร + สีเงา + สีพื้นหลัง + รีเซ็ตสี + รีเซ็ตสีแล้ว + HUD ประสิทธิภาพ + อัลฟา + อัลฟาพื้นหลัง + พื้นหลัง + สเกล + เฟรมไทม์แบบตัวเลข + แบตเตอรีสองชุด + องค์ประกอบ HUD + FPS + คอนโซล + GPU + CPU + RAM + แบตเตอรี + อุณหภูมิ + กราฟ + อุณหภูมิ CPU + บันทึกสเตต + โหลดสเตตที่บันทึก + การโหลดสเตตถูกปิดในโหมดฮาร์ดคอร์ + ความสำเร็จ + สูตรโกง + สูตรโกงถูกปิดในโหมดฮาร์ดคอร์ + รีเซ็ต + กรอไปข้างหน้า + การกรอไปข้างหน้าถูกปิดในโหมดฮาร์ดคอร์ + HUD + แผ่น %1$d/%2$d + เล่นต่อ + หยุดชั่วคราว + ออก + บันทึกไปยังช่อง %1$d + ไม่สามารถบันทึกสเตต + ต้องใช้ BIOS ของ %1$s + เกม PlayStation ต้องใช้ไฟล์ BIOS ของคอนโซลจริงที่คุณต้องจัดหาเอง นำเข้า BIOS (scph5501.bin, scph5500.bin, scph5502.bin, scph1001.bin หรือ scph7001.bin) เพื่อดำเนินการต่อ + นำเข้า BIOS… + ยกเลิก + ช่อง %1$d ว่าง + โหลดช่อง %1$d แล้ว + ไม่สามารถโหลดสเตต + ช่อง %1$d + เปลี่ยนชื่อช่อง %1$d + ทั่วไป + กราฟิก + ประสิทธิภาพ + HUD + อินพุต + เสียง + ออนไลน์ + ยกเลิก + บันทึก + ค่าเริ่มต้น + CRT + LCD + คม + 2x + 4x + เนทีฟ + เกม + ชื่อ + ระบบ + คอร์อีมูเลเตอร์ + เส้นทาง ROM + %1$s BIOS + ติดตั้งแล้ว + ไม่มี — จำเป็นสำหรับการรันเกม %1$s + นำเข้า BIOS… + ลบ BIOS + อาร์ตเวิร์กคลังเกม + ภาพการ์ดเกม + ภาพกริด + ภาพคาโรเซล + ภาพรายการ + ตั้งภาพกำหนดเอง + ตั้งภาพ + ลบ + วิดีโอ + ฟิลเตอร์วิดีโอ + SGSR + SGSR อัปสเกล + HUD ประสิทธิภาพ + คอร์ + ตัวเรนเดอร์ + Vulkan + OpenGL + Software + สเกลความละเอียด + 1x (เนทีฟ) + 1.5x + 2x + 3x + 4x + อัตราส่วนภาพ + ยืด + อัตโนมัติ (มาตรฐาน) + 4:3 + 16:9 + ฟิลเตอร์การแสดงผล + ใกล้สุด + Bilinear (เนียน) + Bilinear (คม) + ฟิลเตอร์พื้นผิว + Bilinear (บังคับ) + Bilinear (PS2) + Bilinear (สไปรต์) + ความแม่นยำการผสม + ต่ำสุด + พื้นฐาน + ปานกลาง + สูง + เต็ม + สูงสุด + เชดเดอร์ CRT / TV + ปิด + สแกนไลน์ + แนวทแยง + สามเหลี่ยม + คลื่น + Lottes + 4xRGSS + NxAGSS + ข้ามเฟรม + ข้าม 1 + ข้าม 2 + ข้าม 3 + มิปแมปปิง + ประสิทธิภาพ + อัตรารอบ EE + 50% + 60% + 75% + 100% (ค่าเริ่มต้น) + 130% + 180% + 300% + ข้ามรอบ EE + 1 + 2 + 3 + VU1 ทันที + VU หลายเธรด (MTVU) + CDVD เร็ว + HUD ประสิทธิภาพ + FPS + ความเร็วการจำลอง + การใช้ CPU + การใช้ GPU + ความละเอียดภายใน + โหมดดีอินเตอร์เลซ + อัตโนมัติ + ปิด + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + อัตราส่วนภาพ FMV + ป้องกันภาพเบลอ + แพตช์จอกว้าง + แพตช์ไม่อินเตอร์เลซ + VU Flag Hack + การตรวจจับ INTC Spin + การตรวจจับลูปรอ + การยืดเวลาเสียง + บัฟเฟอร์เสียง + ความหน่วงเอาต์พุต + %1$d ms + เวลาต่อเฟรม + สถิติ GS + ข้อมูลฮาร์ดแวร์ + เวอร์ชัน + การแสดงอินพุต + บูตด่วน + ออนไลน์ (DEV9) + เปิดใช้งานออนไลน์ + อุปกรณ์อีเทอร์เน็ต + อัตโนมัติ + Wi-Fi + โหมด DNS + กำหนดเอง + ภายใน + DNS หลัก + DNS รอง + ไม่บังคับ + IP อัตโนมัติ (DHCP) + อินพุต + ปุ่มควบคุมบนหน้าจอ + การสั่นตอบสนอง + เสียง + ระดับเสียง + ปิดเสียง + สลับช่องสเตอริโอ + เสียง + ค่าเริ่มต้นเรโทร + ค่าเริ่มต้นที่ใช้กับเกมของแต่ละคอนโซล เว้นแต่จะถูกแทนที่ในการตั้งค่าเฉพาะของเกม + RETROACHIEVEMENTS + บัญชี + ลงชื่อเข้าใช้แล้ว + ยังไม่ได้ลงชื่อเข้าใช้ — เปิดความสำเร็จของเกมเพื่อลงชื่อเข้าใช้ + เปิดใช้งานความสำเร็จ + โหมดฮาร์ดคอร์โดยค่าเริ่มต้น (ไม่มีสเตตบันทึก) + ออกจากระบบ + PLAYSTATION BIOS + ติดตั้งแล้ว + ไม่มี — เกม PS1 ต้องใช้ BIOS + นำเข้า PS1 BIOS… + ลบ PS1 BIOS แล้ว + ไม่มี BIOS ให้ลบ + ลบ PS1 BIOS + PLAYSTATION 2 BIOS + ไม่มี — เกม PS2 ต้องใช้ BIOS + รูปแบบ + ดัมป์ไฟล์เดียวที่รวมกัน (.bin ติดแท็กภูมิภาค, ~4MB) ไม่รับชุด ROM0/MEC/NVM ที่แยกไฟล์ + นำเข้า PS2 BIOS… + ลบ PS2 BIOS แล้ว + ลบ PS2 BIOS + อาร์ตเวิร์กคลังเกม + อาร์ตเคสเรโทร (ตลับ / เคส CD) + อาร์ตกล่อง + ดึงอัตโนมัติจาก thumbnails.libretro.com เมื่อนำเข้า; ภาพกำหนดเองจะแทนที่เสมอ + โฟลเดอร์ ROMS + โฟลเดอร์ + ยังไม่ได้ตั้ง — เลือกโฟลเดอร์เพื่อนำเข้าเกมอัตโนมัติ + นำเข้าอัตโนมัติ + เกมใหม่ในโฟลเดอร์นี้จะถูกเพิ่มลงคลังของคุณอัตโนมัติพร้อมตรวจพบคอนโซลที่ถูกต้อง + เลือกโฟลเดอร์ ROMs + เลือกโฟลเดอร์ ROMs… + เปลี่ยนโฟลเดอร์ ROMs… + สแกนทันที + ค่าเริ่มต้นคอนโซล + แตะคอนโซลเพื่อตั้งค่าเริ่มต้น + ตัวเรนเดอร์ + อัปสเกลความละเอียด + อัตราส่วนภาพ + ยืด + อัตโนมัติ (มาตรฐาน) + 4:3 + 16:9 + ฟิลเตอร์การแสดงผล + ใกล้สุด + Bilinear (เนียน) + Bilinear (คม) + ฟิลเตอร์พื้นผิว + Bilinear (บังคับ) + Bilinear (PS2) + Bilinear (สไปรต์) + ความแม่นยำการผสม + ต่ำสุด + พื้นฐาน + ปานกลาง + สูง + เต็ม + สูงสุด + เชดเดอร์ CRT / TV + ปิด + สแกนไลน์ + แนวทแยง + สามเหลี่ยม + คลื่น + Lottes + 4xRGSS + NxAGSS + ข้ามเฟรม + ข้าม 1 + ข้าม 2 + ข้าม 3 + มิปแมปปิง + อัตรารอบ EE + 50% + 60% + 75% + 100% (ค่าเริ่มต้น) + 130% + 180% + 300% + ข้ามรอบ EE + ปิด + 1 + 2 + 3 + VU1 ทันที + VU หลายเธรด (MTVU) + CDVD เร็ว + ปุ่มควบคุมสัมผัสบนหน้าจอ + เสียง + สลับช่องสเตอริโอ + HUD: FPS + HUD: ความเร็วการจำลอง + HUD: การใช้ CPU + HUD: การใช้ GPU + HUD: ความละเอียดภายใน + เปิดใช้งานออนไลน์ (DEV9) + อุปกรณ์อีเทอร์เน็ต + อัตโนมัติ + Wi-Fi + โหมด DNS + กำหนดเอง + ภายใน + DNS หลัก + DNS รอง + ไม่บังคับ + IP อัตโนมัติ (DHCP) + เชดเดอร์ + SGSR อัปสเกลลิง + HUD ประสิทธิภาพ + เครดิต & ลิขสิทธิ์ + ฟีเจอร์บางอย่างของ WinNative สร้างขึ้นบนโปรเจกต์โอเพนซอร์สเหล่านี้ แตะเพื่อดูแต่ละแหล่งที่มา + ค่าเริ่มต้น + เครดิต + เปิดโหมดฮาร์ดคอร์? + โหมดฮาร์ดคอร์จะรีเซ็ตเกมทันทีและปิดการโหลดสเตตบันทึก การกรอไปข้างหน้า และสูตรโกง ความคืบหน้าที่ยังไม่ได้บันทึกจะสูญหาย ดำเนินการต่อ? + ยกเลิก + เปิดใช้งาน + นำเข้า BIOS แล้ว: %1$s + ไฟล์ BIOS ไม่ถูกต้อง + นำเข้า PS2 BIOS แล้ว: %1$s + ไฟล์ PS2 BIOS ไม่ถูกต้อง + ไม่มีซีเรียลเกมสำหรับค้นหาสูตรโกง + ใช้สูตรโกง %1$d รายการแล้ว + ไม่สามารถใช้สูตรโกง + สูตรโกง + ใช้ + ไม่พบสูตรโกงสำหรับเกมนี้ + ความสำเร็จ + ลงชื่อเข้าใช้ RetroAchievements + ชื่อผู้ใช้ + รหัสผ่าน + เข้าสู่ระบบไม่สำเร็จ + กำลังลงชื่อเข้าใช้… + ลงชื่อเข้าใช้ + %1$d/%2$d • %3$d คะแนน + ไม่มีความสำเร็จสำหรับเกมนี้ + กลับ + เปิดใช้งาน + ปิดใช้งาน + เปลี่ยนชื่อ + บันทึก + ความขัดแย้งการบันทึกบนคลาวด์ + เก็บการบันทึกในเครื่อง + A + เมนู + การแสดงผล + HUD + เสียง + การควบคุม + คลังเป็นปัจจุบัน + ROMs: %1$s + เพิ่ม %1$d + ลบ %1$d + ค่าเริ่มต้น + CRT + LCD + คม + เนทีฟ + อัตราส่วนภาพ + ฟิลเตอร์ NTSC + การลงสี + การแก้สี + ลบขีดจำกัดสไปรต์ + ความละเอียด + การจำลองเฟรมบัฟเฟอร์ + ดิเทอริง + แฮกไวด์สกรีน + 8:7 (เนทีฟ) + 4:3 (TV) + ปิด + RF + คอมโพสิต + S-Video + RGB + อัตโนมัติ + จอ GBA + จอ GBC + เปิด + 320x240 (เนทีฟ) + 640x480 + 960x720 + 1280x960 + 4:3 + 16:9 + 16:9 ปรับแล้ว + เนทีฟ + ภายใน + เปิด (16:9) + RETROACHIEVEMENTS + ลงชื่อเข้าใช้ด้วยบัญชี RetroAchievements ของคุณเพื่อรับและติดตามความสำเร็จของเกมเรโทร + ชื่อผู้ใช้ + รหัสผ่าน + ป้อนชื่อผู้ใช้และรหัสผ่านของคุณ + เข้าสู่ระบบไม่สำเร็จ + ลงชื่อเข้าใช้ + รหัสผ่านของคุณถูกใช้เพียงครั้งเดียวเพื่อรับโทเคนเข้าสู่ระบบ ซึ่งจัดเก็บอย่างปลอดภัยบนอุปกรณ์ + เปิดใช้งานความสำเร็จ + โหมดฮาร์ดคอร์ (ไม่มีสเตตบันทึก) + %1$d / %2$d คะแนน + ไม่พบความสำเร็จสำหรับเกมนี้ + ออกจากระบบ + สูตรโกง + ชื่อ + โค้ด + ยกเลิก + บันทึก + สูตรโกง %1$d + ยังไม่มีสูตรโกง เพิ่มโค้ดสูตรโกงสำหรับเกมนี้ + เพิ่มสูตรโกง + + ไดรเวอร์ GPU + ระบบ (ค่าเริ่มต้น) + ติดตั้งไดรเวอร์ Turnip ใน การตั้งค่า \u2192 ไดรเวอร์ ไดรเวอร์เดียวกันใช้ได้ทั้งเกม PC และ PS2. + + PS2 HDD (DEV9) + ไดรฟ์ภายในเสมือนสำหรับเกมที่ใช้ HDD เช่น Final Fantasy XI รีสตาร์ทเกม + ไดรฟ์ภายในเสมือนสำหรับเกมที่ใช้ HDD เช่น Final Fantasy XI + ตั้งค่าโหมด DNS เป็น Internal เพื่อให้โฮสต์เซิร์ฟเวอร์ที่กำหนดเองของคุณมีผล + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + Add Cheat + Cheat name + Codes (one per line, e.g. 2021A268 00000000) + Custom + Enter a name and at least one valid code + Add + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + PS2 HDD Images + A .raw HDD image, or a .zip containing one (e.g. a game’s downloaded HDD with maps/DLC) + Import HDD Image + Importing… + Imported %1$s + Could not import HDD image + Removed %1$s + Remove %1$s + HDD Image + None + Cheats + Patches + PATCH + Custom + Applied %1$d cheat(s), %2$d patch(es). + No cheats or patches found for this game. + Cheat + Patch + Add +แกน CPU +แกนคู่ +เกมโกงภายใน +ความละเอียดภายใน +ตัวเรนเดอร์ +ตำแหน่งแถบเซนเซอร์ +ข้ามอินโทร BIOS + + + + + + +ล่าง +ตัวแปลคำสั่งแบบแคช +ฮาร์ดแวร์ +ตัวแปลคำสั่ง +JIT +เมาส์ / สัมผัส +อนาล็อกขวา (สัมบูรณ์) +อนาล็อกขวา (สัมพัทธ์) +ซอฟต์แวร์ +ยืดเต็มจอ +บน +ข้าม VBI (ข้ามเฟรมอัตโนมัติ) +จอกว้าง +ตัวชี้ Wiimote +การเปลี่ยนแปลงจะมีผลในครั้งถัดไปที่คุณเปิดเกมนี้ +เปิดเกมนี้หนึ่งครั้งเพื่อให้ตรวจพบซีเรียลของแผ่นดิสก์ จากนั้นเกมโกงและแพตช์จะปรากฏที่นี่ +ข้ามการยืนยันตัวตน DNAS — จำเป็นสำหรับการเล่นออนไลน์ +ใช้อัตโนมัติ (ออนไลน์) +เกมโกง & แพตช์ +ขนาด: %1$s +นำเข้าอิมเมจ HDD +ลบ +เปิดใช้ NetPlay +ปิดอยู่โดยค่าเริ่มต้น เปิดใช้ แล้วเลือกเป็นโฮสต์หรือเข้าร่วมก่อนเริ่มเกม\nจะปิดอีกครั้งเมื่อคุณออกจากเกม +ที่อยู่โฮสต์ +IP หรือชื่อโฮสต์ +เซสชันโฮสต์ +เปิด = รอผู้เล่น ปิด = เข้าร่วมที่อยู่โฮสต์ +NetPlay ใช้พอร์ตผู้เล่นหลายคนในเครือข่ายท้องถิ่นผ่าน TCP (ผู้เล่น 1 เป็นโฮสต์ / ผู้เล่น 2 เป็นไคลเอนต์) การเล่นออนไลน์ของ PS2 ใช้ DEV9 Ethernet แทน +พอร์ต +การ์ดความจำ %1$d +ภาพหน้าจอ +ใช้เซฟบนคลาวด์ +LAN (IP โดยตรง) +กำลังเชื่อมต่อ… +การเชื่อมต่อ +ออนไลน์ (รหัสโฮสต์) +ปิด +NetPlay ของ GameCube/Wii ใช้เอนจินของ Dolphin เอง โฮสต์ = ผู้เล่น 1, เข้าร่วม = ผู้เล่น 2 เลือกโฮสต์หรือเข้าร่วมและประเภทการเชื่อมต่อก่อนเริ่มเกม อุปกรณ์ทั้งสองจะบูตเกมเดียวกันพร้อมกัน +แชร์ IP Wi‑Fi ของอุปกรณ์คุณและพอร์ตนี้ให้ผู้เล่น 2 เกมจะเริ่มโดยอัตโนมัติเมื่อพวกเขาเชื่อมต่อ +รหัสโฮสต์จะแสดงเมื่อเกมบูต — แชร์ให้ผู้เล่น 2 เกมจะเริ่มโดยอัตโนมัติเมื่อพวกเขาเชื่อมต่อ +ป้อน IP Wi‑Fi และพอร์ตของโฮสต์ จากนั้นเริ่มเกมเพื่อเชื่อมต่อ +ป้อนรหัสโฮสต์จากผู้เล่น 1 จากนั้นเริ่มเกมเพื่อเชื่อมต่อ +เปิดใช้ NetPlay ในการตั้งค่าเกมและเลือกโฮสต์หรือเข้าร่วมก่อนเริ่มเกม +ค้นหาห้องบน Wi‑Fi +Game Link · แต่ละหน้าจอเป็นเครื่องพกพาของตัวเอง +การเล่นหลายคนของ GBA ใช้ gpSP + อะแดปเตอร์ไร้สาย ตรวจสอบให้แน่ใจว่าติดตั้ง libgpsp แล้ว +การเล่นหลายคนแบบแชร์หน้าจอผ่าน Wi‑Fi (เหมือน RetroArch)\nโฮสต์ = ผู้เล่น 1, เข้าร่วม = ผู้เล่น 2 อุปกรณ์ทั้งสองแสดงเกมเดียวกัน +Game Link ผ่าน Wi‑Fi — แต่ละอุปกรณ์รันเกมของตัวเอง\nGB/GBC: การเชื่อมต่อแบบซีเรียลของ Gambatte (Pokémon เจน 1–2)\nGBA: อะแดปเตอร์ไร้สาย gpSP (การต่อสู้ Pokémon FR/LG/Emerald) +สร้างห้อง +รหัสโฮสต์ +รหัสโฮสต์ traversal จากโฮสต์ +กำลังเป็นโฮสต์ห้อง +แตะโฮสต์เพื่อเปิดห้องสำหรับเซสชันการเล่นนี้ จากนั้นเริ่มเกม NetPlay จะปิดเมื่อคุณออก +อยู่ในห้อง +เข้าร่วมด้วย IP +เข้าร่วมแล้ว +เข้าร่วม +เมื่อเริ่มเกม +ออก +โฮสต์ = P1 · เข้าร่วม = P2 · เกมเดียวกันบนทั้งสองหน้าจอ +โฮสต์ +เข้าร่วม +กำหนดเอง +ไม่พบห้อง ตรวจสอบให้แน่ใจว่าโฮสต์อยู่บน Wi‑Fi เดียวกันและกำลังเป็นโฮสต์ห้อง +ชื่อที่แสดง +แสดงให้ผู้เล่นคนอื่นเห็น +เชื่อมต่อแล้ว %1$d +ห้องเปิดสำหรับเซสชันนี้เท่านั้น เริ่มเกมเมื่อพร้อม การออกจากเกมจะปิด NetPlay +ผู้เล่น +สแกน Wi‑Fi +สแกนอีกครั้ง +สแกน Wi‑Fi เดียวกันเพื่อหาห้องที่เปิดอยู่ หรือเข้าร่วมด้วยที่อยู่ IP +กำลังสแกน Wi‑Fi… +ผลการสแกน +แตะห้องเพื่อเข้าร่วมทันที (จะไม่บันทึก IP ไว้สำหรับการเริ่มเกมครั้งถัดไป) +หยุดสแกน +NetPlay +%1$s เชื่อมต่อแล้ว +%1$s ตัดการเชื่อมต่อแล้ว +กำลังรอผู้เล่น… +การรองรับ PlayStation 2 กำลังจะมาเร็วๆ นี้ +แสดงปุ่ม L3 / R3 +เมื่อปิด ให้แตะอนาล็อกสองครั้งเพื่อคลิก L3 / R3 +แฟล็กไดรเวอร์ TURNIP +ใช้เฉพาะเมื่อเลือกไดรเวอร์ GPU แบบกำหนดเองด้านบน +ไม่พบไฟล์เกม +ลบ +นำเข้าจากไฟล์… +กำลังโหลด… +NetPlay + Wii Home + เปลี่ยนคอนโซล + ระบุเป็นคอนโซล + ตอนนี้ระบุเป็น %1$s ReShade ใช้เอฟเฟกต์ ReShade (.fx) กับเกม DXVK/VKD3D (Vulkan) ผ่านเลเยอร์ vkBasalt ที่มาพร้อมในตัว วางเอฟเฟกต์แต่ละรายการไว้ในโฟลเดอร์ของตัวเองภายใต้ Android/data/<package>/files/ReShade/ การปรับพารามิเตอร์แบบเรียลไทม์และสวิตช์ในเกมจะมาพร้อมกับการอัปเดตเลเยอร์แบบโหลดซ้ำทันที @@ -1656,4 +2429,27 @@ เปิดใช้ ReShade ไม่มีเอฟเฟกต์ ReShade ในชุดนี้ เพิ่มเอฟเฟกต์ในการตั้งค่าของเกมนี้ (หรือของคอนเทนเนอร์) เพื่อสลับและปรับแต่งที่นี่ เอฟเฟกต์นี้ไม่มีพารามิเตอร์ที่ปรับได้ + กำลังลบเซฟ… + ลบ + ลบเซฟบนคลาวด์จาก %1$s อย่างถาวรหรือไม่ การกระทำนี้ย้อนกลับไม่ได้ + ลบเซฟบนคลาวด์ + ไม่สามารถลบเซฟบนคลาวด์ได้ + ลบเซฟบนคลาวด์แล้ว + ดาวน์โหลดคอร์คอนโซลก่อน — การตั้งค่า › เรโทร + อุปกรณ์นี้ไม่รองรับการจำลอง PS2 — ต้องใช้ OpenGL ES 3.1 ขึ้นไป + ตรวจหาการอัปเดต + กำลังตรวจหาการอัปเดต… + ดาวน์โหลดคอร์คอนโซล + กำลังดาวน์โหลด… %1$d / %2$d MB + คอร์คอนโซล + ติดตั้งแล้ว — บิลด์ %1$s + ติดตั้งแล้ว — บิลด์ %1$s (ตรวจหาการอัปเดตไม่สำเร็จ) + กำลังติดตั้ง… + ยังไม่ได้ติดตั้ง — ดาวน์โหลดเพื่อเล่นเกมเรโทร + สถานะ + อัปเดตคอร์คอนโซล + มีการอัปเดต — บิลด์ %1$s (%2$d MB) + กำลังตรวจสอบไฟล์ที่ดาวน์โหลด… + กำลังดำเนินการ… + ระบบ diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index acd1fe4f0..ff26c2b4f 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -1621,6 +1621,779 @@ Yüklü konum: Klasör oluşturma başarısız oldu Yenile + Retro + Kaydı aktar + Bu oyuna yerel bir kayıt içe aktarın veya oyunun mevcut kaydını dışa aktarın. + Kaydı içe aktar + Kaydı dışa aktar + Kayıt içe aktarıldı + Kayıt içe aktarılamadı + Kayıt dışa aktarıldı + Kayıt dışa aktarılamadı + Bu oyun için henüz bir kayıt yok + Hileler + Hileler Hardcore modunda devre dışı + + + Kaydet + İptal + Durumu Kaydet + Durumu Yükle + Başarımlar + Hileler + Hafıza Kartları + İleri Sarma + Sıfırla + Disk Değiştir + Yuva %1$d + Yüklemek için dokunun + Boş + Üzerine yazmak için dokunun + Boş — kaydetmek için dokunun + Yuva %1$d boş + Yuva %1$d yüklendi + Yuva %1$d yüklenemedi + Yuva %1$d\'e kaydedildi + Kaydetme başarısız + • Yuva 1 + • Yuva 2 + • Kullanmak için dokunun + Yeni Hafıza Kartı + Kart İçe Aktar + Çevrimiçi Etkinleştir (DEV9) + PS2 ağ adaptörü — bağlamak için oyunu yeniden başlatır + Ethernet Aygıtı + DNS Modu + Birincil DNS + İkincil DNS + isteğe bağlı + Otomatik IP (DHCP) + Sunucu: %1$s + IP ayarlamak için dokunun (boş bırakınca kaldırılır) + %1$s → IP + Sunucu Ana Bilgisayarı Ekle + Yeni Sunucu Ana Bilgisayar Adı + örn. bf2.playbattlefront.com + Ekran Kontrolleri + Düzeni Düzenle + Düzeni Sıfırla + Düzen sıfırlandı + Sol Çubuk: X Ters Çevir + Sol Çubuk: Y Ters Çevir + Sağ Çubuk: X Ters Çevir + Sağ Çubuk: Y Ters Çevir + Düğme Rengi + Harf Rengi + Gölge Rengi + Arka Plan Rengi + Renkleri Sıfırla + İşleyici + Vulkan + OpenGL + Software + Çözünürlük Ölçeği + 1x (Yerel) + 1.5x + 2x + 3x + 4x + En Boy Oranı + Uzat + Otomatik (Standart) + 4:3 + 16:9 + Ekran Filtresi + En Yakın + Bilinear (Yumuşak) + Bilinear (Keskin) + Doku Filtresi + Bilinear (Zorunlu) + Bilinear (PS2) + Bilinear (Spritelar) + Karıştırma Doğruluğu + En Az + Temel + Orta + Yüksek + Tam + En Fazla + CRT / TV Gölgelendirici + Kapalı + Tarama Çizgisi + Çapraz + Üçgen + Dalga + Lottes + 4xRGSS + NxAGSS + Kare Atlama + Kapalı + 1 Atla + 2 Atla + 3 Atla + Mipmapping + Ses + %1$d%% + Sessiz + Stereo Kanalları Değiştir + EE Döngü Oranı + 50% + 60% + 75% + 100% (Varsayılan) + 130% + 180% + 300% + EE Döngü Atlama + Kapalı + 1 + 2 + 3 + Anında VU1 + Çok İş Parçacıklı VU (MTVU) + Hızlı CDVD + FPS + Emülasyon Hızı + CPU Kullanımı + GPU Kullanımı + Dahili Çözünürlük + Deinterlace Modu + Otomatik + Kapalı + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + FMV En-Boy Oranı + Bulanıklık Önleme + Geniş Ekran Yamaları + Taramasız Yamalar + VU Flag Hack + INTC Döngü Algılama + Bekleme Döngüsü Algılama + Ses Zaman Esnetme + Ses Arabelleği + Çıkış Gecikmesi + %1$d ms + Kare Süreleri + GS İstatistikleri + Donanım Bilgisi + Sürüm + Giriş Göstergesi + Menü + Ekran + Performans + HUD + Ses + Çevrimiçi + Kontroller + Devam Et + Duraklat + Çıkış + BIOS içe aktarıldı: %1$s + Geçersiz BIOS dosyası + Geçersiz retro oyun + ROM bulunamadı: %1$s + Bu arşivdeki ROM okunamadı + Çekirdek yüklü değil: %1$s + Hileler etkin — bu oturumda başarımlar devre dışı + Bulut kaydı geri yüklendi + Geri yükleme başarısız + %1$s için daha yeni bir bulut kaydı var. Eşitlemek ister misiniz ve hangi bulut kaydını tutmayı tercih edersiniz? + Bulut kaydı + Retro + Emülatör çekirdeği yüklenemedi + ROM yüklenemedi + Bu çekirdek için grafik desteklenmiyor + Emülatör hatası + Varsayılan + CRT + LCD + Keskin + SGSR + SGSR Ölçekleme + Yerel + Ses + Sol Çubuk: X Ters Çevir + Sol Çubuk: Y Ters Çevir + Sağ Çubuk: X Ters Çevir + Sağ Çubuk: Y Ters Çevir + Ekran Kontrolleri + Dokunsal Geri Bildirim + Dikey + Yatay + Düzeni Düzenle (%1$s) + %1$s Düzenini Sıfırla + %1$s düzeni sıfırlandı + Düğme Rengi + Harf Rengi + Gölge Rengi + Arka Plan Rengi + Renkleri Sıfırla + Renkler sıfırlandı + Performans HUD + Alfa + Arka Plan Alfası + Arka Plan + Ölçek + Sayısal Kare Süresi + Çift Seri Pil + HUD ÖĞELERİ + FPS + Konsol + GPU + CPU + RAM + Pil + Sıcaklık + Grafik + CPU Sıcaklığı + Durumu Kaydet + Durumu Yükle + Durum yükleme Hardcore modunda devre dışı + Başarımlar + Hileler + Hileler Hardcore modunda devre dışı + Sıfırla + İleri Sarma + İleri sarma Hardcore modunda devre dışı + HUD + Disk %1$d/%2$d + Devam Et + Duraklat + Çıkış + Yuva %1$d\'e kaydedildi + Durum kaydedilemedi + %1$s BIOS gerekli + PlayStation oyunları, sizin sağlamanız gereken gerçek bir konsol BIOS dosyasına ihtiyaç duyar. Devam etmek için bir BIOS (scph5501.bin, scph5500.bin, scph5502.bin, scph1001.bin veya scph7001.bin) içe aktarın. + BIOS İçe Aktar… + İptal + Yuva %1$d boş + Yuva %1$d yüklendi + Durum yüklenemedi + Yuva %1$d + Yuva %1$d\'i Yeniden Adlandır + Genel + Grafik + Performans + HUD + Giriş + Ses + Çevrimiçi + İptal + Kaydet + Varsayılan + CRT + LCD + Keskin + 2x + 4x + Yerel + OYUN + Ad + Sistem + Emülatör Çekirdeği + ROM Yolu + %1$s BIOS + Yüklü + Yok — %1$s oyunlarını çalıştırmak için gerekli + BIOS İçe Aktar… + BIOS Kaldır + KİTAPLIK GÖRSELİ + Oyun Kartı Görseli + Izgara Görseli + Atlıkarınca Görseli + Liste Görseli + Özel görsel ayarlandı + Görsel ayarla + Kaldır + VİDEO + Video Filtresi + SGSR + SGSR Ölçekleme + Performans HUD + ÇEKİRDEK + İşleyici + Vulkan + OpenGL + Software + Çözünürlük Ölçeği + 1x (Yerel) + 1.5x + 2x + 3x + 4x + En Boy Oranı + Uzat + Otomatik (Standart) + 4:3 + 16:9 + Ekran Filtresi + En Yakın + Bilinear (Yumuşak) + Bilinear (Keskin) + Doku Filtresi + Bilinear (Zorunlu) + Bilinear (PS2) + Bilinear (Spritelar) + Karıştırma Doğruluğu + En Az + Temel + Orta + Yüksek + Tam + En Fazla + CRT / TV Gölgelendirici + Kapalı + Tarama Çizgisi + Çapraz + Üçgen + Dalga + Lottes + 4xRGSS + NxAGSS + Kare Atlama + 1 Atla + 2 Atla + 3 Atla + Mipmapping + PERFORMANS + EE Döngü Oranı + 50% + 60% + 75% + 100% (Varsayılan) + 130% + 180% + 300% + EE Döngü Atlama + 1 + 2 + 3 + Anında VU1 + Çok İş Parçacıklı VU (MTVU) + Hızlı CDVD + PERFORMANS HUD + FPS + Emülasyon Hızı + CPU Kullanımı + GPU Kullanımı + Dahili Çözünürlük + Deinterlace Modu + Otomatik + Kapalı + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + FMV En-Boy Oranı + Bulanıklık Önleme + Geniş Ekran Yamaları + Taramasız Yamalar + VU Flag Hack + INTC Döngü Algılama + Bekleme Döngüsü Algılama + Ses Zaman Esnetme + Ses Arabelleği + Çıkış Gecikmesi + %1$d ms + Kare Süreleri + GS İstatistikleri + Donanım Bilgisi + Sürüm + Giriş Göstergesi + Hızlı Başlatma + ÇEVRİMİÇİ (DEV9) + Çevrimiçi Etkinleştir + Ethernet Aygıtı + Otomatik + Wi-Fi + DNS Modu + Manuel + Dahili + Birincil DNS + İkincil DNS + isteğe bağlı + Otomatik IP (DHCP) + GİRİŞ + Ekran kontrolleri + Dokunsal Geri Bildirim + SES + Ses + Sessiz + Stereo Kanalları Değiştir + Ses + RETRO VARSAYILANLARI + Bir oyunun kendi ayarlarında geçersiz kılınmadıkça her konsolun oyunlarına uygulanan varsayılanlar. + RETROACHIEVEMENTS + Hesap + Giriş yapıldı + Giriş yapılmadı — giriş yapmak için bir oyunun Başarımlarını açın + Başarımlar etkin + Varsayılan olarak Hardcore modu (durum kaydı yok) + Çıkış Yap + PLAYSTATION BIOS + Yüklü + Yok — PS1 oyunları BIOS gerektirir + PS1 BIOS İçe Aktar… + PS1 BIOS kaldırıldı + Kaldırılacak BIOS yok + PS1 BIOS Kaldır + PLAYSTATION 2 BIOS + Yok — PS2 oyunları BIOS gerektirir + Biçim + Birleştirilmiş tek dosyalık döküm (bölge etiketli .bin, ~4MB). Bölünmüş ROM0/MEC/NVM setleri kabul edilmez. + PS2 BIOS İçe Aktar… + PS2 BIOS kaldırıldı + PS2 BIOS Kaldır + KİTAPLIK GÖRSELİ + Retro kutu görseli (kartuş / CD kutusu) + Kutu görseli + İçe aktarımda thumbnails.libretro.com adresinden otomatik olarak alınır; özel bir görsel her zaman onu geçersiz kılar. + ROM KLASÖRÜ + Klasör + Ayarlanmadı — oyunları otomatik içe aktarmak için bir klasör seçin + Otomatik içe aktar + Bu klasördeki yeni oyunlar, doğru konsol algılanarak kitaplığınıza otomatik olarak eklenir. + ROM Klasörü Seç + ROM Klasörü Seç… + ROM Klasörünü Değiştir… + Şimdi Tara + KONSOL VARSAYILANLARI + Varsayılan ayarlarını yapmak için bir konsola dokunun. + İşleyici + Çözünürlüğü ölçekle + En Boy Oranı + Uzat + Otomatik (Standart) + 4:3 + 16:9 + Ekran Filtresi + En Yakın + Bilinear (Yumuşak) + Bilinear (Keskin) + Doku Filtresi + Bilinear (Zorunlu) + Bilinear (PS2) + Bilinear (Spritelar) + Karıştırma Doğruluğu + En Az + Temel + Orta + Yüksek + Tam + En Fazla + CRT / TV Gölgelendirici + Kapalı + Tarama Çizgisi + Çapraz + Üçgen + Dalga + Lottes + 4xRGSS + NxAGSS + Kare Atlama + 1 Atla + 2 Atla + 3 Atla + Mipmapping + EE Döngü Oranı + 50% + 60% + 75% + 100% (Varsayılan) + 130% + 180% + 300% + EE Döngü Atlama + Kapalı + 1 + 2 + 3 + Anında VU1 + Çok İş Parçacıklı VU (MTVU) + Hızlı CDVD + Ekran dokunmatik kontrolleri + Ses + Stereo Kanalları Değiştir + HUD: FPS + HUD: Emülasyon Hızı + HUD: CPU Kullanımı + HUD: GPU Kullanımı + HUD: Dahili Çözünürlük + Çevrimiçi Etkinleştir (DEV9) + Ethernet Aygıtı + Otomatik + Wi-Fi + DNS Modu + Manuel + Dahili + Birincil DNS + İkincil DNS + isteğe bağlı + Otomatik IP (DHCP) + Gölgelendirici + SGSR ölçekleme + Performans HUD + KATKIDA BULUNANLAR & LİSANSLAR + WinNative\'in bazı özellikleri bu açık kaynaklı projeler üzerine kuruludur. Her kaynağı görüntülemek için dokunun. + Varsayılanlar + Katkıda Bulunanlar + Hardcore modu etkinleştirilsin mi? + Hardcore modu oyunu şimdi sıfırlar ve durum kaydı yükleme, ileri sarma ile hileleri devre dışı bırakır. Kaydedilmemiş tüm ilerleme kaybolur. Devam edilsin mi? + İptal + Etkinleştir + BIOS içe aktarıldı: %1$s + Geçersiz BIOS dosyası + PS2 BIOS içe aktarıldı: %1$s + Geçersiz PS2 BIOS dosyası + Hile aranacak oyun seri numarası yok. + %1$d hile uygulandı. + Hileler uygulanamadı. + Hileler + Uygula + Bu oyun için hile bulunamadı. + Başarımlar + RetroAchievements\'e giriş yap + Kullanıcı adı + Parola + Giriş başarısız + Giriş yapılıyor… + Giriş Yap + %1$d/%2$d • %3$d puan + Bu oyun için başarım yok. + Geri + Etkin + Devre dışı + Yeniden Adlandır + Kaydet + Bulut Kaydı Çakışması + Yerel Kaydı Tut + A + Menü + Ekran + HUD + Ses + Kontroller + Kitaplık güncel + ROM: %1$s + %1$d eklendi + %1$d kaldırıldı + Varsayılan + CRT + LCD + Keskin + Yerel + En Boy Oranı + NTSC Filtresi + Renklendirme + Renk Düzeltme + Sprite Sınırını Kaldır + Çözünürlük + Kare Arabelleği Emülasyonu + Dithering + Geniş Ekran Hilesi + 8:7 (Yerel) + 4:3 (TV) + Kapalı + RF + Kompozit + S-Video + RGB + Otomatik + GBA Ekranı + GBC Ekranı + Açık + 320x240 (Yerel) + 640x480 + 960x720 + 1280x960 + 4:3 + 16:9 + 16:9 Ayarlı + Yerel + Dahili + Açık (16:9) + RETROACHIEVEMENTS + Retro oyunlar için başarım kazanmak ve takip etmek için RetroAchievements hesabınızla giriş yapın. + Kullanıcı adı + Parola + Kullanıcı adınızı ve parolanızı girin + Giriş başarısız + Giriş Yap + Parolanız yalnızca bir kez giriş belirteci almak için kullanılır ve bu belirteç aygıtta güvenli şekilde saklanır. + Başarımlar etkin + Hardcore modu (durum kaydı yok) + %1$d / %2$d puan + Bu oyun için başarım bulunamadı. + Çıkış Yap + HİLELER + Ad + Kod + İptal + Kaydet + Hile %1$d + Henüz hile yok. Bu oyun için bir hile kodu ekleyin. + Hile Ekle + + GPU Sürücüsü + Sistem (Varsayılan) + Turnip sürücülerini Ayarlar \u2192 Sürücüler altından yükleyin. Aynı sürücüler hem PC hem de PS2 oyunları için çalışır. + + PS2 HDD (DEV9) + Final Fantasy XI gibi HDD tabanlı oyunlar için sanal dahili sürücü. Oyunu yeniden başlatır. + Final Fantasy XI gibi HDD tabanlı oyunlar için sanal dahili sürücü. + Özel sunucu ana bilgisayarlarınızın etkili olması için DNS Modu Internal olarak ayarlandı. + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + Add Cheat + Cheat name + Codes (one per line, e.g. 2021A268 00000000) + Custom + Enter a name and at least one valid code + Add + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + PS2 HDD Images + A .raw HDD image, or a .zip containing one (e.g. a game’s downloaded HDD with maps/DLC) + Import HDD Image + Importing… + Imported %1$s + Could not import HDD image + Removed %1$s + Remove %1$s + HDD Image + None + Cheats + Patches + PATCH + Custom + Applied %1$d cheat(s), %2$d patch(es). + No cheats or patches found for this game. + Cheat + Patch + Add +CPU Çekirdeği +Çift Çekirdek +Dahili Hileler +Dahili Çözünürlük +İşleyici +Sensör Çubuğu Konumu +BIOS Girişini Atla + + + + + + +Alt +Önbelleğe Alınmış Yorumlayıcı +Donanım +Yorumlayıcı +JIT +Fare / Dokunma +Sağ Çubuk (Mutlak) +Sağ Çubuk (Göreceli) +Yazılım +Uzat +Üst +VBI Atlama (Otomatik Kare Atlama) +Geniş Ekran +Wiimote İşaretçisi +Değişiklikler bu oyunu bir sonraki başlatışınızda uygulanır. +Disk seri numarasının algılanabilmesi için bu oyunu bir kez başlatın; ardından hileler ve yamalar burada görünecek. +DNAS kimlik doğrulama atlaması — çevrimiçi oynamak için gereklidir +Otomatik Uygulanan (Çevrimiçi) +Hileler & Yamalar +Boyut: %1$s +HDD İmajını İçe Aktar +Kaldır +NetPlay\'i Etkinleştir +Varsayılan olarak kapalı. Etkinleştirin, ardından başlatmadan önce Sunucu veya Katıl seçin.\nOyundan çıktığınızda tekrar kapanır. +Sunucu adresi +IP veya ana bilgisayar adı +Sunucu oturumu +Açık = bir oyuncu bekle. Kapalı = sunucu adresine katıl +NetPlay, TCP üzerinden yerel çok oyunculu bağlantı noktalarını kullanır (oyuncu 1 sunucu / oyuncu 2 istemci). PS2 çevrimiçi oyun bunun yerine DEV9 Ethernet kullanır. +Bağlantı Noktası +Hafıza Kartı %1$d +Ekran Görüntüsü +Bulut Kaydını Kullan +LAN (doğrudan IP) +Bağlanıyor… +Bağlantı +Çevrimiçi (sunucu kodu) +Kapat +GameCube/Wii NetPlay, Dolphin\'in kendi motorunu kullanır. Sunucu = Oyuncu 1, Katıl = Oyuncu 2. Başlatmadan önce Sunucu veya Katıl ile bir bağlantı türü seçin; her iki cihaz da aynı oyunu birlikte başlatır. +Cihazınızın Wi‑Fi IP adresini ve bu bağlantı noktasını Oyuncu 2 ile paylaşın. Bağlandıklarında oyun otomatik olarak başlar. +Oyun başlatıldığında bir sunucu kodu gösterilir — bunu Oyuncu 2 ile paylaşın. Bağlandıklarında oyun otomatik olarak başlar. +Sunucunun Wi‑Fi IP adresini ve bağlantı noktasını girin, ardından bağlanmak için başlatın. +Oyuncu 1\'den gelen sunucu kodunu girin, ardından bağlanmak için başlatın. +Oyun ayarlarında NetPlay\'i etkinleştirin ve başlatmadan önce Sunucu veya Katıl seçin +Wi‑Fi üzerinde oda bul +Game Link · her ekran kendi el konsolu +GBA çok oyunculu oyun gpSP + Kablosuz Adaptör kullanır. libgpsp\'nin yüklü olduğundan emin olun. +Wi‑Fi üzerinden paylaşımlı ekran çok oyunculu (RetroArch gibi).\nSunucu = Oyuncu 1, Katıl = Oyuncu 2. Her iki cihaz da aynı oyunu gösterir. +Wi‑Fi üzerinden Game Link — her cihaz kendi oyununu çalıştırır.\nGB/GBC: Gambatte seri bağlantı (Pokémon 1–2. Nesil).\nGBA: gpSP Kablosuz Adaptör (Pokémon FR/LG/Emerald savaşları). +Oda oluştur +Sunucu kodu +Sunucudan gelen geçiş sunucu kodu +Oda barındırılıyor +Bu oyun oturumu için bir oda açmak üzere Sunucu\'ya dokunun, ardından oyunu başlatın. Oyundan çıktığınızda NetPlay kapanır. +Odada +IP ile katıl +Katıldı +Katıl +Başlatıldığında +Ayrıl +Sunucu = O1 · Katıl = O2 · her iki ekranda aynı oyun +Sunucu +Katıl +Manuel +Oda bulunamadı. Sunucunun aynı Wi‑Fi ağında olduğundan ve bir oda barındırdığından emin olun. +Görünen ad +Diğer oyunculara gösterilir +%1$d bağlı +Oda yalnızca bu oturum için açık. Hazır olduğunuzda başlatın. Oyundan çıkmak NetPlay\'i kapatır. +Oyuncular +Wi‑Fi Tara +Tekrar tara +Açık odalar için aynı Wi‑Fi ağını tarayın veya IP adresiyle katılın. +Wi‑Fi taranıyor… +Tarama sonuçları +Şimdi katılmak için bir odaya dokunun (IP\'yi bir sonraki başlatma için kaydetmez). +Taramayı durdur +NetPlay +%1$s bağlandı +%1$s bağlantısı kesildi +Oyuncular bekleniyor… +PlayStation 2 desteği yakında geliyor +L3 / R3 Düğmelerini Göster +Kapalıyken, L3 / R3\'e tıklamak için bir çubuğa çift dokunun +TURNIP SÜRÜCÜ BAYRAKLARI +Yalnızca yukarıda özel bir GPU sürücüsü seçildiğinde uygulanır. +Oyun dosyası bulunamadı +Sil +Dosyadan içe aktar… +Yükleniyor… +NetPlay + Wii Home + Konsolu değiştir + Konsol olarak tanımla + Artık %1$s olarak tanımlandı ReShade Yerleşik vkBasalt katmanı aracılığıyla DXVK/VKD3D (Vulkan) oyunlarına bir ReShade efekti (.fx) uygulayın. Her efekti Android/data/<package>/files/ReShade/ altında kendi klasörüne yerleştirin. Canlı parametre ayarı ve oyun içi anahtar, canlı yeniden yükleme katmanı güncellemesiyle gelecek. @@ -1656,4 +2429,27 @@ Yüklü konum: ReShade\'i etkinleştir Bu sette ReShade efekti yok. Burada değiştirmek ve ayarlamak için bu oyunun (veya kapsayıcının) ayarlarına efekt ekleyin. Bu efektin ayarlanabilir parametresi yok. + Kayıt siliniyor… + Sil + %1$s üzerindeki bulut kaydı kalıcı olarak silinsin mi? Bu işlem geri alınamaz. + Bulut Kaydını Sil + Bulut kaydı silinemedi + Bulut kaydı silindi + Önce konsol çekirdeklerini indirin — Ayarlar › Retro + Bu cihaz PS2 emülasyonunu çalıştıramıyor — OpenGL ES 3.1 veya üstü gerekiyor. + Güncellemeleri denetle + Güncellemeler denetleniyor… + Konsol çekirdeklerini indir + İndiriliyor… %1$d / %2$d MB + Konsol Çekirdekleri + Yüklü — sürüm %1$s + Yüklü — sürüm %1$s (güncelleme denetimi başarısız) + Yükleniyor… + Yüklü değil — retro oyunları oynamak için indirin + Durum + Konsol çekirdeklerini güncelle + Güncelleme mevcut — sürüm %1$s (%2$d MB) + İndirme doğrulanıyor… + Çalışıyor… + Sistem diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index aa2251751..1b5c1ac4b 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -1628,6 +1628,779 @@ Працювати у фоні Залишати чат активним після виходу з WinNative Оновити + Ретро + Перенесення збереження + Імпортуйте локальне збереження для цієї гри або експортуйте поточне збереження. + Імпортувати збереження + Експортувати збереження + Збереження імпортовано + Не вдалося імпортувати збереження + Збереження експортовано + Не вдалося експортувати збереження + Для цієї гри ще немає збереження + Чити + Чити вимкнено в режимі Hardcore + + + Зберегти + Скасувати + Зберегти стан + Завантажити стан + Досягнення + Чити + Карти пам\'яті + Прискорення + Скинути + Змінити диск + Слот %1$d + Торкніться, щоб завантажити + Порожньо + Торкніться, щоб перезаписати + Порожньо — торкніться, щоб зберегти + Слот %1$d порожній + Завантажено слот %1$d + Не вдалося завантажити слот %1$d + Збережено в слот %1$d + Не вдалося зберегти + • Слот 1 + • Слот 2 + • Торкніться, щоб використати + Нова карта пам\'яті + Імпортувати карту + Увімкнути мережу (DEV9) + Мережевий адаптер PS2 — перезапускає гру, щоб під\'єднати його + Пристрій Ethernet + Режим DNS + Основний DNS + Додатковий DNS + необов\'язково + Авто IP (DHCP) + Сервер: %1$s + торкніться, щоб задати IP (порожнє видаляє) + %1$s → IP + Додати хост сервера + Нове ім\'я хоста сервера + напр. bf2.playbattlefront.com + Екранне керування + Редагувати розкладку + Скинути розкладку + Розкладку скинуто + Ліва ручка: інвертувати X + Ліва ручка: інвертувати Y + Права ручка: інвертувати X + Права ручка: інвертувати Y + Колір кнопки + Колір літери + Колір тіні + Колір фону + Скинути кольори + Рендерер + Vulkan + OpenGL + Software + Масштаб роздільності + 1x (нативний) + 1.5x + 2x + 3x + 4x + Співвідношення сторін + Розтягнути + Авто (стандарт) + 4:3 + 16:9 + Фільтр зображення + Найближчий + Білінійний (гладкий) + Білінійний (чіткий) + Фільтр текстур + Білінійний (примусовий) + Білінійний (PS2) + Білінійний (спрайти) + Точність змішування + Мінімальна + Базова + Середня + Висока + Повна + Максимальна + Шейдер CRT / TV + Вимк. + Рядки розгортки + Діагональний + Трикутний + Хвиля + Lottes + 4xRGSS + NxAGSS + Пропуск кадрів + Вимк. + Пропуск 1 + Пропуск 2 + Пропуск 3 + Міпмапінг + Гучність + %1$d%% + Без звуку + Поміняти стереоканали + Частота циклів EE + 50% + 60% + 75% + 100% (за замовч.) + 130% + 180% + 300% + Пропуск циклів EE + Вимк. + 1 + 2 + 3 + Миттєвий VU1 + Багатопотоковий VU (MTVU) + Швидкий CDVD + FPS + Швидкість емуляції + Використання CPU + Використання GPU + Внутрішня роздільність + Режим деінтерлейсингу + Авто + Вимк. + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + Співвідношення сторін FMV + Антирозмиття + Широкоекранні патчі + Патчі без черезрядковості + VU Flag Hack + Виявлення циклу INTC + Виявлення циклу очікування + Розтягнення звуку в часі + Аудіобуфер + Затримка виводу + %1$d мс + Час кадрів + Статистика GS + Інформація про обладнання + Версія + Відображення вводу + Меню + Екран + Продуктивність + HUD + Звук + Мережа + Керування + Продовжити + Пауза + Вийти + BIOS імпортовано: %1$s + Недійсний файл BIOS + Недійсна ретрогра + ROM не знайдено: %1$s + Не вдалося прочитати ROM у цьому архіві + Ядро не встановлено: %1$s + Чити увімкнено — досягнення вимкнено для цього сеансу + Хмарне збереження відновлено + Не вдалося відновити + Для %1$s існує новіше хмарне збереження. Бажаєте синхронізувати, і яке хмарне збереження залишити? + Хмарне збереження + Retro + Не вдалося завантажити ядро емулятора + Не вдалося завантажити ROM + Графіка не підтримується для цього ядра + Помилка емулятора + За замовчуванням + CRT + LCD + Чіткий + SGSR + Масштабування SGSR + Нативний + Звук + Ліва ручка: інвертувати X + Ліва ручка: інвертувати Y + Права ручка: інвертувати X + Права ручка: інвертувати Y + Екранне керування + Тактильний відгук + Портрет + Ландшафт + Редагувати розкладку (%1$s) + Скинути розкладку %1$s + Розкладку %1$s скинуто + Колір кнопки + Колір літери + Колір тіні + Колір фону + Скинути кольори + Кольори скинуто + HUD продуктивності + Альфа + Альфа фону + Фон + Масштаб + Числовий час кадру + Батарея двох рядів + ЕЛЕМЕНТИ HUD + FPS + Консоль + GPU + CPU + RAM + Батарея + Темп. + Графік + Темп. CPU + Зберегти стан + Завантажити стан + Завантаження станів вимкнено в режимі Hardcore + Досягнення + Чити + Чити вимкнено в режимі Hardcore + Скинути + Прискорення + Прискорення вимкнено в режимі Hardcore + HUD + Диск %1$d/%2$d + Продовжити + Пауза + Вийти + Збережено в слот %1$d + Не вдалося зберегти стан + Потрібен BIOS %1$s + Ігри PlayStation потребують справжнього файлу BIOS консолі, який ви маєте надати. Імпортуйте BIOS (scph5501.bin, scph5500.bin, scph5502.bin, scph1001.bin або scph7001.bin), щоб продовжити. + Імпортувати BIOS… + Скасувати + Слот %1$d порожній + Завантажено слот %1$d + Не вдалося завантажити стан + Слот %1$d + Перейменувати слот %1$d + Загальні + Графіка + Продуктивність + HUD + Введення + Аудіо + Мережа + Скасувати + Зберегти + За замовчуванням + CRT + LCD + Чіткий + 2x + 4x + Нативний + ГРА + Назва + Система + Ядро емулятора + Шлях до ROM + BIOS %1$s + Встановлено + Немає — потрібен для запуску ігор %1$s + Імпортувати BIOS… + Видалити BIOS + ОБКЛАДИНКИ БІБЛІОТЕКИ + Зображення картки гри + Зображення сітки + Зображення каруселі + Зображення списку + Власне зображення задано + Задати зображення + Видалити + ВІДЕО + Відеофільтр + SGSR + Масштабування SGSR + HUD продуктивності + ЯДРО + Рендерер + Vulkan + OpenGL + Software + Масштаб роздільності + 1x (нативний) + 1.5x + 2x + 3x + 4x + Співвідношення сторін + Розтягнути + Авто (стандарт) + 4:3 + 16:9 + Фільтр зображення + Найближчий + Білінійний (гладкий) + Білінійний (чіткий) + Фільтр текстур + Білінійний (примусовий) + Білінійний (PS2) + Білінійний (спрайти) + Точність змішування + Мінімальна + Базова + Середня + Висока + Повна + Максимальна + Шейдер CRT / TV + Вимк. + Рядки розгортки + Діагональний + Трикутний + Хвиля + Lottes + 4xRGSS + NxAGSS + Пропуск кадрів + Пропуск 1 + Пропуск 2 + Пропуск 3 + Міпмапінг + ПРОДУКТИВНІСТЬ + Частота циклів EE + 50% + 60% + 75% + 100% (за замовч.) + 130% + 180% + 300% + Пропуск циклів EE + 1 + 2 + 3 + Миттєвий VU1 + Багатопотоковий VU (MTVU) + Швидкий CDVD + HUD ПРОДУКТИВНОСТІ + FPS + Швидкість емуляції + Використання CPU + Використання GPU + Внутрішня роздільність + Режим деінтерлейсингу + Авто + Вимк. + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + Співвідношення сторін FMV + Антирозмиття + Широкоекранні патчі + Патчі без черезрядковості + VU Flag Hack + Виявлення циклу INTC + Виявлення циклу очікування + Розтягнення звуку в часі + Аудіобуфер + Затримка виводу + %1$d мс + Час кадрів + Статистика GS + Інформація про обладнання + Версія + Відображення вводу + Швидке завантаження + МЕРЕЖА (DEV9) + Увімкнути мережу + Пристрій Ethernet + Авто + Wi-Fi + Режим DNS + Вручну + Внутрішній + Основний DNS + Додатковий DNS + необов\'язково + Авто IP (DHCP) + ВВЕДЕННЯ + Екранне керування + Тактильний відгук + АУДІО + Гучність + Без звуку + Поміняти стереоканали + Звук + СТАНДАРТНІ НАЛАШТУВАННЯ RETRO + Стандартні налаштування застосовуються до ігор кожної консолі, якщо не змінені у власних налаштуваннях гри. + RETROACHIEVEMENTS + Обліковий запис + Виконано вхід + Вхід не виконано — відкрийте Досягнення гри, щоб увійти + Досягнення увімкнено + Режим Hardcore за замовчуванням (без станів) + Вийти + BIOS PLAYSTATION + Встановлено + Немає — ігри PS1 потребують BIOS + Імпортувати BIOS PS1… + BIOS PS1 видалено + Немає BIOS для видалення + Видалити BIOS PS1 + BIOS PLAYSTATION 2 + Немає — ігри PS2 потребують BIOS + Формат + Об\'єднаний однофайловий дамп (.bin з тегом регіону, ~4 МБ). Розділені набори ROM0/MEC/NVM не приймаються. + Імпортувати BIOS PS2… + BIOS PS2 видалено + Видалити BIOS PS2 + ОБКЛАДИНКИ БІБЛІОТЕКИ + Ретрообкладинка (картридж / CD-бокс) + Обкладинка + Отримується автоматично з thumbnails.libretro.com під час імпорту; власне зображення завжди має пріоритет. + ПАПКА ROM + Папка + Не задано — виберіть папку для автоімпорту ігор + Автоімпорт + Нові ігри в цій папці автоматично додаються до вашої бібліотеки з визначенням правильної консолі. + Виберіть папку ROM + Виберіть папку ROM… + Змінити папку ROM… + Сканувати зараз + СТАНДАРТНІ НАЛАШТУВАННЯ КОНСОЛІ + Торкніться консолі, щоб задати її стандартні налаштування. + Рендерер + Масштабувати роздільність + Співвідношення сторін + Розтягнути + Авто (стандарт) + 4:3 + 16:9 + Фільтр зображення + Найближчий + Білінійний (гладкий) + Білінійний (чіткий) + Фільтр текстур + Білінійний (примусовий) + Білінійний (PS2) + Білінійний (спрайти) + Точність змішування + Мінімальна + Базова + Середня + Висока + Повна + Максимальна + Шейдер CRT / TV + Вимк. + Рядки розгортки + Діагональний + Трикутний + Хвиля + Lottes + 4xRGSS + NxAGSS + Пропуск кадрів + Пропуск 1 + Пропуск 2 + Пропуск 3 + Міпмапінг + Частота циклів EE + 50% + 60% + 75% + 100% (за замовч.) + 130% + 180% + 300% + Пропуск циклів EE + Вимк. + 1 + 2 + 3 + Миттєвий VU1 + Багатопотоковий VU (MTVU) + Швидкий CDVD + Екранне сенсорне керування + Звук + Поміняти стереоканали + HUD: FPS + HUD: швидкість емуляції + HUD: використання CPU + HUD: використання GPU + HUD: внутрішня роздільність + Увімкнути мережу (DEV9) + Пристрій Ethernet + Авто + Wi-Fi + Режим DNS + Вручну + Внутрішній + Основний DNS + Додатковий DNS + необов\'язково + Авто IP (DHCP) + Шейдер + Масштабування SGSR + HUD продуктивності + АВТОРИ & ЛІЦЕНЗІЇ + Деякі функції WinNative побудовані на цих проєктах з відкритим кодом. Торкніться, щоб переглянути кожне джерело. + Стандартні + Автори + Увімкнути режим Hardcore? + Режим Hardcore зараз скидає гру та вимикає завантаження станів, прискорення й чити. Будь-який незбережений прогрес буде втрачено. Продовжити? + Скасувати + Увімкнути + BIOS імпортовано: %1$s + Недійсний файл BIOS + BIOS PS2 імпортовано: %1$s + Недійсний файл BIOS PS2 + Немає серійного номера гри для пошуку читів. + Застосовано %1$d чит(ів). + Не вдалося застосувати чити. + Чити + Застосувати + Читів для цієї гри не знайдено. + Досягнення + Увійти в RetroAchievements + Ім\'я користувача + Пароль + Не вдалося увійти + Вхід… + Увійти + %1$d/%2$d • %3$d очок + Для цієї гри немає досягнень. + Назад + Увімкнено + Вимкнено + Перейменувати + Зберегти + Конфлікт хмарного збереження + Залишити локальне збереження + A + Меню + Екран + HUD + Звук + Керування + Бібліотека актуальна + ROM: %1$s + додано %1$d + видалено %1$d + За замовчуванням + CRT + LCD + Чіткий + Нативний + Співвідношення сторін + Фільтр NTSC + Колоризація + Корекція кольору + Зняти ліміт спрайтів + Роздільність + Емуляція буфера кадрів + Дизеринг + Широкоекранний хак + 8:7 (нативний) + 4:3 (TV) + Вимк. + RF + Composite + S-Video + RGB + Авто + Екран GBA + Екран GBC + Увімк. + 320x240 (нативний) + 640x480 + 960x720 + 1280x960 + 4:3 + 16:9 + 16:9 скориговане + Нативний + Внутрішній + Увімк. (16:9) + RETROACHIEVEMENTS + Увійдіть за допомогою облікового запису RetroAchievements, щоб заробляти та відстежувати досягнення в ретроіграх. + Ім\'я користувача + Пароль + Введіть ім\'я користувача та пароль + Не вдалося увійти + Увійти + Ваш пароль використовується лише один раз для отримання токена входу, який надійно зберігається на пристрої. + Досягнення увімкнено + Режим Hardcore (без станів) + %1$d / %2$d очок + Досягнень для цієї гри не знайдено. + Вийти + ЧИТИ + Назва + Код + Скасувати + Зберегти + Чит %1$d + Читів ще немає. Додайте чит-код для цієї гри. + Додати чит + + Драйвер GPU + Системний (За замовчуванням) + Встановіть драйвери Turnip у розділі Налаштування \u2192 Драйвери. Одні й ті самі драйвери працюють для ігор PC та PS2. + + HDD PS2 (DEV9) + Віртуальний внутрішній диск для ігор на HDD, як-от Final Fantasy XI. Перезапускає гру. + Віртуальний внутрішній диск для ігор на HDD, як-от Final Fantasy XI. + Режим DNS встановлено на Internal, щоб ваші власні хости сервера набули чинності. + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + Add Cheat + Cheat name + Codes (one per line, e.g. 2021A268 00000000) + Custom + Enter a name and at least one valid code + Add + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + PS2 HDD Images + A .raw HDD image, or a .zip containing one (e.g. a game’s downloaded HDD with maps/DLC) + Import HDD Image + Importing… + Imported %1$s + Could not import HDD image + Removed %1$s + Remove %1$s + HDD Image + None + Cheats + Patches + PATCH + Custom + Applied %1$d cheat(s), %2$d patch(es). + No cheats or patches found for this game. + Cheat + Patch + Add +Ядро CPU +Два ядра +Внутрішні чити +Внутрішня роздільна здатність +Рендерер +Положення сенсорної панелі +Пропустити заставку BIOS + + + + + + +Знизу +Кешований інтерпретатор +Апаратний +Інтерпретатор +JIT +Миша / дотик +Правий стік (абсолютний) +Правий стік (відносний) +Програмний +Розтягнути +Зверху +Пропуск VBI (авто пропуск кадрів) +Широкий екран +Вказівник Wiimote +Зміни застосуються під час наступного запуску цієї гри. +Запустіть цю гру один раз, щоб визначити серійний номер диска, тоді тут з\'являться чити та патчі. +Обхід автентифікації DNAS — потрібен для гри онлайн +Автоматично застосовано (онлайн) +Чити & патчі +Розмір: %1$s +Імпортувати образ HDD +Видалити +Увімкнути NetPlay +Вимкнено за замовчуванням. Увімкніть, потім виберіть «Хост» або «Приєднатися» перед запуском.\nЗнову вимикається, коли ви виходите з гри. +Адреса хоста +IP або ім\'я хоста +Сеанс хоста +Увімк = чекати на гравця. Вимк = приєднатися до адреси хоста +NetPlay використовує локальні порти для кількох гравців через TCP (гравець 1 — хост / гравець 2 — клієнт). Онлайн-гра PS2 натомість використовує Ethernet DEV9. +Порт +Карта пам\'яті %1$d +Знімок екрана +Використати хмарне збереження +LAN (пряма IP) +Підключення… +Підключення +Онлайн (код хоста) +Закрити +NetPlay для GameCube/Wii використовує власний рушій Dolphin. Хост = гравець 1, приєднання = гравець 2. Виберіть «Хост» або «Приєднатися» та тип підключення перед запуском; обидва пристрої запускають ту саму гру разом. +Поділіться Wi‑Fi IP свого пристрою та цим портом з гравцем 2. Гра запускається автоматично, щойно вони підключаться. +Код хоста показується під час завантаження гри — поділіться ним з гравцем 2. Гра запускається автоматично, щойно вони підключаться. +Введіть Wi‑Fi IP та порт хоста, потім запустіть, щоб підключитися. +Введіть код хоста від гравця 1, потім запустіть, щоб підключитися. +Увімкніть NetPlay у налаштуваннях гри та виберіть «Хост» або «Приєднатися» перед запуском +Знайти кімнати у Wi‑Fi +Game Link · кожен екран — окрема консоль +Багатокористувацька гра GBA використовує gpSP + бездротовий адаптер. Переконайтеся, що libgpsp встановлено. +Багатокористувацька гра зі спільним екраном через Wi‑Fi (як RetroArch).\nХост = гравець 1, приєднання = гравець 2. Обидва пристрої показують ту саму гру. +Game Link через Wi‑Fi — кожен пристрій запускає власну гру.\nGB/GBC: послідовне з\'єднання Gambatte (Pokémon Gen 1–2).\nGBA: бездротовий адаптер gpSP (битви Pokémon FR/LG/Emerald). +Створити кімнату +Код хоста +Код хоста traversal від хоста +Хостинг кімнати +Натисніть «Хост», щоб відкрити кімнату для цього сеансу гри, потім запустіть гру. NetPlay вимикається, коли ви виходите. +У кімнаті +Приєднатися за IP +Приєднано +Приєднатися +Під час запуску +Вийти +Хост = P1 · Приєднання = P2 · та сама гра на обох екранах +Хост +Приєднатися +Вручну +Кімнат не знайдено. Переконайтеся, що хост у тій самій мережі Wi‑Fi та хостить кімнату. +Ім\'я для відображення +Показується іншим гравцям +%1$d підключено +Кімната відкрита лише для цього сеансу. Запустіть, коли будете готові. Вихід із гри вимикає NetPlay. +Гравці +Сканувати Wi‑Fi +Сканувати знову +Скануйте ту саму мережу Wi‑Fi на наявність відкритих кімнат або приєднайтеся за IP-адресою. +Сканування Wi‑Fi… +Результати сканування +Натисніть кімнату, щоб приєднатися зараз (IP не зберігається для наступного запуску). +Зупинити сканування +NetPlay +%1$s підключився +%1$s відключився +Очікування гравців… +Підтримка PlayStation 2 незабаром +Показати кнопки L3 / R3 +Коли вимкнено, двічі торкніться стіка, щоб натиснути L3 / R3 +ПРАПОРЦІ ДРАЙВЕРА TURNIP +Застосовується лише коли вибрано власний драйвер GPU вище. +Файл гри не знайдено +Видалити +Імпортувати з файлу… +Завантаження… +NetPlay + Wii Home + Змінити консоль + Ідентифікувати як консоль + Тепер ідентифіковано як %1$s ReShade Застосовуйте ефект ReShade (.fx) до ігор DXVK/VKD3D (Vulkan) через вбудований шар vkBasalt. Помістіть кожен ефект в окрему папку в Android/data/<package>/files/ReShade/. Налаштування параметрів у реальному часі та перемикач у грі з’являться з оновленням шару з гарячим перезавантаженням. @@ -1663,5 +2436,28 @@ Увімкнути ReShade У цьому наборі немає ефектів ReShade. Додайте ефекти в налаштуваннях цієї гри (або контейнера), щоб перемикати та налаштовувати їх тут. Цей ефект не має регульованих параметрів. + Видалення збереження… + Видалити + Остаточно видалити хмарне збереження з %1$s? Цю дію не можна скасувати. + Видалити хмарне збереження + Не вдалося видалити хмарне збереження + Хмарне збереження видалено + Спочатку завантажте ядра консолей — Налаштування › Ретро + Цей пристрій не може запустити емуляцію PS2 — потрібен OpenGL ES 3.1 або новіший. + Перевірити оновлення + Перевірка оновлень… + Завантажити ядра консолей + Завантаження… %1$d / %2$d МБ + Ядра консолей + Встановлено — збірка %1$s + Встановлено — збірка %1$s (не вдалося перевірити оновлення) + Встановлення… + Не встановлено — завантажте, щоб грати в ретроігри + Стан + Оновити ядра консолей + Доступне оновлення — збірка %1$s (%2$d МБ) + Перевірка завантаження… + Виконується… + Система diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index fb359c30b..3b03b34c2 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -1622,6 +1622,779 @@ 在后台运行 退出 WinNative 后保持聊天运行 刷新 + 复古 + 传输存档 + 为此游戏导入本地存档,或导出当前存档。 + 导入存档 + 导出存档 + 存档已导入 + 无法导入存档 + 存档已导出 + 无法导出存档 + 此游戏尚无存档 + 金手指 + 硬核模式下已禁用金手指 + + + 保存 + 取消 + 保存即时存档 + 加载即时存档 + 成就 + 金手指 + 记忆卡 + 快进 + 重置 + 更换光盘 + 插槽 %1$d + 点按加载 + + 点按覆盖 + 空 — 点按保存 + 插槽 %1$d 为空 + 已加载插槽 %1$d + 无法加载插槽 %1$d + 已保存至插槽 %1$d + 保存失败 + • 插槽 1 + • 插槽 2 + • 点按使用 + 新建记忆卡 + 导入记忆卡 + 启用联机 (DEV9) + PS2 网络适配器 — 重启游戏以接入 + 以太网设备 + DNS 模式 + 首选 DNS + 备用 DNS + 可选 + 自动 IP (DHCP) + 服务器:%1$s + 点按设置 IP(留空则移除) + %1$s → IP + 添加服务器主机 + 新服务器主机名 + 例如 bf2.playbattlefront.com + 屏幕控制 + 编辑布局 + 重置布局 + 布局已重置 + 左摇杆:反转 X 轴 + 左摇杆:反转 Y 轴 + 右摇杆:反转 X 轴 + 右摇杆:反转 Y 轴 + 按钮颜色 + 字母颜色 + 阴影颜色 + 背景颜色 + 重置颜色 + 渲染器 + Vulkan + OpenGL + Software + 分辨率缩放 + 1x(原生) + 1.5x + 2x + 3x + 4x + 宽高比 + 拉伸 + 自动(标准) + 4:3 + 16:9 + 显示滤镜 + 最近邻 + 双线性(平滑) + 双线性(锐利) + 纹理滤镜 + 双线性(强制) + 双线性 (PS2) + 双线性(精灵) + 混合精度 + 最低 + 基本 + 中等 + + 完整 + 最高 + CRT / TV 着色器 + 关闭 + 扫描线 + 对角线 + 三角形 + 波纹 + Lottes + 4xRGSS + NxAGSS + 跳帧 + 关闭 + 跳 1 + 跳 2 + 跳 3 + Mipmap 贴图 + 音量 + %1$d%% + 静音 + 交换立体声声道 + EE 周期速率 + 50% + 60% + 75% + 100%(默认) + 130% + 180% + 300% + EE 周期跳过 + 关闭 + 1 + 2 + 3 + 即时 VU1 + 多线程 VU (MTVU) + 快速 CDVD + FPS + 模拟速度 + CPU 占用 + GPU 占用 + 内部分辨率 + 反交错模式 + 自动 + 关闭 + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + FMV 宽高比 + 抗模糊 + 宽屏补丁 + 逐行扫描补丁 + VU Flag Hack + INTC 自旋检测 + 等待循环检测 + 音频时间拉伸 + 音频缓冲 + 输出延迟 + %1$d ms + 帧时间 + GS 统计 + 硬件信息 + 版本 + 输入显示 + 菜单 + 显示 + 性能 + HUD + 声音 + 联机 + 控制 + 继续 + 暂停 + 退出 + 已导入 BIOS:%1$s + 无效的 BIOS 文件 + 无效的复古游戏 + 未找到 ROM:%1$s + 无法读取此压缩包内的 ROM + 核心未安装:%1$s + 已启用金手指 — 本次会话已禁用成就 + 已恢复云存档 + 恢复失败 + %1$s 存在更新的云存档。是否要同步?您希望保留哪个云存档? + 云存档 + 复古 + 加载模拟器核心失败 + 加载 ROM 失败 + 此核心不支持图形显示 + 模拟器错误 + 默认 + CRT + LCD + 锐利 + SGSR + SGSR 放大 + 原生 + 声音 + 左摇杆:反转 X 轴 + 左摇杆:反转 Y 轴 + 右摇杆:反转 X 轴 + 右摇杆:反转 Y 轴 + 屏幕控制 + 触觉反馈 + 竖屏 + 横屏 + 编辑布局 (%1$s) + 重置 %1$s 布局 + %1$s 布局已重置 + 按钮颜色 + 字母颜色 + 阴影颜色 + 背景颜色 + 重置颜色 + 颜色已重置 + 性能 HUD + 透明度 + 背景透明度 + 背景 + 缩放 + 数字帧时间 + 双系列电池 + HUD 元素 + FPS + 主机 + GPU + CPU + RAM + 电池 + 温度 + 图表 + CPU 温度 + 保存即时存档 + 加载即时存档 + 硬核模式下禁用加载存档 + 成就 + 金手指 + 硬核模式下禁用金手指 + 重置 + 快进 + 硬核模式下禁用快进 + HUD + 光盘 %1$d/%2$d + 继续 + 暂停 + 退出 + 已保存至插槽 %1$d + 无法保存即时存档 + 需要 %1$s BIOS + PlayStation 游戏需要您提供真实主机的 BIOS 文件。请导入 BIOS(scph5501.bin、scph5500.bin、scph5502.bin、scph1001.bin 或 scph7001.bin)以继续。 + 导入 BIOS… + 取消 + 插槽 %1$d 为空 + 已加载插槽 %1$d + 无法加载即时存档 + 插槽 %1$d + 重命名插槽 %1$d + 常规 + 图形 + 性能 + HUD + 输入 + 音频 + 联机 + 取消 + 保存 + 默认 + CRT + LCD + 锐利 + 2x + 4x + 原生 + 游戏 + 名称 + 系统 + 模拟器核心 + ROM 路径 + %1$s BIOS + 已安装 + 无 — 运行 %1$s 游戏所需 + 导入 BIOS… + 移除 BIOS + 库封面 + 游戏卡片图片 + 网格图片 + 轮播图片 + 列表图片 + 已设置自定义图片 + 设置图片 + 移除 + 视频 + 视频滤镜 + SGSR + SGSR 放大 + 性能 HUD + 核心 + 渲染器 + Vulkan + OpenGL + Software + 分辨率缩放 + 1x(原生) + 1.5x + 2x + 3x + 4x + 宽高比 + 拉伸 + 自动(标准) + 4:3 + 16:9 + 显示滤镜 + 最近邻 + 双线性(平滑) + 双线性(锐利) + 纹理滤镜 + 双线性(强制) + 双线性 (PS2) + 双线性(精灵) + 混合精度 + 最低 + 基本 + 中等 + + 完整 + 最高 + CRT / TV 着色器 + 关闭 + 扫描线 + 对角线 + 三角形 + 波纹 + Lottes + 4xRGSS + NxAGSS + 跳帧 + 跳 1 + 跳 2 + 跳 3 + Mipmap 贴图 + 性能 + EE 周期速率 + 50% + 60% + 75% + 100%(默认) + 130% + 180% + 300% + EE 周期跳过 + 1 + 2 + 3 + 即时 VU1 + 多线程 VU (MTVU) + 快速 CDVD + 性能 HUD + FPS + 模拟速度 + CPU 占用 + GPU 占用 + 内部分辨率 + 反交错模式 + 自动 + 关闭 + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + FMV 宽高比 + 抗模糊 + 宽屏补丁 + 逐行扫描补丁 + VU Flag Hack + INTC 自旋检测 + 等待循环检测 + 音频时间拉伸 + 音频缓冲 + 输出延迟 + %1$d ms + 帧时间 + GS 统计 + 硬件信息 + 版本 + 输入显示 + 快速启动 + 联机 (DEV9) + 启用联机 + 以太网设备 + 自动 + Wi-Fi + DNS 模式 + 手动 + 内部 + 首选 DNS + 备用 DNS + 可选 + 自动 IP (DHCP) + 输入 + 屏幕控制 + 触觉反馈 + 音频 + 音量 + 静音 + 交换立体声声道 + 声音 + 复古默认设置 + 除非在游戏自身设置中覆盖,否则将应用到各主机的游戏。 + RETROACHIEVEMENTS + 账户 + 已登录 + 未登录 — 打开游戏的成就以登录 + 已启用成就 + 默认硬核模式(无即时存档) + 退出登录 + PLAYSTATION BIOS + 已安装 + 无 — PS1 游戏需要 BIOS + 导入 PS1 BIOS… + 已移除 PS1 BIOS + 没有可移除的 BIOS + 移除 PS1 BIOS + PLAYSTATION 2 BIOS + 无 — PS2 游戏需要 BIOS + 格式 + 合并的单文件转储(带区域标记的 .bin,约 4MB)。不接受拆分的 ROM0/MEC/NVM 组。 + 导入 PS2 BIOS… + 已移除 PS2 BIOS + 移除 PS2 BIOS + 库封面 + 复古外壳图(卡带 / CD 盒) + 封面图 + 导入时自动从 thumbnails.libretro.com 获取;自定义图片始终会覆盖它。 + ROM 文件夹 + 文件夹 + 未设置 — 选择文件夹以自动导入游戏 + 自动导入 + 此文件夹中的新游戏会自动添加到您的库中,并检测出正确的主机。 + 选择 ROM 文件夹 + 选择 ROM 文件夹… + 更改 ROM 文件夹… + 立即扫描 + 主机默认设置 + 点按主机以设置其默认设置。 + 渲染器 + 放大分辨率 + 宽高比 + 拉伸 + 自动(标准) + 4:3 + 16:9 + 显示滤镜 + 最近邻 + 双线性(平滑) + 双线性(锐利) + 纹理滤镜 + 双线性(强制) + 双线性 (PS2) + 双线性(精灵) + 混合精度 + 最低 + 基本 + 中等 + + 完整 + 最高 + CRT / TV 着色器 + 关闭 + 扫描线 + 对角线 + 三角形 + 波纹 + Lottes + 4xRGSS + NxAGSS + 跳帧 + 跳 1 + 跳 2 + 跳 3 + Mipmap 贴图 + EE 周期速率 + 50% + 60% + 75% + 100%(默认) + 130% + 180% + 300% + EE 周期跳过 + 关闭 + 1 + 2 + 3 + 即时 VU1 + 多线程 VU (MTVU) + 快速 CDVD + 屏幕触摸控制 + 声音 + 交换立体声声道 + HUD:FPS + HUD:模拟速度 + HUD:CPU 占用 + HUD:GPU 占用 + HUD:内部分辨率 + 启用联机 (DEV9) + 以太网设备 + 自动 + Wi-Fi + DNS 模式 + 手动 + 内部 + 首选 DNS + 备用 DNS + 可选 + 自动 IP (DHCP) + 着色器 + SGSR 放大 + 性能 HUD + 鸣谢 & 许可 + WinNative 的部分功能基于这些开源项目构建。点按可查看各来源。 + 默认 + 鸣谢 + 启用硬核模式? + 硬核模式将立即重置游戏,并禁用加载即时存档、快进和金手指。任何未保存的进度都将丢失。是否继续? + 取消 + 启用 + 已导入 BIOS:%1$s + 无效的 BIOS 文件 + 已导入 PS2 BIOS:%1$s + 无效的 PS2 BIOS 文件 + 没有可用于查找金手指的游戏序列号。 + 已应用 %1$d 个金手指。 + 无法应用金手指。 + 金手指 + 应用 + 未找到此游戏的金手指。 + 成就 + 登录 RetroAchievements + 用户名 + 密码 + 登录失败 + 正在登录… + 登录 + %1$d/%2$d • %3$d 分 + 此游戏没有成就。 + 返回 + 已启用 + 已禁用 + 重命名 + 保存 + 云存档冲突 + 保留本地存档 + + 菜单 + 显示 + HUD + 声音 + 控制 + 库已是最新 + ROM:%1$s + 新增 %1$d + 移除 %1$d + 默认 + CRT + LCD + 锐利 + 原生 + 宽高比 + NTSC 滤镜 + 着色 + 色彩校正 + 移除精灵数量限制 + 分辨率 + 帧缓冲模拟 + 抖动 + 宽屏修改 + 8:7(原生) + 4:3(电视) + 关闭 + RF + 复合 + S-Video + RGB + 自动 + GBA 屏幕 + GBC 屏幕 + 开启 + 320x240(原生) + 640x480 + 960x720 + 1280x960 + 4:3 + 16:9 + 16:9 调整 + 原生 + 内部 + 开启 (16:9) + RETROACHIEVEMENTS + 使用您的 RetroAchievements 账户登录,以获取并追踪复古游戏的成就。 + 用户名 + 密码 + 请输入您的用户名和密码 + 登录失败 + 登录 + 您的密码仅使用一次以获取登录令牌,该令牌安全存储在设备上。 + 已启用成就 + 硬核模式(无即时存档) + %1$d / %2$d 分 + 未找到此游戏的成就。 + 退出登录 + 金手指 + 名称 + 代码 + 取消 + 保存 + 金手指 %1$d + 暂无金手指。为此游戏添加金手指代码。 + 添加金手指 + + GPU 驱动 + 系统(默认) + 在设置 \u2192 驱动中安装 Turnip 驱动。同一驱动适用于 PC 和 PS2 游戏。 + + PS2 HDD (DEV9) + 用于 Final Fantasy XI 等基于 HDD 的游戏的虚拟内置驱动器。将重启游戏。 + 用于 Final Fantasy XI 等基于 HDD 的游戏的虚拟内置驱动器。 + DNS 模式已设为 Internal,以便你的自定义服务器主机生效。 + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + Add Cheat + Cheat name + Codes (one per line, e.g. 2021A268 00000000) + Custom + Enter a name and at least one valid code + Add + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + PS2 HDD Images + A .raw HDD image, or a .zip containing one (e.g. a game’s downloaded HDD with maps/DLC) + Import HDD Image + Importing… + Imported %1$s + Could not import HDD image + Removed %1$s + Remove %1$s + HDD Image + None + Cheats + Patches + PATCH + Custom + Applied %1$d cheat(s), %2$d patch(es). + No cheats or patches found for this game. + Cheat + Patch + Add + CPU 核心 + 双核心 + 内置金手指 + 内部分辨率 + 渲染器 + 感应条位置 + 跳过 BIOS 开场 + + + + + + + 底部 + 缓存解释器 + 硬件 + 解释器 + JIT + 鼠标 / 触摸 + 右摇杆(绝对) + 右摇杆(相对) + 软件 + 拉伸 + 顶部 + VBI 跳过(自动跳帧) + 宽屏 + Wiimote 指针 + 更改将在下次启动此游戏时生效。 + 先启动此游戏一次以便检测其光盘序列号,之后金手指和补丁将显示在此处。 + DNAS 认证绕过 — 联机游玩所需 + 自动应用(联机) + 金手指 & 补丁 + 大小:%1$s + 导入 HDD 镜像 + 移除 + 启用 NetPlay + 默认关闭。启用后,在启动前选择主机或加入。\n退出游戏时会再次关闭。 + 主机地址 + IP 或主机名 + 主持会话 + 开 = 等待玩家。关 = 加入主机地址 + NetPlay 通过 TCP 使用本地多人游戏端口(玩家 1 主机 / 玩家 2 客户端)。PS2 联机改用 DEV9 以太网。 + 端口 + 记忆卡 %1$d + 截图 + 使用云存档 + 局域网(直连 IP) + 正在连接… + 连接 + 联机(主机代码) + 关闭 + GameCube/Wii NetPlay 使用 Dolphin 自己的引擎。主机 = 玩家 1,加入 = 玩家 2。在启动前选择主机或加入以及连接类型;两台设备将一起启动同一游戏。 + 与玩家 2 分享你设备的 Wi‑Fi IP 和此端口。他们连接后游戏会自动开始。 + 游戏启动时会显示主机代码 — 与玩家 2 分享它。他们连接后游戏会自动开始。 + 输入主机的 Wi‑Fi IP 和端口,然后启动以连接。 + 输入来自玩家 1 的主机代码,然后启动以连接。 + 在游戏设置中启用 NetPlay,并在启动前选择主机或加入 + 在 Wi‑Fi 上查找房间 + Game Link · 每个屏幕都是独立的掌机 + GBA 多人游戏使用 gpSP + 无线适配器。请确保已安装 libgpsp。 + 通过 Wi‑Fi 的共享屏幕多人游戏(类似 RetroArch)。\n主机 = 玩家 1,加入 = 玩家 2。两台设备显示同一游戏。 + 通过 Wi‑Fi 的 Game Link — 每台设备运行自己的游戏。\nGB/GBC:Gambatte 串行连接(Pokémon 第 1–2 世代)。\nGBA:gpSP 无线适配器(Pokémon FR/LG/Emerald 对战)。 + 主持房间 + 主机代码 + 来自主机的穿透主机代码 + 正在主持房间 + 点按主机为此游玩会话开启一个房间,然后启动游戏。退出时 NetPlay 会关闭。 + 在房间中 + 通过 IP 加入 + 已加入 + 加入 + 启动时 + 离开 + 主机 = P1 · 加入 = P2 · 两个屏幕显示同一游戏 + 主机 + 加入 + 手动 + 未找到房间。请确保主机在同一 Wi‑Fi 上并正在主持房间。 + 显示名称 + 向其他玩家显示 + 已连接 %1$d 人 + 房间仅在此会话中开放。准备好后启动。退出游戏会关闭 NetPlay。 + 玩家 + 扫描 Wi‑Fi + 再次扫描 + 扫描同一 Wi‑Fi 以查找开放的房间,或通过 IP 地址加入。 + 正在扫描 Wi‑Fi… + 扫描结果 + 点按一个房间立即加入(不会为下次启动保存该 IP)。 + 停止扫描 + NetPlay + %1$s 已连接 + %1$s 已断开连接 + 正在等待玩家… + PlayStation 2 支持即将推出 + 显示 L3 / R3 按钮 + 关闭时,双击摇杆以点击 L3 / R3 + TURNIP 驱动标志 + 仅在上方选择了自定义 GPU 驱动时应用。 + 未找到游戏文件 + 删除 + 从文件导入… + 正在加载… + NetPlay + Wii Home + 切换主机 + 识别为主机 + 现已识别为 %1$s ReShade 通过内置的 vkBasalt 层将 ReShade 效果(.fx)应用于 DXVK/VKD3D(Vulkan)游戏。将每个效果放入 Android/data/<package>/files/ReShade/ 下各自的文件夹中。实时参数调整和游戏内开关将随实时重载层更新一起提供。 @@ -1657,5 +2430,28 @@ 启用 ReShade 此配置中没有 ReShade 效果。在此游戏(或容器)的设置中添加效果,即可在此切换和调整。 此效果没有可调整的参数。 + 正在删除存档… + 删除 + 永久删除来自 %1$s 的云存档?此操作无法撤销。 + 删除云存档 + 无法删除云存档 + 云存档已删除 + 请先下载主机核心 — 设置 › 复古 + 此设备无法运行 PS2 模拟 — 需要 OpenGL ES 3.1 或更高版本。 + 检查更新 + 正在检查更新… + 下载主机核心 + 正在下载… %1$d / %2$d MB + 主机核心 + 已安装 — 版本 %1$s + 已安装 — 版本 %1$s(检查更新失败) + 正在安装… + 未安装 — 下载后即可畅玩复古游戏 + 状态 + 更新主机核心 + 有可用更新 — 版本 %1$s(%2$d MB) + 正在校验下载… + 处理中… + 系统 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 6312633aa..08f9bf84f 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -1621,6 +1621,779 @@ 在背景執行 離開 WinNative 後保持聊天執行 重新整理 + 復古 + 傳輸存檔 + 為此遊戲匯入本機存檔,或匯出目前的存檔。 + 匯入存檔 + 匯出存檔 + 已匯入存檔 + 無法匯入存檔 + 已匯出存檔 + 無法匯出存檔 + 此遊戲尚無存檔 + 金手指 + 硬派模式下已停用金手指 + + + 儲存 + 取消 + 儲存即時存檔 + 載入即時存檔 + 成就 + 金手指 + 記憶卡 + 快轉 + 重置 + 更換光碟 + 插槽 %1$d + 點按載入 + + 點按覆寫 + 空 — 點按儲存 + 插槽 %1$d 為空 + 已載入插槽 %1$d + 無法載入插槽 %1$d + 已儲存至插槽 %1$d + 儲存失敗 + • 插槽 1 + • 插槽 2 + • 點按使用 + 新增記憶卡 + 匯入記憶卡 + 啟用連線 (DEV9) + PS2 網路轉接器 — 重新啟動遊戲以接入 + 乙太網路裝置 + DNS 模式 + 主要 DNS + 次要 DNS + 選填 + 自動 IP (DHCP) + 伺服器:%1$s + 點按設定 IP(留空則移除) + %1$s → IP + 新增伺服器主機 + 新伺服器主機名稱 + 例如 bf2.playbattlefront.com + 螢幕控制 + 編輯配置 + 重置配置 + 配置已重置 + 左搖桿:反轉 X 軸 + 左搖桿:反轉 Y 軸 + 右搖桿:反轉 X 軸 + 右搖桿:反轉 Y 軸 + 按鈕顏色 + 字母顏色 + 陰影顏色 + 背景顏色 + 重置顏色 + 渲染器 + Vulkan + OpenGL + Software + 解析度縮放 + 1x(原生) + 1.5x + 2x + 3x + 4x + 長寬比 + 拉伸 + 自動(標準) + 4:3 + 16:9 + 顯示濾鏡 + 最近鄰 + 雙線性(平滑) + 雙線性(銳利) + 紋理濾鏡 + 雙線性(強制) + 雙線性 (PS2) + 雙線性(精靈) + 混合精度 + 最低 + 基本 + 中等 + + 完整 + 最高 + CRT / TV 著色器 + 關閉 + 掃描線 + 對角線 + 三角形 + 波紋 + Lottes + 4xRGSS + NxAGSS + 跳格 + 關閉 + 跳 1 + 跳 2 + 跳 3 + Mipmap 貼圖 + 音量 + %1$d%% + 靜音 + 交換立體聲聲道 + EE 週期速率 + 50% + 60% + 75% + 100%(預設) + 130% + 180% + 300% + EE 週期跳過 + 關閉 + 1 + 2 + 3 + 即時 VU1 + 多執行緒 VU (MTVU) + 快速 CDVD + FPS + 模擬速度 + CPU 使用率 + GPU 使用率 + 內部解析度 + 反交錯模式 + 自動 + 關閉 + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + FMV 長寬比 + 抗模糊 + 寬螢幕補丁 + 逐行掃描補丁 + VU Flag Hack + INTC 自旋偵測 + 等待迴圈偵測 + 音訊時間延展 + 音訊緩衝 + 輸出延遲 + %1$d ms + 影格時間 + GS 統計 + 硬體資訊 + 版本 + 輸入顯示 + 選單 + 顯示 + 效能 + HUD + 聲音 + 連線 + 控制 + 繼續 + 暫停 + 離開 + 已匯入 BIOS:%1$s + 無效的 BIOS 檔案 + 無效的復古遊戲 + 找不到 ROM:%1$s + 無法讀取此壓縮檔內的 ROM + 核心未安裝:%1$s + 已啟用金手指 — 本次工作階段已停用成就 + 已還原雲端存檔 + 還原失敗 + %1$s 有更新的雲端存檔。是否要同步?您希望保留哪個雲端存檔? + 雲端存檔 + 復古 + 載入模擬器核心失敗 + 載入 ROM 失敗 + 此核心不支援圖形顯示 + 模擬器錯誤 + 預設 + CRT + LCD + 銳利 + SGSR + SGSR 放大 + 原生 + 聲音 + 左搖桿:反轉 X 軸 + 左搖桿:反轉 Y 軸 + 右搖桿:反轉 X 軸 + 右搖桿:反轉 Y 軸 + 螢幕控制 + 觸覺回饋 + 直向 + 橫向 + 編輯配置 (%1$s) + 重置 %1$s 配置 + %1$s 配置已重置 + 按鈕顏色 + 字母顏色 + 陰影顏色 + 背景顏色 + 重置顏色 + 顏色已重置 + 效能 HUD + 透明度 + 背景透明度 + 背景 + 縮放 + 數字影格時間 + 雙系列電池 + HUD 元素 + FPS + 主機 + GPU + CPU + RAM + 電池 + 溫度 + 圖表 + CPU 溫度 + 儲存即時存檔 + 載入即時存檔 + 硬派模式下停用載入存檔 + 成就 + 金手指 + 硬派模式下停用金手指 + 重置 + 快轉 + 硬派模式下停用快轉 + HUD + 光碟 %1$d/%2$d + 繼續 + 暫停 + 離開 + 已儲存至插槽 %1$d + 無法儲存即時存檔 + 需要 %1$s BIOS + PlayStation 遊戲需要您提供真實主機的 BIOS 檔案。請匯入 BIOS(scph5501.bin、scph5500.bin、scph5502.bin、scph1001.bin 或 scph7001.bin)以繼續。 + 匯入 BIOS… + 取消 + 插槽 %1$d 為空 + 已載入插槽 %1$d + 無法載入即時存檔 + 插槽 %1$d + 重新命名插槽 %1$d + 一般 + 圖形 + 效能 + HUD + 輸入 + 音訊 + 連線 + 取消 + 儲存 + 預設 + CRT + LCD + 銳利 + 2x + 4x + 原生 + 遊戲 + 名稱 + 系統 + 模擬器核心 + ROM 路徑 + %1$s BIOS + 已安裝 + 無 — 執行 %1$s 遊戲所需 + 匯入 BIOS… + 移除 BIOS + 遊戲庫封面 + 遊戲卡片圖片 + 網格圖片 + 輪播圖片 + 清單圖片 + 已設定自訂圖片 + 設定圖片 + 移除 + 視訊 + 視訊濾鏡 + SGSR + SGSR 放大 + 效能 HUD + 核心 + 渲染器 + Vulkan + OpenGL + Software + 解析度縮放 + 1x(原生) + 1.5x + 2x + 3x + 4x + 長寬比 + 拉伸 + 自動(標準) + 4:3 + 16:9 + 顯示濾鏡 + 最近鄰 + 雙線性(平滑) + 雙線性(銳利) + 紋理濾鏡 + 雙線性(強制) + 雙線性 (PS2) + 雙線性(精靈) + 混合精度 + 最低 + 基本 + 中等 + + 完整 + 最高 + CRT / TV 著色器 + 關閉 + 掃描線 + 對角線 + 三角形 + 波紋 + Lottes + 4xRGSS + NxAGSS + 跳格 + 跳 1 + 跳 2 + 跳 3 + Mipmap 貼圖 + 效能 + EE 週期速率 + 50% + 60% + 75% + 100%(預設) + 130% + 180% + 300% + EE 週期跳過 + 1 + 2 + 3 + 即時 VU1 + 多執行緒 VU (MTVU) + 快速 CDVD + 效能 HUD + FPS + 模擬速度 + CPU 使用率 + GPU 使用率 + 內部解析度 + 反交錯模式 + 自動 + 關閉 + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + FMV 長寬比 + 抗模糊 + 寬螢幕補丁 + 逐行掃描補丁 + VU Flag Hack + INTC 自旋偵測 + 等待迴圈偵測 + 音訊時間延展 + 音訊緩衝 + 輸出延遲 + %1$d ms + 影格時間 + GS 統計 + 硬體資訊 + 版本 + 輸入顯示 + 快速開機 + 連線 (DEV9) + 啟用連線 + 乙太網路裝置 + 自動 + Wi-Fi + DNS 模式 + 手動 + 內部 + 主要 DNS + 次要 DNS + 選填 + 自動 IP (DHCP) + 輸入 + 螢幕控制 + 觸覺回饋 + 音訊 + 音量 + 靜音 + 交換立體聲聲道 + 聲音 + 復古預設設定 + 除非在遊戲本身的設定中覆寫,否則將套用至各主機的遊戲。 + RETROACHIEVEMENTS + 帳戶 + 已登入 + 未登入 — 開啟遊戲的成就以登入 + 已啟用成就 + 預設硬派模式(無即時存檔) + 登出 + PLAYSTATION BIOS + 已安裝 + 無 — PS1 遊戲需要 BIOS + 匯入 PS1 BIOS… + 已移除 PS1 BIOS + 沒有可移除的 BIOS + 移除 PS1 BIOS + PLAYSTATION 2 BIOS + 無 — PS2 遊戲需要 BIOS + 格式 + 合併的單一檔案傾印(帶區域標記的 .bin,約 4MB)。不接受拆分的 ROM0/MEC/NVM 組。 + 匯入 PS2 BIOS… + 已移除 PS2 BIOS + 移除 PS2 BIOS + 遊戲庫封面 + 復古外殼圖(卡帶 / CD 盒) + 封面圖 + 匯入時自動從 thumbnails.libretro.com 取得;自訂圖片一律會覆寫它。 + ROM 資料夾 + 資料夾 + 未設定 — 選擇資料夾以自動匯入遊戲 + 自動匯入 + 此資料夾中的新遊戲會自動加入您的遊戲庫,並偵測出正確的主機。 + 選擇 ROM 資料夾 + 選擇 ROM 資料夾… + 變更 ROM 資料夾… + 立即掃描 + 主機預設設定 + 點按主機以設定其預設設定。 + 渲染器 + 放大解析度 + 長寬比 + 拉伸 + 自動(標準) + 4:3 + 16:9 + 顯示濾鏡 + 最近鄰 + 雙線性(平滑) + 雙線性(銳利) + 紋理濾鏡 + 雙線性(強制) + 雙線性 (PS2) + 雙線性(精靈) + 混合精度 + 最低 + 基本 + 中等 + + 完整 + 最高 + CRT / TV 著色器 + 關閉 + 掃描線 + 對角線 + 三角形 + 波紋 + Lottes + 4xRGSS + NxAGSS + 跳格 + 跳 1 + 跳 2 + 跳 3 + Mipmap 貼圖 + EE 週期速率 + 50% + 60% + 75% + 100%(預設) + 130% + 180% + 300% + EE 週期跳過 + 關閉 + 1 + 2 + 3 + 即時 VU1 + 多執行緒 VU (MTVU) + 快速 CDVD + 螢幕觸控 + 聲音 + 交換立體聲聲道 + HUD:FPS + HUD:模擬速度 + HUD:CPU 使用率 + HUD:GPU 使用率 + HUD:內部解析度 + 啟用連線 (DEV9) + 乙太網路裝置 + 自動 + Wi-Fi + DNS 模式 + 手動 + 內部 + 主要 DNS + 次要 DNS + 選填 + 自動 IP (DHCP) + 著色器 + SGSR 放大 + 效能 HUD + 鳴謝 & 授權 + WinNative 的部分功能建置於這些開源專案之上。點按即可檢視各來源。 + 預設 + 鳴謝 + 啟用硬派模式? + 硬派模式將立即重置遊戲,並停用載入即時存檔、快轉和金手指。任何未儲存的進度都將遺失。是否繼續? + 取消 + 啟用 + 已匯入 BIOS:%1$s + 無效的 BIOS 檔案 + 已匯入 PS2 BIOS:%1$s + 無效的 PS2 BIOS 檔案 + 沒有可用於查詢金手指的遊戲序號。 + 已套用 %1$d 個金手指。 + 無法套用金手指。 + 金手指 + 套用 + 找不到此遊戲的金手指。 + 成就 + 登入 RetroAchievements + 使用者名稱 + 密碼 + 登入失敗 + 正在登入… + 登入 + %1$d/%2$d • %3$d 分 + 此遊戲沒有成就。 + 返回 + 已啟用 + 已停用 + 重新命名 + 儲存 + 雲端存檔衝突 + 保留本機存檔 + + 選單 + 顯示 + HUD + 聲音 + 控制 + 遊戲庫已是最新 + ROM:%1$s + 新增 %1$d + 移除 %1$d + 預設 + CRT + LCD + 銳利 + 原生 + 長寬比 + NTSC 濾鏡 + 上色 + 色彩校正 + 移除精靈數量限制 + 解析度 + 影格緩衝模擬 + 抖動 + 寬螢幕修改 + 8:7(原生) + 4:3(電視) + 關閉 + RF + 複合 + S-Video + RGB + 自動 + GBA 螢幕 + GBC 螢幕 + 開啟 + 320x240(原生) + 640x480 + 960x720 + 1280x960 + 4:3 + 16:9 + 16:9 調整 + 原生 + 內部 + 開啟 (16:9) + RETROACHIEVEMENTS + 使用您的 RetroAchievements 帳戶登入,以獲取並追蹤復古遊戲的成就。 + 使用者名稱 + 密碼 + 請輸入您的使用者名稱和密碼 + 登入失敗 + 登入 + 您的密碼僅使用一次以取得登入權杖,該權杖安全儲存在裝置上。 + 已啟用成就 + 硬派模式(無即時存檔) + %1$d / %2$d 分 + 找不到此遊戲的成就。 + 登出 + 金手指 + 名稱 + 代碼 + 取消 + 儲存 + 金手指 %1$d + 尚無金手指。為此遊戲新增金手指代碼。 + 新增金手指 + + GPU 驅動程式 + 系統(預設) + 在設定 \u2192 驅動程式中安裝 Turnip 驅動程式。同一驅動程式適用於 PC 和 PS2 遊戲。 + + PS2 HDD (DEV9) + 用於 Final Fantasy XI 等基於 HDD 的遊戲的虛擬內建磁碟機。將重新啟動遊戲。 + 用於 Final Fantasy XI 等基於 HDD 的遊戲的虛擬內建磁碟機。 + DNS 模式已設為 Internal,讓你的自訂伺服器主機生效。 + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + Add Cheat + Cheat name + Codes (one per line, e.g. 2021A268 00000000) + Custom + Enter a name and at least one valid code + Add + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + PS2 HDD Images + A .raw HDD image, or a .zip containing one (e.g. a game’s downloaded HDD with maps/DLC) + Import HDD Image + Importing… + Imported %1$s + Could not import HDD image + Removed %1$s + Remove %1$s + HDD Image + None + Cheats + Patches + PATCH + Custom + Applied %1$d cheat(s), %2$d patch(es). + No cheats or patches found for this game. + Cheat + Patch + Add +CPU 核心 +雙核心 +內建作弊碼 +內部解析度 +算繪器 +感應棒位置 +略過 BIOS 開場 + + + + + + +下方 +快取直譯器 +硬體 +直譯器 +JIT +滑鼠/觸控 +右搖桿(絕對) +右搖桿(相對) +軟體 +拉伸 +上方 +VBI 跳過(自動跳幀) +寬螢幕 +Wiimote 指標 +變更將於下次啟動此遊戲時套用。 +先啟動此遊戲一次以偵測其光碟序號,之後作弊碼與修補檔便會顯示於此。 +DNAS 認證繞過 — 線上遊玩所需 +自動套用(線上) +作弊碼與修補檔 +大小:%1$s +匯入 HDD 映像 +移除 +啟用 NetPlay +預設關閉。啟用後,於啟動前選擇 Host 或 Join。\n退出遊戲時會再次關閉。 +主機位址 +IP 或主機名稱 +主持工作階段 +開 = 等待玩家。關 = 加入主機位址 +NetPlay 使用透過 TCP 的本機多人遊戲連接埠(玩家 1 為主機/玩家 2 為用戶端)。PS2 線上則改用 DEV9 乙太網路。 +連接埠 +記憶卡 %1$d +螢幕截圖 +使用雲端存檔 +區域網路(直接 IP) +連線中… +連線 +線上(主機代碼) +關閉 +GameCube/Wii NetPlay 使用 Dolphin 自己的引擎。Host = 玩家 1,Join = 玩家 2。啟動前先選擇 Host 或 Join 以及連線類型;兩台裝置會一起啟動同一款遊戲。 +將你裝置的 Wi‑Fi IP 與此連接埠分享給玩家 2。對方連線後遊戲會自動開始。 +遊戲啟動時會顯示主機代碼 — 將它分享給玩家 2。對方連線後遊戲會自動開始。 +輸入主機的 Wi‑Fi IP 與連接埠,然後啟動以連線。 +輸入玩家 1 的主機代碼,然後啟動以連線。 +於遊戲設定中啟用 NetPlay,並在啟動前選擇 Host 或 Join +在 Wi‑Fi 上尋找房間 +Game Link · 每個螢幕都是獨立的掌機 +GBA 多人遊戲使用 gpSP + 無線轉接器。請確認已安裝 libgpsp。 +透過 Wi‑Fi 的共享螢幕多人遊戲(類似 RetroArch)。\nHost = 玩家 1,Join = 玩家 2。兩台裝置顯示同一款遊戲。 +透過 Wi‑Fi 的 Game Link — 每台裝置執行自己的遊戲。\nGB/GBC:Gambatte 序列連線(Pokémon 第 1–2 世代)。\nGBA:gpSP 無線轉接器(Pokémon FR/LG/綠寶石對戰)。 +主持房間 +主機代碼 +來自主機的穿透主機代碼 +主持房間中 +點選 Host 為此次遊玩開啟房間,然後啟動遊戲。退出時 NetPlay 會關閉。 +在房間中 +依 IP 加入 +已加入 +Join +啟動時 +離開 +Host = P1 · Join = P2 · 兩個螢幕上為同一款遊戲 +Host +Join +手動 +找不到房間。請確認主機位於同一個 Wi‑Fi 並正在主持房間。 +顯示名稱 +顯示給其他玩家 +%1$d 位已連線 +房間僅於此工作階段開啟。準備好即可啟動。退出遊戲會關閉 NetPlay。 +玩家 +掃描 Wi‑Fi +重新掃描 +掃描同一個 Wi‑Fi 以尋找開放的房間,或依 IP 位址加入。 +掃描 Wi‑Fi 中… +掃描結果 +點選房間立即加入(不會為下次啟動儲存該 IP)。 +停止掃描 +NetPlay +%1$s 已連線 +%1$s 已中斷連線 +等待玩家中… +PlayStation 2 支援即將推出 +顯示 L3 / R3 按鈕 +關閉時,連點兩下搖桿即可點擊 L3 / R3 +TURNIP 驅動程式旗標 +僅在上方選擇了自訂 GPU 驅動程式時才會套用。 +找不到遊戲檔案 +刪除 +從檔案匯入… +載入中… +NetPlay + Wii Home + 變更主機 + 識別為主機 + 現在識別為 %1$s ReShade 透過內建的 vkBasalt 層將 ReShade 效果(.fx)套用至 DXVK/VKD3D(Vulkan)遊戲。將每個效果放入 Android/data/<package>/files/ReShade/ 下各自的資料夾中。即時參數調整和遊戲內開關將隨即時重新載入層更新一起提供。 @@ -1656,5 +2429,28 @@ 啟用 ReShade 此配置中沒有 ReShade 效果。在此遊戲(或容器)的設定中新增效果,即可在此切換與調整。 此效果沒有可調整的參數。 + 正在刪除存檔… + 刪除 + 永久刪除來自 %1$s 的雲端存檔?此操作無法復原。 + 刪除雲端存檔 + 無法刪除雲端存檔 + 雲端存檔已刪除 + 請先下載主機核心 — 設定 › 復古 + 此裝置無法執行 PS2 模擬 — 需要 OpenGL ES 3.1 或更新版本。 + 檢查更新 + 正在檢查更新… + 下載主機核心 + 正在下載… %1$d / %2$d MB + 主機核心 + 已安裝 — 版本 %1$s + 已安裝 — 版本 %1$s(檢查更新失敗) + 正在安裝… + 未安裝 — 下載後即可遊玩復古遊戲 + 狀態 + 更新主機核心 + 有可用更新 — 版本 %1$s(%2$d MB) + 正在驗證下載… + 處理中… + 系統 diff --git a/app/src/main/res/values/refs.xml b/app/src/main/res/values/refs.xml index 7b1a060b6..af4194ce9 100644 --- a/app/src/main/res/values/refs.xml +++ b/app/src/main/res/values/refs.xml @@ -9,7 +9,9 @@ + + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 364f9c208..c52c9a741 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1143,6 +1143,20 @@ E.g. META for META key, \n Wine Debug Channel Debug + Retro + Transfer Save + Import a local save file to this game, or export this game\'s current save. + Import Save + Export Save + Save imported + Could not import save + Save exported + Could not export save + No save exists yet for this game + Cheats + Cheats are disabled in Hardcore mode + PlayStation 2 support is coming soon + Game file not found Enable Wine Debug Logs Write Wine debug output to file Enable Box86/64 Logs @@ -1459,6 +1473,12 @@ Installed path: If you change your mind, you can restore it from Save History. Refresh Rename + Delete + Delete Cloud Save + Permanently delete the cloud save from %1$s? This cannot be undone. + Cloud save deleted + Could not delete cloud save + Deleting save… Name this backup e.g. Boss fight, Before ending Save @@ -1659,4 +1679,787 @@ Installed path: Rename failed Create folder failed Refresh + + + + Save + Cancel + Save State + Load Save State + Achievements + Cheats + Memory Cards + Fast Forward + Reset + Swap Disc + Slot %1$d + Tap to load + Empty + Tap to overwrite + Empty — tap to save + Slot %1$d is empty + Loaded slot %1$d + Could not load slot %1$d + Saved to slot %1$d + Save failed + • Slot 1 + • Slot 2 + • Tap to use + New Memory Card + Import Card + Enable Online (DEV9) + PS2 network adapter — restarts the game to attach it + Ethernet Device + DNS Mode + Primary DNS + Secondary DNS + optional + Auto IP (DHCP) + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + Server: %1$s + tap to set IP (blank removes) + %1$s → IP + Add Server Host + New Server Hostname + e.g. bf2.playbattlefront.com + On-screen Controls + Edit Layout + Reset Layout + Layout reset + Left Stick: Invert X + Left Stick: Invert Y + Right Stick: Invert X + Right Stick: Invert Y + Button Color + Letter Color + Shadow Color + Background Color + Reset Colors + Renderer + Vulkan + OpenGL + Software + Resolution Scale + 1x (Native) + 1.5x + 2x + 3x + 4x + Aspect Ratio + Stretch + Auto (Standard) + 4:3 + 16:9 + Display Filter + Nearest + Bilinear (Smooth) + Bilinear (Sharp) + Texture Filter + Bilinear (Forced) + Bilinear (PS2) + Bilinear (Sprites) + Blending Accuracy + Minimum + Basic + Medium + High + Full + Maximum + CRT / TV Shader + Off + Scanline + Diagonal + Triangular + Wave + Lottes + 4xRGSS + NxAGSS + Frame Skip + Off + Skip 1 + Skip 2 + Skip 3 + Mipmapping + Volume + %1$d%% + Mute + Swap Stereo Channels + EE Cycle Rate + 50% + 60% + 75% + 100% (Default) + 130% + 180% + 300% + EE Cycle Skip + Off + 1 + 2 + 3 + Instant VU1 + Multi-Threaded VU (MTVU) + Fast CDVD + FPS + Emulation Speed + CPU Usage + GPU Usage + Internal Resolution + Deinterlace Mode + Auto + Off + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + FMV Aspect Ratio + Anti-Blur + Widescreen Patches + No-Interlace Patches + VU Flag Hack + INTC Spin Detection + Wait Loop Detection + Audio Time Stretch + Audio Buffer + Output Latency + %1$d ms + Frame Times + GS Statistics + Hardware Info + Version + Input Display + Menu + Display + Performance + HUD + Sound + Online + Controls + Resume + Pause + Exit + + BIOS imported: %1$s + Invalid BIOS file + Invalid retro game + ROM not found: %1$s + Could not read the ROM inside this archive + Core not installed: %1$s + Cheats enabled — achievements are disabled for this session + Cloud save restored + Restore failed + A newer cloud save exists for %1$s. Do you wish to sync, and which cloud save would you prefer to keep? + Cloud save + Use Cloud Save + Retro + Failed to load emulator core + Failed to load ROM + Graphics not supported for this core + This device can\'t run PS2 emulation — it needs OpenGL ES 3.1 or newer. + Emulator error + Default + CRT + LCD + Sharp + SGSR + SGSR Upscale + Native + Sound + Left Stick: Invert X + Left Stick: Invert Y + Right Stick: Invert X + Right Stick: Invert Y + On-screen Controls + Haptic Feedback + Portrait + Landscape + Edit Layout (%1$s) + Reset %1$s Layout + %1$s layout reset + Button Color + Letter Color + Shadow Color + Background Color + Reset Colors + Colors reset + Performance HUD + Alpha + Background Alpha + Background + Scale + Numeric Frametime + Dual-series Battery + HUD ELEMENTS + FPS + Console + GPU + CPU + RAM + Battery + Temp + Graph + CPU Temp + Save State + Load Save State + Loading states is disabled in Hardcore mode + Achievements + Cheats + Cheats are disabled in Hardcore mode + Reset + Fast Forward + Fast forward is disabled in Hardcore mode + HUD + Disc %1$d/%2$d + Resume + Pause + Exit + Saved to slot %1$d + Could not save state + %1$s BIOS required + PlayStation games need a real console BIOS file that you must provide. Import a BIOS (scph5501.bin, scph5500.bin, scph5502.bin, scph1001.bin or scph7001.bin) to continue. + Import BIOS… + Cancel + Slot %1$d is empty + Loaded slot %1$d + Could not load state + Slot %1$d + Rename Slot %1$d + + General + Graphics + Performance + HUD + Input + Audio + Online + Cancel + Save + Default + CRT + LCD + Sharp + 2x + 4x + Native + GAME + Name + System + Emulator Core + Change console + Identify as console + Now identified as %1$s + ROM Path + %1$s BIOS + Installed + None — required to run %1$s games + Import BIOS… + Remove BIOS + LIBRARY ARTWORK + Game Card Image + Grid Image + Carousel Image + List Image + Custom image set + Set image + Remove + VIDEO + Video Filter + SGSR + SGSR Upscale + Performance HUD + CORE + Renderer + Vulkan + OpenGL + Software + Resolution Scale + 1x (Native) + 1.5x + 2x + 3x + 4x + Aspect Ratio + Stretch + Auto (Standard) + 4:3 + 16:9 + Display Filter + Nearest + Bilinear (Smooth) + Bilinear (Sharp) + Texture Filter + Bilinear (Forced) + Bilinear (PS2) + Bilinear (Sprites) + Blending Accuracy + Minimum + Basic + Medium + High + Full + Maximum + CRT / TV Shader + Off + Scanline + Diagonal + Triangular + Wave + Lottes + 4xRGSS + NxAGSS + Frame Skip + Skip 1 + Skip 2 + Skip 3 + Mipmapping + PERFORMANCE + EE Cycle Rate + 50% + 60% + 75% + 100% (Default) + 130% + 180% + 300% + EE Cycle Skip + 1 + 2 + 3 + Instant VU1 + Multi-Threaded VU (MTVU) + Fast CDVD + PERFORMANCE HUD + FPS + Emulation Speed + CPU Usage + GPU Usage + Internal Resolution + Deinterlace Mode + Auto + Off + Weave (TFF) + Weave (BFF) + Bob (TFF) + Bob (BFF) + Blend (TFF) + Blend (BFF) + Adaptive (TFF) + Adaptive (BFF) + FMV Aspect Ratio + Anti-Blur + Widescreen Patches + No-Interlace Patches + VU Flag Hack + INTC Spin Detection + Wait Loop Detection + Audio Time Stretch + Audio Buffer + Output Latency + %1$d ms + Frame Times + GS Statistics + Hardware Info + Version + Input Display + Fast Boot + ONLINE (DEV9) + Enable Online + Enable NetPlay + Off by default. Enable, then choose Host or Join before launch.\nTurns off again when you exit the game. + Enable NetPlay in game settings and pick Host or Join before launch + Host session + On = wait for a player. Off = join host address + Host address + IP or hostname + Port + NetPlay uses local multiplayer ports over TCP (player 1 host / player 2 client). PS2 online uses DEV9 Ethernet instead. + NetPlay + Shared-screen multiplayer over Wi‑Fi (like RetroArch).\nHost = Player 1, Join = Player 2. Both devices show the same game. + Game Link over Wi‑Fi — each device runs its own game.\nGB/GBC: Gambatte serial link (Pokémon Gen 1–2).\nGBA: gpSP Wireless Adapter (Pokémon FR/LG/Emerald battles). + Host = P1 · Join = P2 · same game on both screens + Game Link · each screen is its own handheld + GBA multiplayer uses gpSP + Wireless Adapter. Ensure libgpsp is installed. + Display name + Shown to other players + On launch + Host + Join + Manual + Tap Host to open a room for this play session, then launch the game. NetPlay turns off when you exit. + Room is open for this session only. Launch when ready. Exiting the game turns NetPlay off. + %1$s connected + %1$s disconnected + Scan the same Wi‑Fi for open rooms, or join by IP address. + Find rooms on Wi‑Fi + Hosting room + Waiting for players… + Scanning Wi‑Fi… + Scan results + Scan again + No rooms found. Make sure the host is on the same Wi‑Fi and hosting a room. + Tap a room to join now (does not save the IP for next launch). + Connecting… + In room + Leave + Dismiss + Host room + Join by IP + Scan Wi‑Fi + Stop scan + Join + Players + %1$d connected + Joined + Wii Home + GameCube/Wii NetPlay uses Dolphin\'s own engine. Host = Player 1, Join = Player 2. Pick Host or Join and a connection type before launch; both devices boot the same game together. + Connection + LAN (direct IP) + Online (host code) + Host code + Traversal host code from the host + Share your device\'s Wi‑Fi IP and this port with Player 2. The game starts automatically once they connect. + A host code is shown when the game boots — share it with Player 2. The game starts automatically once they connect. + Enter the host\'s Wi‑Fi IP and port, then launch to connect. + Enter the host code from Player 1, then launch to connect. + NetPlay + Ethernet Device + Auto + Wi-Fi + DNS Mode + Manual + Internal + Primary DNS + Secondary DNS + optional + Auto IP (DHCP) + DNAS Auth Bypass + Auto-skip Sony\'s dead DNAS login for supported online games (SOCOM, Syphon Filter, etc.) + INPUT + On-screen controls + Adaptive Sticks + TURNIP DRIVER FLAGS + Applied only when a custom GPU driver is selected above. + Show L3 / R3 Buttons + When off, double-tap a stick to click L3 / R3 + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + Sticks stay hidden until you touch their area, then appear where you press + Adaptive Sticks + Haptic Feedback + AUDIO + Volume + Mute + Swap Stereo Channels + Sound + + RETRO DEFAULTS + Defaults applied to each console\'s games unless overridden in a game\'s own settings. + Download the console cores first — Settings › Retro + Console Cores + Status + Installed — build %1$s + Installed — build %1$s (update check failed) + Not installed — download to play retro games + Update available — build %1$s (%2$d MB) + Checking for updates… + Working… + Downloading… %1$d / %2$d MB + Verifying download… + Installing… + Download console cores + Update console cores + Check for updates + RETROACHIEVEMENTS + Account + Signed in + Not signed in — open a game\'s Achievements to sign in + Achievements enabled + Hardcore mode by default (no save states) + Sign Out + PS1 BIOS + Installed + None — PS1 games require a BIOS + Import PS1 BIOS… + PS1 BIOS removed + No BIOS to remove + Remove PS1 BIOS + PS2 BIOS + None — PS2 games require a BIOS + Format + Merged single-file dump (region-tagged .bin, ~4MB). Split ROM0/MEC/NVM sets are not accepted. + Import PS2 BIOS… + PS2 BIOS removed + Remove PS2 BIOS + LIBRARY ARTWORK + Retro case art (cartridge / CD case) + Box art + Fetched automatically from thumbnails.libretro.com on import; a custom image always overrides it. + ROMS FOLDER + Folder + Not set — pick a folder to auto-import games + Auto-import + New games in this folder are added to your library automatically with the right console detected. + Select ROMs Folder + Select ROMs Folder… + Change ROMs Folder… + Scan Now + CONSOLE DEFAULTS + Tap a console to set its default settings. + Renderer + Upscale resolution + Aspect Ratio + Stretch + Auto (Standard) + 4:3 + 16:9 + Display Filter + Nearest + Bilinear (Smooth) + Bilinear (Sharp) + Texture Filter + Bilinear (Forced) + Bilinear (PS2) + Bilinear (Sprites) + Blending Accuracy + Minimum + Basic + Medium + High + Full + Maximum + CRT / TV Shader + Off + Scanline + Diagonal + Triangular + Wave + Lottes + 4xRGSS + NxAGSS + Frame Skip + Skip 1 + Skip 2 + Skip 3 + Mipmapping + EE Cycle Rate + 50% + 60% + 75% + 100% (Default) + 130% + 180% + 300% + EE Cycle Skip + Off + 1 + 2 + 3 + Instant VU1 + Multi-Threaded VU (MTVU) + Fast CDVD + On-screen touch controls + Sound + Swap Stereo Channels + HUD: FPS + HUD: Emulation Speed + HUD: CPU Usage + HUD: GPU Usage + HUD: Internal Resolution + Enable Online (DEV9) + Ethernet Device + Auto + Wi-Fi + DNS Mode + Manual + Internal + Primary DNS + Secondary DNS + optional + Auto IP (DHCP) + Shader + SGSR upscaling + Performance HUD + CREDITS & LICENSES + Some of WinNative\'s features are built on these open-source projects. Tap to view each source. + Defaults + Credits + Enable Hardcore mode? + Hardcore mode resets the game now and disables loading save states, fast forward, and cheats. Any unsaved progress will be lost. Continue? + Cancel + Enable + BIOS imported: %1$s + Invalid BIOS file + PS2 BIOS imported: %1$s + Invalid PS2 BIOS file + No game serial to look up cheats for. + Applied %1$d cheat(s). + Couldn\'t apply cheats. + Cheats + Apply + Add Cheat + Cheat name + Codes (one per line, e.g. 2021A268 00000000) + Custom + Enter a name and at least one valid code + Add + No cheats found for this game. + Cheats + Patches + PATCH + Custom + Applied %1$d cheat(s), %2$d patch(es). + No cheats or patches found for this game. + Add + Cheat + Patch + Achievements + Sign in to RetroAchievements + Username + Password + Login failed + Signing in… + Sign In + %1$d/%2$d • %3$d pts + No achievements for this game. + Back + Enabled + Disabled + Rename + Save + Cloud Save Conflict + Keep Local Save + A + + Menu + Display + HUD + Sound + Controls + System + Library up to date + ROMs: %1$s + added %1$d + removed %1$d + Default + CRT + LCD + Sharp + Native + + Aspect Ratio + NTSC Filter + Colorization + Color Correction + Remove Sprite Limit + Resolution + Framebuffer Emulation + Dithering + Widescreen Hack + 8:7 (Native) + 4:3 (TV) + Off + RF + Composite + S-Video + RGB + Auto + GBA Screen + GBC Screen + On + 320x240 (Native) + 640x480 + 960x720 + 1280x960 + 4:3 + 16:9 + 16:9 Adjusted + Native + Internal + On (16:9) + Renderer + Hardware + Software + Internal Resolution + CPU Core + Dual Core + Widescreen + Internal Cheats + Skip BIOS Intro + Sensor Bar Position + Wiimote Pointer + VBI Skip (Auto Frameskip) + Screenshot + Memory Card %1$d + + + + + + + JIT + Cached Interpreter + Interpreter + Stretch + Bottom + Top + Right Stick (Absolute) + Right Stick (Relative) + Mouse / Touch + + RETROACHIEVEMENTS + Sign in with your RetroAchievements account to earn and track achievements for retro games. + Username + Password + Enter your username and password + Login failed + Sign In + Your password is only used once to obtain a login token, which is stored securely on device. + Achievements enabled + Hardcore mode (no save states) + %1$d / %2$d points + No achievements found for this game. + Sign Out + CHEATS + Name + Code + Cancel + Save + Cheat %1$d + No cheats yet. Add a cheat code for this game. + Add Cheat + + GPU Driver + System (Default) + Install Turnip drivers under Settings \u2192 Drivers. The same drivers work for both PC and PS2 games. + + PS2 HDD (DEV9) + Virtual internal drive for HDD-based games like Final Fantasy XI. Restarts the game. + Virtual internal drive for HDD-based games like Final Fantasy XI. + DNS Mode set to Internal so your custom server hosts take effect. + PS2 HDD Images + A .raw HDD image, or a .zip containing one (e.g. a game’s downloaded HDD with maps/DLC) + Import HDD Image + Importing… + Imported %1$s + Could not import HDD image + Removed %1$s + Remove %1$s + HDD Image + Import from file… + Delete + Cheats & Patches + Launch this game once so its disc serial can be detected, then cheats and patches will appear here. + Changes apply next time you launch this game. + Loading… + Auto-Applied (Online) + DNAS auth bypass — required for online play + Size: %1$s + Import HDD Image + Remove + None diff --git a/app/src/main/res/values/styles.xml b/app/src/main/res/values/styles.xml index c76cd27f9..c241308b6 100644 --- a/app/src/main/res/values/styles.xml +++ b/app/src/main/res/values/styles.xml @@ -145,6 +145,16 @@ @android:color/transparent + + + diff --git a/armsx2/src/main/res/values/colors.xml b/armsx2/src/main/res/values/colors.xml new file mode 100644 index 000000000..f8c6127d3 --- /dev/null +++ b/armsx2/src/main/res/values/colors.xml @@ -0,0 +1,10 @@ + + + #FFBB86FC + #FF6200EE + #FF3700B3 + #FF03DAC5 + #FF018786 + #FF000000 + #FFFFFFFF + \ No newline at end of file diff --git a/armsx2/src/main/res/values/strings.xml b/armsx2/src/main/res/values/strings.xml new file mode 100644 index 000000000..08de25b8d --- /dev/null +++ b/armsx2/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + ARMSX2 + \ No newline at end of file diff --git a/armsx2/src/main/res/values/themes.xml b/armsx2/src/main/res/values/themes.xml new file mode 100644 index 000000000..c67f22d9e --- /dev/null +++ b/armsx2/src/main/res/values/themes.xml @@ -0,0 +1,13 @@ + + + diff --git a/armsx2/src/main/res/xml/backup_rules.xml b/armsx2/src/main/res/xml/backup_rules.xml new file mode 100644 index 000000000..4df925582 --- /dev/null +++ b/armsx2/src/main/res/xml/backup_rules.xml @@ -0,0 +1,13 @@ + + + + \ No newline at end of file diff --git a/armsx2/src/main/res/xml/data_extraction_rules.xml b/armsx2/src/main/res/xml/data_extraction_rules.xml new file mode 100644 index 000000000..9ee9997b0 --- /dev/null +++ b/armsx2/src/main/res/xml/data_extraction_rules.xml @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/armsx2/src/main/res/xml/network_security_config.xml b/armsx2/src/main/res/xml/network_security_config.xml new file mode 100644 index 000000000..5ade7336e --- /dev/null +++ b/armsx2/src/main/res/xml/network_security_config.xml @@ -0,0 +1,7 @@ + + + + 127.0.0.1 + localhost + + diff --git a/build.gradle b/build.gradle index 70ec1c14c..7cebf38d6 100644 --- a/build.gradle +++ b/build.gradle @@ -1,5 +1,6 @@ plugins { alias(libs.plugins.androidApplication) apply false + alias(libs.plugins.androidLibrary) apply false alias(libs.plugins.kotlinAndroid) apply false alias(libs.plugins.kotlinCompose) apply false alias(libs.plugins.ksp) apply false diff --git a/cores/DOLPHIN.md b/cores/DOLPHIN.md new file mode 100644 index 000000000..93d108843 --- /dev/null +++ b/cores/DOLPHIN.md @@ -0,0 +1,52 @@ +# Dolphin (GameCube / Wii) + +> **Packaging note (current):** the emucore and its runtime data are no longer committed +> here. They are built in the [WinNative-Emu](https://github.com/WinNative-Emu) fork and +> shipped in the [Retro-Consoles](https://github.com/WinNative-Emu/Retro-Consoles) bundle +> the app downloads at runtime. The build/patch details below describe how that fork +> produces the binary and remain accurate for the fork. + +Ships as a **prebuilt** libretro core (not built via `build-cores.sh`), placed only in +the always-merged jniLibs dir (same as the N64/mupen64 core): + +- `app/src/main/jniLibs/arm64-v8a/libdolphin_libretro_android.so` + +Do **not** also copy it into `app/prebuilt/libretro-cores/` — that dir mirrors the +source-built cores and is merged alongside jniLibs when `-PbuildLibretroCores=false`, +so a copy there collides with the jniLibs one (duplicate JNI lib merge failure). + +Sys data (game INIs, fonts) is under `app/src/main/assets/retro/dolphin-emu/Sys` and +copied to app files on first launch (`RetroCoreManager.ensureDolphinSys`). + +User data (saves, memcards, `Dolphin.ini`) lives under `files/retro/saves/User` +(`ensureDolphinUser` creates `GC/{USA,EUR,JAP}/Card A|B` and pins SlotA GCI folder). + +## Graphics / Adreno + +dolphin-libretro renders through **libretrodroid GLES** (system Adreno GLES 3.x). + +WinNative **Turnip / adrenotools** Vulkan drivers (`contents/adrenotools`, +`graphics_driver/*`) are for Wine containers and PS2 Vulkan — they are **not** +loaded for this core. Preferring system Adreno GLES is correct for libretro. + +## Performance defaults (`RetroCoreOptions`) + +| Option | Value | Why | +|--------|-------|-----| +| `dolphin_cpu_core` | `4` (JITARM64) | ~5–10× vs Cached Interpreter | +| `dolphin_main_cpu_thread` | `disabled` | Dual core SIGSEGV in Adreno GLES mid-game | +| `dolphin_efb_scale` | `1` | Native IR | +| `dolphin_efb_to_texture` / XFB | `enabled` | Avoid EFB/XFB→RAM copies | +| `dolphin_dsp_hle` | `enabled` | Fast audio DSP | +| `dolphin_fastmem` / arena | `disabled` | RWX/mmap SIGSEGV under Android SELinux + Adreno | +| `dolphin_shader_compilation_mode` | `0` (sync) | Async skip → flicker/stale frames on GLES | +| `dolphin_skip_dupe_frames` / Early XFB | off | Ghost/old-frame blending on Adreno | +| Audio | larger Oboe buffer | `preferLowLatencyAudio=false` for Dolphin | + +If a title hangs on memcard check, try Dual Core **off** for that game. + +Upstream core nightlies: https://buildbot.libretro.com/nightly/android/latest/arm64-v8a/dolphin_libretro_android.so.zip +Source reference: https://github.com/dolphin-emu/dolphin and https://github.com/libretro/dolphin + +Local rebuild of the core (optional, heavy): clone libretro/dolphin and follow its Android +libretro NDK build; install the resulting `.so` with the `lib` prefix above. diff --git a/cores/DOLPHIN_EMBED.md b/cores/DOLPHIN_EMBED.md new file mode 100644 index 000000000..c30f86a6f --- /dev/null +++ b/cores/DOLPHIN_EMBED.md @@ -0,0 +1,210 @@ +# Embedded Dolphin (Route B2) — WinNative-driven GC/Wii + +> **Packaging note (current):** the emucore and its runtime data are no longer committed +> here. They are built in the [WinNative-Emu](https://github.com/WinNative-Emu) fork and +> shipped in the [Retro-Consoles](https://github.com/WinNative-Emu/Retro-Consoles) bundle +> the app downloads at runtime. The build/patch details below describe how that fork +> produces the binary and remain accurate for the fork. + +Decision (2026-07-22): replace the dolphin-libretro GLES path for GameCube/Wii with an +embedded standalone Dolphin core, mirroring the ARMSX2/PS2 pattern. WinNative drives +everything — Dolphin's own menus/UI are stripped; every setting, driver and toggle is +fed from WinNative's surfaces (Shortcut Settings, Settings > Retro, in-game drawer). + +Why: dolphin-libretro can only render GLES via libretrodroid, and the system Adreno +GLES driver SIGSEGVs on new silicon (see DOLPHIN_VULKAN.md). Standalone Dolphin brings +its own Vulkan backend + native adrenotools/Turnip loading, RetroAchievements, netplay, +and save infrastructure. + +## Module: `dolphin/` + +- `build-emucore.sh` — clones dolphin-emu/dolphin at pinned SHA + `b008142f72a099a9bcb971776209504f085ae0be` (+ submodules), applies `patches/`, + CMake+Ninja (NDK toolchain, arm64-v8a, android-26, flexible page sizes ON, + analytics/autoupdate/tests OFF, RetroAchievements ON) and builds: + - `libmain.so` — Dolphin core + JNI + - `libhook_impl.so`, `libmain_hook.so`, `libgsl_alloc_hook.so`, + `libfile_redirect_hook.so` — libadrenotools (custom Vulkan driver loading) +- `build.gradle` — library module `org.dolphinemu.dolphinemu`; native build is opt-in + via `-Pdolphin.buildNative=true` until the pipeline is proven; otherwise packages + `prebuilt/emucore/`. +- Emulation runs in the `:gc` process via + `org.dolphinemu.dolphinemu.wn.DolphinEmulationActivity` (WinNative-owned; no + upstream fragments/menus). + +## Phases + +Status 2026-07-22: Phases 1–5 done and verified on-device (CPH2749): TP GC boots on +Vulkan crash-free, input proven via chained input-only transitions, settings bridge +verified both directions (stretch applied / auto restored), and **Turnip verified on +Adreno 840** — WN-Turnip-1.06 staged via wn.gc.driver → GpuDrivers/Extracted, +libvulkan_freedreno.so confirmed mapped in-process, clean rendering. GPU Driver +pickers live on both GC/Wii settings surfaces. + +Phases 6–7 (2026-07-22, verified on-device): DolphinGameOverlay attaches the shared +WinNative RetroInputView (GC/Wii themes) + drawer menu via the DolphinHost hook +(Ps2GameOverlay pattern; PluviaApp installs in every process, :gc gets light init). +Verified: overlay renders over the game, drawer opens, save state wrote GZ2E01.s01, +Exit → StopEmulation → clean finish. Routing: GC/Wii launches go to embedded Dolphin +in both launch paths behind `wn.gc.embedded` (default true; off = libretro fallback). +Settings parity pass (2026-07-22, compile-verified; device was disconnected): +- **In-game drawer** now has Menu (save/load slots 1–3 with timestamps, Screenshot, + HUD toggle, Pause/Exit) + Display (ALL GC/Wii core options, live via + applyVariable → INI rewrite → ReloadConfig) + Sound (audio toggle → [DSP] Muted) + + Controls (touch on/off, haptic, edit/reset layout; back exits edit mode). +- **Settings hierarchy verified**: Console default (Settings > Retro, + `retro_def_var__` / `retro_def_*`) → Shortcut extra (`retro_var_*` / + `retro_*`) → launch (resolvedCoreVariables + wn_touch/wn_audio/wn_hud) → in-game + changes apply live AND persist back to the shortcut. GPU driver = `wn.gc.driver` + (global for GC+Wii, PS2 pattern). +- **VBI Skip now has a UI toggle** (GC + Wii lists, default On). +- **HUD** maps to Dolphin's native OSD (ShowFPS/VPS/Speed); audio to [DSP] Muted. +- Shader/SGSR/upscale (libretrodroid-only) are hidden on both static surfaces for + GC/Wii while embedded is enabled; they reappear if `wn.gc.embedded` is off. +- Known quirk: Shortcut Settings save() snapshots ALL option values into the + shortcut (pre-existing behavior for every console) — after first save, console + defaults no longer flow to that shortcut. + +Start/teardown lifecycle (2026-07-22, compile-verified): the Dolphin core cannot +reliably boot twice in one process, so :gc follows the ARMSX2 model — fresh process +per session. `teardown()` (idempotent; Exit button, back press, Run() returning, and +onDestroy-when-finishing all funnel into it) does StopEmulation → join the Run thread +(≤15s, so memcards/saves flush) → delete `.running_rom` marker → finish() → kill the +:gc process. onPause/onResume skip pausing while stopping (no pause-during-shutdown +races). Launch side: the game activity now JOINS the Library task (NEW_TASK only from +non-activity contexts) so exiting lands back on the Library; `prepareLaunch` kills a +lingering :gc before starting UNLESS the `.running_rom` marker matches the requested +ROM (tapping Play on the running game resumes instead of restarting). + +Drawer parity + shared-source pass (2026-07-22, compile-verified): +- GC/Wii drawer now uses the FULL shared tab set via `RetroDrawerTabs.build` + (Menu / Display / HUD / Sound / Controls; netplay correctly absent). +- **Memory Card save UI**: Save/Load State from the main menu opens the shared + SaveSlot-card pane (RetroPane.SAVES) with 4 native Dolphin slots titled + "Memory Card N" + timestamps — same cards/flow as every other console. +- **Controls pane extracted to `RetroControlsMenu`** — single source used by BOTH + RetroActivity (all libretro consoles, incl. the PSX-inversion gate) and the + Dolphin overlay: touch toggle, **adaptive sticks (now on GC/Wii too — wn_adaptive + rides the launch vars)**, haptics, edit/reset layout, and the four button-color + pickers + reset. +- **HUD tab**: shared `RetroHudSupport.buildHudEntries` + FrameRating with new + shared container-JSON persistence (`loadContainerHudSettings`/`save…`); master + toggle also drives Dolphin's native OSD (ShowFPS/VPS/Speed). FPS/graph elements + default off for Dolphin (no per-frame Java callback; native OSD covers it). +- Remaining dedup candidate: RetroActivity still has its older inline HUD-JSON + load/save — same schema as the new shared funcs; migrate it next pass. + +Settings surfaces + persistence pass 2 (compile-verified): +- Shortcut Settings now has a HUD tab for ALL retro consoles (shared + RetroLibretroHudSection: global master + element toggles; PS2 keeps its own). +- GPU Driver moved to the TOP of Graphics (shortcut dialog) and top of the + expanded GC/Wii console-defaults section (extracted DolphinGpuDriverDropdown). +- Persistence model: HUD is now UNIVERSAL (global prefs: retro_def_hud_global + + retro_hud_style/elements) — one HUD everywhere, edited from any surface or + in-game; per-shortcut KEY_HUD no longer read. Per-game: core options, touch + controls, adaptive sticks, audio, shader/upscale (libretro). Per-console: + L3/R3 visibility, console defaults. RetroActivity + Dolphin overlay both load/ + save the global HUD store (container-JSON path retired to legacy). + +Open items: overlay polish (FrameRating-style HUD, touch-IR for Wii ir_mode, +controller-connected hiding, playtime/cloud hooks), RetroAchievements for the +embedded path, defaults tuning (dual core ON), retiring the libretro dolphin core +after parity sign-off. On-device retest checklist when phone reconnects: drawer tabs +render + live-apply (aspect change visible), audio mute, HUD OSD, VBI toggle, +touch-controls hide, edit-layout back handling, Play-button routing end-to-end. + +1. **Scaffold** (done): module, build script, manifest, stub activity, app wiring. +2. **Emucore + JNI surface**: build `libmain.so`; vendor the minimal Java classes + Dolphin's `IDCache`/JNI_OnLoad requires (`NativeLibrary`, `NativeConfig`, + `GpuDriverHelper`, model classes); patch `IDCache` to drop upstream-UI-only classes. +3. **DolphinEmulationActivity**: SurfaceView → `NativeLibrary.SurfaceChanged`, + `Run(rom)`, pause/resume, input forwarding, clean shutdown. +4. **Settings bridge**: generate `User/Config/Dolphin.ini` + `GFX.ini` from WinNative + prefs pre-boot (renderer=Vulkan, IR scale, aspect, dual core, JIT, skip BIOS, + widescreen, sensor bar, IR mode, cheats); live updates via `NativeConfig` where + safe. Same keys/surfaces as the current GC/Wii settings (RetroCoreOptions ids map + 1:1 onto Dolphin ini keys). +5. **GPU driver**: reuse `CustomDriver` Turnip packs through Dolphin's + `GpuDriverHelper`; per-console `wn.gc.driver` pref; default system Vulkan. +6. **Overlay**: `DolphinGameOverlay` (Ps2GameOverlay analogue) — RetroInputView touch + overlay, WinNative drawer (save states via `NativeLibrary.SaveState/LoadState`, + live settings, HUD, cheats), playtime stats, exit cloud backup. +7. **Routing**: `RetroShortcuts.launch` sends gc/wii to the embedded activity (toggle + first, libretro fallback until parity); settings surfaces switch to the Dolphin + sections; decide native RetroAchievements vs RetroAchievementsManager. + +## Phase 2 analysis (done) + +Authoritative JNI-required Java surface (every `FindClass` under `Source/Android/jni/`), +30 classes — all model/util, **no upstream UI**: + +- `NativeLibrary` +- cheats models: `ARCheat`, `GeckoCheat`, `PatchCheat`, `GraphicsMod`, `GraphicsModGroup` +- input models: `controlleremu/{Control, ControlGroup, ControlGroupContainer, + ControlReference, EmulatedController, NumericSetting}`, `CoreDevice(+$Control)`, + `InputDetector` +- netplay: `NetplaySession`, `model/Player` +- `riivolution/model/RiivolutionPatches`, `skylanders/model/SkylanderPair` +- `model/GameFile`, `model/GameFileCache` +- utils: `Analytics`, `AudioUtils`, `BooleanSupplier`, `CompressCallback`, + `ContentHandler`, `NetworkHelper`, `PermissionsHandler`, `WiiUpdateCallback` +- plus `utils/GpuDriverHelper` (static-native Kotlin side of the adrenotools bridge; + native impl `jni/GpuDriver.cpp` calls `adrenotools_*` directly — Phase 5 hook point) + +Naive transitive closure is 92 files because a few bridge classes import the UI web. +Patch these cut points (in `patches/`), then the closure collapses to ~50 UI-free files: + +1. `NativeLibrary.kt` — replace `EmulationActivity`/`AlertMessage` references with a + `WnHost` callback interface our activity registers (alerts, exit, orientation, + title changes). This IS the B2 design: UI callbacks go to WinNative. +2. `utils/Analytics.kt` — strip the `FragmentActivity` dialog method (analytics is + compiled out with `-DENABLE_ANALYTICS=OFF`). +3. `NetplaySession.kt` — sever imports of netplay UI (`NetplaySetupActivity`, + viewmodels) if present; keep the session/Player model. +4. `Settings.kt`/`NativeConfig` chain — sever `SettingsActivity`/`MenuTag` imports. +5. Drop `DolphinApplication` (not JNI-required); our module provides directory init + via `DirectoryInitialization` directly. +6. Skylander/Infinity `ui/` adapters fall out once `EmulationActivity` is cut. + +Vendoring mechanism: gradle Copy task from `emucore-src/.../java` (post-patch) into +`build/generated/dolphinJava`, added as a srcDir — no duplicated sources in-repo. + +## MMJR2 fork review (2026-07-22) + +Reviewed Medard22/Dolphin-MMJR2-VBI, nachoverdon/Dolphin-MMJR2, Mato00KAN/Dolphin-MMJR2 +for patches worth adopting: + +- **VBI Skip (the headline MMJR2-VBI feature, by Sam Belliveau) is already in our + pinned upstream base** — it was upstreamed into official Dolphin: `bVISkip` + (VideoConfig.h:307), adaptive gate `CoreTiming::UpdateVISkip/GetVISkip` (only skips + when the core runs behind real time; auto-off under determinism/netplay), interrupt + suppression in VideoInterface.cpp:986. Config: `GFX.ini [Hacks] VISkip`; vendored + `BooleanSetting.GFX_HACK_VI_SKIP` already exposes it to our bridge. Nothing to port. + **Phase 4: expose as a WinNative "VBI Skip (auto frameskip)" toggle, default ON** + (adaptive — no cost at full speed; this is the MMJR2 "runs better" effect). +- The other two forks are "MMJR2 rebased onto latest official dev source with the old + MMJR UI and no scoped storage" — both properties irrelevant to us (we build current + master, strip all Dolphin UI, and own the data paths via SetUserDirectory). +- No other distinguishing native patches found worth carrying; MMJR-style value comes + from *defaults*, which our settings bridge already curates (JITARM64, DSP-HLE, + EFB-to-texture, sync shaders, + VISkip on). + +## Notes + +- The libretro core (`libdolphin_libretro_android.so`) stays in place until Phase 7 + parity, then is removed along with its jniLibs entry. +- ARMSX2 reference costs: 17k LOC bridge, 1.3k LOC overlay — expect the same order. + +Cloud-save bucket fix (2026-07-22): the real reason Save History was blank for +ALL retro consoles — auto-upload used cloudGameId ("retro_gc_") but the +History UI and manual backup query under customGameId (":.desktop") += two different Google buckets, so nothing ever appeared. Worse, backupSaveToGoogle +resolves the save DIR from the gameId (getCustomSaveSources → findShortcut → +retroSaveDir); a cloudGameId resolves no shortcut, so it found no files and +silently uploaded nothing. Fix: everything now uploads/restores under customGameId +(same as the working PS2 path). retroSaveDir extended to return the full per-game +set: PS2=memcards, GC/Wii=DolphinCloudSync staging (states+GC memcards), other +libretro=RetroSaveStates.gameDir (states+sram). Internal staging dir stays keyed +by cloudGameId (a stable path token) while the Google bucket uses customGameId — +the two IDs have distinct roles. findCustomShortcutByContainerAndFile resolves +retro shortcuts via loadShortcuts() (retroContainer id 0), confirmed. diff --git a/cores/DOLPHIN_VULKAN.md b/cores/DOLPHIN_VULKAN.md new file mode 100644 index 000000000..2a18179b9 --- /dev/null +++ b/cores/DOLPHIN_VULKAN.md @@ -0,0 +1,154 @@ +# Scope: routing Dolphin (GC/Wii) through Vulkan + Turnip + +> **Packaging note (current):** the emucore and its runtime data are no longer committed +> here. They are built in the [WinNative-Emu](https://github.com/WinNative-Emu) fork and +> shipped in the [Retro-Consoles](https://github.com/WinNative-Emu/Retro-Consoles) bundle +> the app downloads at runtime. The build/patch details below describe how that fork +> produces the binary and remain accurate for the fork. + +## Why + +On Snapdragon 8 Elite Gen 5 / Adreno 840 (device CPH2749, driver `libGLESv2_adreno.so` +v0842.41), the Dolphin libretro core reliably SIGSEGVs ~13s into 3D rendering: + +``` +#00 __memmove_aarch64_nt libc.so +#01 libGLESv2_adreno.so +9444 ← system Adreno GLES driver faults +#02..#08 libdolphin_libretro_android.so ← Dolphin OGL backend +#09 ← JITARM64 game code (single-core, "CPU-GPU thread") +``` + +The fault is *inside* the system Adreno GLES driver's vertex-streaming path — not app +code, and not fixable from our GLES side. The durable fix is to stop using the GLES +backend for Dolphin and use its Vulkan backend instead, optionally on the Turnip +(Mesa) driver, which the app already ships for PS2/Wine. + +## What we confirmed + +- **Core is Vulkan-ready.** The prebuilt `.so` contains the full Vulkan backend + (`VKGfx`/`VKSwapChain`/`VulkanContext`/`VulkanLoader`) AND the libretro Vulkan HW + interface shim (`DolphinLibretro/Vulkan.cpp`). `HAS_VULKAN` is on. +- **Core contract (RetroArch Vulkan model):** on `GET_PREFERRED_HW_RENDER` returning + `RETRO_HW_CONTEXT_VULKAN`, the core: + 1. `SET_HW_RENDER` with `context_type = VULKAN`, `version = VK_API_VERSION_1_0`. + 2. `SET_HW_RENDER_CONTEXT_NEGOTIATION_INTERFACE` → gives us + `retro_hw_render_context_negotiation_interface_vulkan` (`GetApplicationInfo`, + `CreateDevice`). The **frontend creates the `VkInstance`**, the **core creates the + `VkDevice`** (picks GPU, features, extensions) via its `CreateDevice`. + 3. On `context_reset`, core calls `GET_HW_RENDER_INTERFACE` expecting a + `retro_hw_render_interface_vulkan` from us (instance, gpu, device, queue, + `get_*_proc_addr`, `set_image`, `set_command_buffers`, `lock/unlock_queue`, + `get_sync_index`, `wait_sync_index`). + 4. Each frame: core renders into its own `VkImage`, calls `set_image(...)`; the + frontend presents it. +- **The blocker is 100% frontend.** libretrodroid is GLES-only: + - `GLRetroView` extends Android `GLSurfaceView` + `setEGLContextClientVersion(3)` + (`GLRetroView.kt:50,90`). GLSurfaceView cannot host Vulkan. + - `environment.cpp:265` hardcodes `GET_PREFERRED_HW_RENDER = OPENGLES3`; + `libretrodroid.cpp:369` rejects anything that isn't GLES3. + - The compositor (shader chain: Default/CRT/LCD/Sharp/SGSR, viewport, rotation, + aspect) is entirely GLES (`video.cpp`, `renderers/es3/*`, `ShaderManager`). +- **Turnip plumbing already exists.** `app/src/main/cpp/adrenotools/` + + `com.armsx2.CustomDriver` download `libvulkan_freedreno.so` and + `adrenotools_open_libvulkan(...)` returns a hooked `libvulkan.so`. PS2/ARMSX2 already + uses it. A retro Vulkan backend would load its instance through the same handle. + +## Work required + +### Route A — add a Vulkan HW-render backend to libretrodroid (the "proper" fix) + +**A1. Surface / thread (structural).** Replace GLSurfaceView with a plain `SurfaceView` ++ `ANativeWindow` and a manual render thread for the Dolphin path. libretrodroid assumes +GLSurfaceView + GLThread + EGL throughout; this must become backend-selectable at launch +(new `GLRetroViewData` flag), keeping every other core on the untouched GLES path. +*Largest structural risk.* + +**A2. Vulkan HW interface (`libretro_vulkan.h`).** New native module (~1500–2500 LOC, +comparable to a scoped-down RetroArch `vulkan_common.c`): +- Create `VkInstance` (via adrenotools/Turnip handle or system libvulkan). +- Accept VULKAN in `SET_HW_RENDER`; store the negotiation interface; run negotiation + (`CreateDevice`) → device, queues, `VkSurfaceKHR` from the ANativeWindow. +- Implement the full `retro_hw_render_interface_vulkan` (set_image, queue locking, + sync-index tracking, command buffers). +- Swapchain create/recreate/present; receive the core `VkImage` and blit/letterbox to + the swapchain. +- Drive `context_reset`/`context_destroy` on the Vulkan timeline. + +**A3. Compositor.** GLES shader chain does not run in Vulkan mode. Minimum viable: +present the core image directly with correct aspect/rotation/viewport (Dolphin has its +own internal-res scaling; shaders/SGSR are a nicety). Full parity = SPIR-V ports of the +shader passes (large; defer). + +**A4. Turnip wiring (mostly done).** Reuse `adrenotools_open_libvulkan`; add a Dolphin +GPU-driver picker mirroring the PS2 one (`RetroDefaultsScreen`/`RetroGameSettings` +already have the pattern) → new pref, e.g. `retro_def_var_gc_driver` / `_wii_`. + +**A5. Routing / settings.** Only GC/Wii use the Vulkan backend; add the driver picker +(System Vulkan vs installed Turnip) to the three GC/Wii settings surfaces. + +### Route B — embed standalone Dolphin (mirror the PS2/ARMSX2 pattern) + +Instead of retrofitting a GLES-only libretro frontend, embed a standalone Dolphin build +(its own Vulkan renderer + adrenotools, own SurfaceView, separate process) exactly like +ARMSX2 is embedded for PS2 (`NativeApp.renderVulkan()`, `CustomDriver`, `Ps2GameOverlay`). +- **Pro:** reuses the *working* PS2 Turnip path; no fork of libretrodroid; Dolphin's own + mature Vulkan+driver handling. +- **Con:** a second Dolphin engine to ship/maintain; GC/Wii lose the libretro features + wired this session (RetroAchievements incl. hardcore, netplay, unified save-states, + shared retro UI/overlays) unless re-bridged. + +## Route B in detail (embed standalone Dolphin, mirror ARMSX2/PS2) + +**Reference cost — what the ARMSX2/PS2 embed actually is (measured in-repo):** +- `armsx2/emucore-src` = **5.9 GB** source (a PCSX2 fork), built from source via + `build-emucore.sh` (git clone + NDK/CMake/ninja). +- **17,382 LOC** Kotlin/Java bridge in `armsx2/src/main/java`. +- `Ps2GameOverlay.kt` alone = **1,341 LOC** — just the overlay + settings/achievements/ + OSD/dev9 bridge that maps the WinNative drawer onto the native emu. +- Its own `:ps2` process activity (`com.armsx2.Main`) + a large `NativeApp` JNI surface + (settings, achievements, OSD, patches, netplay). + +A `:dolphin` module is the **same class of effort** (vendor a multi-GB emulator, JNI, +process, overlay). The mitigating fact: **upstream Dolphin already has, natively,** +Vulkan, adrenotools/Turnip ("GPU Driver Manager" in Graphics settings — K0bin's +libadrenotools integration), RetroAchievements (incl. hardcore), netplay, save +states/memcards/Wii saves, and AR/Gecko cheats. So Dolphin gives the *features* for free; +the cost is the *bridge/UX*, which splits Route B in two: + +- **B1 — bolt-on (small bridge).** Launch GC/Wii into Dolphin's *own* Android UI (reuse + the `launchEmbeddedPs2` hand-off pattern; pass ROM + driver). Cheapest path to a + working, non-crashing, Turnip-capable GC/Wii. **But** it *discards this session's entire + WinNative GC/Wii integration* (shared drawer, HUD, `RetroInputView` overlays, the + settings just wired, libretro RetroAchievements/netplay) — GC/Wii would look and behave + like a different app, and you maintain a second full emulator + its multi-GB build. +- **B2 — unified (ARMSX2-scale bridge).** Embed Dolphin's core and rebuild the WinNative + drawer/HUD/overlay/settings bridge on top (the ~10k-LOC `Ps2GameOverlay`+`NativeApp` + analogue). Preserves UX parity; **largest effort of all options.** + +**Key contrast with Route A:** Route A swaps only the render backend *under* libretrodroid, +so it **keeps 100% of this session's WinNative GC/Wii work** (menus, overlays, HUD, +achievements, netplay) — only rendering changes. Route B1 throws that away; Route B2 +rebuilds it. + +## Risks to validate BEFORE building (cheap gates) + +1. **Does system Vulkan alone dodge the crash?** Turnip may be unnecessary — just moving + Dolphin off the GLES backend onto the stock Adreno *Vulkan* driver may fix it. If so, + Route A without Turnip is the fix and Turnip is optional polish. +2. **Does Turnip support Adreno 840 (A8xx / SM8850 "canoe")?** Mesa/Turnip lags on newest + silicon. **Cheap check: run a PS2 title with a Turnip driver on THIS device** — if PS2 + renders on Turnip, A840 Turnip works and Route A/B-with-Turnip is viable here. +3. **libretrodroid is third-party (swordfish).** A Vulkan backend is a hard fork; future + upstream merges get harder. Route B avoids this. + +## Recommendation + +- Gate first (risks 1 & 2) — a few minutes, no code: try Dolphin `renderer=Software` + (proves GPU driver is the culprit) and a PS2+Turnip run (proves A840 Turnip). +- If system Vulkan fixes it: **Route A** is the clean long-term answer but is a + multi-week, ~2–4k-LOC native effort with the GLSurfaceView→Vulkan structural change as + the main risk. **Route B** is likely less code and directly reuses the proven PS2 path, + at the cost of a second engine and re-bridging libretro features. +- Recommended sequence: validate gates → prototype Route A's Vulkan instance-on-Turnip + + present-only compositor (no shaders) behind a launch flag for GC/Wii only → measure + stability → decide whether to invest in the full compositor or pivot to Route B. diff --git a/dolphin/.gitignore b/dolphin/.gitignore new file mode 100644 index 000000000..6d737ee8e --- /dev/null +++ b/dolphin/.gitignore @@ -0,0 +1,3 @@ +emucore-src/ +emucore-out/ +build/ diff --git a/dolphin/build.gradle b/dolphin/build.gradle new file mode 100644 index 000000000..87b5cac54 --- /dev/null +++ b/dolphin/build.gradle @@ -0,0 +1,51 @@ +plugins { + id 'com.android.library' + id 'org.jetbrains.kotlin.android' +} + +android { + namespace 'org.dolphinemu.dolphinemu' + compileSdk 35 + ndkVersion '27.3.13750724' + + defaultConfig { + minSdk 26 + ndk { + abiFilters 'arm64-v8a' + } + buildConfigField 'String', 'APPLICATION_ID', '"org.dolphinemu.dolphinemu.wn"' + } + + buildFeatures { + buildConfig true + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } + kotlinOptions { + jvmTarget = '17' + } + + packaging { + jniLibs { + useLegacyPackaging true + } + } + + def dolphinVendorOut = file("$projectDir/vendored/java") + + sourceSets { + main { + java.srcDirs += dolphinVendorOut + } + } + +} + +dependencies { + implementation libs.coreKtx + implementation libs.activityKtx + implementation libs.appcompat +} diff --git a/dolphin/src/main/AndroidManifest.xml b/dolphin/src/main/AndroidManifest.xml new file mode 100644 index 000000000..ac1c7ebb0 --- /dev/null +++ b/dolphin/src/main/AndroidManifest.xml @@ -0,0 +1,14 @@ + + + + + + + diff --git a/dolphin/src/main/java/org/dolphinemu/dolphinemu/DolphinApplication.kt b/dolphin/src/main/java/org/dolphinemu/dolphinemu/DolphinApplication.kt new file mode 100644 index 000000000..e6f0b482d --- /dev/null +++ b/dolphin/src/main/java/org/dolphinemu/dolphinemu/DolphinApplication.kt @@ -0,0 +1,20 @@ +package org.dolphinemu.dolphinemu + +import android.content.Context + +/** WinNative replacement: vendored upstream classes call + * DolphinApplication.getAppContext(); the host app (or DolphinEmulationActivity) + * installs the context before any Dolphin code runs. */ +object DolphinApplication { + @Volatile + private var appContext: Context? = null + + @JvmStatic + fun install(context: Context) { + appContext = context.applicationContext + } + + @JvmStatic + fun getAppContext(): Context = + appContext ?: error("DolphinApplication.install() not called") +} diff --git a/dolphin/src/main/java/org/dolphinemu/dolphinemu/NativeLibrary.kt b/dolphin/src/main/java/org/dolphinemu/dolphinemu/NativeLibrary.kt new file mode 100644 index 000000000..3d1335a35 --- /dev/null +++ b/dolphin/src/main/java/org/dolphinemu/dolphinemu/NativeLibrary.kt @@ -0,0 +1,166 @@ +package org.dolphinemu.dolphinemu + +import android.view.Surface +import androidx.annotation.Keep + +/** WinNative replacement matching upstream's JNI contract; UI callbacks route + * to the registered [WnHost]. */ +object NativeLibrary { + object ButtonType { + const val WIIMOTE_BUTTON_A = 100 + } + + interface WnHost { + fun onToast(message: String, long: Boolean) + + fun onAlert( + caption: String, + text: String, + yesNo: Boolean, + isWarning: Boolean, + nonBlocking: Boolean, + ): Boolean + + fun onUpdateTouchPointer() + + fun onTitleChanged() + + fun onEmulationFinished() + } + + @Volatile + var host: WnHost? = null + + @Volatile + var frameListener: Runnable? = null + + @Keep + @JvmStatic + fun onGameFrame() { + frameListener?.run() + } + + @Keep + @JvmStatic + fun displayToastMsg(message: String, long: Boolean) { + host?.onToast(message, long) + } + + @Keep + @JvmStatic + fun displayAlertMsg( + caption: String, + text: String, + yesNo: Boolean, + isWarning: Boolean, + nonBlocking: Boolean, + ): Boolean = host?.onAlert(caption, text, yesNo, isWarning, nonBlocking) ?: true + + @Keep + @JvmStatic + fun updateTouchPointer() { + host?.onUpdateTouchPointer() + } + + @Keep + @JvmStatic + fun onTitleChanged() { + host?.onTitleChanged() + } + + @Keep + @JvmStatic + fun finishEmulationActivity() { + host?.onEmulationFinished() + } + + @Keep + @JvmStatic + fun getRenderSurfaceScale(): Float = + android.content.res.Resources.getSystem().displayMetrics.density + + @JvmStatic external fun Initialize() + + @JvmStatic external fun ReloadConfig() + + @JvmStatic external fun ReloadLoggerConfig() + + @JvmStatic external fun SetUserDirectory(directory: String) + + @JvmStatic external fun GetUserDirectory(): String + + @JvmStatic external fun SetCacheDirectory(directory: String) + + @JvmStatic external fun SetObscuredPixelsLeft(width: Int) + + @JvmStatic external fun SetObscuredPixelsTop(height: Int) + + @JvmStatic external fun SurfaceChanged(surf: Surface) + + @JvmStatic external fun SurfaceDestroyed() + + @JvmStatic external fun HasSurface(): Boolean + + @JvmStatic external fun Run(path: Array, riivolution: Boolean) + + @JvmStatic external fun Run( + path: Array, + riivolution: Boolean, + savestatePath: String, + deleteSavestate: Boolean, + ) + + @JvmStatic external fun RunNetPlay( + path: Array, + riivolution: Boolean, + bootSessionDataPointer: Long, + ) + + @JvmStatic external fun RunSystemMenu() + + @JvmStatic external fun ChangeDisc(path: String) + + @JvmStatic external fun PauseEmulation() + + @JvmStatic external fun UnPauseEmulation() + + @JvmStatic external fun StopEmulation() + + @JvmStatic external fun IsRunning(): Boolean + + @JvmStatic external fun IsRunningAndUnpaused(): Boolean + + @JvmStatic external fun IsUninitialized(): Boolean + + @JvmStatic external fun IsEmulatingWiiUnchecked(): Boolean + + @JvmStatic external fun GetCurrentTitleDescriptionUnchecked(): String + + @JvmStatic external fun GetCurrentGameIDUnchecked(): String + + @JvmStatic external fun SetIsBooting() + + @JvmStatic external fun SaveState(slot: Int, wait: Boolean) + + @JvmStatic external fun SaveStateAs(path: String, wait: Boolean) + + @JvmStatic external fun LoadState(slot: Int) + + @JvmStatic external fun LoadStateAs(path: String) + + @JvmStatic external fun GetUnixTimeOfStateSlot(slot: Int): Long + + @JvmStatic external fun SaveScreenShot() + + @JvmStatic external fun RefreshWiimotes() + + @JvmStatic external fun GetGitRevision(): String + + @JvmStatic external fun GetVersionString(): String + + @JvmStatic external fun DefaultCPUCore(): Int + + @JvmStatic external fun GetGameAspectRatio(): Float + + @JvmStatic external fun GetDefaultGraphicsBackendConfigName(): String +} diff --git a/dolphin/src/main/java/org/dolphinemu/dolphinemu/overlay/InputOverlayPointer.kt b/dolphin/src/main/java/org/dolphinemu/dolphinemu/overlay/InputOverlayPointer.kt new file mode 100644 index 000000000..43b0b1053 --- /dev/null +++ b/dolphin/src/main/java/org/dolphinemu/dolphinemu/overlay/InputOverlayPointer.kt @@ -0,0 +1,9 @@ +package org.dolphinemu.dolphinemu.overlay + +/** WinNative stub: only the IR-mode constants vendored settings code references. + * The real touch pointer is driven by WinNative's overlay via InputOverrider. */ +object InputOverlayPointer { + const val MODE_DISABLED = 0 + const val MODE_FOLLOW = 1 + const val MODE_DRAG = 2 +} diff --git a/dolphin/src/main/java/org/dolphinemu/dolphinemu/utils/Analytics.kt b/dolphin/src/main/java/org/dolphinemu/dolphinemu/utils/Analytics.kt new file mode 100644 index 000000000..901568439 --- /dev/null +++ b/dolphin/src/main/java/org/dolphinemu/dolphinemu/utils/Analytics.kt @@ -0,0 +1,9 @@ +package org.dolphinemu.dolphinemu.utils + +import androidx.annotation.Keep + +object Analytics { + @Keep + @JvmStatic + fun getValue(key: String): String = "" +} diff --git a/dolphin/src/main/java/org/dolphinemu/dolphinemu/utils/DirectoryInitialization.kt b/dolphin/src/main/java/org/dolphinemu/dolphinemu/utils/DirectoryInitialization.kt new file mode 100644 index 000000000..b0cb4493e --- /dev/null +++ b/dolphin/src/main/java/org/dolphinemu/dolphinemu/utils/DirectoryInitialization.kt @@ -0,0 +1,58 @@ +package org.dolphinemu.dolphinemu.utils + +import android.content.Context +import java.io.File + +object DirectoryInitialization { + @JvmStatic + external fun SetSysDirectory(path: String) + + @JvmStatic + external fun SetGpuDriverDirectories(path: String, libPath: String) + + fun userDir(context: Context): File = File(context.filesDir, "dolphin-embed/User") + + @Volatile + private var sysDirSet = false + + fun ensureDirectories(context: Context): File { + val sysDir = File(context.filesDir, "dolphin-embed/Sys") + val marker = File(sysDir, ".wn_sys_ready") + if (!marker.isFile) { + val bundled = File(context.filesDir, "retro/bundle/data/dolphin-emu/Sys") + val copied = runCatching { bundled.copyRecursively(sysDir, overwrite = true) }.getOrDefault(false) + if (copied) marker.writeText("1") + } + if (!sysDirSet) { + sysDirSet = true + SetSysDirectory(sysDir.path + File.separator) + val driverRoot = File(context.filesDir, "dolphin-embed/GpuDrivers") + File(driverRoot, "Extracted").mkdirs() + File(driverRoot, "Tmp").mkdirs() + File(driverRoot, "FileRedirect").mkdirs() + SetGpuDriverDirectories(driverRoot.path, context.applicationInfo.nativeLibraryDir) + } + val user = userDir(context) + File(user, "Config").mkdirs() + return user + } + + fun writeBaseConfig(userDir: File) { + val ini = File(userDir, "Config/Dolphin.ini") + if (!ini.isFile) { + ini.writeText( + """ + [Core] + GFXBackend = Vulkan + """.trimIndent() + "\n", + ) + } + File(userDir, "Config/Logger.ini").writeText( + """ + [Options] + Verbosity = 2 + WriteToConsole = True + """.trimIndent() + "\n", + ) + } +} diff --git a/dolphin/src/main/java/org/dolphinemu/dolphinemu/utils/FileBrowserHelper.kt b/dolphin/src/main/java/org/dolphinemu/dolphinemu/utils/FileBrowserHelper.kt new file mode 100644 index 000000000..c3be9c492 --- /dev/null +++ b/dolphin/src/main/java/org/dolphinemu/dolphinemu/utils/FileBrowserHelper.kt @@ -0,0 +1,12 @@ +package org.dolphinemu.dolphinemu.utils + +object FileBrowserHelper { + @JvmStatic + fun getExtension(fileName: String?, forceLowerCase: Boolean): String? { + if (fileName == null) return null + val dot = fileName.lastIndexOf('.') + if (dot < 0 || dot == fileName.length - 1) return null + val ext = fileName.substring(dot + 1) + return if (forceLowerCase) ext.lowercase() else ext + } +} diff --git a/dolphin/src/main/java/org/dolphinemu/dolphinemu/utils/PermissionsHandler.kt b/dolphin/src/main/java/org/dolphinemu/dolphinemu/utils/PermissionsHandler.kt new file mode 100644 index 000000000..70c539138 --- /dev/null +++ b/dolphin/src/main/java/org/dolphinemu/dolphinemu/utils/PermissionsHandler.kt @@ -0,0 +1,31 @@ +package org.dolphinemu.dolphinemu.utils + +import android.Manifest +import android.app.Activity +import android.content.Context +import android.content.pm.PackageManager +import androidx.annotation.Keep +import androidx.core.app.ActivityCompat +import androidx.core.content.ContextCompat + +object PermissionsHandler { + const val REQUEST_RECORD_AUDIO = 900 + + @Keep + @JvmStatic + fun hasRecordAudioPermission(context: Context?): Boolean = + context != null && + ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == + PackageManager.PERMISSION_GRANTED + + @Keep + @JvmStatic + fun requestRecordAudioPermission(activity: Activity?) { + if (activity == null) return + ActivityCompat.requestPermissions( + activity, + arrayOf(Manifest.permission.RECORD_AUDIO), + REQUEST_RECORD_AUDIO, + ) + } +} diff --git a/dolphin/src/main/java/org/dolphinemu/dolphinemu/wn/DolphinConfigWriter.kt b/dolphin/src/main/java/org/dolphinemu/dolphinemu/wn/DolphinConfigWriter.kt new file mode 100644 index 000000000..f9094e8a1 --- /dev/null +++ b/dolphin/src/main/java/org/dolphinemu/dolphinemu/wn/DolphinConfigWriter.kt @@ -0,0 +1,87 @@ +package org.dolphinemu.dolphinemu.wn + +import java.io.File + +object DolphinConfigWriter { + fun write(userDir: File, vars: Map) { + val core = linkedMapOf() + core["GFXBackend"] = + if (vars["dolphin_renderer"] == "Software") "Software Renderer" else "Vulkan" + core["CPUCore"] = vars["dolphin_cpu_core"]?.toIntOrNull()?.toString() ?: "4" + core["CPUThread"] = ini(vars["dolphin_main_cpu_thread"] == "enabled") + core["SkipIPL"] = ini(vars["dolphin_skip_gc_bios"] != "disabled") + core["EnableCheats"] = ini(vars["dolphin_cheats_enabled"] == "enabled") + core["DSPHLE"] = ini(vars["dolphin_dsp_hle"] != "disabled") + core["FastDiscSpeed"] = ini(vars["dolphin_fast_disc_speed"] == "enabled") + mergeIni(File(userDir, "Config/Dolphin.ini"), "Core", core) + + val dsp = linkedMapOf() + dsp["Muted"] = ini(vars["wn_audio"] == "0") + mergeIni(File(userDir, "Config/Dolphin.ini"), "DSP", dsp) + + val gfxSettings = linkedMapOf() + gfxSettings["InternalResolution"] = + vars["dolphin_efb_scale"]?.toIntOrNull()?.coerceIn(1, 6)?.toString() ?: "1" + gfxSettings["AspectRatio"] = + vars["dolphin_aspect_ratio"]?.toIntOrNull()?.coerceIn(0, 6)?.toString() ?: "0" + gfxSettings["wideScreenHack"] = ini(vars["dolphin_widescreen_hack"] == "enabled") + gfxSettings["DriverLibName"] = vars["dolphin_gpu_driver_lib"].orEmpty() + gfxSettings["ShowFPS"] = "False" + gfxSettings["ShowVPS"] = "False" + gfxSettings["ShowSpeed"] = "False" + mergeIni(File(userDir, "Config/GFX.ini"), "Settings", gfxSettings) + + val gfxHacks = linkedMapOf() + gfxHacks["VISkip"] = ini(vars["dolphin_vi_skip"] != "disabled") + mergeIni(File(userDir, "Config/GFX.ini"), "Hacks", gfxHacks) + + vars["dolphin_log_verbosity"]?.toIntOrNull()?.let { level -> + mergeIni(File(userDir, "Config/Logger.ini"), "Options", mapOf("Verbosity" to level.toString())) + } + } + + fun wiiWidescreen(vars: Map): Boolean = vars["dolphin_widescreen"] != "disabled" + + fun sensorBarTop(vars: Map): Boolean = vars["dolphin_sensor_bar_position"] == "1" + + private fun ini(value: Boolean) = if (value) "True" else "False" + + private fun mergeIni(file: File, section: String, keys: Map) { + val source = if (file.isFile) file.readText() else "" + val lines = source.replace("\r\n", "\n").split('\n').toMutableList() + val header = "[$section]" + var start = lines.indexOfFirst { it.trim().equals(header, ignoreCase = true) } + if (start < 0) { + val builder = StringBuilder(source.trimEnd()) + if (builder.isNotEmpty()) builder.append("\n\n") + builder.append(header).append('\n') + for ((k, v) in keys) builder.append(k).append(" = ").append(v).append('\n') + file.parentFile?.mkdirs() + file.writeText(builder.toString()) + return + } + var end = lines.size + for (i in (start + 1) until lines.size) { + val t = lines[i].trim() + if (t.startsWith("[") && t.endsWith("]")) { + end = i + break + } + } + val remaining = keys.toMutableMap() + for (i in (start + 1) until end) { + val t = lines[i].trim() + if (t.isEmpty() || t.startsWith("#") || t.startsWith(";")) continue + val eq = t.indexOf('=') + if (eq <= 0) continue + val key = t.substring(0, eq).trim() + val wanted = remaining.remove(key) ?: continue + lines[i] = "$key = $wanted" + } + if (remaining.isNotEmpty()) { + lines.addAll(end, remaining.map { (k, v) -> "$k = $v" }) + } + file.parentFile?.mkdirs() + file.writeText(lines.joinToString("\n").let { if (it.endsWith("\n")) it else "$it\n" }) + } +} diff --git a/dolphin/src/main/java/org/dolphinemu/dolphinemu/wn/DolphinEmulationActivity.kt b/dolphin/src/main/java/org/dolphinemu/dolphinemu/wn/DolphinEmulationActivity.kt new file mode 100644 index 000000000..ea99caa4b --- /dev/null +++ b/dolphin/src/main/java/org/dolphinemu/dolphinemu/wn/DolphinEmulationActivity.kt @@ -0,0 +1,630 @@ +package org.dolphinemu.dolphinemu.wn + +import android.content.Context +import android.os.Bundle +import androidx.activity.addCallback +import android.util.Log +import android.view.InputDevice +import android.view.KeyEvent +import android.view.MotionEvent +import android.view.SurfaceHolder +import android.view.SurfaceView +import android.view.WindowManager +import android.widget.Toast +import org.dolphinemu.dolphinemu.DolphinApplication +import org.dolphinemu.dolphinemu.NativeLibrary +import org.dolphinemu.dolphinemu.features.input.model.InputOverrider +import org.dolphinemu.dolphinemu.features.input.model.InputOverrider.ControlId +import org.dolphinemu.dolphinemu.utils.DirectoryInitialization +import java.io.File +import kotlin.concurrent.thread +import kotlin.math.abs + +class DolphinEmulationActivity : + androidx.activity.ComponentActivity(), + SurfaceHolder.Callback, + NativeLibrary.WnHost { + companion object { + private const val TAG = "WnDolphin" + const val EXTRA_ROM_PATH = "dolphin_rom_path" + const val EXTRA_SYSTEM_ID = "dolphin_system_id" + const val EXTRA_GAME_NAME = "dolphin_game_name" + const val EXTRA_VARIABLES = "dolphin_variables" + const val EXTRA_VARIABLES_STRING = "dolphin_vars" + const val EXTRA_SHORTCUT_PATH = "dolphin_shortcut_path" + const val EXTRA_CONTAINER_ID = "dolphin_container_id" + const val EXTRA_RA_ENABLED = "dolphin_ra_enabled" + const val EXTRA_RA_USER = "dolphin_ra_user" + const val EXTRA_RA_TOKEN = "dolphin_ra_token" + const val EXTRA_RA_HARDCORE = "dolphin_ra_hardcore" + + @Volatile + var currentVariables: Map = emptyMap() + private set + + @Volatile + var currentGameId: String = "" + private set + + @Volatile + private var nativeLoadResult: Boolean? = null + + @Synchronized + fun ensureNativeLibrary(context: Context): Boolean = + nativeLoadResult ?: runCatching { + System.load(File(context.filesDir, "retro/bundle/cores/libmain.so").absolutePath) + }.isSuccess.also { nativeLoadResult = it } + + @Volatile + private var emulationStarted = false + + @Volatile + private var stopping = false + + @Volatile + private var bootedInProcess = false + + @Volatile + private var runThread: Thread? = null + } + + private fun teardown() { + if (stopping) return + stopping = true + runCatching { File(filesDir, "dolphin-embed/.running_rom").delete() } + thread(name = "WnDolphinTeardown") { + runCatching { DolphinNetplay.stop() } + if (emulationStarted) { + runCatching { NativeLibrary.StopEmulation() } + runThread?.join(15000) + } + if (bootedInProcess) { + runCatching { DolphinHost.onStageSaves?.invoke(this) } + .onFailure { Log.w(TAG, "stage saves failed", it) } + } + runOnUiThread { if (!isFinishing) finish() } + Thread.sleep(250) + Log.i(TAG, "teardown complete, ending :gc process") + android.os.Process.killProcess(android.os.Process.myPid()) + } + } + + private var surfaceView: SurfaceView? = null + private var isWii = false + private var overridesRegistered = false + + private val invertPrefs by lazy { + getSharedPreferences("${packageName}_preferences", android.content.Context.MODE_PRIVATE) + } + + @Volatile + private var surfaceLive = false + + private val customDriverActive: Boolean + get() = !currentVariables["dolphin_gpu_driver_lib"].isNullOrBlank() + + private fun initialSurfaceParams(): android.widget.FrameLayout.LayoutParams { + val lp = + android.widget.FrameLayout.LayoutParams( + android.widget.FrameLayout.LayoutParams.MATCH_PARENT, + android.widget.FrameLayout.LayoutParams.MATCH_PARENT, + ) + if (currentVariables["wn_touch"] != "0") { + val bounds = + if (android.os.Build.VERSION.SDK_INT >= 30) { + windowManager.currentWindowMetrics.bounds + } else { + val dm = resources.displayMetrics + android.graphics.Rect(0, 0, dm.widthPixels, dm.heightPixels) + } + val w = maxOf(bounds.width(), bounds.height()) + val h = minOf(bounds.width(), bounds.height()) + val gameWidth = (h * 4f / 3f).coerceAtMost(w.toFloat()) + lp.width = gameWidth.toInt() + lp.height = h + lp.leftMargin = ((w - gameWidth) * 0.5f).toInt() + } + return lp + } + + private fun applyImmersiveMode() { + androidx.core.view.WindowCompat.setDecorFitsSystemWindows(window, false) + if (android.os.Build.VERSION.SDK_INT >= 28) { + val attrs = window.attributes + attrs.layoutInDisplayCutoutMode = + if (android.os.Build.VERSION.SDK_INT >= 30) { + WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS + } else { + WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES + } + window.attributes = attrs + } + val controller = + androidx.core.view.WindowInsetsControllerCompat(window, window.decorView) + controller.hide(androidx.core.view.WindowInsetsCompat.Type.systemBars()) + controller.systemBarsBehavior = + androidx.core.view.WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE + } + + override fun onWindowFocusChanged(hasFocus: Boolean) { + super.onWindowFocusChanged(hasFocus) + if (hasFocus) applyImmersiveMode() + } + + private fun stageGpuDriver(vars: Map) { + val packDir = vars["dolphin_gpu_driver"]?.takeIf { it.isNotBlank() } ?: return + runCatching { + val extracted = File(filesDir, "dolphin-embed/GpuDrivers/Extracted") + extracted.mkdirs() + File(packDir).listFiles()?.forEach { src -> + if (!src.isFile) return@forEach + val dst = File(extracted, src.name) + if (!dst.isFile || dst.length() != src.length()) src.copyTo(dst, overwrite = true) + } + Log.i(TAG, "GPU driver staged from $packDir lib=${vars["dolphin_gpu_driver_lib"]}") + }.onFailure { Log.w(TAG, "GPU driver staging failed: $it") } + } + + private fun resolveVariables(): Map { + @Suppress("UNCHECKED_CAST", "DEPRECATION") + val map = (intent.getSerializableExtra(EXTRA_VARIABLES) as? HashMap) ?: HashMap() + intent.getStringExtra(EXTRA_VARIABLES_STRING)?.split(';')?.forEach { pair -> + val eq = pair.indexOf('=') + if (eq > 0) map[pair.substring(0, eq).trim()] = pair.substring(eq + 1).trim() + } + return map + } + + private fun initAchievements() { + if (!intent.getBooleanExtra(EXTRA_RA_ENABLED, false)) return + val user = intent.getStringExtra(EXTRA_RA_USER).orEmpty() + val token = intent.getStringExtra(EXTRA_RA_TOKEN).orEmpty() + if (user.isBlank() || token.isBlank()) return + runCatching { + val base = org.dolphinemu.dolphinemu.features.settings.model.NativeConfig.LAYER_BASE + org.dolphinemu.dolphinemu.features.settings.model.NativeConfig + .setBoolean(base, "RetroAchievements", "Achievements", "Enabled", true) + org.dolphinemu.dolphinemu.features.settings.model.NativeConfig + .setString(base, "RetroAchievements", "Achievements", "Username", user) + org.dolphinemu.dolphinemu.features.settings.model.NativeConfig + .setString(base, "RetroAchievements", "Achievements", "ApiToken", token) + org.dolphinemu.dolphinemu.features.settings.model.NativeConfig.setBoolean( + base, "RetroAchievements", "Achievements", "HardcoreEnabled", + intent.getBooleanExtra(EXTRA_RA_HARDCORE, false), + ) + org.dolphinemu.dolphinemu.features.settings.model.AchievementModel.init() + thread(name = "WnDolphinRaLogin") { + runCatching { + kotlinx.coroutines.runBlocking { + org.dolphinemu.dolphinemu.features.settings.model.AchievementModel.asyncLogin("") + } + }.onFailure { Log.w(TAG, "RA login failed", it) } + } + }.onFailure { Log.w(TAG, "RA init failed", it) } + } + + private fun applySysconf(vars: Map) { + runCatching { + org.dolphinemu.dolphinemu.features.settings.model.NativeConfig.setBoolean( + org.dolphinemu.dolphinemu.features.settings.model.NativeConfig.LAYER_BASE, + "SYSCONF", + "IPL", + "AR", + DolphinConfigWriter.wiiWidescreen(vars), + ) + org.dolphinemu.dolphinemu.features.settings.model.NativeConfig.setInt( + org.dolphinemu.dolphinemu.features.settings.model.NativeConfig.LAYER_BASE, + "SYSCONF", + "BT", + "BAR", + if (DolphinConfigWriter.sensorBarTop(vars)) 1 else 0, + ) + }.onFailure { Log.w(TAG, "sysconf apply failed: $it") } + } + + private fun registerInputOverrides() { + if (overridesRegistered || !NativeLibrary.IsRunning()) return + overridesRegistered = true + isWii = runCatching { NativeLibrary.IsEmulatingWiiUnchecked() }.getOrDefault(false) || + intent.getStringExtra(EXTRA_SYSTEM_ID) == "wii" + InputOverrider.registerGameCube(0) + InputOverrider.registerWii(0) + runCatching { NativeLibrary.GetCurrentGameIDUnchecked() } + .getOrNull() + ?.takeIf { it.isNotBlank() } + ?.let { currentGameId = it } + Log.i(TAG, "input overrides registered (wiiHint=$isWii)") + } + + private fun unregisterInputOverrides() { + if (!overridesRegistered) return + overridesRegistered = false + runCatching { InputOverrider.unregisterGameCube(0) } + runCatching { InputOverrider.unregisterWii(0) } + } + + private fun set(control: Int, state: Double) { + if (overridesRegistered) InputOverrider.setControlState(0, control, state) + } + + private fun gcButtonFor(keyCode: Int): Int? = + when (keyCode) { + KeyEvent.KEYCODE_BUTTON_A -> ControlId.GCPAD_A_BUTTON + KeyEvent.KEYCODE_BUTTON_B -> ControlId.GCPAD_B_BUTTON + KeyEvent.KEYCODE_BUTTON_X -> ControlId.GCPAD_X_BUTTON + KeyEvent.KEYCODE_BUTTON_Y -> ControlId.GCPAD_Y_BUTTON + KeyEvent.KEYCODE_BUTTON_START -> ControlId.GCPAD_START_BUTTON + KeyEvent.KEYCODE_BUTTON_L1, KeyEvent.KEYCODE_BUTTON_R1 -> ControlId.GCPAD_Z_BUTTON + KeyEvent.KEYCODE_BUTTON_L2 -> ControlId.GCPAD_L_DIGITAL + KeyEvent.KEYCODE_BUTTON_R2 -> ControlId.GCPAD_R_DIGITAL + KeyEvent.KEYCODE_DPAD_UP -> ControlId.GCPAD_DPAD_UP + KeyEvent.KEYCODE_DPAD_DOWN -> ControlId.GCPAD_DPAD_DOWN + KeyEvent.KEYCODE_DPAD_LEFT -> ControlId.GCPAD_DPAD_LEFT + KeyEvent.KEYCODE_DPAD_RIGHT -> ControlId.GCPAD_DPAD_RIGHT + else -> null + } + + private fun wiiButtonFor(keyCode: Int): Int? = + when (keyCode) { + KeyEvent.KEYCODE_BUTTON_A -> ControlId.WIIMOTE_A_BUTTON + KeyEvent.KEYCODE_BUTTON_B -> ControlId.WIIMOTE_B_BUTTON + KeyEvent.KEYCODE_BUTTON_X -> ControlId.WIIMOTE_ONE_BUTTON + KeyEvent.KEYCODE_BUTTON_Y -> ControlId.WIIMOTE_TWO_BUTTON + KeyEvent.KEYCODE_BUTTON_START -> ControlId.WIIMOTE_PLUS_BUTTON + KeyEvent.KEYCODE_BUTTON_SELECT -> ControlId.WIIMOTE_MINUS_BUTTON + KeyEvent.KEYCODE_BUTTON_MODE -> ControlId.WIIMOTE_HOME_BUTTON + KeyEvent.KEYCODE_BUTTON_L1 -> ControlId.NUNCHUK_C_BUTTON + KeyEvent.KEYCODE_BUTTON_L2, KeyEvent.KEYCODE_BUTTON_R1, + KeyEvent.KEYCODE_BUTTON_R2, + -> ControlId.NUNCHUK_Z_BUTTON + KeyEvent.KEYCODE_DPAD_UP -> ControlId.WIIMOTE_DPAD_UP + KeyEvent.KEYCODE_DPAD_DOWN -> ControlId.WIIMOTE_DPAD_DOWN + KeyEvent.KEYCODE_DPAD_LEFT -> ControlId.WIIMOTE_DPAD_LEFT + KeyEvent.KEYCODE_DPAD_RIGHT -> ControlId.WIIMOTE_DPAD_RIGHT + else -> null + } + + @Volatile + var menuButtonHandler: (() -> Unit)? = null + + override fun dispatchKeyEvent(event: KeyEvent): Boolean { + registerInputOverrides() + if (event.keyCode == KeyEvent.KEYCODE_BUTTON_MODE && + intent.getStringExtra(EXTRA_SYSTEM_ID) != "wii" + ) { + if (event.action == KeyEvent.ACTION_DOWN) menuButtonHandler?.invoke() + return true + } + val gc = gcButtonFor(event.keyCode) + val wii = wiiButtonFor(event.keyCode) + if ((gc != null || wii != null) && overridesRegistered) { + val state = if (event.action == KeyEvent.ACTION_DOWN) 1.0 else 0.0 + gc?.let { set(it, state) } + wii?.let { set(it, state) } + if (event.keyCode == KeyEvent.KEYCODE_BUTTON_L2) { + set(ControlId.GCPAD_L_ANALOG, state) + } + if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R2) { + set(ControlId.GCPAD_R_ANALOG, state) + } + return true + } + return super.dispatchKeyEvent(event) + } + + override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean { + registerInputOverrides() + if (!overridesRegistered || + event.action != MotionEvent.ACTION_MOVE || + event.source and InputDevice.SOURCE_JOYSTICK != InputDevice.SOURCE_JOYSTICK + ) { + return super.dispatchGenericMotionEvent(event) + } + val invSys = intent.getStringExtra(EXTRA_SYSTEM_ID) ?: "gc" + val invLX = invertPrefs.getBoolean("retro_inv_lx_$invSys", false) + val invLY = invertPrefs.getBoolean("retro_inv_ly_$invSys", false) + val invRX = invertPrefs.getBoolean("retro_inv_rx_$invSys", false) + val invRY = invertPrefs.getBoolean("retro_inv_ry_$invSys", false) + val lx = event.getAxisValue(MotionEvent.AXIS_X).toDouble().let { if (invLX) -it else it } + val ly = (-event.getAxisValue(MotionEvent.AXIS_Y).toDouble()).let { if (invLY) -it else it } + val rx = event.getAxisValue(MotionEvent.AXIS_Z).toDouble().let { if (invRX) -it else it } + val ry = (-event.getAxisValue(MotionEvent.AXIS_RZ).toDouble()).let { if (invRY) -it else it } + val lt = maxOf(event.getAxisValue(MotionEvent.AXIS_LTRIGGER), event.getAxisValue(MotionEvent.AXIS_BRAKE)).toDouble() + val rt = maxOf(event.getAxisValue(MotionEvent.AXIS_RTRIGGER), event.getAxisValue(MotionEvent.AXIS_GAS)).toDouble() + val hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X) + val hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y) + set(ControlId.GCPAD_MAIN_STICK_X, lx) + set(ControlId.GCPAD_MAIN_STICK_Y, ly) + set(ControlId.GCPAD_C_STICK_X, rx) + set(ControlId.GCPAD_C_STICK_Y, ry) + set(ControlId.GCPAD_L_ANALOG, lt) + set(ControlId.GCPAD_R_ANALOG, rt) + set(ControlId.GCPAD_L_DIGITAL, if (lt > 0.9) 1.0 else 0.0) + set(ControlId.GCPAD_R_DIGITAL, if (rt > 0.9) 1.0 else 0.0) + set(ControlId.GCPAD_DPAD_LEFT, if (hatX < -0.5f) 1.0 else 0.0) + set(ControlId.GCPAD_DPAD_RIGHT, if (hatX > 0.5f) 1.0 else 0.0) + set(ControlId.GCPAD_DPAD_UP, if (hatY < -0.5f) 1.0 else 0.0) + set(ControlId.GCPAD_DPAD_DOWN, if (hatY > 0.5f) 1.0 else 0.0) + set(ControlId.NUNCHUK_STICK_X, lx) + set(ControlId.NUNCHUK_STICK_Y, ly) + set(ControlId.WIIMOTE_IR_X, rx) + set(ControlId.WIIMOTE_IR_Y, ry) + set(ControlId.NUNCHUK_Z_BUTTON, if (rt > 0.5) 1.0 else 0.0) + set(ControlId.NUNCHUK_C_BUTTON, if (lt > 0.5) 1.0 else 0.0) + set(ControlId.WIIMOTE_DPAD_LEFT, if (hatX < -0.5f) 1.0 else 0.0) + set(ControlId.WIIMOTE_DPAD_RIGHT, if (hatX > 0.5f) 1.0 else 0.0) + set(ControlId.WIIMOTE_DPAD_UP, if (hatY < -0.5f) 1.0 else 0.0) + set(ControlId.WIIMOTE_DPAD_DOWN, if (hatY > 0.5f) 1.0 else 0.0) + return true + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + DolphinApplication.install(this) + window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + applyImmersiveMode() + onBackPressedDispatcher.addCallback(this) { + if (emulationStarted) { + Log.i(TAG, "back pressed, tearing down") + teardown() + } else { + finish() + } + } + + if (!ensureNativeLibrary(this)) { + Log.e(TAG, "libmain failed to load") + Toast.makeText(this, "Dolphin emucore not installed — download the console cores in Settings › Retro", Toast.LENGTH_LONG).show() + finish() + return + } + + val romPath = intent.getStringExtra(EXTRA_ROM_PATH) + if (romPath.isNullOrBlank() || !File(romPath).isFile) { + Log.e(TAG, "ROM not found: $romPath") + Toast.makeText(this, "ROM not found", Toast.LENGTH_LONG).show() + finish() + return + } + + NativeLibrary.host = this + if (!emulationStarted) { + val vars = resolveVariables() + currentVariables = vars + emulationStarted = true + stopping = false + bootedInProcess = true + runThread = + thread(name = "WnDolphinRun") { + val userDir = DirectoryInitialization.ensureDirectories(this) + DirectoryInitialization.writeBaseConfig(userDir) + stageGpuDriver(vars) + DolphinConfigWriter.write(userDir, vars) + NativeLibrary.SetUserDirectory(userDir.path) + NativeLibrary.SetCacheDirectory(File(cacheDir, "dolphin-embed").also { it.mkdirs() }.path) + NativeLibrary.Initialize() + NativeLibrary.ReloadConfig() + applySysconf(vars) + initAchievements() + runCatching { File(filesDir, "dolphin-embed/.running_rom").writeText(romPath) } + val netplay = DolphinNetplay.fromIntent(intent) + if (netplay != null) { + Log.i(TAG, "Netplay ${if (netplay.host) "host" else "join"} boot $romPath") + val bootData = DolphinNetplay.startAndAwaitBoot(this, romPath, netplay) + if (bootData == 0L) { + Log.w(TAG, "Netplay boot aborted") + emulationStarted = false + teardown() + return@thread + } + NativeLibrary.RunNetPlay(arrayOf(romPath), false, bootData) + } else { + Log.i(TAG, "Booting $romPath vars=${vars.size}") + NativeLibrary.Run(arrayOf(romPath), false) + } + Log.i(TAG, "Run() returned") + emulationStarted = false + teardown() + } + } else { + Log.i(TAG, "Emulation already running, reattaching surface") + registerInputOverrides() + } + + val view = SurfaceView(this) + view.holder.addCallback(this) + surfaceView = view + val container = android.widget.FrameLayout(this) + container.addView(view, initialSurfaceParams()) + setContentView(container) + window.decorView.post { + if (!isFinishing && !isDestroyed) { + Log.i(TAG, "attachOverlay hook present=${DolphinHost.attachOverlay != null}") + runCatching { DolphinHost.attachOverlay?.invoke(this) } + .onFailure { Log.e(TAG, "overlay attach failed", it) } + } + } + } + + fun sendOverlayButton(keyCode: Int, down: Boolean) { + registerInputOverrides() + val state = if (down) 1.0 else 0.0 + gcButtonFor(keyCode)?.let { set(it, state) } + wiiButtonFor(keyCode)?.let { set(it, state) } + if (keyCode == KeyEvent.KEYCODE_BUTTON_L2) set(ControlId.GCPAD_L_ANALOG, state) + if (keyCode == KeyEvent.KEYCODE_BUTTON_R2) set(ControlId.GCPAD_R_ANALOG, state) + } + + fun sendOverlayLeftStick(x: Float, y: Float) { + registerInputOverrides() + set(ControlId.GCPAD_MAIN_STICK_X, x.toDouble()) + set(ControlId.GCPAD_MAIN_STICK_Y, -y.toDouble()) + set(ControlId.NUNCHUK_STICK_X, x.toDouble()) + set(ControlId.NUNCHUK_STICK_Y, -y.toDouble()) + } + + fun sendOverlayRightStick(x: Float, y: Float) { + registerInputOverrides() + set(ControlId.GCPAD_C_STICK_X, x.toDouble()) + set(ControlId.GCPAD_C_STICK_Y, -y.toDouble()) + set(ControlId.WIIMOTE_IR_X, x.toDouble()) + set(ControlId.WIIMOTE_IR_Y, -y.toDouble()) + } + + fun sendOverlayDpad(x: Float, y: Float) { + registerInputOverrides() + set(ControlId.GCPAD_DPAD_LEFT, if (x < -0.5f) 1.0 else 0.0) + set(ControlId.GCPAD_DPAD_RIGHT, if (x > 0.5f) 1.0 else 0.0) + set(ControlId.GCPAD_DPAD_UP, if (y < -0.5f) 1.0 else 0.0) + set(ControlId.GCPAD_DPAD_DOWN, if (y > 0.5f) 1.0 else 0.0) + set(ControlId.WIIMOTE_DPAD_LEFT, if (x < -0.5f) 1.0 else 0.0) + set(ControlId.WIIMOTE_DPAD_RIGHT, if (x > 0.5f) 1.0 else 0.0) + set(ControlId.WIIMOTE_DPAD_UP, if (y < -0.5f) 1.0 else 0.0) + set(ControlId.WIIMOTE_DPAD_DOWN, if (y > 0.5f) 1.0 else 0.0) + } + + val emulationRunning: Boolean + get() = emulationStarted && NativeLibrary.IsRunning() + + fun pauseGame() { + if (emulationRunning && NativeLibrary.IsRunningAndUnpaused()) NativeLibrary.PauseEmulation() + } + + fun resumeGame() { + if (emulationRunning && !NativeLibrary.IsRunningAndUnpaused()) NativeLibrary.UnPauseEmulation() + } + + val gamePaused: Boolean + get() = emulationRunning && !NativeLibrary.IsRunningAndUnpaused() + + fun saveStateSlot(slot: Int) { + if (emulationRunning) NativeLibrary.SaveState(slot, false) + } + + fun loadStateSlot(slot: Int) { + if (emulationRunning) NativeLibrary.LoadState(slot) + } + + fun stateSlotTime(slot: Int): Long = + if (emulationRunning) runCatching { NativeLibrary.GetUnixTimeOfStateSlot(slot) }.getOrDefault(0L) else 0L + + fun stopGame() { + teardown() + } + + fun pressWiiHome() { + registerInputOverrides() + if (!overridesRegistered) return + set(ControlId.WIIMOTE_HOME_BUTTON, 1.0) + window.decorView.postDelayed({ set(ControlId.WIIMOTE_HOME_BUTTON, 0.0) }, 120) + } + + fun applyVariable(key: String, value: String) { + val merged = currentVariables.toMutableMap() + merged[key] = value + currentVariables = merged + thread(name = "WnDolphinApply") { + runCatching { + DolphinConfigWriter.write(DirectoryInitialization.userDir(this), merged) + NativeLibrary.ReloadConfig() + applySysconf(merged) + }.onFailure { Log.w(TAG, "applyVariable failed: $it") } + } + } + + fun setSurfaceBounds(bounds: android.graphics.RectF?) { + if (surfaceLive && customDriverActive) return + runOnUiThread { + val view = surfaceView ?: return@runOnUiThread + val lp = view.layoutParams as? android.widget.FrameLayout.LayoutParams ?: return@runOnUiThread + if (bounds == null) { + lp.width = android.widget.FrameLayout.LayoutParams.MATCH_PARENT + lp.height = android.widget.FrameLayout.LayoutParams.MATCH_PARENT + lp.leftMargin = 0 + lp.topMargin = 0 + } else { + lp.width = bounds.width().toInt() + lp.height = bounds.height().toInt() + lp.leftMargin = bounds.left.toInt() + lp.topMargin = bounds.top.toInt() + } + view.layoutParams = lp + } + } + + override fun surfaceCreated(holder: SurfaceHolder) { + surfaceLive = true + } + + override fun surfaceChanged( + holder: SurfaceHolder, + format: Int, + width: Int, + height: Int, + ) { + Log.i(TAG, "surfaceChanged ${width}x$height") + NativeLibrary.SurfaceChanged(holder.surface) + } + + override fun surfaceDestroyed(holder: SurfaceHolder) { + Log.i(TAG, "surfaceDestroyed") + NativeLibrary.SurfaceDestroyed() + } + + override fun onResume() { + super.onResume() + if (emulationStarted && !stopping && NativeLibrary.IsRunning()) { + NativeLibrary.UnPauseEmulation() + } + } + + override fun onPause() { + super.onPause() + if (emulationStarted && !stopping && NativeLibrary.IsRunningAndUnpaused()) { + NativeLibrary.PauseEmulation() + } + } + + override fun onDestroy() { + unregisterInputOverrides() + if (isFinishing && bootedInProcess) { + teardown() + } + NativeLibrary.host = null + super.onDestroy() + } + + override fun onToast(message: String, long: Boolean) { + Log.i(TAG, "toast: $message") + runOnUiThread { + Toast.makeText(this, message, if (long) Toast.LENGTH_LONG else Toast.LENGTH_SHORT).show() + } + } + + override fun onAlert( + caption: String, + text: String, + yesNo: Boolean, + isWarning: Boolean, + nonBlocking: Boolean, + ): Boolean { + Log.w(TAG, "alert [$caption] $text") + return true + } + + override fun onUpdateTouchPointer() {} + + override fun onTitleChanged() { + Log.i(TAG, "title: " + runCatching { NativeLibrary.GetCurrentTitleDescriptionUnchecked() }.getOrDefault("")) + runCatching { NativeLibrary.GetCurrentGameIDUnchecked() } + .getOrNull() + ?.takeIf { it.isNotBlank() } + ?.let { currentGameId = it } + runOnUiThread { registerInputOverrides() } + } + + override fun onEmulationFinished() { + Log.i(TAG, "emulation finished") + runOnUiThread { if (!isFinishing) finish() } + } +} diff --git a/dolphin/src/main/java/org/dolphinemu/dolphinemu/wn/DolphinHost.kt b/dolphin/src/main/java/org/dolphinemu/dolphinemu/wn/DolphinHost.kt new file mode 100644 index 000000000..5ddc1255e --- /dev/null +++ b/dolphin/src/main/java/org/dolphinemu/dolphinemu/wn/DolphinHost.kt @@ -0,0 +1,14 @@ +package org.dolphinemu.dolphinemu.wn + +import android.app.Activity + +object DolphinHost { + @Volatile + var attachOverlay: ((Activity) -> Unit)? = null + + @Volatile + var onStageSaves: ((Activity) -> Unit)? = null + + @Volatile + var onNetplayStatus: ((hosting: Boolean, hostCode: String?, members: List) -> Unit)? = null +} diff --git a/dolphin/src/main/java/org/dolphinemu/dolphinemu/wn/DolphinNetplay.kt b/dolphin/src/main/java/org/dolphinemu/dolphinemu/wn/DolphinNetplay.kt new file mode 100644 index 000000000..c7e0e30b3 --- /dev/null +++ b/dolphin/src/main/java/org/dolphinemu/dolphinemu/wn/DolphinNetplay.kt @@ -0,0 +1,215 @@ +package org.dolphinemu.dolphinemu.wn + +import android.content.Intent +import android.util.Log +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeoutOrNull +import java.util.concurrent.atomic.AtomicInteger +import org.dolphinemu.dolphinemu.NativeLibrary +import org.dolphinemu.dolphinemu.features.netplay.NetplaySession +import org.dolphinemu.dolphinemu.features.netplay.model.TraversalState +import org.dolphinemu.dolphinemu.features.settings.model.BooleanSetting +import org.dolphinemu.dolphinemu.features.settings.model.IntSetting +import org.dolphinemu.dolphinemu.features.settings.model.NativeConfig +import org.dolphinemu.dolphinemu.features.settings.model.StringSetting +import org.dolphinemu.dolphinemu.model.GameFile + +object DolphinNetplay { + private const val TAG = "WnDolphinNet" + + const val EXTRA_ENABLE = "dolphin_np_enable" + const val EXTRA_HOST = "dolphin_np_host" + const val EXTRA_TRAVERSAL = "dolphin_np_traversal" + const val EXTRA_ADDRESS = "dolphin_np_address" + const val EXTRA_HOST_CODE = "dolphin_np_host_code" + const val EXTRA_PORT = "dolphin_np_port" + const val EXTRA_NICKNAME = "dolphin_np_nickname" + + const val DEFAULT_PORT = 2626 + + data class Config( + val host: Boolean, + val traversal: Boolean, + val address: String, + val hostCode: String, + val port: Int, + val nickname: String, + ) + + fun fromIntent(intent: Intent): Config? { + if (!intent.getBooleanExtra(EXTRA_ENABLE, false)) return null + return Config( + host = intent.getBooleanExtra(EXTRA_HOST, true), + traversal = intent.getBooleanExtra(EXTRA_TRAVERSAL, false), + address = intent.getStringExtra(EXTRA_ADDRESS).orEmpty(), + hostCode = intent.getStringExtra(EXTRA_HOST_CODE).orEmpty(), + port = intent.getIntExtra(EXTRA_PORT, DEFAULT_PORT), + nickname = intent.getStringExtra(EXTRA_NICKNAME).orEmpty(), + ) + } + + @Volatile + private var session: NetplaySession? = null + + @Volatile + private var scope: CoroutineScope? = null + + @Volatile + private var hostCode: String? = null + + @Volatile + private var members: List = emptyList() + + val active: Boolean + get() = session != null + + private fun pushStatus() { + DolphinHost.onNetplayStatus?.invoke(session != null, hostCode, members) + } + + private fun applyConfig(cfg: Config) { + val base = NativeConfig.LAYER_BASE + StringSetting.NETPLAY_NICKNAME.setString(base, cfg.nickname.ifBlank { "Player" }) + StringSetting.NETPLAY_TRAVERSAL_CHOICE.setString( + base, + if (cfg.traversal) "traversal" else "direct", + ) + if (cfg.host) { + IntSetting.NETPLAY_HOST_PORT.setInt(base, cfg.port) + BooleanSetting.NETPLAY_USE_UPNP.setBoolean(base, false) + } else if (cfg.traversal) { + StringSetting.NETPLAY_HOST_CODE.setString(base, cfg.hostCode.trim()) + } else { + StringSetting.NETPLAY_ADDRESS.setString(base, cfg.address.trim()) + IntSetting.NETPLAY_CONNECT_PORT.setInt(base, cfg.port) + } + } + + fun startAndAwaitBoot(host: NativeLibrary.WnHost?, romPath: String, cfg: Config): Long { + runCatching { applyConfig(cfg) } + .onFailure { Log.e(TAG, "applyConfig failed", it); return 0L } + + val gameFile = runCatching { GameFile.parse(romPath) }.getOrNull() + if (gameFile == null) { + Log.e(TAG, "GameFile.parse failed for $romPath") + host?.onToast("Netplay: unreadable game file", true) + return 0L + } + + val s = NetplaySession(arrayOf(gameFile)) { session = null } + session = s + val sc = CoroutineScope(SupervisorJob() + Dispatchers.IO) + scope = sc + hostCode = null + members = emptyList() + pushStatus() + + val bootData = CompletableDeferred() + + s.players + .onEach { players -> + members = players.map { it.name } + pushStatus() + } + .launchIn(sc) + + s.launchGame + .onEach { + Log.i(TAG, "netplay boot ready ($it)") + if (!bootData.isCompleted) bootData.complete(s.consumeBootSessionData()) + } + .launchIn(sc) + + s.connectionErrors + .onEach { msg -> + Log.w(TAG, "netplay error: $msg") + host?.onToast("Netplay: $msg", true) + } + .launchIn(sc) + + s.connectionLost + .onEach { + host?.onToast("Netplay connection lost", true) + if (!bootData.isCompleted) bootData.complete(0L) + } + .launchIn(sc) + + if (cfg.host && cfg.traversal) { + s.traversalState + .onEach { state -> + if (state is TraversalState.Connected) { + Log.i(TAG, "traversal host code: ${state.hostCode}") + hostCode = state.hostCode + pushStatus() + } + } + .launchIn(sc) + } + + sc.launch { + val ok = runCatching { if (cfg.host) s.host() else s.join() }.getOrDefault(false) + if (!ok) { + host?.onToast( + if (cfg.host) "Netplay: could not host" else "Netplay: could not connect", + true, + ) + if (!bootData.isCompleted) bootData.complete(0L) + return@launch + } + if (cfg.host) { + host?.onToast("Waiting for player…", false) + runCatching { s.changeGame(gameFile) } + val playerCount = AtomicInteger(1) + val tracker = s.players.onEach { playerCount.set(it.size) }.launchIn(sc) + withTimeoutOrNull(120_000L) { + var announced = false + while (isActive) { + if (playerCount.get() >= 2) { + if (!announced) { + announced = true + host?.onToast("Player connected — verifying game…", false) + } + if (runCatching { s.doAllPlayersHaveGame() }.getOrDefault(false)) { + host?.onToast("Starting…", false) + runCatching { s.startGame() } + return@withTimeoutOrNull + } + } + delay(1_000L) + } + } + tracker.cancel() + } + } + + val result = runBlocking { + withTimeoutOrNull(180_000L) { bootData.await() } ?: 0L + } + if (result == 0L) { + host?.onToast("Netplay: no game started", true) + stop() + } + return result + } + + fun stop() { + val s = session + session = null + runCatching { runBlocking { s?.close() } } + scope?.cancel() + scope = null + hostCode = null + members = emptyList() + pushStatus() + } +} diff --git a/dolphin/src/main/res/values/dolphin_strings.xml b/dolphin/src/main/res/values/dolphin_strings.xml new file mode 100644 index 000000000..056673959 --- /dev/null +++ b/dolphin/src/main/res/values/dolphin_strings.xml @@ -0,0 +1,10 @@ + + + Buffer size changed to %1$d + Possible desync detected: %1$s might have desynced at frame %2$d + Game changed to %1$s + "Host input authority %1$s" + Couldn\'t look up central server + Dolphin is too old for traversal server + GameCube Adapter couldn\'t be opened. Please re-plug the device. + diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/ARCheat.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/ARCheat.kt new file mode 100644 index 000000000..7d3013ee3 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/ARCheat.kt @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.cheats.model + +import androidx.annotation.Keep + +class ARCheat : AbstractCheat { + @Keep + private val pointer: Long + + constructor() { + pointer = createNew() + } + + @Keep + private constructor(pointer: Long) { + this.pointer = pointer + } + + external fun finalize() + + private external fun createNew(): Long + + override fun supportsCreator(): Boolean = false + + override fun supportsNotes(): Boolean = false + + external override fun getName(): String + + external override fun getCode(): String + + external override fun getUserDefined(): Boolean + + external override fun getEnabled(): Boolean + + external override fun setEnabledImpl(enabled: Boolean) + + external override fun setCheatImpl( + name: String, + creator: String, + notes: String, + code: String + ): Int + + companion object { + @JvmStatic + external fun loadCodes(gameId: String, revision: Int): Array + + @JvmStatic + external fun saveCodes(gameId: String, revision: Int, codes: Array) + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/AbstractCheat.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/AbstractCheat.kt new file mode 100644 index 000000000..d9e17ffd4 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/AbstractCheat.kt @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.cheats.model + +import org.dolphinemu.dolphinemu.features.cheats.model.Cheat.Companion.TRY_SET_FAIL_NO_NAME +import org.dolphinemu.dolphinemu.features.cheats.model.Cheat.Companion.TRY_SET_SUCCESS + +abstract class AbstractCheat : ReadOnlyCheat() { + override fun supportsCode(): Boolean { + return true + } + + override fun setCheat( + name: String, + creator: String, + notes: String, + code: String + ): Int { + var finalName = name + var finalCode = code + if (finalCode.isNotEmpty() && finalCode[0] == '$') { + val firstLineEnd = finalCode.indexOf('\n') + if (firstLineEnd == -1) { + finalName = finalCode.substring(1) + finalCode = "" + } else { + finalName = finalCode.substring(1, firstLineEnd) + finalCode = finalCode.substring(firstLineEnd + 1) + } + } + + if (finalName.isEmpty()) return TRY_SET_FAIL_NO_NAME + + val result = setCheatImpl(finalName, creator, notes, finalCode) + + if (result == TRY_SET_SUCCESS) onChanged() + + return result + } + + protected abstract fun setCheatImpl( + name: String, + creator: String, + notes: String, + code: String + ): Int +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/Cheat.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/Cheat.kt new file mode 100644 index 000000000..848acf3ea --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/Cheat.kt @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.cheats.model + +interface Cheat { + fun supportsCreator(): Boolean + + fun supportsNotes(): Boolean + + fun supportsCode(): Boolean + + fun getName(): String = "" + + fun getCreator(): String = "" + + fun getNotes(): String = "" + + fun getCode(): String = "" + + fun setCheat( + name: String, + creator: String, + notes: String, + code: String + ): Int + + fun getUserDefined(): Boolean + + fun getEnabled(): Boolean + + fun setEnabled(isChecked: Boolean) + + fun setChangedCallback(callback: Runnable?) + + companion object { + // Result codes greater than 0 represent an error on the corresponding code line (one-indexed) + const val TRY_SET_FAIL_CODE_MIXED_ENCRYPTION = -3 + const val TRY_SET_FAIL_NO_CODE_LINES = -2 + const val TRY_SET_FAIL_NO_NAME = -1 + const val TRY_SET_SUCCESS = 0 + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/CheatsViewModel.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/CheatsViewModel.kt new file mode 100644 index 000000000..e2d52bbc7 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/CheatsViewModel.kt @@ -0,0 +1,207 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.cheats.model + +import androidx.lifecycle.LiveData +import androidx.lifecycle.MutableLiveData +import androidx.lifecycle.ViewModel +import org.dolphinemu.dolphinemu.features.cheats.model.ARCheat.Companion.loadCodes +import org.dolphinemu.dolphinemu.features.cheats.model.ARCheat.Companion.saveCodes +import kotlin.collections.ArrayList + +class CheatsViewModel : ViewModel() { + private var loaded = false + + private var selectedCheatPosition = -1 + private val _selectedCheat = MutableLiveData(null) + val selectedCheat: LiveData get() = _selectedCheat + private val _isAdding = MutableLiveData(false) + val isAdding: LiveData get() = _isAdding + private val _isEditing = MutableLiveData(false) + val isEditing: LiveData get() = _isEditing + + private val _cheatAddedEvent = MutableLiveData(null) + val cheatAddedEvent: LiveData get() = _cheatAddedEvent + private val _cheatChangedEvent = MutableLiveData(null) + val cheatChangedEvent: LiveData get() = _cheatChangedEvent + private val _cheatDeletedEvent = MutableLiveData(null) + val cheatDeletedEvent: LiveData get() = _cheatDeletedEvent + private val _geckoCheatsDownloadedEvent = MutableLiveData(null) + val geckoCheatsDownloadedEvent: LiveData get() = _geckoCheatsDownloadedEvent + private val _openDetailsViewEvent = MutableLiveData(false) + val openDetailsViewEvent: LiveData get() = _openDetailsViewEvent + + private var graphicsModGroup: GraphicsModGroup? = null + var graphicsMods: ArrayList = ArrayList() + var patchCheats: ArrayList = ArrayList() + var aRCheats: ArrayList = ArrayList() + var geckoCheats: ArrayList = ArrayList() + + private var graphicsModsNeedSaving = false + private var patchCheatsNeedSaving = false + private var aRCheatsNeedSaving = false + private var geckoCheatsNeedSaving = false + + fun load(gameID: String, revision: Int) { + if (loaded) return + + graphicsModGroup = GraphicsModGroup.load(gameID) + graphicsMods.addAll(graphicsModGroup!!.mods) + patchCheats.addAll(PatchCheat.loadCodes(gameID, revision)) + aRCheats.addAll(loadCodes(gameID, revision)) + geckoCheats.addAll(GeckoCheat.loadCodes(gameID, revision)) + + for (mod in graphicsMods) { + mod.setChangedCallback { graphicsModsNeedSaving = true } + } + for (cheat in patchCheats) { + cheat.setChangedCallback { patchCheatsNeedSaving = true } + } + for (cheat in aRCheats) { + cheat.setChangedCallback { aRCheatsNeedSaving = true } + } + for (cheat in geckoCheats) { + cheat.setChangedCallback { geckoCheatsNeedSaving = true } + } + + loaded = true + } + + fun saveIfNeeded(gameID: String, revision: Int) { + if (graphicsModsNeedSaving) { + graphicsModGroup!!.save() + graphicsModsNeedSaving = false + } + + if (patchCheatsNeedSaving) { + PatchCheat.saveCodes(gameID, revision, patchCheats.toTypedArray()) + patchCheatsNeedSaving = false + } + + if (aRCheatsNeedSaving) { + saveCodes(gameID, revision, aRCheats.toTypedArray()) + aRCheatsNeedSaving = false + } + + if (geckoCheatsNeedSaving) { + GeckoCheat.saveCodes(gameID, revision, geckoCheats.toTypedArray()) + geckoCheatsNeedSaving = false + } + } + + fun setSelectedCheat(cheat: Cheat?, position: Int) { + if (isEditing.value!!) setIsEditing(false) + + _selectedCheat.value = cheat + selectedCheatPosition = position + } + + fun startAddingCheat(cheat: Cheat?, position: Int) { + _selectedCheat.value = cheat + selectedCheatPosition = position + + _isAdding.value = true + _isEditing.value = true + } + + fun finishAddingCheat() { + check(isAdding.value!!) + + _isAdding.value = false + _isEditing.value = false + + when (val cheat = selectedCheat.value) { + is PatchCheat -> { + patchCheats.add(cheat) + cheat.setChangedCallback(Runnable { patchCheatsNeedSaving = true }) + patchCheatsNeedSaving = true + } + is ARCheat -> { + aRCheats.add(cheat) + cheat.setChangedCallback(Runnable { patchCheatsNeedSaving = true }) + aRCheatsNeedSaving = true + } + is GeckoCheat -> { + geckoCheats.add(cheat) + cheat.setChangedCallback(Runnable { geckoCheatsNeedSaving = true }) + geckoCheatsNeedSaving = true + } + else -> throw UnsupportedOperationException() + } + + notifyCheatAdded() + } + + fun setIsEditing(isEditing: Boolean) { + _isEditing.value = isEditing + if (isAdding.value!! && !isEditing) { + _isAdding.value = false + setSelectedCheat(null, -1) + } + } + + private fun notifyCheatAdded() { + _cheatAddedEvent.value = selectedCheatPosition + _cheatAddedEvent.value = null + } + + /** + * Notifies that an edit has been made to the contents of the currently selected cheat. + */ + fun notifySelectedCheatChanged() { + notifyCheatChanged(selectedCheatPosition) + } + + /** + * Notifies that an edit has been made to the contents of the cheat at the given position. + */ + private fun notifyCheatChanged(position: Int) { + _cheatChangedEvent.value = position + _cheatChangedEvent.value = null + } + + fun deleteSelectedCheat() { + val cheat = selectedCheat.value + val position = selectedCheatPosition + + setSelectedCheat(null, -1) + + if (patchCheats.remove(cheat)) patchCheatsNeedSaving = true + if (aRCheats.remove(cheat)) aRCheatsNeedSaving = true + if (geckoCheats.remove(cheat)) geckoCheatsNeedSaving = true + + notifyCheatDeleted(position) + } + + /** + * Notifies that the cheat at the given position has been deleted. + */ + private fun notifyCheatDeleted(position: Int) { + _cheatDeletedEvent.value = position + _cheatDeletedEvent.value = null + } + + fun addDownloadedGeckoCodes(cheats: Array): Int { + var cheatsAdded = 0 + + for (cheat in cheats) { + if (!geckoCheats.contains(cheat)) { + geckoCheats.add(cheat) + cheatsAdded++ + } + } + + if (cheatsAdded != 0) { + geckoCheatsNeedSaving = true + _geckoCheatsDownloadedEvent.value = cheatsAdded + _geckoCheatsDownloadedEvent.value = null + } + + return cheatsAdded + } + + fun openDetailsView() { + _openDetailsViewEvent.value = true + _openDetailsViewEvent.value = false + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/GeckoCheat.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/GeckoCheat.kt new file mode 100644 index 000000000..7a2306654 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/GeckoCheat.kt @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +package org.dolphinemu.dolphinemu.features.cheats.model + +import androidx.annotation.Keep + +class GeckoCheat : AbstractCheat { + @Keep + private val mPointer: Long + + constructor() { + mPointer = createNew() + } + + @Keep + private constructor(pointer: Long) { + mPointer = pointer + } + + external fun finalize() + + private external fun createNew(): Long + + override fun equals(other: Any?): Boolean { + return other != null && javaClass == other.javaClass && equalsImpl(other as GeckoCheat) + } + + override fun hashCode(): Int { + return mPointer.hashCode() + } + + override fun supportsCreator(): Boolean { + return true + } + + override fun supportsNotes(): Boolean { + return true + } + + external override fun getName(): String + + external override fun getCreator(): String + + external override fun getNotes(): String + + external override fun getCode(): String + + external override fun getUserDefined(): Boolean + + external override fun getEnabled(): Boolean + + private external fun equalsImpl(other: GeckoCheat): Boolean + + external override fun setCheatImpl( + name: String, + creator: String, + notes: String, + code: String + ): Int + + external override fun setEnabledImpl(enabled: Boolean) + + companion object { + @JvmStatic + external fun loadCodes(gameId: String, revision: Int): Array + + @JvmStatic + external fun saveCodes(gameId: String, revision: Int, codes: Array) + + @JvmStatic + external fun downloadCodes(gameTdbId: String): Array? + } +} \ No newline at end of file diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/GraphicsMod.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/GraphicsMod.kt new file mode 100644 index 000000000..3ea8c23e4 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/GraphicsMod.kt @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.cheats.model + +import androidx.annotation.Keep + +class GraphicsMod @Keep private constructor( + @Keep private val pointer: Long, + // When a C++ GraphicsModGroup object is destroyed, it also destroys the GraphicsMods it owns. + // To avoid getting dangling pointers, we keep a reference to the GraphicsModGroup here. + @Keep private val parent: GraphicsModGroup +) : ReadOnlyCheat() { + override fun supportsCreator(): Boolean = true + + override fun supportsNotes(): Boolean = true + + override fun supportsCode(): Boolean = false + + external override fun getName(): String + + external override fun getCreator(): String + + external override fun getNotes(): String + + // Technically graphics mods can be user defined, but we don't support editing graphics mods + // in the GUI, and editability is what this really controls + override fun getUserDefined(): Boolean = false + + external override fun getEnabled(): Boolean + + external override fun setEnabledImpl(enabled: Boolean) +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/GraphicsModGroup.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/GraphicsModGroup.kt new file mode 100644 index 000000000..5d9b8b221 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/GraphicsModGroup.kt @@ -0,0 +1,17 @@ +package org.dolphinemu.dolphinemu.features.cheats.model + +import androidx.annotation.Keep + +class GraphicsModGroup @Keep private constructor(@field:Keep private val pointer: Long) { + external fun finalize() + + val mods: Array + external get + + external fun save() + + companion object { + @JvmStatic + external fun load(gameId: String): GraphicsModGroup + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/PatchCheat.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/PatchCheat.kt new file mode 100644 index 000000000..f4cd9660a --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/PatchCheat.kt @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.cheats.model + +import androidx.annotation.Keep + +class PatchCheat : AbstractCheat { + @Keep + private val pointer: Long + + constructor() { + pointer = createNew() + } + + @Keep + private constructor(pointer: Long) { + this.pointer = pointer + } + + external fun finalize() + + private external fun createNew(): Long + + override fun supportsCreator(): Boolean { + return false + } + + override fun supportsNotes(): Boolean { + return false + } + + external override fun getName(): String + + external override fun getCode(): String + + external override fun getUserDefined(): Boolean + + external override fun getEnabled(): Boolean + + external override fun setCheatImpl( + name: String, + creator: String, + notes: String, + code: String + ): Int + + external override fun setEnabledImpl(enabled: Boolean) + + companion object { + @JvmStatic + external fun loadCodes(gameId: String, revision: Int): Array + + @JvmStatic + external fun saveCodes(gameId: String, revision: Int, codes: Array) + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/ReadOnlyCheat.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/ReadOnlyCheat.kt new file mode 100644 index 000000000..542a40779 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/cheats/model/ReadOnlyCheat.kt @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.cheats.model + +abstract class ReadOnlyCheat : Cheat { + private var onChangedCallback: Runnable? = null + + override fun setCheat( + name: String, + creator: String, + notes: String, + code: String + ): Int { + throw UnsupportedOperationException() + } + + override fun setEnabled(isChecked: Boolean) { + setEnabledImpl(isChecked) + onChanged() + } + + override fun setChangedCallback(callback: Runnable?) { + onChangedCallback = callback + } + + protected fun onChanged() { + if (onChangedCallback != null) onChangedCallback!!.run() + } + + protected abstract fun setEnabledImpl(enabled: Boolean) +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/infinitybase/InfinityConfig.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/infinitybase/InfinityConfig.kt new file mode 100644 index 000000000..0e2e54acb --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/infinitybase/InfinityConfig.kt @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.infinitybase + +object InfinityConfig { + var LIST_FIGURES: Map = getFigureMap() + var REVERSE_LIST_FIGURES: Map = getInverseFigureMap() + + private external fun getFigureMap(): Map + private external fun getInverseFigureMap(): Map + + @JvmStatic + external fun removeFigure(position: Int) + + @JvmStatic + external fun loadFigure(position: Int, fileName: String): String? + + @JvmStatic + external fun createFigure( + figureNumber: Long, + fileName: String, + position: Int + ): String? +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/infinitybase/model/Figure.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/infinitybase/model/Figure.kt new file mode 100644 index 000000000..b65b978e3 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/infinitybase/model/Figure.kt @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.infinitybase.model + +data class Figure(var number: Long, var name: String) { + + companion object { + @JvmField + val BLANK_FIGURE = Figure(-1, "Blank") + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/ControlGroupEnabledSetting.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/ControlGroupEnabledSetting.kt new file mode 100644 index 000000000..43c983cc4 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/ControlGroupEnabledSetting.kt @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.input.model + +import org.dolphinemu.dolphinemu.features.input.model.controlleremu.ControlGroup +import org.dolphinemu.dolphinemu.features.settings.model.AbstractBooleanSetting +import org.dolphinemu.dolphinemu.features.settings.model.Settings + +class ControlGroupEnabledSetting(private val controlGroup: ControlGroup) : AbstractBooleanSetting { + override val boolean: Boolean + get() = controlGroup.getEnabled() + + override fun setBoolean(settings: Settings, newValue: Boolean) = + controlGroup.setEnabled(newValue) + + override val isOverridden: Boolean = false + + override val isRuntimeEditable: Boolean = true + + override fun delete(settings: Settings): Boolean { + val newValue = controlGroup.getDefaultEnabledValue() != ControlGroup.DEFAULT_ENABLED_NO + controlGroup.setEnabled(newValue) + return true + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/ControllerInterface.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/ControllerInterface.kt new file mode 100644 index 000000000..b412b6ef9 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/ControllerInterface.kt @@ -0,0 +1,214 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.input.model + +import android.content.Context +import android.hardware.input.InputManager +import android.media.AudioAttributes +import android.os.Build +import android.os.Handler +import android.os.HandlerThread +import android.os.Looper +import android.os.VibrationAttributes +import android.os.VibrationEffect +import android.os.Vibrator +import android.os.VibratorManager +import android.view.InputDevice +import android.view.KeyEvent +import android.view.MotionEvent +import androidx.annotation.Keep +import androidx.lifecycle.LiveData +import androidx.lifecycle.MutableLiveData +import org.dolphinemu.dolphinemu.DolphinApplication +import java.util.concurrent.atomic.AtomicBoolean + +/** + * This class interfaces with the native ControllerInterface, + * which is where the emulator core gets inputs from. + */ +object ControllerInterface { + private var inputDeviceListener: InputDeviceListener? = null + private var handlerThread: HandlerThread? = null + + private val inputStateUpdatePending = AtomicBoolean(false) + private val inputStateVersion = MutableLiveData(0) + private val devicesVersion = MutableLiveData(0) + + val inputStateChanged: LiveData + get() = inputStateVersion + + val devicesChanged: LiveData + get() = devicesVersion + + /** + * Activities which want to pass on inputs to native code + * should call this in their own dispatchKeyEvent method. + * + * @return true if the emulator core seems to be interested in this event. + * false if the event should be passed on to the default dispatchKeyEvent. + */ + fun dispatchKeyEvent(event: KeyEvent): Boolean { + val result = dispatchKeyEventNative(event) + onInputStateChanged() + return result + } + + private external fun dispatchKeyEventNative(event: KeyEvent): Boolean + + /** + * Activities which want to pass on inputs to native code + * should call this in their own dispatchGenericMotionEvent method. + * + * @return true if the emulator core seems to be interested in this event. + * false if the event should be passed on to the default dispatchGenericMotionEvent. + */ + fun dispatchGenericMotionEvent(event: MotionEvent): Boolean { + val result = dispatchGenericMotionEventNative(event) + onInputStateChanged() + return result + } + + private external fun dispatchGenericMotionEventNative(event: MotionEvent): Boolean + + /** + * [DolphinSensorEventListener] calls this for each axis of a received SensorEvent. + * + * @return true if the emulator core seems to be interested in this event. + * false if the sensor can be suspended to save battery. + */ + fun dispatchSensorEvent(deviceQualifier: String, axisName: String, value: Float): Boolean { + val result = dispatchSensorEventNative(deviceQualifier, axisName, value) + onInputStateChanged() + return result + } + + private external fun dispatchSensorEventNative( + deviceQualifier: String, axisName: String, value: Float + ): Boolean + + /** + * Called when a sensor is suspended or unsuspended. + * + * @param deviceQualifier A string used by native code for uniquely identifying devices. + * @param axisNames The name of all axes for the sensor. + * @param suspended Whether the sensor is now suspended. + */ + external fun notifySensorSuspendedState( + deviceQualifier: String, axisNames: Array, suspended: Boolean + ) + + external fun getAllDeviceStrings(): Array + + external fun getDevice(deviceString: String): CoreDevice? + + private fun onInputStateChanged() { + // When a single SensorEvent is dispatched, this method is likely to get called many times. + // For the sake of performance, let's batch input state updates so that observers only have + // to process one update. + if (!inputStateUpdatePending.getAndSet(true)) { + Handler(Looper.getMainLooper()).post { + if (inputStateUpdatePending.getAndSet(false)) { + inputStateVersion.value = inputStateVersion.value?.plus(1) + } + } + } + } + + @Keep + @JvmStatic + private fun onDevicesChanged() { + Handler(Looper.getMainLooper()).post { + devicesVersion.value = devicesVersion.value?.plus(1) + } + } + + @Keep + @JvmStatic + private fun registerInputDeviceListener() { + if (inputDeviceListener == null) { + handlerThread = HandlerThread("Hotplug thread").apply { start() } + val thread = requireNotNull(handlerThread) { "HandlerThread is not available" } + + val im = DolphinApplication.getAppContext() + .getSystemService(Context.INPUT_SERVICE) as InputManager + val looper = requireNotNull(thread.looper) { + "HandlerThread looper is not available" + } + + inputDeviceListener = InputDeviceListener() + im.registerInputDeviceListener(inputDeviceListener, Handler(looper)) + } + } + + @Keep + @JvmStatic + private fun unregisterInputDeviceListener() { + if (inputDeviceListener != null) { + val im = DolphinApplication.getAppContext() + .getSystemService(Context.INPUT_SERVICE) as InputManager + + im.unregisterInputDeviceListener(inputDeviceListener) + inputDeviceListener = null + handlerThread?.quitSafely() + handlerThread = null + } + } + + @Keep + @JvmStatic + private fun getVibratorManager(device: InputDevice): DolphinVibratorManager { + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + DolphinVibratorManagerPassthrough(device.vibratorManager) + } else { + @Suppress("DEPRECATION") + DolphinVibratorManagerCompat(device.vibrator) + } + } + + @Keep + @JvmStatic + private fun getSystemVibratorManager(): DolphinVibratorManager { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + val vibratorManager = DolphinApplication.getAppContext() + .getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager? + if (vibratorManager != null) { + return DolphinVibratorManagerPassthrough(vibratorManager) + } + } + @Suppress("DEPRECATION") + val vibrator = DolphinApplication.getAppContext() + .getSystemService(Context.VIBRATOR_SERVICE) as Vibrator + return DolphinVibratorManagerCompat(vibrator) + } + + @Keep + @JvmStatic + private fun vibrate(vibrator: Vibrator) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + vibrator.vibrate( + VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE), + VibrationAttributes.Builder().setUsage(VibrationAttributes.USAGE_MEDIA).build() + ) + } else { + val attributes = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).build() + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + @Suppress("DEPRECATION") + vibrator.vibrate( + VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE), + attributes + ) + } else { + @Suppress("DEPRECATION") + vibrator.vibrate(100, attributes) + } + } + } + + private class InputDeviceListener : InputManager.InputDeviceListener { + override external fun onInputDeviceAdded(deviceId: Int) + + override external fun onInputDeviceRemoved(deviceId: Int) + + override external fun onInputDeviceChanged(deviceId: Int) + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/CoreDevice.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/CoreDevice.kt new file mode 100644 index 000000000..53f886412 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/CoreDevice.kt @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.input.model + +import androidx.annotation.Keep + +/** + * Represents a C++ ciface::Core::Device. + */ +@Keep +class CoreDevice private constructor(private val pointer: Long) { + /** + * Represents a C++ ciface::Core::Device::Control. + * + * This class is marked inner to ensure that the CoreDevice parent does not get garbage collected + * while a Control is still accessible. (CoreDevice's finalizer may delete the native controls.) + */ + @Keep + inner class Control private constructor(private val pointer: Long) { + external fun getName(): String + + external fun getState(): Double + } + + protected external fun finalize() + + external fun getInputs(): Array + + external fun getOutputs(): Array +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/DolphinSensorEventListener.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/DolphinSensorEventListener.kt new file mode 100644 index 000000000..6aa5ce2fc --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/DolphinSensorEventListener.kt @@ -0,0 +1,551 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.input.model + +import android.content.Context +import android.hardware.Sensor +import android.hardware.SensorEvent +import android.hardware.SensorEventListener +import android.hardware.SensorManager +import android.os.Build +import android.view.InputDevice +import android.view.Surface +import androidx.annotation.Keep +import org.dolphinemu.dolphinemu.DolphinApplication +import org.dolphinemu.dolphinemu.utils.Log +import java.util.Collections + +class DolphinSensorEventListener : SensorEventListener { + private class AxisSetDetails(val firstAxisOfSet: Int, val axisSetType: Int) + + private class SensorDetails( + val sensor: Sensor, + val sensorType: Int, + val axisNames: Array, + val axisSetDetails: Array + ) { + var isSuspended = true + var hasRegisteredListener = false + } + + private val sensorManager: SensorManager? + + private val sensorDetails = ArrayList() + + private val rotateCoordinatesForScreenOrientation: Boolean + + /** + * AOSP has a bug in InputDeviceSensorManager where + * InputSensorEventListenerDelegate.removeSensor attempts to modify an ArrayList it's iterating + * through in a way that throws a ConcurrentModificationException. Because of this, we can't + * suspend individual sensors for InputDevices, but we can suspend all sensors at once. + */ + private val canSuspendSensorsIndividually: Boolean + + private var unsuspendedSensors = 0 + + private var deviceQualifier = "" + + @Keep + constructor() { + sensorManager = DolphinApplication.getAppContext() + .getSystemService(Context.SENSOR_SERVICE) as SensorManager? + rotateCoordinatesForScreenOrientation = true + canSuspendSensorsIndividually = true + addSensors() + sortSensorDetails() + } + + @Keep + constructor(inputDevice: InputDevice) { + rotateCoordinatesForScreenOrientation = false + canSuspendSensorsIndividually = false + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + sensorManager = inputDevice.sensorManager + addSensors() + } else { + sensorManager = null + } + sortSensorDetails() + } + + private fun addSensors() { + tryAddSensor( + Sensor.TYPE_ACCELEROMETER, + arrayOf( + "Accel Right", + "Accel Left", + "Accel Forward", + "Accel Backward", + "Accel Up", + "Accel Down" + ), + arrayOf(AxisSetDetails(0, AXIS_SET_TYPE_DEVICE_COORDINATES)) + ) + + tryAddSensor( + Sensor.TYPE_GYROSCOPE, + arrayOf( + "Gyro Pitch Up", + "Gyro Pitch Down", + "Gyro Roll Right", + "Gyro Roll Left", + "Gyro Yaw Left", + "Gyro Yaw Right" + ), + arrayOf(AxisSetDetails(0, AXIS_SET_TYPE_DEVICE_COORDINATES)) + ) + + tryAddSensor(Sensor.TYPE_LIGHT, "Light") + + tryAddSensor(Sensor.TYPE_PRESSURE, "Pressure") + + tryAddSensor(Sensor.TYPE_TEMPERATURE, "Device Temperature") + + tryAddSensor(Sensor.TYPE_PROXIMITY, "Proximity") + + tryAddSensor( + Sensor.TYPE_GRAVITY, + arrayOf( + "Gravity Right", + "Gravity Left", + "Gravity Forward", + "Gravity Backward", + "Gravity Up", + "Gravity Down" + ), + arrayOf(AxisSetDetails(0, AXIS_SET_TYPE_DEVICE_COORDINATES)) + ) + + tryAddSensor( + Sensor.TYPE_LINEAR_ACCELERATION, + arrayOf( + "Linear Acceleration Right", + "Linear Acceleration Left", + "Linear Acceleration Forward", + "Linear Acceleration Backward", + "Linear Acceleration Up", + "Linear Acceleration Down" + ), + arrayOf(AxisSetDetails(0, AXIS_SET_TYPE_DEVICE_COORDINATES)) + ) + + // The values provided by this sensor can be interpreted as an Euler vector or a quaternion. + // The directions of X and Y are flipped to match the Wii Remote coordinate system. + tryAddSensor( + Sensor.TYPE_ROTATION_VECTOR, + arrayOf( + "Rotation Vector X-", + "Rotation Vector X+", + "Rotation Vector Y-", + "Rotation Vector Y+", + "Rotation Vector Z+", + "Rotation Vector Z-", + "Rotation Vector R", + "Rotation Vector Heading Accuracy" + ), + arrayOf(AxisSetDetails(0, AXIS_SET_TYPE_DEVICE_COORDINATES)) + ) + + tryAddSensor(Sensor.TYPE_RELATIVE_HUMIDITY, "Relative Humidity") + + tryAddSensor(Sensor.TYPE_AMBIENT_TEMPERATURE, "Ambient Temperature") + + // The values provided by this sensor can be interpreted as an Euler vector or a quaternion. + // The directions of X and Y are flipped to match the Wii Remote coordinate system. + tryAddSensor( + Sensor.TYPE_GAME_ROTATION_VECTOR, + arrayOf( + "Game Rotation Vector X-", + "Game Rotation Vector X+", + "Game Rotation Vector Y-", + "Game Rotation Vector Y+", + "Game Rotation Vector Z+", + "Game Rotation Vector Z-", + "Game Rotation Vector R" + ), + arrayOf(AxisSetDetails(0, AXIS_SET_TYPE_DEVICE_COORDINATES)) + ) + + tryAddSensor( + Sensor.TYPE_GYROSCOPE_UNCALIBRATED, + arrayOf( + "Gyro Uncalibrated Pitch Up", + "Gyro Uncalibrated Pitch Down", + "Gyro Uncalibrated Roll Right", + "Gyro Uncalibrated Roll Left", + "Gyro Uncalibrated Yaw Left", + "Gyro Uncalibrated Yaw Right", + "Gyro Drift Pitch Up", + "Gyro Drift Pitch Down", + "Gyro Drift Roll Right", + "Gyro Drift Roll Left", + "Gyro Drift Yaw Left", + "Gyro Drift Yaw Right" + ), + arrayOf( + AxisSetDetails(0, AXIS_SET_TYPE_DEVICE_COORDINATES), + AxisSetDetails(3, AXIS_SET_TYPE_DEVICE_COORDINATES) + ) + ) + + tryAddSensor(Sensor.TYPE_HEART_RATE, "Heart Rate") + + if (Build.VERSION.SDK_INT >= 24) { + tryAddSensor(Sensor.TYPE_HEART_BEAT, "Heart Beat") + } + + if (Build.VERSION.SDK_INT >= 26) { + tryAddSensor( + Sensor.TYPE_ACCELEROMETER_UNCALIBRATED, + arrayOf( + "Accel Uncalibrated Right", + "Accel Uncalibrated Left", + "Accel Uncalibrated Forward", + "Accel Uncalibrated Backward", + "Accel Uncalibrated Up", + "Accel Uncalibrated Down", + "Accel Bias Right", + "Accel Bias Left", + "Accel Bias Forward", + "Accel Bias Backward", + "Accel Bias Up", + "Accel Bias Down" + ), + arrayOf( + AxisSetDetails(0, AXIS_SET_TYPE_DEVICE_COORDINATES), + AxisSetDetails(3, AXIS_SET_TYPE_DEVICE_COORDINATES) + ) + ) + } + + if (Build.VERSION.SDK_INT >= 30) { + tryAddSensor(Sensor.TYPE_HINGE_ANGLE, "Hinge Angle") + } + + if (Build.VERSION.SDK_INT >= 33) { + // The values provided by this sensor can be interpreted as an Euler vector. + // The directions of X and Y are flipped to match the Wii Remote coordinate system. + tryAddSensor( + Sensor.TYPE_HEAD_TRACKER, + arrayOf( + "Head Rotation Vector X-", + "Head Rotation Vector X+", + "Head Rotation Vector Y-", + "Head Rotation Vector Y+", + "Head Rotation Vector Z+", + "Head Rotation Vector Z-", + "Head Pitch Up", + "Head Pitch Down", + "Head Roll Right", + "Head Roll Left", + "Head Yaw Left", + "Head Yaw Right" + ), + arrayOf( + AxisSetDetails(0, AXIS_SET_TYPE_OTHER_COORDINATES), + AxisSetDetails(3, AXIS_SET_TYPE_OTHER_COORDINATES) + ) + ) + + tryAddSensor(Sensor.TYPE_HEADING, arrayOf("Heading", "Heading Accuracy"), arrayOf()) + } + } + + private fun tryAddSensor(sensorType: Int, axisName: String) { + tryAddSensor(sensorType, arrayOf(axisName), arrayOf()) + } + + private fun tryAddSensor( + sensorType: Int, + axisNames: Array, + axisSetDetails: Array + ) { + val sensor = sensorManager!!.getDefaultSensor(sensorType) + if (sensor != null) { + sensorDetails.add(SensorDetails(sensor, sensorType, axisNames, axisSetDetails)) + } + } + + private fun sortSensorDetails() { + Collections.sort( + sensorDetails, + Comparator.comparingInt { s: SensorDetails -> s.sensorType } + ) + } + + override fun onSensorChanged(sensorEvent: SensorEvent) { + val sensorDetails = sensorDetails.first{s -> sensorsAreEqual(s.sensor, sensorEvent.sensor)} + + val values = sensorEvent.values + val axisNames = sensorDetails.axisNames + val axisSetDetails = sensorDetails.axisSetDetails + + var eventAxisIndex = 0 + var detailsAxisIndex = 0 + var detailsAxisSetIndex = 0 + var keepSensorAlive = false + while (eventAxisIndex < values.size && detailsAxisIndex < axisNames.size) { + if (detailsAxisSetIndex < axisSetDetails.size && + axisSetDetails[detailsAxisSetIndex].firstAxisOfSet == eventAxisIndex + ) { + var rotation = Surface.ROTATION_0 + if (rotateCoordinatesForScreenOrientation && + axisSetDetails[detailsAxisSetIndex].axisSetType == AXIS_SET_TYPE_DEVICE_COORDINATES + ) { + rotation = deviceRotation + } + + var x: Float + var y: Float + when (rotation) { + Surface.ROTATION_0 -> { + x = values[eventAxisIndex] + y = values[eventAxisIndex + 1] + } + + Surface.ROTATION_90 -> { + x = -values[eventAxisIndex + 1] + y = values[eventAxisIndex] + } + + Surface.ROTATION_180 -> { + x = -values[eventAxisIndex] + y = -values[eventAxisIndex + 1] + } + + Surface.ROTATION_270 -> { + x = values[eventAxisIndex + 1] + y = -values[eventAxisIndex] + } + + else -> { + x = values[eventAxisIndex] + y = values[eventAxisIndex + 1] + } + } + + val z = values[eventAxisIndex + 2] + + keepSensorAlive = keepSensorAlive or ControllerInterface.dispatchSensorEvent( + deviceQualifier, + axisNames[detailsAxisIndex], + x + ) + keepSensorAlive = keepSensorAlive or ControllerInterface.dispatchSensorEvent( + deviceQualifier, + axisNames[detailsAxisIndex + 1], + x + ) + keepSensorAlive = keepSensorAlive or ControllerInterface.dispatchSensorEvent( + deviceQualifier, + axisNames[detailsAxisIndex + 2], + y + ) + keepSensorAlive = keepSensorAlive or ControllerInterface.dispatchSensorEvent( + deviceQualifier, + axisNames[detailsAxisIndex + 3], + y + ) + keepSensorAlive = keepSensorAlive or ControllerInterface.dispatchSensorEvent( + deviceQualifier, + axisNames[detailsAxisIndex + 4], + z + ) + keepSensorAlive = keepSensorAlive or ControllerInterface.dispatchSensorEvent( + deviceQualifier, + axisNames[detailsAxisIndex + 5], + z + ) + + eventAxisIndex += 3 + detailsAxisIndex += 6 + detailsAxisSetIndex++ + } else { + keepSensorAlive = keepSensorAlive or ControllerInterface.dispatchSensorEvent( + deviceQualifier, + axisNames[detailsAxisIndex], values[eventAxisIndex] + ) + + eventAxisIndex++ + detailsAxisIndex++ + } + } + if (!keepSensorAlive) { + setSensorSuspended(sensorDetails, true) + } + } + + override fun onAccuracyChanged(sensor: Sensor, i: Int) { + // We don't care about this + } + + /** + * The device qualifier set here will be passed on to native code, + * for the purpose of letting native code identify which device this object belongs to. + */ + @Keep + fun setDeviceQualifier(deviceQualifier: String) { + this.deviceQualifier = deviceQualifier + } + + /** + * If a sensor has been suspended to save battery, this unsuspends it. + * If the sensor isn't currently suspended, nothing happens. + * + * @param axisName The name of any of the sensor's axes. + */ + @Keep + fun requestUnsuspendSensor(axisName: String) { + for (sd in sensorDetails) { + if (listOf(*sd.axisNames).contains(axisName)) { + setSensorSuspended(sd, false) + } + } + } + + private fun setSensorSuspended(sensorDetails: SensorDetails, suspend: Boolean) { + var changeOccurred = false + + synchronized(sensorDetails) { + if (sensorDetails.isSuspended != suspend) { + ControllerInterface.notifySensorSuspendedState( + deviceQualifier, + sensorDetails.axisNames, + suspend + ) + + if (suspend) { + unsuspendedSensors -= 1 + } else { + unsuspendedSensors += 1 + } + + if (canSuspendSensorsIndividually) { + if (suspend) { + sensorManager!!.unregisterListener(this, sensorDetails.sensor) + } else { + sensorManager!!.registerListener( + this, + sensorDetails.sensor, + SAMPLING_PERIOD_US + ) + } + sensorDetails.hasRegisteredListener = !suspend + } else { + if (suspend) { + // If there are no unsuspended sensors left, unregister them all. + // Otherwise, leave unregistering for later. A possible alternative could be + // to unregister everything and then re-register the sensors we still want, + // but I fear this could lead to dropped inputs. + if (unsuspendedSensors == 0) { + sensorManager!!.unregisterListener(this) + for (sd in this.sensorDetails) { + sd.hasRegisteredListener = false + } + } + } else { + if (!sensorDetails.hasRegisteredListener) { + sensorManager!!.registerListener( + this, + sensorDetails.sensor, + SAMPLING_PERIOD_US + ) + sensorDetails.hasRegisteredListener = true + } + } + } + + sensorDetails.isSuspended = suspend + + changeOccurred = true + } + } + + if (changeOccurred) { + Log.info((if (suspend) "Suspended sensor " else "Unsuspended sensor ") + sensorDetails.sensor.name) + } + } + + @Keep + fun getAxisNames(): Array { + val axisNames = ArrayList() + for (sensorDetails in sensorDetails) { + sensorDetails.axisNames.forEach { axisNames.add(it) } + } + return axisNames.toArray(arrayOf()) + } + + @Keep + fun getNegativeAxes(): BooleanArray { + val negativeAxes = ArrayList() + + for (sensorDetails in sensorDetails) { + var eventAxisIndex = 0 + var detailsAxisIndex = 0 + var detailsAxisSetIndex = 0 + while (detailsAxisIndex < sensorDetails.axisNames.size) { + if (detailsAxisSetIndex < sensorDetails.axisSetDetails.size && + sensorDetails.axisSetDetails[detailsAxisSetIndex].firstAxisOfSet == eventAxisIndex + ) { + negativeAxes.add(false) + negativeAxes.add(true) + negativeAxes.add(false) + negativeAxes.add(true) + negativeAxes.add(false) + negativeAxes.add(true) + + eventAxisIndex += 3 + detailsAxisIndex += 6 + detailsAxisSetIndex++ + } else { + negativeAxes.add(false) + + eventAxisIndex++ + detailsAxisIndex++ + } + } + } + + val result = BooleanArray(negativeAxes.size) + for (i in result.indices) { + result[i] = negativeAxes[i] + } + + return result + } + + companion object { + // Set of three axes. Creates a negative companion to each axis, and corrects for device rotation. + private const val AXIS_SET_TYPE_DEVICE_COORDINATES = 0 + + // Set of three axes. Creates a negative companion to each axis. + private const val AXIS_SET_TYPE_OTHER_COORDINATES = 1 + + private var deviceRotation = Surface.ROTATION_0 + + // The fastest sampling rate Android lets us use without declaring the HIGH_SAMPLING_RATE_SENSORS + // permission is 200 Hz. This is also the sampling rate of a Wii Remote, so it fits us perfectly. + private const val SAMPLING_PERIOD_US = 1000000 / 200 + + /** + * Should be called when an activity or other component that uses sensor events is resumed. + * + * Sensor events that contain device coordinates will have the coordinates rotated by the value + * passed to this function. + * + * @param deviceRotation The current rotation of the device (i.e. rotation of the default display) + */ + fun setDeviceRotation(deviceRotation: Int) { + this.deviceRotation = deviceRotation + } + + private fun sensorsAreEqual(s1: Sensor, s2: Sensor): Boolean { + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && s1.id > 0 && s2.id > 0) { + s1.type == s2.type && s1.id == s2.id + } else { + s1.type == s2.type && s1.name == s2.name + } + } + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/DolphinVibratorManager.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/DolphinVibratorManager.kt new file mode 100644 index 000000000..c3c6ba28d --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/DolphinVibratorManager.kt @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.input.model + +import android.os.Vibrator +import androidx.annotation.Keep + +/** + * A wrapper around [android.os.VibratorManager], for backwards compatibility. + */ +@Keep +interface DolphinVibratorManager { + fun getVibrator(vibratorId: Int): Vibrator + + fun getVibratorIds(): IntArray +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/DolphinVibratorManagerCompat.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/DolphinVibratorManagerCompat.kt new file mode 100644 index 000000000..039f0ecb6 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/DolphinVibratorManagerCompat.kt @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.input.model + +import android.os.Vibrator + +class DolphinVibratorManagerCompat(vibrator: Vibrator) : DolphinVibratorManager { + private val vibrator: Vibrator + private val vibratorIds: IntArray + + init { + this.vibrator = vibrator + vibratorIds = if (vibrator.hasVibrator()) intArrayOf(0) else intArrayOf() + } + + override fun getVibrator(vibratorId: Int): Vibrator { + if (vibratorId > vibratorIds.size) + throw IndexOutOfBoundsException() + + return vibrator + } + + override fun getVibratorIds(): IntArray = vibratorIds +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/DolphinVibratorManagerPassthrough.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/DolphinVibratorManagerPassthrough.kt new file mode 100644 index 000000000..089548431 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/DolphinVibratorManagerPassthrough.kt @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.input.model + +import android.os.Build +import android.os.Vibrator +import android.os.VibratorManager +import androidx.annotation.RequiresApi + +@RequiresApi(api = Build.VERSION_CODES.S) +class DolphinVibratorManagerPassthrough(private val vibratorManager: VibratorManager) : + DolphinVibratorManager { + override fun getVibrator(vibratorId: Int): Vibrator = vibratorManager.getVibrator(vibratorId) + + override fun getVibratorIds(): IntArray = vibratorManager.vibratorIds +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/InputDetector.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/InputDetector.kt new file mode 100644 index 000000000..e180814a5 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/InputDetector.kt @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.input.model + +import androidx.annotation.Keep + +/** + * Waits for the user to press inputs, and reports which inputs were pressed. + * + * The caller is responsible for forwarding input events from Android to ControllerInterface + * and then calling [update]. + */ +class InputDetector { + @Keep + private val pointer: Long + + constructor() { + pointer = createNew() + } + + @Keep + private constructor(pointer: Long) { + this.pointer = pointer + } + + external fun finalize() + + private external fun createNew(): Long + + /** + * Starts a detection session. + * + * @param defaultDevice The device to detect inputs from. + * @param allDevices Whether to also detect inputs from devices other than the specified one. + */ + external fun start(defaultDevice: String, allDevices: Boolean) + + /** + * Checks what inputs are currently pressed and updates internal state. + * + * During a detection session, this should be called after each call to + * [ControllerInterface.dispatchKeyEvent] and [ControllerInterface#dispatchGenericMotionEvent]. + */ + external fun update() + + /** + * Returns whether a detection session has finished. + * + * A detection session can end once the user has pressed and released an input or once a timeout + * has been reached. + */ + external fun isComplete(): Boolean + + /** + * Returns the result of a detection session. + * + * The result of each detection session is only returned once. If this method is called more + * than once without starting a new detection session, the second call onwards will return an + * empty string. + * + * @param defaultDevice The device to detect inputs from. Should normally be the same as the one + * passed to [start]. + * + * @return The input(s) pressed by the user in the form of an InputCommon expression, + * or an empty string if there were no inputs. + */ + external fun takeResults(defaultDevice: String): String +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/InputMappingBooleanSetting.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/InputMappingBooleanSetting.kt new file mode 100644 index 000000000..5771db54e --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/InputMappingBooleanSetting.kt @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.input.model + +import org.dolphinemu.dolphinemu.features.input.model.controlleremu.NumericSetting +import org.dolphinemu.dolphinemu.features.settings.model.AbstractBooleanSetting +import org.dolphinemu.dolphinemu.features.settings.model.Settings + +class InputMappingBooleanSetting(private val numericSetting: NumericSetting) : + AbstractBooleanSetting { + override val boolean: Boolean + get() = numericSetting.getBooleanValue() + + override fun setBoolean(settings: Settings, newValue: Boolean) = + numericSetting.setBooleanValue(newValue) + + override val isOverridden: Boolean = false + + override val isRuntimeEditable: Boolean = true + + override fun delete(settings: Settings): Boolean { + numericSetting.setBooleanValue(numericSetting.getBooleanDefaultValue()) + return true + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/InputMappingDoubleSetting.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/InputMappingDoubleSetting.kt new file mode 100644 index 000000000..e2da06225 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/InputMappingDoubleSetting.kt @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.input.model + +import org.dolphinemu.dolphinemu.features.input.model.controlleremu.NumericSetting +import org.dolphinemu.dolphinemu.features.settings.model.AbstractFloatSetting +import org.dolphinemu.dolphinemu.features.settings.model.Settings + +// Yes, floats are not the same thing as doubles... They're close enough, though +class InputMappingDoubleSetting(private val numericSetting: NumericSetting) : AbstractFloatSetting { + override val float: Float + get() = numericSetting.getDoubleValue().toFloat() + + override fun setFloat(settings: Settings, newValue: Float) = + numericSetting.setDoubleValue(newValue.toDouble()) + + override val isOverridden: Boolean = false + + override val isRuntimeEditable: Boolean = true + + override fun delete(settings: Settings): Boolean { + numericSetting.setDoubleValue(numericSetting.getDoubleDefaultValue()) + return true + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/InputMappingIntSetting.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/InputMappingIntSetting.kt new file mode 100644 index 000000000..3e8a14afc --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/InputMappingIntSetting.kt @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.input.model + +import org.dolphinemu.dolphinemu.features.input.model.controlleremu.NumericSetting +import org.dolphinemu.dolphinemu.features.settings.model.AbstractIntSetting +import org.dolphinemu.dolphinemu.features.settings.model.Settings + +class InputMappingIntSetting(private val numericSetting: NumericSetting) : AbstractIntSetting { + override val int: Int + get() = numericSetting.getIntValue() + + override fun setInt(settings: Settings, newValue: Int) = numericSetting.setIntValue(newValue) + + override val isOverridden: Boolean = false + + override val isRuntimeEditable: Boolean = true + + override fun delete(settings: Settings): Boolean { + numericSetting.setIntValue(numericSetting.getIntDefaultValue()) + return true + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/InputOverrider.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/InputOverrider.kt new file mode 100644 index 000000000..8224434ee --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/InputOverrider.kt @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.input.model + +object InputOverrider { + external fun registerGameCube(controllerIndex: Int) + + external fun registerWii(controllerIndex: Int) + + external fun unregisterGameCube(controllerIndex: Int) + + external fun unregisterWii(controllerIndex: Int) + + external fun setControlState(controllerIndex: Int, control: Int, state: Double) + + external fun clearControlState(controllerIndex: Int, control: Int) + + // Angle is in radians and should be non-negative + external fun getGateRadiusAtAngle(emuPadId: Int, stick: Int, angle: Double): Double + + object ControlId { + const val GCPAD_A_BUTTON = 0 + const val GCPAD_B_BUTTON = 1 + const val GCPAD_X_BUTTON = 2 + const val GCPAD_Y_BUTTON = 3 + const val GCPAD_Z_BUTTON = 4 + const val GCPAD_START_BUTTON = 5 + const val GCPAD_DPAD_UP = 6 + const val GCPAD_DPAD_DOWN = 7 + const val GCPAD_DPAD_LEFT = 8 + const val GCPAD_DPAD_RIGHT = 9 + const val GCPAD_L_DIGITAL = 10 + const val GCPAD_R_DIGITAL = 11 + const val GCPAD_L_ANALOG = 12 + const val GCPAD_R_ANALOG = 13 + const val GCPAD_MAIN_STICK_X = 14 + const val GCPAD_MAIN_STICK_Y = 15 + const val GCPAD_C_STICK_X = 16 + const val GCPAD_C_STICK_Y = 17 + + const val WIIMOTE_A_BUTTON = 18 + const val WIIMOTE_B_BUTTON = 19 + const val WIIMOTE_ONE_BUTTON = 20 + const val WIIMOTE_TWO_BUTTON = 21 + const val WIIMOTE_PLUS_BUTTON = 22 + const val WIIMOTE_MINUS_BUTTON = 23 + const val WIIMOTE_HOME_BUTTON = 24 + const val WIIMOTE_DPAD_UP = 25 + const val WIIMOTE_DPAD_DOWN = 26 + const val WIIMOTE_DPAD_LEFT = 27 + const val WIIMOTE_DPAD_RIGHT = 28 + const val WIIMOTE_IR_X = 29 + const val WIIMOTE_IR_Y = 30 + + const val NUNCHUK_C_BUTTON = 31 + const val NUNCHUK_Z_BUTTON = 32 + const val NUNCHUK_STICK_X = 33 + const val NUNCHUK_STICK_Y = 34 + + const val CLASSIC_A_BUTTON = 35 + const val CLASSIC_B_BUTTON = 36 + const val CLASSIC_X_BUTTON = 37 + const val CLASSIC_Y_BUTTON = 38 + const val CLASSIC_ZL_BUTTON = 39 + const val CLASSIC_ZR_BUTTON = 40 + const val CLASSIC_PLUS_BUTTON = 41 + const val CLASSIC_MINUS_BUTTON = 42 + const val CLASSIC_HOME_BUTTON = 43 + const val CLASSIC_DPAD_UP = 44 + const val CLASSIC_DPAD_DOWN = 45 + const val CLASSIC_DPAD_LEFT = 46 + const val CLASSIC_DPAD_RIGHT = 47 + const val CLASSIC_L_DIGITAL = 48 + const val CLASSIC_R_DIGITAL = 49 + const val CLASSIC_L_ANALOG = 50 + const val CLASSIC_R_ANALOG = 51 + const val CLASSIC_LEFT_STICK_X = 52 + const val CLASSIC_LEFT_STICK_Y = 53 + const val CLASSIC_RIGHT_STICK_X = 54 + const val CLASSIC_RIGHT_STICK_Y = 55 + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/MappingCommon.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/MappingCommon.kt new file mode 100644 index 000000000..622f4f551 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/MappingCommon.kt @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.input.model + +object MappingCommon { + external fun getExpressionForControl( + control: String, + device: String, + defaultDevice: String + ): String + + external fun save() +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/controlleremu/Control.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/controlleremu/Control.kt new file mode 100644 index 000000000..fcc420c74 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/controlleremu/Control.kt @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.input.model.controlleremu + +import androidx.annotation.Keep + +/** + * Represents a C++ ControllerEmu::Control. + * + * The lifetime of this class is managed by C++ code. Calling methods on it after it's destroyed + * in C++ is undefined behavior! + */ +@Keep +class Control private constructor(private val pointer: Long) { + external fun getUiName(): String + + external fun getControlReference(): ControlReference +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/controlleremu/ControlGroup.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/controlleremu/ControlGroup.kt new file mode 100644 index 000000000..9c5132b1a --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/controlleremu/ControlGroup.kt @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.input.model.controlleremu + +import androidx.annotation.Keep + +/** + * Represents a C++ ControllerEmu::ControlGroup. + * + * The lifetime of this class is managed by C++ code. Calling methods on it after it's destroyed + * in C++ is undefined behavior! + */ +@Keep +class ControlGroup private constructor(private val pointer: Long) { + external fun getUiName(): String + + external fun getGroupType(): Int + + external fun getDefaultEnabledValue(): Int + + external fun getEnabled(): Boolean + + external fun setEnabled(value: Boolean) + + external fun getControlCount(): Int + + external fun getControl(i: Int): Control + + external fun getNumericSettingCount(): Int + + external fun getNumericSetting(i: Int): NumericSetting + + /** + * If getGroupType returns TYPE_ATTACHMENTS, this returns the attachment selection setting. + * Otherwise, undefined behavior! + */ + external fun getAttachmentSetting(): NumericSetting + + companion object { + const val TYPE_OTHER = 0 + const val TYPE_STICK = 1 + const val TYPE_MIXED_TRIGGERS = 2 + const val TYPE_BUTTONS = 3 + const val TYPE_FORCE = 4 + const val TYPE_ATTACHMENTS = 5 + const val TYPE_TILT = 6 + const val TYPE_CURSOR = 7 + const val TYPE_TRIGGERS = 8 + const val TYPE_SLIDER = 9 + const val TYPE_SHAKE = 10 + const val TYPE_IMU_ACCELEROMETER = 11 + const val TYPE_IMU_GYROSCOPE = 12 + const val TYPE_IMU_CURSOR = 13 + + const val DEFAULT_ENABLED_ALWAYS = 0 + const val DEFAULT_ENABLED_YES = 1 + const val DEFAULT_ENABLED_NO = 2 + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/controlleremu/ControlReference.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/controlleremu/ControlReference.kt new file mode 100644 index 000000000..cd0c7848a --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/controlleremu/ControlReference.kt @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.input.model.controlleremu + +import androidx.annotation.Keep + +/** + * Represents a C++ ControlReference. + * + * The lifetime of this class is managed by C++ code. Calling methods on it after it's destroyed + * in C++ is undefined behavior! + */ +@Keep +class ControlReference private constructor(private val pointer: Long) { + external fun getState(): Double + + external fun getExpression(): String + + /** + * Sets the expression for this control reference. + * + * @param expr The new expression + * @return null on success, a human-readable error on failure + */ + external fun setExpression(expr: String): String? + + external fun isInput(): Boolean +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/controlleremu/EmulatedController.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/controlleremu/EmulatedController.kt new file mode 100644 index 000000000..e0938b975 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/controlleremu/EmulatedController.kt @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.input.model.controlleremu + +import androidx.annotation.Keep + +/** + * Represents a C++ ControllerEmu::ControlGroupContainer. + * + * The lifetime of this class is managed by C++ code. Calling methods on it after it's destroyed + * in C++ is undefined behavior! + */ +@Keep +open class ControlGroupContainer constructor(private val pointer: Long) { + external fun getGroupCount(): Int + + external fun getGroup(index: Int): ControlGroup +} + +/** + * Represents a C++ ControllerEmu::EmulatedController. + * + * The lifetime of this class is managed by C++ code. Calling methods on it after it's destroyed + * in C++ is undefined behavior! + */ +@Keep +class EmulatedController private constructor(private val pointer: Long) : ControlGroupContainer(pointer) { + external fun getDefaultDevice(): String + + external fun setDefaultDevice(device: String) + + external fun updateSingleControlReference(controlReference: ControlReference) + + external fun loadDefaultSettings() + + external fun clearSettings() + + external fun loadProfile(path: String) + + external fun saveProfile(path: String) + + external fun getProfileKey(): String + + external fun getUserProfileDirectoryPath(): String + + external fun getSysProfileDirectoryPath(): String + + companion object { + @JvmStatic + external fun getGcPad(controllerIndex: Int): EmulatedController + + @JvmStatic + external fun getGcKeyboard(controllerIndex: Int): EmulatedController + + @JvmStatic + external fun getWiimote(controllerIndex: Int): EmulatedController + + @JvmStatic + external fun getWiimoteAttachment( + controllerIndex: Int, + attachmentIndex: Int + ): ControlGroupContainer + + @JvmStatic + external fun getSelectedWiimoteAttachment(controllerIndex: Int): Int + + @JvmStatic + external fun getSidewaysWiimoteSetting(controllerIndex: Int): NumericSetting + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/controlleremu/NumericSetting.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/controlleremu/NumericSetting.kt new file mode 100644 index 000000000..0a2485dea --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/input/model/controlleremu/NumericSetting.kt @@ -0,0 +1,97 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.input.model.controlleremu + +import androidx.annotation.Keep + +/** + * Represents a C++ ControllerEmu::NumericSetting. + * + * The lifetime of this class is managed by C++ code. Calling methods on it after it's destroyed + * in C++ is undefined behavior! + */ +@Keep +class NumericSetting private constructor(private val pointer: Long) { + /** + * @return The name used in the UI. + */ + external fun getUiName(): String + + /** + * @return A string applied to the number in the UI (unit of measure). + */ + external fun getUiSuffix(): String + + /** + * @return Detailed description of the setting. + */ + external fun getUiDescription(): String + + /** + * @return TYPE_INT, TYPE_DOUBLE or TYPE_BOOLEAN + */ + external fun getType(): Int + + external fun getControlReference(): ControlReference + + /** + * If the type is TYPE_INT, gets the current value. Otherwise, undefined behavior! + */ + external fun getIntValue(): Int + + /** + * If the type is TYPE_INT, sets the current value. Otherwise, undefined behavior! + */ + external fun setIntValue(value: Int) + + /** + * If the type is TYPE_INT, gets the default value. Otherwise, undefined behavior! + */ + external fun getIntDefaultValue(): Int + + /** + * If the type is TYPE_DOUBLE, gets the current value. Otherwise, undefined behavior! + */ + external fun getDoubleValue(): Double + + /** + * If the type is TYPE_DOUBLE, sets the current value. Otherwise, undefined behavior! + */ + external fun setDoubleValue(value: Double) + + /** + * If the type is TYPE_DOUBLE, gets the default value. Otherwise, undefined behavior! + */ + external fun getDoubleDefaultValue(): Double + + /** + * If the type is TYPE_DOUBLE, returns the minimum valid value. Otherwise, undefined behavior! + */ + external fun getDoubleMin(): Double + + /** + * If the type is TYPE_DOUBLE, returns the maximum valid value. Otherwise, undefined behavior! + */ + external fun getDoubleMax(): Double + + /** + * If the type is TYPE_BOOLEAN, gets the current value. Otherwise, undefined behavior! + */ + external fun getBooleanValue(): Boolean + + /** + * If the type is TYPE_BOOLEAN, sets the current value. Otherwise, undefined behavior! + */ + external fun setBooleanValue(value: Boolean) + + /** + * If the type is TYPE_BOOLEAN, gets the default value. Otherwise, undefined behavior! + */ + external fun getBooleanDefaultValue(): Boolean + + companion object { + const val TYPE_INT = 0 + const val TYPE_DOUBLE = 1 + const val TYPE_BOOLEAN = 2 + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/netplay/NetplaySession.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/netplay/NetplaySession.kt new file mode 100644 index 000000000..2026064d7 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/netplay/NetplaySession.kt @@ -0,0 +1,448 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.netplay + +import androidx.annotation.Keep +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.channels.BufferOverflow +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asSharedFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.merge +import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.flow.receiveAsFlow +import kotlinx.coroutines.flow.runningFold +import kotlinx.coroutines.isActive +import kotlinx.coroutines.withContext +import org.dolphinemu.dolphinemu.features.netplay.model.GameDigestProgress +import org.dolphinemu.dolphinemu.features.netplay.model.NetplayMessage +import org.dolphinemu.dolphinemu.features.netplay.model.Player +import org.dolphinemu.dolphinemu.features.netplay.model.SaveTransferProgress +import org.dolphinemu.dolphinemu.features.netplay.model.TraversalState +import org.dolphinemu.dolphinemu.features.settings.model.StringSetting +import org.dolphinemu.dolphinemu.model.GameFile + +class NetplaySession( + gameFiles: Array = emptyArray(), + private val onClosed: (NetplaySession) -> Unit, +) { + + @Keep + private var netPlayUICallbacksPointer: Long = + nativeCreateUICallbacks(gameFiles) + + @Keep + private var netPlayClientPointer: Long = 0 + + @Keep + private var netPlayServerPointer: Long = 0 + + @Keep + private var bootSessionDataPointer: Long = 0 + + private val sessionScope = CoroutineScope(SupervisorJob()) + + @Volatile + var isClosed = false + private set + + val isHosting: Boolean + get() = netPlayServerPointer != 0L + + val isLaunching: Boolean + get() = bootSessionDataPointer != 0L + + val nickName by lazy { StringSetting.NETPLAY_NICKNAME.string } + + private val _launchGame = Channel(Channel.CONFLATED) + val launchGame = _launchGame.receiveAsFlow() + + private val _stopGame = Channel(Channel.CONFLATED) + val stopGame = _stopGame.receiveAsFlow() + + private val _connectionLost = Channel(Channel.CONFLATED) + val connectionLost = _connectionLost.receiveAsFlow() + + private val _connectionErrors = Channel(Channel.BUFFERED) + val connectionErrors = _connectionErrors.receiveAsFlow() + + private val _messages = MutableSharedFlow>( + replay = 1, + onBufferOverflow = BufferOverflow.DROP_OLDEST + ) + val messages = _messages.asSharedFlow() + + private val _players = MutableSharedFlow>( + replay = 1, + onBufferOverflow = BufferOverflow.DROP_OLDEST + ) + val players = _players.asSharedFlow().distinctUntilChanged() + + private val _chatMessages = MutableSharedFlow( + extraBufferCapacity = 32, + onBufferOverflow = BufferOverflow.DROP_OLDEST + ) + val chatMessages = _chatMessages.asSharedFlow() + + private val _game = MutableSharedFlow( + replay = 1, + onBufferOverflow = BufferOverflow.DROP_OLDEST + ) + val game = _game.asSharedFlow() + + private val _hostInputAuthorityEnabled = MutableSharedFlow( + replay = 1, + onBufferOverflow = BufferOverflow.DROP_OLDEST + ) + val hostInputAuthorityEnabled = _hostInputAuthorityEnabled.asSharedFlow() + + private val _padBuffer = MutableSharedFlow( + replay = 1, + onBufferOverflow = BufferOverflow.DROP_OLDEST + ) + val padBuffer = _padBuffer.asSharedFlow() + + private val _desyncMessages = MutableSharedFlow( + extraBufferCapacity = 32, + onBufferOverflow = BufferOverflow.DROP_OLDEST + ) + val desyncMessages = _desyncMessages.asSharedFlow() + + private val _saveTransferProgress = MutableStateFlow(null) + val saveTransferProgress = _saveTransferProgress.asStateFlow() + + private val _gameDigestProgress = MutableStateFlow(null) + val gameDigestProgress = _gameDigestProgress.asStateFlow() + + private val _traversalState = MutableSharedFlow( + replay = 1, + onBufferOverflow = BufferOverflow.DROP_OLDEST + ) + val traversalState = _traversalState.asSharedFlow() + + private val _fatalTraversalError = Channel(Channel.CONFLATED) + val fatalTraversalError = _fatalTraversalError.receiveAsFlow() + + suspend fun join(): Boolean = withContext(Dispatchers.IO) { + if (isClosed) throw IllegalStateException("Cannot join a closed session") + + mergeMessages() + .runningFold(emptyList()) { acc, msg -> listOf(msg) + acc } + .onEach { _messages.tryEmit(it) } + .launchIn(sessionScope) + + netPlayClientPointer = nativeJoin() + + if (netPlayClientPointer == 0L || !isActive) { + closeBlocking() + return@withContext false + } + + true + } + + suspend fun host(): Boolean = withContext(Dispatchers.IO) { + if (isClosed) throw IllegalStateException("Cannot host a closed session") + + netPlayServerPointer = nativeHost() + if (netPlayServerPointer == 0L || !isActive) { + closeBlocking() + return@withContext false + } + + join() + } + + fun sendMessage(message: String) { + _chatMessages.tryEmit("$nickName: $message") + nativeSendMessage(message) + } + + fun setHostInputAuthority(enable: Boolean) = nativeSetHostInputAuthority(enable) + + fun adjustClientPadBufferSize(buffer: Int) = nativeAdjustClientPadBufferSize(buffer) + + fun adjustServerPadBufferSize(buffer: Int) = nativeAdjustServerPadBufferSize(buffer) + + fun changeGame(gameFile: GameFile) = nativeChangeGame(gameFile) + + fun doAllPlayersHaveGame(): Boolean = nativeDoAllPlayersHaveGame() + + fun startGame() = nativeStartGame() + + fun getPort(): Int = nativeGetPort() + + fun getExternalIpAddress(): String? = nativeGetExternalIpAddress() + + fun reconnectTraversal() = nativeReconnectTraversal() + + fun consumeBootSessionData(): Long { + return bootSessionDataPointer.also { + bootSessionDataPointer = 0 + } + } + + suspend fun close() = withContext(Dispatchers.IO) { + closeBlocking() + } + + @Synchronized + fun closeBlocking() { + if (isClosed) return + isClosed = true + sessionScope.cancel() + releaseNativeResources() + onClosed(this) + } + + protected fun finalize() { + releaseNativeResources() + } + + private fun mergeMessages(): Flow = merge( + chatMessages.map { NetplayMessage.Chat(it) }, + game.map { NetplayMessage.GameChanged(it) }, + hostInputAuthorityEnabled.map { NetplayMessage.HostInputAuthorityChanged(it) }, + padBuffer.map { NetplayMessage.BufferChanged(it) }, + desyncMessages, + ) + + private fun releaseNativeResources() { + val currentBootSessionDataPointer = bootSessionDataPointer + if (currentBootSessionDataPointer != 0L) { + bootSessionDataPointer = 0 + nativeReleaseBootSessionData(currentBootSessionDataPointer) + } + + val currentNetPlayClientPointer = netPlayClientPointer + if (currentNetPlayClientPointer != 0L) { + netPlayClientPointer = 0 + nativeReleaseClient(currentNetPlayClientPointer) + } + + val currentNetPlayServerPointer = netPlayServerPointer + if (currentNetPlayServerPointer != 0L) { + netPlayServerPointer = 0 + nativeReleaseServer(currentNetPlayServerPointer) + } + + val currentNetPlayUICallbacksPointer = netPlayUICallbacksPointer + if (currentNetPlayUICallbacksPointer != 0L) { + netPlayUICallbacksPointer = 0 + nativeReleaseUICallbacks(currentNetPlayUICallbacksPointer) + } + } + + // JNI methods + + private external fun nativeCreateUICallbacks(gameFiles: Array): Long + + private external fun nativeJoin(): Long + + private external fun nativeHost(): Long + + private external fun nativeSendMessage(message: String) + + private external fun nativeSetHostInputAuthority(enable: Boolean) + + private external fun nativeAdjustClientPadBufferSize(buffer: Int) + + private external fun nativeAdjustServerPadBufferSize(buffer: Int) + + private external fun nativeReleaseUICallbacks(pointer: Long) + + private external fun nativeReleaseClient(pointer: Long) + + private external fun nativeReleaseServer(pointer: Long) + + private external fun nativeReleaseBootSessionData(pointer: Long) + + private external fun nativeChangeGame(gameFile: GameFile) + + private external fun nativeDoAllPlayersHaveGame(): Boolean + + private external fun nativeStartGame() + + private external fun nativeGetPort(): Int + + private external fun nativeGetExternalIpAddress(): String? + + private external fun nativeReconnectTraversal() + + // NetPlayUI callbacks + + @Keep + fun onBootGame(gameFilePath: String, bootSessionDataPointer: Long) { + this.bootSessionDataPointer = bootSessionDataPointer + _stopGame.flush() + _launchGame.trySend(gameFilePath) + } + + @Keep + fun onStopGame() { + _stopGame.trySend(Unit) + } + + @Keep + fun onConnectionLost() { + _connectionLost.trySend(Unit) + } + + @Keep + fun onConnectionError(message: String) { + _connectionErrors.trySend(message) + } + + @Keep + fun onUpdate(players: Array) { + _players.tryEmit(players.toList()) + } + + @Keep + fun onChatMessageReceived(message: String) { + _chatMessages.tryEmit(message) + } + + @Keep + fun onHostInputAuthorityChanged(enabled: Boolean) { + _hostInputAuthorityEnabled.tryEmit(enabled) + } + + @Keep + fun onGameChanged(game: String) { + _game.tryEmit(game) + } + + @Keep + fun onPadBufferChanged(buffer: Int) { + if (_hostInputAuthorityEnabled.replayCache.firstOrNull() == true) return + _padBuffer.tryEmit(buffer) + } + + @Keep + fun onDesync(frame: Int, player: String) { + _desyncMessages.tryEmit(NetplayMessage.Desync(player, frame)) + } + + @Keep + fun onShowChunkedProgressDialog(title: String, dataSize: Long, playerIds: IntArray) { + val players = _players.replayCache.firstOrNull() + _saveTransferProgress.value = SaveTransferProgress( + title = title, + totalSize = dataSize, + playerProgresses = playerIds.map { playerId -> + SaveTransferProgress.PlayerProgress( + playerId = playerId, + name = players?.find { it.pid == playerId }?.name ?: "Invalid Player ID", + progress = 0, + ) + }, + ) + } + + @Keep + fun onSetChunkedProgress(playerId: Int, progress: Long) { + val current = _saveTransferProgress.value + _saveTransferProgress.value = current?.copy( + playerProgresses = current.playerProgresses.map { + if (it.playerId == playerId) { + it.copy(progress = progress) + } else { + it + } + } + ) + } + + @Keep + fun onHideChunkedProgressDialog() { + _saveTransferProgress.value = null + } + + @Keep + fun onShowGameDigestDialog(title: String) { + val players = _players.replayCache.firstOrNull() + _gameDigestProgress.value = GameDigestProgress( + title = title, + playerProgresses = players?.map { player -> + GameDigestProgress.PlayerProgress( + playerId = player.pid, + name = player.name, + progress = 0, + result = null, + ) + } ?: emptyList(), + matches = null, + ) + } + + @Keep + fun onSetGameDigestProgress(playerId: Int, progress: Int) { + val current = _gameDigestProgress.value ?: return + _gameDigestProgress.value = current.copy( + playerProgresses = current.playerProgresses.map { + if (it.playerId == playerId) it.copy(progress = progress) else it + } + ) + } + + @Keep + fun onSetGameDigestResult(playerId: Int, result: String) { + val current = _gameDigestProgress.value ?: return + val updated = current.copy( + playerProgresses = current.playerProgresses.map { + if (it.playerId == playerId) it.copy(result = result) else it + } + ) + val finished = updated.playerProgresses.all { it.result != null } + _gameDigestProgress.value = if (finished) { + val results = updated.playerProgresses.map { it.result } + updated.copy(matches = results.distinct().size == 1) + } else { + updated + } + } + + /** + * Hosts send this when they dismiss their dialog even in a successful scenario. Ensuring + * that the value is cleared before a new game digest is started. Without this, StateFlow + * would not be a good choice. + */ + @Keep + fun onAbortGameDigest() { + _gameDigestProgress.value = null + } + + @Keep + fun onTraversalStateChanged( + state: Int, + hostCode: String?, + externalAddress: String?, + failureReason: String?, + ) { + val traversalState = when (state) { + 0 -> TraversalState.Connecting + 1 -> TraversalState.Connected(hostCode!!, externalAddress!!) + 2 -> TraversalState.Failure(failureReason!!) + else -> return + } + _traversalState.tryEmit(traversalState) + + if (failureReason == "BadHost" || failureReason == "VersionTooOld") { + _fatalTraversalError.trySend(TraversalState.Failure(failureReason)) + } + } +} + +private fun Channel.flush() { + while (this.tryReceive().isSuccess) Unit +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/netplay/model/GameDigestProgress.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/netplay/model/GameDigestProgress.kt new file mode 100644 index 000000000..923f03068 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/netplay/model/GameDigestProgress.kt @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.netplay.model + +data class GameDigestProgress( + val title: String, + val playerProgresses: List, + val matches: Boolean?, +) { + data class PlayerProgress( + val playerId: Int, + val name: String, + val progress: Int, + val result: String?, + ) +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/netplay/model/NetplayMessage.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/netplay/model/NetplayMessage.kt new file mode 100644 index 000000000..c408d3be9 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/netplay/model/NetplayMessage.kt @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.netplay.model + +import android.content.Context +import org.dolphinemu.dolphinemu.R + +sealed class NetplayMessage { + abstract fun message(context: Context): String + + class Chat(private val chatMessage: String) : NetplayMessage() { + override fun message(context: Context) = chatMessage + } + + class GameChanged(private val game: String) : NetplayMessage() { + override fun message(context: Context) = + context.getString(R.string.netplay_message_game_changed, game) + } + + class HostInputAuthorityChanged(private val hostInputAuthorityEnabled: Boolean) : NetplayMessage() { + override fun message(context: Context) = context.getString( + R.string.netplay_message_host_input_authority_changed, + if (hostInputAuthorityEnabled) "enabled" else "disabled" + ) + } + + class BufferChanged(private val buffer: Int) : NetplayMessage() { + override fun message(context: Context) = + context.getString(R.string.netplay_message_buffer_changed, buffer) + } + + class Desync(private val player: String, private val frame: Int) : NetplayMessage() { + override fun message(context: Context) = + context.getString(R.string.netplay_message_desync, player, frame) + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/netplay/model/Player.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/netplay/model/Player.kt new file mode 100644 index 000000000..31d0d0ccf --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/netplay/model/Player.kt @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.netplay.model + +import androidx.annotation.Keep + +@Keep +data class Player( + val pid: Int, + val name: String, + val revision: String, + val ping: Int, + val isHost: Boolean, + val mapping: String, +) \ No newline at end of file diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/netplay/model/SaveTransferProgress.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/netplay/model/SaveTransferProgress.kt new file mode 100644 index 000000000..826510141 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/netplay/model/SaveTransferProgress.kt @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.netplay.model + +data class SaveTransferProgress( + val title: String, + val totalSize: Long, + val playerProgresses: List +) { + data class PlayerProgress( + val playerId: Int, + val name: String, + val progress: Long, + ) +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/netplay/model/TraversalState.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/netplay/model/TraversalState.kt new file mode 100644 index 000000000..0c36fdf58 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/netplay/model/TraversalState.kt @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.netplay.model + +import android.content.Context +import org.dolphinemu.dolphinemu.R + +sealed class TraversalState { + data object Connecting : TraversalState() + + data class Connected(val hostCode: String, val externalAddress: String) : TraversalState() + + data class Failure(val reason: String) : TraversalState() { + fun message(context: Context) = when (reason) { + "BadHost" -> context.getString(R.string.netplay_traversal_error_bad_host) + "VersionTooOld" -> context.getString(R.string.netplay_traversal_error_version_too_old) + else -> reason + } + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/riivolution/model/RiivolutionPatches.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/riivolution/model/RiivolutionPatches.kt new file mode 100644 index 000000000..ba3fd41d6 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/riivolution/model/RiivolutionPatches.kt @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.riivolution.model + +import androidx.annotation.Keep + +class RiivolutionPatches( + private val gameId: String, + private val revision: Int, + private val discNumber: Int +) { + private var unsavedChanges = false + + @Keep + private val pointer: Long = initialize() + + external fun finalize() + + external fun getDiscCount(): Int + + external fun getDiscName(discIndex: Int): String + + external fun getSectionCount(discIndex: Int): Int + + external fun getSectionName(discIndex: Int, sectionIndex: Int): String + + external fun getOptionCount(discIndex: Int, sectionIndex: Int): Int + + external fun getOptionName(discIndex: Int, sectionIndex: Int, optionIndex: Int): String + + external fun getChoiceCount(discIndex: Int, sectionIndex: Int, optionIndex: Int): Int + + external fun getChoiceName( + discIndex: Int, + sectionIndex: Int, + optionIndex: Int, + choiceIndex: Int + ): String + + /** + * @return 0 if no choice is selected, otherwise the index of the selected choice plus one. + */ + external fun getSelectedChoice(discIndex: Int, sectionIndex: Int, optionIndex: Int): Int + + /** + * @param choiceIndex 0 to select no choice, otherwise the choice index plus one. + */ + fun setSelectedChoice(discIndex: Int, sectionIndex: Int, optionIndex: Int, choiceIndex: Int) { + unsavedChanges = true + setSelectedChoiceImpl(discIndex, sectionIndex, optionIndex, choiceIndex) + } + + /** + * @param choiceIndex 0 to select no choice, otherwise the choice index plus one. + */ + private external fun setSelectedChoiceImpl( + discIndex: Int, sectionIndex: Int, optionIndex: Int, + choiceIndex: Int + ) + + fun loadConfig() { + loadConfigImpl(gameId, revision, discNumber) + } + + private external fun loadConfigImpl(gameId: String, revision: Int, discNumber: Int) + + fun saveConfig() { + if (unsavedChanges) { + unsavedChanges = false + saveConfigImpl(gameId) + } + } + + private external fun saveConfigImpl(gameId: String) + + companion object { + @JvmStatic + private external fun initialize(): Long + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AbstractBooleanSetting.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AbstractBooleanSetting.kt new file mode 100644 index 000000000..6196597da --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AbstractBooleanSetting.kt @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.settings.model + +interface AbstractBooleanSetting : AbstractSetting { + val boolean: Boolean + + fun setBoolean(settings: Settings, newValue: Boolean) +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AbstractFloatSetting.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AbstractFloatSetting.kt new file mode 100644 index 000000000..7dd4c82c0 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AbstractFloatSetting.kt @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.settings.model + +interface AbstractFloatSetting : AbstractSetting { + val float: Float + + fun setFloat(settings: Settings, newValue: Float) +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AbstractIntSetting.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AbstractIntSetting.kt new file mode 100644 index 000000000..f22077dd6 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AbstractIntSetting.kt @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.settings.model + +interface AbstractIntSetting : AbstractSetting { + val int: Int + + fun setInt(settings: Settings, newValue: Int) +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AbstractSetting.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AbstractSetting.kt new file mode 100644 index 000000000..6afcfab2e --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AbstractSetting.kt @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.settings.model + +interface AbstractSetting { + val isOverridden: Boolean + val isRuntimeEditable: Boolean + + fun delete(settings: Settings): Boolean +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AbstractStringSetting.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AbstractStringSetting.kt new file mode 100644 index 000000000..7828dbd55 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AbstractStringSetting.kt @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.settings.model + +interface AbstractStringSetting : AbstractSetting { + val string: String + + fun setString(settings: Settings, newValue: String) +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AchievementModel.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AchievementModel.kt new file mode 100644 index 000000000..f62b2f146 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AchievementModel.kt @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.settings.model + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +object AchievementModel { + @JvmStatic + external fun init() + + suspend fun asyncLogin(password: String): Boolean { + return withContext(Dispatchers.IO) { + login(password) + } + } + + @JvmStatic + private external fun login(password: String): Boolean + + @JvmStatic + external fun logout() + + @JvmStatic + external fun isHardcoreModeActive(): Boolean + + @JvmStatic + external fun shutdown() + + @JvmStatic + external fun getAchievementsJSON(): String +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AdHocBooleanSetting.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AdHocBooleanSetting.kt new file mode 100644 index 000000000..f62ead325 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AdHocBooleanSetting.kt @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.settings.model + +class AdHocBooleanSetting( + private val file: String, + private val section: String, + private val key: String, + private val defaultValue: Boolean +) : AbstractBooleanSetting { + init { + require( + NativeConfig.isSettingSaveable( + file, + section, + key + ) + ) { "File/section/key is unknown or legacy" } + } + + override val isOverridden: Boolean + get() = NativeConfig.isOverridden(file, section, key) + + override val isRuntimeEditable: Boolean = true + + override fun delete(settings: Settings): Boolean { + return NativeConfig.deleteKey(settings.writeLayer, file, section, key) + } + + override val boolean: Boolean + get() = NativeConfig.getBoolean(NativeConfig.LAYER_ACTIVE, file, section, key, defaultValue) + + override fun setBoolean(settings: Settings, newValue: Boolean) { + NativeConfig.setBoolean(settings.writeLayer, file, section, key, newValue) + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AdHocStringSetting.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AdHocStringSetting.kt new file mode 100644 index 000000000..fd416d890 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/AdHocStringSetting.kt @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.settings.model + +class AdHocStringSetting( + private val file: String, + private val section: String, + private val key: String, + private val defaultValue: String +) : AbstractStringSetting { + init { + require( + NativeConfig.isSettingSaveable( + file, + section, + key + ) + ) { "File/section/key is unknown or legacy" } + } + + override val isOverridden: Boolean + get() = NativeConfig.isOverridden(file, section, key) + + override val isRuntimeEditable: Boolean = true + + override fun delete(settings: Settings): Boolean { + return NativeConfig.deleteKey(settings.writeLayer, file, section, key) + } + + override val string: String + get() = NativeConfig.getString(NativeConfig.LAYER_ACTIVE, file, section, key, defaultValue) + + override fun setString(settings: Settings, newValue: String) { + NativeConfig.setString(settings.writeLayer, file, section, key, newValue) + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/BooleanSetting.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/BooleanSetting.kt new file mode 100644 index 000000000..68c859082 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/BooleanSetting.kt @@ -0,0 +1,1040 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.settings.model + +import java.util.* + +enum class BooleanSetting( + private val file: String, + private val section: String, + private val key: String, + private val defaultValue: Boolean +) : AbstractBooleanSetting { + // These entries have the same names and order as in C++, just for consistency. + MAIN_SKIP_IPL(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "SkipIPL", true), + MAIN_DSP_HLE(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "DSPHLE", true), + MAIN_FASTMEM(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "Fastmem", true), + MAIN_PAGE_TABLE_FASTMEM(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "PageTableFastmem", true), + MAIN_FASTMEM_ARENA(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "FastmemArena", true), + MAIN_LARGE_ENTRY_POINTS_MAP(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "LargeEntryPointsMap", true), + MAIN_CPU_THREAD(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "CPUThread", true), + MAIN_SYNC_ON_SKIP_IDLE( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_CORE, + "SyncOnSkipIdle", + true + ), + MAIN_ENABLE_CHEATS(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "EnableCheats", false), + MAIN_OVERRIDE_REGION_SETTINGS( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_CORE, + "OverrideRegionSettings", + false + ), + MAIN_AUDIO_FILL_GAPS(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "AudioFillGaps", true), + MAIN_AUDIO_PRESERVE_PITCH(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "AudioPreservePitch", false), + MAIN_BBA_XLINK_CHAT_OSD( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_CORE, + "BBA_XLINK_CHAT_OSD", + false + ), + MAIN_ADAPTER_RUMBLE_0(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "AdapterRumble0", true), + MAIN_ADAPTER_RUMBLE_1(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "AdapterRumble1", true), + MAIN_ADAPTER_RUMBLE_2(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "AdapterRumble2", true), + MAIN_ADAPTER_RUMBLE_3(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "AdapterRumble3", true), + MAIN_SIMULATE_KONGA_0( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_CORE, + "SimulateKonga0", + false + ), + MAIN_SIMULATE_KONGA_1( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_CORE, + "SimulateKonga1", + false + ), + MAIN_SIMULATE_KONGA_2( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_CORE, + "SimulateKonga2", + false + ), + MAIN_SIMULATE_KONGA_3( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_CORE, + "SimulateKonga3", + false + ), + MAIN_WII_SD_CARD(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "WiiSDCard", true), + MAIN_WII_SD_CARD_ENABLE_FOLDER_SYNC( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_CORE, + "WiiSDCardEnableFolderSync", + false + ), + MAIN_WIIMOTE_CONTINUOUS_SCANNING( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_CORE, + "WiimoteContinuousScanning", + false + ), + MAIN_WIIMOTE_ENABLE_SPEAKER( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_CORE, + "WiimoteEnableSpeaker", + false + ), + MAIN_MMU(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "MMU", false), + MAIN_PAUSE_ON_PANIC(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "PauseOnPanic", false), + MAIN_ACCURATE_CPU_CACHE( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_CORE, + "AccurateCPUCache", + false + ), + MAIN_SYNC_GPU(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "SyncGPU", false), + MAIN_FAST_DISC_SPEED(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "FastDiscSpeed", false), + MAIN_OVERCLOCK_ENABLE( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_CORE, + "OverclockEnable", + false + ), + MAIN_VI_OVERCLOCK_ENABLE( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_CORE, + "VIOverclockEnable", + false + ), + MAIN_RAM_OVERRIDE_ENABLE( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_CORE, + "RAMOverrideEnable", + false + ), + MAIN_CUSTOM_RTC_ENABLE( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_CORE, + "EnableCustomRTC", + false + ), + MAIN_AUTO_DISC_CHANGE( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_CORE, + "AutoDiscChange", + false + ), + MAIN_ALLOW_SD_WRITES( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_CORE, + "WiiSDCardAllowWrites", + true + ), + MAIN_ENABLE_SAVESTATES( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_CORE, + "EnableSaveStates", + false + ), + MAIN_WII_WIILINK_ENABLE(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "EnableWiiLink", false), + MAIN_DSP_JIT(Settings.FILE_DOLPHIN, Settings.SECTION_INI_DSP, "EnableJIT", true), + MAIN_TIME_TRACKING( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_GENERAL, + "EnablePlayTimeTracking", + true + ), + MAIN_EXPAND_TO_CUTOUT_AREA( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_INTERFACE, + "ExpandToCutoutArea", + false + ), + MAIN_USE_PANIC_HANDLERS( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_INTERFACE, + "UsePanicHandlers", + true + ), + MAIN_OSD_MESSAGES( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_INTERFACE, + "OnScreenDisplayMessages", + true + ), + MAIN_ANALYTICS_ENABLED(Settings.FILE_DOLPHIN, Settings.SECTION_ANALYTICS, "Enabled", false), + MAIN_ANALYTICS_PERMISSION_ASKED( + Settings.FILE_DOLPHIN, + Settings.SECTION_ANALYTICS, + "PermissionAsked", + false + ), + MAIN_RECURSIVE_ISO_PATHS( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_GENERAL, + "RecursiveISOPaths", + false + ), + MAIN_USE_GAME_COVERS( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_GENERAL, + "UseGameCovers", + true + ), + MAIN_DEBUG_JIT_OFF(Settings.FILE_DOLPHIN, Settings.SECTION_DEBUG, "JitOff", false), + MAIN_DEBUG_JIT_LOAD_STORE_OFF( + Settings.FILE_DOLPHIN, + Settings.SECTION_DEBUG, + "JitLoadStoreOff", + false + ), + MAIN_DEBUG_JIT_LOAD_STORE_FLOATING_OFF( + Settings.FILE_DOLPHIN, + Settings.SECTION_DEBUG, + "JitLoadStoreFloatingOff", + false + ), + MAIN_DEBUG_JIT_LOAD_STORE_PAIRED_OFF( + Settings.FILE_DOLPHIN, + Settings.SECTION_DEBUG, + "JitLoadStorePairedOff", + false + ), + MAIN_DEBUG_JIT_FLOATING_POINT_OFF( + Settings.FILE_DOLPHIN, + Settings.SECTION_DEBUG, + "JitFloatingPointOff", + false + ), + MAIN_DEBUG_JIT_INTEGER_OFF( + Settings.FILE_DOLPHIN, + Settings.SECTION_DEBUG, + "JitIntegerOff", + false + ), + MAIN_DEBUG_JIT_PAIRED_OFF(Settings.FILE_DOLPHIN, Settings.SECTION_DEBUG, "JitPairedOff", false), + MAIN_DEBUG_JIT_SYSTEM_REGISTERS_OFF( + Settings.FILE_DOLPHIN, + Settings.SECTION_DEBUG, + "JitSystemRegistersOff", + false + ), + MAIN_DEBUG_JIT_BRANCH_OFF(Settings.FILE_DOLPHIN, Settings.SECTION_DEBUG, "JitBranchOff", false), + MAIN_DEBUG_JIT_REGISTER_CACHE_OFF( + Settings.FILE_DOLPHIN, + Settings.SECTION_DEBUG, + "JitRegisterCacheOff", + false + ), + MAIN_DEBUG_JIT_ENABLE_PROFILING( + Settings.FILE_DOLPHIN, + Settings.SECTION_DEBUG, + "JitEnableProfiling", + false + ), + MAIN_EMULATE_SKYLANDER_PORTAL( + Settings.FILE_DOLPHIN, + Settings.SECTION_EMULATED_USB_DEVICES, + "EmulateSkylanderPortal", + false + ), + MAIN_EMULATE_INFINITY_BASE( + Settings.FILE_DOLPHIN, + Settings.SECTION_EMULATED_USB_DEVICES, + "EmulateInfinityBase", + false + ), + MAIN_EMULATE_WII_SPEAK( + Settings.FILE_DOLPHIN, + Settings.SECTION_EMULATED_USB_DEVICES, + "EmulateWiiSpeak", + false + ), + MAIN_WII_SPEAK_MUTED( + Settings.FILE_DOLPHIN, + Settings.SECTION_EMULATED_USB_DEVICES, + "WiiSpeakMuted", + true + ), + MAIN_SHOW_GAME_TITLES( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID, + "ShowGameTitles", + true + ), + MAIN_USE_BLACK_BACKGROUNDS( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID, + "UseBlackBackgrounds", + false + ), + MAIN_JOYSTICK_REL_CENTER( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID, + "JoystickRelCenter", + true + ), + MAIN_SHOW_INPUT_OVERLAY( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID, + "ShowInputOverlay", + true + ), + MAIN_IR_ALWAYS_RECENTER( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID, + "IRAlwaysRecenter", + false + ), + MAIN_BUTTON_TOGGLE_GC_0( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleGCButtonA", + true + ), + MAIN_BUTTON_TOGGLE_GC_1( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleGCButtonB", + true + ), + MAIN_BUTTON_TOGGLE_GC_2( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleGCButtonX", + true + ), + MAIN_BUTTON_TOGGLE_GC_3( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleGCButtonY", + true + ), + MAIN_BUTTON_TOGGLE_GC_4( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleGCButtonZ", + true + ), + MAIN_BUTTON_TOGGLE_GC_5( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleGCButtonStart", + true + ), + MAIN_BUTTON_TOGGLE_GC_6( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleGCTriggerL", + true + ), + MAIN_BUTTON_TOGGLE_GC_7( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleGCTriggerR", + true + ), + MAIN_BUTTON_TOGGLE_GC_8( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleGCDPad", + true + ), + MAIN_BUTTON_TOGGLE_GC_9( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleGCStickMain", + true + ), + MAIN_BUTTON_TOGGLE_GC_10( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleGCStickC", + true + ), + MAIN_BUTTON_LATCHING_GC_0( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingGCButtonA", + false + ), + MAIN_BUTTON_LATCHING_GC_1( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingGCButtonB", + false + ), + MAIN_BUTTON_LATCHING_GC_2( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingGCButtonX", + false + ), + MAIN_BUTTON_LATCHING_GC_3( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingGCButtonY", + false + ), + MAIN_BUTTON_LATCHING_GC_4( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingGCButtonZ", + false + ), + MAIN_BUTTON_LATCHING_GC_5( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingGCButtonStart", + false + ), + MAIN_BUTTON_LATCHING_GC_6( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingGCTriggerL", + false + ), + MAIN_BUTTON_LATCHING_GC_7( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingGCTriggerR", + false + ), + MAIN_BUTTON_TOGGLE_CLASSIC_0( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleClassicButtonA", + true + ), + MAIN_BUTTON_TOGGLE_CLASSIC_1( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleClassicButtonB", + true + ), + MAIN_BUTTON_TOGGLE_CLASSIC_2( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleClassicButtonX", + true + ), + MAIN_BUTTON_TOGGLE_CLASSIC_3( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleClassicButtonY", + true + ), + MAIN_BUTTON_TOGGLE_CLASSIC_4( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleClassicButtonPlus", + true + ), + MAIN_BUTTON_TOGGLE_CLASSIC_5( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleClassicButtonMinus", + true + ), + MAIN_BUTTON_TOGGLE_CLASSIC_6( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleClassicButtonHome", + true + ), + MAIN_BUTTON_TOGGLE_CLASSIC_7( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleClassicTriggerL", + true + ), + MAIN_BUTTON_TOGGLE_CLASSIC_8( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleClassicTriggerR", + true + ), + MAIN_BUTTON_TOGGLE_CLASSIC_9( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleClassicButtonZL", + true + ), + MAIN_BUTTON_TOGGLE_CLASSIC_10( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleClassicButtonZR", + true + ), + MAIN_BUTTON_TOGGLE_CLASSIC_11( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleClassicDPad", + true + ), + MAIN_BUTTON_TOGGLE_CLASSIC_12( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleClassicStickLeft", + true + ), + MAIN_BUTTON_TOGGLE_CLASSIC_13( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleClassicStickRight", + true + ), + MAIN_BUTTON_LATCHING_CLASSIC_0( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingClassicButtonA", + false + ), + MAIN_BUTTON_LATCHING_CLASSIC_1( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingClassicButtonB", + false + ), + MAIN_BUTTON_LATCHING_CLASSIC_2( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingClassicButtonX", + false + ), + MAIN_BUTTON_LATCHING_CLASSIC_3( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingClassicButtonY", + false + ), + MAIN_BUTTON_LATCHING_CLASSIC_4( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingClassicButtonPlus", + false + ), + MAIN_BUTTON_LATCHING_CLASSIC_5( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingClassicButtonMinus", + false + ), + MAIN_BUTTON_LATCHING_CLASSIC_6( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingClassicButtonHome", + false + ), + MAIN_BUTTON_LATCHING_CLASSIC_7( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingClassicTriggerL", + false + ), + MAIN_BUTTON_LATCHING_CLASSIC_8( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingClassicTriggerR", + false + ), + MAIN_BUTTON_LATCHING_CLASSIC_9( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingClassicButtonZL", + false + ), + MAIN_BUTTON_LATCHING_CLASSIC_10( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingClassicButtonZR", + false + ), + MAIN_BUTTON_TOGGLE_WII_0( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleWiimoteButtonA", + true + ), + MAIN_BUTTON_TOGGLE_WII_1( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleWiimoteButtonB", + true + ), + MAIN_BUTTON_TOGGLE_WII_2( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleWiimoteButton1", + true + ), + MAIN_BUTTON_TOGGLE_WII_3( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleWiimoteButton2", + true + ), + MAIN_BUTTON_TOGGLE_WII_4( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleWiimoteButtonPlus", + true + ), + MAIN_BUTTON_TOGGLE_WII_5( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleWiimoteButtonMinus", + true + ), + MAIN_BUTTON_TOGGLE_WII_6( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleWiimoteButtonHome", + true + ), + MAIN_BUTTON_TOGGLE_WII_7( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleWiimoteDPad", + true + ), + MAIN_BUTTON_TOGGLE_WII_8( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleNunchukC", + true + ), + MAIN_BUTTON_TOGGLE_WII_9( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleNunchukZ", + true + ), + MAIN_BUTTON_TOGGLE_WII_10( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonToggleNunchukStick", + true + ), + MAIN_BUTTON_LATCHING_WII_0( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingWiimoteButtonA", + false + ), + MAIN_BUTTON_LATCHING_WII_1( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingWiimoteButtonB", + false + ), + MAIN_BUTTON_LATCHING_WII_2( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingWiimoteButton1", + false + ), + MAIN_BUTTON_LATCHING_WII_3( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingWiimoteButton2", + false + ), + MAIN_BUTTON_LATCHING_WII_4( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingWiimoteButtonPlus", + false + ), + MAIN_BUTTON_LATCHING_WII_5( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingWiimoteButtonMinus", + false + ), + MAIN_BUTTON_LATCHING_WII_6( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingWiimoteButtonHome", + false + ), + MAIN_BUTTON_LATCHING_WII_8( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingNunchukC", + false + ), + MAIN_BUTTON_LATCHING_WII_9( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "ButtonLatchingNunchukZ", + false + ), + SYSCONF_SCREENSAVER(Settings.FILE_SYSCONF, "IPL", "SSV", false), + SYSCONF_WIDESCREEN(Settings.FILE_SYSCONF, "IPL", "AR", true), + SYSCONF_PROGRESSIVE_SCAN(Settings.FILE_SYSCONF, "IPL", "PGS", true), + SYSCONF_PAL60(Settings.FILE_SYSCONF, "IPL", "E60", true), + SYSCONF_WIIMOTE_MOTOR(Settings.FILE_SYSCONF, "BT", "MOT", true), + GFX_VSYNC(Settings.FILE_GFX, Settings.SECTION_GFX_HARDWARE, "VSync", false), + GFX_WIDESCREEN_HACK(Settings.FILE_GFX, Settings.SECTION_GFX_SETTINGS, "wideScreenHack", false), + GFX_CROP_TO_ASPECT_RATIO(Settings.FILE_GFX, Settings.SECTION_GFX_SETTINGS, "Crop", false), + GFX_CROP_CUSTOM(Settings.FILE_GFX, Settings.SECTION_GFX_SETTINGS, "CropCustom", false), + GFX_SHOW_FPS(Settings.FILE_GFX, Settings.SECTION_GFX_SETTINGS, "ShowFPS", false), + GFX_SHOW_FTIMES(Settings.FILE_GFX, Settings.SECTION_GFX_SETTINGS, "ShowFTimes", false), + GFX_SHOW_VPS(Settings.FILE_GFX, Settings.SECTION_GFX_SETTINGS, "ShowVPS", false), + GFX_SHOW_VTIMES(Settings.FILE_GFX, Settings.SECTION_GFX_SETTINGS, "ShowVTimes", false), + GFX_SHOW_GRAPHS(Settings.FILE_GFX, Settings.SECTION_GFX_SETTINGS, "ShowGraphs", false), + GFX_SHOW_SPEED(Settings.FILE_GFX, Settings.SECTION_GFX_SETTINGS, "ShowSpeed", false), + GFX_SHOW_SPEED_COLORS( + Settings.FILE_GFX, + Settings.SECTION_GFX_SETTINGS, + "ShowSpeedColors", + true + ), + GFX_LOG_RENDER_TIME_TO_FILE( + Settings.FILE_GFX, + Settings.SECTION_GFX_SETTINGS, + "LogRenderTimeToFile", + false + ), + GFX_OVERLAY_STATS(Settings.FILE_GFX, Settings.SECTION_GFX_SETTINGS, "OverlayStats", false), + GFX_OVERLAY_PROJ_STATS( + Settings.FILE_GFX, + Settings.SECTION_GFX_SETTINGS, + "OverlayProjStats", + false + ), + GFX_SHOW_INTERNAL_RESOLUTION( + Settings.FILE_GFX, + Settings.SECTION_GFX_SETTINGS, + "ShowInternalResolution", + false + ), + GFX_DUMP_TEXTURES(Settings.FILE_GFX, Settings.SECTION_GFX_SETTINGS, "DumpTextures", false), + GFX_DUMP_MIP_TEXTURES( + Settings.FILE_GFX, + Settings.SECTION_GFX_SETTINGS, + "DumpMipTextures", + false + ), + GFX_DUMP_BASE_TEXTURES( + Settings.FILE_GFX, + Settings.SECTION_GFX_SETTINGS, + "DumpBaseTextures", + false + ), + GFX_HIRES_TEXTURES(Settings.FILE_GFX, Settings.SECTION_GFX_SETTINGS, "HiresTextures", false), + GFX_CACHE_HIRES_TEXTURES( + Settings.FILE_GFX, + Settings.SECTION_GFX_SETTINGS, + "CacheHiresTextures", + false + ), + GFX_DUMP_EFB_TARGET(Settings.FILE_GFX, Settings.SECTION_GFX_SETTINGS, "DumpEFBTarget", false), + GFX_DUMP_XFB_TARGET(Settings.FILE_GFX, Settings.SECTION_GFX_SETTINGS, "DumpXFBTarget", false), + GFX_INTERNAL_RESOLUTION_FRAME_DUMPS( + Settings.FILE_GFX, + Settings.SECTION_GFX_SETTINGS, + "InternalResolutionFrameDumps", + false + ), + GFX_ENABLE_GPU_TEXTURE_DECODING( + Settings.FILE_GFX, + Settings.SECTION_GFX_SETTINGS, + "EnableGPUTextureDecoding", + false + ), + GFX_ENABLE_PIXEL_LIGHTING( + Settings.FILE_GFX, + Settings.SECTION_GFX_SETTINGS, + "EnablePixelLighting", + false + ), + GFX_FAST_DEPTH_CALC(Settings.FILE_GFX, Settings.SECTION_GFX_SETTINGS, "FastDepthCalc", true), + GFX_TEXFMT_OVERLAY_ENABLE( + Settings.FILE_GFX, + Settings.SECTION_GFX_SETTINGS, + "TexFmtOverlayEnable", + false + ), + GFX_ENABLE_WIREFRAME(Settings.FILE_GFX, Settings.SECTION_GFX_SETTINGS, "WireFrame", false), + GFX_DISABLE_FOG(Settings.FILE_GFX, Settings.SECTION_GFX_SETTINGS, "DisableFog", false), + GFX_ENABLE_VALIDATION_LAYER( + Settings.FILE_GFX, + Settings.SECTION_GFX_SETTINGS, + "EnableValidationLayer", + false + ), + GFX_BACKEND_MULTITHREADING( + Settings.FILE_GFX, + Settings.SECTION_GFX_SETTINGS, + "BackendMultithreading", + true + ), + GFX_WAIT_FOR_SHADERS_BEFORE_STARTING( + Settings.FILE_GFX, + Settings.SECTION_GFX_SETTINGS, + "WaitForShadersBeforeStarting", + false + ), + GFX_SAVE_TEXTURE_CACHE_TO_STATE( + Settings.FILE_GFX, + Settings.SECTION_GFX_SETTINGS, + "SaveTextureCacheToState", + true + ), + GFX_PREFER_VS_FOR_LINE_POINT_EXPANSION( + Settings.FILE_GFX, + Settings.SECTION_GFX_SETTINGS, + "PreferVSForLinePointExpansion", + false + ), + GFX_CPU_CULL(Settings.FILE_GFX, Settings.SECTION_GFX_SETTINGS, "CPUCull", false), + GFX_MODS_ENABLE(Settings.FILE_GFX, Settings.SECTION_GFX_SETTINGS, "EnableMods", false), + GFX_ENHANCE_FORCE_TRUE_COLOR( + Settings.FILE_GFX, + Settings.SECTION_GFX_ENHANCEMENTS, + "ForceTrueColor", + true + ), + GFX_ENHANCE_DISABLE_COPY_FILTER( + Settings.FILE_GFX, + Settings.SECTION_GFX_ENHANCEMENTS, + "DisableCopyFilter", + true + ), + GFX_ENHANCE_ARBITRARY_MIPMAP_DETECTION( + Settings.FILE_GFX, + Settings.SECTION_GFX_ENHANCEMENTS, + "ArbitraryMipmapDetection", + false + ), + GFX_CC_CORRECT_COLOR_SPACE( + Settings.FILE_GFX, + Settings.SECTION_GFX_COLOR_CORRECTION, + "CorrectColorSpace", + false + ), + GFX_CC_CORRECT_GAMMA( + Settings.FILE_GFX, + Settings.SECTION_GFX_COLOR_CORRECTION, + "CorrectGamma", + false + ), + GFX_STEREO_SWAP_EYES(Settings.FILE_GFX, Settings.SECTION_STEREOSCOPY, "StereoSwapEyes", false), + GFX_HACK_EFB_ACCESS_ENABLE( + Settings.FILE_GFX, + Settings.SECTION_GFX_HACKS, + "EFBAccessEnable", + false + ), + GFX_HACK_EFB_DEFER_INVALIDATION( + Settings.FILE_GFX, + Settings.SECTION_GFX_HACKS, + "EFBAccessDeferInvalidation", + false + ), + GFX_HACK_BBOX_ENABLE(Settings.FILE_GFX, Settings.SECTION_GFX_HACKS, "BBoxEnable", false), + GFX_HACK_SKIP_EFB_COPY_TO_RAM( + Settings.FILE_GFX, + Settings.SECTION_GFX_HACKS, + "EFBToTextureEnable", + true + ), + GFX_HACK_SKIP_XFB_COPY_TO_RAM( + Settings.FILE_GFX, + Settings.SECTION_GFX_HACKS, + "XFBToTextureEnable", + true + ), + GFX_HACK_DISABLE_COPY_TO_VRAM( + Settings.FILE_GFX, + Settings.SECTION_GFX_HACKS, + "DisableCopyToVRAM", + false + ), + GFX_HACK_DEFER_EFB_COPIES( + Settings.FILE_GFX, + Settings.SECTION_GFX_HACKS, + "DeferEFBCopies", + true + ), + GFX_HACK_IMMEDIATE_XFB( + Settings.FILE_GFX, + Settings.SECTION_GFX_HACKS, + "ImmediateXFBEnable", + false + ), + GFX_HACK_SKIP_DUPLICATE_XFBS( + Settings.FILE_GFX, + Settings.SECTION_GFX_HACKS, + "SkipDuplicateXFBs", + true + ), + GFX_HACK_COPY_EFB_SCALED(Settings.FILE_GFX, Settings.SECTION_GFX_HACKS, "EFBScaledCopy", true), + GFX_HACK_EFB_EMULATE_FORMAT_CHANGES( + Settings.FILE_GFX, + Settings.SECTION_GFX_HACKS, + "EFBEmulateFormatChanges", + false + ), + GFX_HACK_VERTEX_ROUNDING( + Settings.FILE_GFX, + Settings.SECTION_GFX_HACKS, + "VertexRounding", + false + ), + GFX_HACK_VI_SKIP(Settings.FILE_GFX, Settings.SECTION_GFX_HACKS, "VISkip", false), + GFX_HACK_FAST_TEXTURE_SAMPLING( + Settings.FILE_GFX, + Settings.SECTION_GFX_HACKS, + "FastTextureSampling", + true + ), + LOGGER_WRITE_TO_FILE( + Settings.FILE_LOGGER, + Settings.SECTION_LOGGER_OPTIONS, + "WriteToFile", + false + ), + ACHIEVEMENTS_ENABLED( + Settings.FILE_ACHIEVEMENTS, + Settings.SECTION_ACHIEVEMENTS, + "Enabled", + false + ), + ACHIEVEMENTS_HARDCORE_ENABLED( + Settings.FILE_ACHIEVEMENTS, + Settings.SECTION_ACHIEVEMENTS, + "HardcoreEnabled", + true + ), + ACHIEVEMENTS_UNOFFICIAL_ENABLED( + Settings.FILE_ACHIEVEMENTS, + Settings.SECTION_ACHIEVEMENTS, + "UnofficialEnabled", + false + ), + ACHIEVEMENTS_ENCORE_ENABLED( + Settings.FILE_ACHIEVEMENTS, + Settings.SECTION_ACHIEVEMENTS, + "EncoreEnabled", + false + ), + ACHIEVEMENTS_SPECTATOR_ENABLED( + Settings.FILE_ACHIEVEMENTS, + Settings.SECTION_ACHIEVEMENTS, + "SpectatorEnabled", + false + ), + ACHIEVEMENTS_LEADERBOARD_TRACKER_ENABLED( + Settings.FILE_ACHIEVEMENTS, + Settings.SECTION_ACHIEVEMENTS, + "LeaderboardTrackerEnabled", + true + ), + ACHIEVEMENTS_CHALLENGE_INDICATORS_ENABLED( + Settings.FILE_ACHIEVEMENTS, + Settings.SECTION_ACHIEVEMENTS, + "ChallengeIndicatorsEnabled", + true + ), + ACHIEVEMENTS_PROGRESS_ENABLED( + Settings.FILE_ACHIEVEMENTS, + Settings.SECTION_ACHIEVEMENTS, + "ProgressEnabled", + false + ), + NETPLAY_USE_UPNP(Settings.FILE_DOLPHIN, Settings.SECTION_INI_NETPLAY, "UseUPNP", false); + + override val isOverridden: Boolean + get() = NativeConfig.isOverridden(file, section, key) + + override val isRuntimeEditable: Boolean + get() { + if (file == Settings.FILE_SYSCONF) return false + for (setting in NOT_RUNTIME_EDITABLE) { + if (setting == this) return false + } + return NativeConfig.isSettingSaveable(file, section, key) + } + + override fun delete(settings: Settings): Boolean { + if (!NativeConfig.isSettingSaveable(file, section, key)) { + throw UnsupportedOperationException("Unsupported setting: $file, $section, $key") + } + return NativeConfig.deleteKey(settings.writeLayer, file, section, key) + } + + override val boolean: Boolean + get() = NativeConfig.getBoolean( + NativeConfig.LAYER_ACTIVE, + file, + section, + key, + defaultValue + ) + + override fun setBoolean(settings: Settings, newValue: Boolean) { + if (!NativeConfig.isSettingSaveable(file, section, key)) { + throw UnsupportedOperationException("Unsupported setting: $file, $section, $key") + } + NativeConfig.setBoolean(settings.writeLayer, file, section, key, newValue) + } + + fun setBoolean(layer: Int, newValue: Boolean) { + if (!NativeConfig.isSettingSaveable(file, section, key)) { + throw UnsupportedOperationException("Unsupported setting: $file, $section, $key") + } + NativeConfig.setBoolean(layer, file, section, key, newValue) + } + + companion object { + private val NOT_RUNTIME_EDITABLE_ARRAY = arrayOf( + MAIN_DSP_HLE, + MAIN_FASTMEM_ARENA, + MAIN_LARGE_ENTRY_POINTS_MAP, + MAIN_CPU_THREAD, + MAIN_ENABLE_CHEATS, + MAIN_OVERRIDE_REGION_SETTINGS, + MAIN_MMU, + MAIN_PAUSE_ON_PANIC, + MAIN_RAM_OVERRIDE_ENABLE, + MAIN_CUSTOM_RTC_ENABLE, + MAIN_DSP_JIT, + MAIN_TIME_TRACKING, + MAIN_EMULATE_SKYLANDER_PORTAL, + MAIN_EMULATE_INFINITY_BASE, + MAIN_EMULATE_WII_SPEAK, + ACHIEVEMENTS_ENABLED, + ACHIEVEMENTS_HARDCORE_ENABLED, + ACHIEVEMENTS_UNOFFICIAL_ENABLED, + ACHIEVEMENTS_ENCORE_ENABLED, + ACHIEVEMENTS_SPECTATOR_ENABLED + ) + private val NOT_RUNTIME_EDITABLE: Set = + HashSet(listOf(*NOT_RUNTIME_EDITABLE_ARRAY)) + + @JvmStatic + fun getSettingForAdapterRumble(channel: Int): BooleanSetting { + return arrayOf( + MAIN_ADAPTER_RUMBLE_0, + MAIN_ADAPTER_RUMBLE_1, + MAIN_ADAPTER_RUMBLE_2, + MAIN_ADAPTER_RUMBLE_3 + )[channel] + } + + @JvmStatic + fun getSettingForSimulateKonga(channel: Int): BooleanSetting { + return arrayOf( + MAIN_SIMULATE_KONGA_0, + MAIN_SIMULATE_KONGA_1, + MAIN_SIMULATE_KONGA_2, + MAIN_SIMULATE_KONGA_3 + )[channel] + } + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/ConfigChangedCallback.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/ConfigChangedCallback.kt new file mode 100644 index 000000000..4415efa9e --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/ConfigChangedCallback.kt @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.settings.model + +import androidx.annotation.Keep + +/** + * Calls the passed-in Runnable when Dolphin's config changes. + * + * Please note: The Runnable may be called from any thread. + */ +class ConfigChangedCallback(runnable: Runnable) { + @Keep + private var pointer: Long = initialize(runnable) + + /** + * Stops the callback from being called in the future. + */ + fun unregister() { + if (pointer != 0L) { + deinitialize(pointer) + pointer = 0L + } + } + + companion object { + @JvmStatic + private external fun initialize(runnable: Runnable): Long + + @JvmStatic + private external fun deinitialize(pointer: Long) + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/FloatSetting.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/FloatSetting.kt new file mode 100644 index 000000000..67ea46195 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/FloatSetting.kt @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.settings.model + +enum class FloatSetting( + private val file: String, + private val section: String, + private val key: String, + private val defaultValue: Float +) : AbstractFloatSetting { + // These entries have the same names and order as in C++, just for consistency. + MAIN_EMULATION_SPEED(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "EmulationSpeed", 1.0f), + MAIN_OVERCLOCK(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "Overclock", 1.0f), + MAIN_VI_OVERCLOCK(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "VIOverclock", 1.0f), + GFX_CC_GAME_GAMMA(Settings.FILE_GFX, Settings.SECTION_GFX_COLOR_CORRECTION, "GameGamma", 2.35f), + GFX_STEREO_DEPTH(Settings.FILE_GFX, Settings.SECTION_STEREOSCOPY, "StereoDepth", 20.0f), + GFX_STEREO_CONVERGENCE(Settings.FILE_GFX, Settings.SECTION_STEREOSCOPY, "StereoConvergence", 20.0f); + + override val isOverridden: Boolean + get() = NativeConfig.isOverridden(file, section, key) + + override val isRuntimeEditable: Boolean + get() = NativeConfig.isSettingSaveable(file, section, key) + + override fun delete(settings: Settings): Boolean { + if (!NativeConfig.isSettingSaveable(file, section, key)) { + throw UnsupportedOperationException("Unsupported setting: $file, $section, $key") + } + return NativeConfig.deleteKey(settings.writeLayer, file, section, key) + } + + override val float: Float + get() = NativeConfig.getFloat(NativeConfig.LAYER_ACTIVE, file, section, key, defaultValue) + + override fun setFloat(settings: Settings, newValue: Float) { + if (!NativeConfig.isSettingSaveable(file, section, key)) { + throw UnsupportedOperationException("Unsupported setting: $file, $section, $key") + } + NativeConfig.setFloat(settings.writeLayer, file, section, key, newValue) + } + + fun setFloat(layer: Int, newValue: Float) { + NativeConfig.setFloat(layer, file, section, key, newValue) + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/IntSetting.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/IntSetting.kt new file mode 100644 index 000000000..4d5f49b54 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/IntSetting.kt @@ -0,0 +1,253 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.settings.model + +import android.content.pm.ActivityInfo +import org.dolphinemu.dolphinemu.NativeLibrary +import org.dolphinemu.dolphinemu.overlay.InputOverlayPointer +import java.util.* + +enum class IntSetting( + private val file: String, + private val section: String, + private val key: String, + private val defaultValue: Int +) : AbstractIntSetting { + // These entries have the same names and order as in C++, just for consistency. + MAIN_CPU_CORE( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_CORE, + "CPUCore", + NativeLibrary.DefaultCPUCore() + ), + MAIN_GC_LANGUAGE(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "SelectedLanguage", 0), + MAIN_MEM1_SIZE(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "MEM1Size", 0x01800000), + MAIN_MEM2_SIZE(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "MEM2Size", 0x04000000), + MAIN_SLOT_A(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "SlotA", 8), + MAIN_SLOT_B(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "SlotB", 255), + MAIN_SERIAL_PORT_1(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "SerialPort1", 255), + MAIN_FALLBACK_REGION(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "FallbackRegion", 2), + MAIN_SI_DEVICE_0(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "SIDevice0", 6), + MAIN_SI_DEVICE_1(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "SIDevice1", 0), + MAIN_SI_DEVICE_2(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "SIDevice2", 0), + MAIN_SI_DEVICE_3(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "SIDevice3", 0), + MAIN_AUDIO_VOLUME(Settings.FILE_DOLPHIN, Settings.SECTION_INI_DSP, "Volume", 100), + MAIN_AUDIO_BUFFER_SIZE(Settings.FILE_DOLPHIN, Settings.SECTION_INI_DSP, "AudioBufferSize", 80), + MAIN_OVERLAY_GC_CONTROLLER( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID, + "OverlayGCController", + 0 + ), + + // Defaults to GameCube controller 1 + MAIN_OVERLAY_WII_CONTROLLER( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID, + "OverlayWiiController", + 4 + ), + + // Defaults to Wii Remote 1 + MAIN_CONTROL_SCALE(Settings.FILE_DOLPHIN, Settings.SECTION_INI_ANDROID, "ControlScale", 50), + MAIN_CONTROL_OPACITY(Settings.FILE_DOLPHIN, Settings.SECTION_INI_ANDROID, "ControlOpacity", 65), + MAIN_EMULATION_ORIENTATION( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID, + "EmulationOrientation", + ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE + ), + MAIN_INTERFACE_THEME(Settings.FILE_DOLPHIN, Settings.SECTION_INI_ANDROID, "InterfaceTheme", 0), + MAIN_INTERFACE_THEME_MODE( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID, + "InterfaceThemeMode", + -1 + ), + MAIN_LAST_PLATFORM_TAB( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID, + "LastPlatformTab", + 0 + ), + MAIN_IR_MODE( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID, + "IRMode", + InputOverlayPointer.MODE_FOLLOW + ), + MAIN_DOUBLE_TAP_BUTTON( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_ANDROID_OVERLAY_BUTTONS, + "DoubleTapButton", + NativeLibrary.ButtonType.WIIMOTE_BUTTON_A + ), + SYSCONF_LANGUAGE(Settings.FILE_SYSCONF, "IPL", "LNG", 0x01), + SYSCONF_SOUND_MODE(Settings.FILE_SYSCONF, "IPL", "SND", 0x01), + SYSCONF_SENSOR_BAR_POSITION(Settings.FILE_SYSCONF, "BT", "BAR", 0x01), + SYSCONF_SENSOR_BAR_SENSITIVITY(Settings.FILE_SYSCONF, "BT", "SENS", 0x03), + SYSCONF_SPEAKER_VOLUME(Settings.FILE_SYSCONF, "BT", "SPKV", 0x58), + GFX_ASPECT_RATIO(Settings.FILE_GFX, Settings.SECTION_GFX_SETTINGS, "AspectRatio", 0), + GFX_SAFE_TEXTURE_CACHE_COLOR_SAMPLES( + Settings.FILE_GFX, + Settings.SECTION_GFX_SETTINGS, + "SafeTextureCacheColorSamples", + 128 + ), + GFX_PNG_COMPRESSION_LEVEL( + Settings.FILE_GFX, + Settings.SECTION_GFX_SETTINGS, + "PNGCompressionLevel", + 6 + ), + GFX_MSAA(Settings.FILE_GFX, Settings.SECTION_GFX_SETTINGS, "MSAA", 1), + GFX_EFB_SCALE(Settings.FILE_GFX, Settings.SECTION_GFX_SETTINGS, "InternalResolution", 1), + GFX_SHADER_COMPILATION_MODE( + Settings.FILE_GFX, + Settings.SECTION_GFX_SETTINGS, + "ShaderCompilationMode", + 0 + ), + GFX_ENHANCE_FORCE_TEXTURE_FILTERING( + Settings.FILE_GFX, + Settings.SECTION_GFX_ENHANCEMENTS, + "ForceTextureFiltering", + 0 + ), + GFX_ENHANCE_MAX_ANISOTROPY( + Settings.FILE_GFX, + Settings.SECTION_GFX_ENHANCEMENTS, + "MaxAnisotropy", + 0 + ), + GFX_CC_GAME_COLOR_SPACE( + Settings.FILE_GFX, + Settings.SECTION_GFX_COLOR_CORRECTION, + "GameColorSpace", + 0 + ), + GFX_STEREO_MODE(Settings.FILE_GFX, Settings.SECTION_STEREOSCOPY, "StereoMode", 0), + GFX_PERF_SAMP_WINDOW( + Settings.FILE_GFX, + Settings.SECTION_GFX_SETTINGS, + "PerfSampWindowMS", + 1000 + ), + GFX_CROP_CUSTOM_TOP( + Settings.FILE_GFX, + Settings.SECTION_GFX_SETTINGS, + "CropCustomTop", + 0 + ), + GFX_CROP_CUSTOM_BOTTOM( + Settings.FILE_GFX, + Settings.SECTION_GFX_SETTINGS, + "CropCustomBottom", + 0 + ), + GFX_CROP_CUSTOM_LEFT( + Settings.FILE_GFX, + Settings.SECTION_GFX_SETTINGS, + "CropCustomLeft", + 0 + ), + GFX_CROP_CUSTOM_RIGHT( + Settings.FILE_GFX, + Settings.SECTION_GFX_SETTINGS, + "CropCustomRight", + 0 + ), + LOGGER_VERBOSITY(Settings.FILE_LOGGER, Settings.SECTION_LOGGER_OPTIONS, "Verbosity", 1), + WIIMOTE_1_SOURCE(Settings.FILE_WIIMOTE, "Wiimote1", "Source", 1), + WIIMOTE_2_SOURCE(Settings.FILE_WIIMOTE, "Wiimote2", "Source", 0), + WIIMOTE_3_SOURCE(Settings.FILE_WIIMOTE, "Wiimote3", "Source", 0), + WIIMOTE_4_SOURCE(Settings.FILE_WIIMOTE, "Wiimote4", "Source", 0), + WIIMOTE_BB_SOURCE(Settings.FILE_WIIMOTE, "BalanceBoard", "Source", 0), + NETPLAY_CONNECT_PORT(Settings.FILE_DOLPHIN, Settings.SECTION_INI_NETPLAY, "ConnectPort", 2626), + NETPLAY_HOST_PORT(Settings.FILE_DOLPHIN, Settings.SECTION_INI_NETPLAY, "HostPort", 2626), + NETPLAY_CLIENT_BUFFER_SIZE( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_NETPLAY, + "BufferSizeClient", + 1 + ), + NETPLAY_BUFFER_SIZE( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_NETPLAY, + "BufferSize", + 5 + ); + + override val isOverridden: Boolean + get() = NativeConfig.isOverridden(file, section, key) + + override val isRuntimeEditable: Boolean + get() { + if (file == Settings.FILE_SYSCONF) return false + for (setting in NOT_RUNTIME_EDITABLE) { + if (setting == this) return false + } + return NativeConfig.isSettingSaveable(file, section, key) + } + + override fun delete(settings: Settings): Boolean { + if (!NativeConfig.isSettingSaveable(file, section, key)) { + throw UnsupportedOperationException("Unsupported setting: $file, $section, $key") + } + return NativeConfig.deleteKey(settings.writeLayer, file, section, key) + } + + override val int: Int + get() = NativeConfig.getInt(NativeConfig.LAYER_ACTIVE, file, section, key, defaultValue) + + override fun setInt(settings: Settings, newValue: Int) { + if (!NativeConfig.isSettingSaveable(file, section, key)) { + throw UnsupportedOperationException("Unsupported setting: $file, $section, $key") + } + NativeConfig.setInt(settings.writeLayer, file, section, key, newValue) + } + + fun setInt(layer: Int, newValue: Int) { + if (!NativeConfig.isSettingSaveable(file, section, key)) { + throw UnsupportedOperationException("Unsupported setting: $file, $section, $key") + } + NativeConfig.setInt(layer, file, section, key, newValue) + } + + companion object { + private val NOT_RUNTIME_EDITABLE_ARRAY = arrayOf( + MAIN_CPU_CORE, + MAIN_GC_LANGUAGE, + MAIN_MEM1_SIZE, + MAIN_MEM2_SIZE, + MAIN_SLOT_A, + MAIN_SLOT_B, + MAIN_SERIAL_PORT_1, + MAIN_FALLBACK_REGION + ) + + private val NOT_RUNTIME_EDITABLE: Set = + HashSet(listOf(*NOT_RUNTIME_EDITABLE_ARRAY)) + + @JvmStatic + fun getSettingForSIDevice(channel: Int): IntSetting { + return arrayOf( + MAIN_SI_DEVICE_0, + MAIN_SI_DEVICE_1, + MAIN_SI_DEVICE_2, + MAIN_SI_DEVICE_3 + )[channel] + } + + @JvmStatic + fun getSettingForWiimoteSource(index: Int): IntSetting { + return arrayOf( + WIIMOTE_1_SOURCE, + WIIMOTE_2_SOURCE, + WIIMOTE_3_SOURCE, + WIIMOTE_4_SOURCE, + WIIMOTE_BB_SOURCE + )[index] + } + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/NativeConfig.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/NativeConfig.kt new file mode 100644 index 000000000..5a2b31ce4 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/NativeConfig.kt @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.settings.model + +object NativeConfig { + const val LAYER_BASE_OR_CURRENT = 0 + const val LAYER_BASE = 1 + const val LAYER_LOCAL_GAME = 2 + const val LAYER_ACTIVE = 3 + const val LAYER_CURRENT = 4 + + @JvmStatic + external fun isSettingSaveable(file: String, section: String, key: String): Boolean + + @JvmStatic + external fun loadGameInis(gameId: String, revision: Int) + + @JvmStatic + external fun unloadGameInis() + + @JvmStatic + external fun save(layer: Int) + + @JvmStatic + external fun deleteAllKeys(layer: Int) + + @JvmStatic + external fun isOverridden(file: String, section: String, key: String): Boolean + + @JvmStatic + external fun deleteKey(layer: Int, file: String, section: String, key: String): Boolean + + @JvmStatic + external fun exists(layer: Int, file: String, section: String, key: String): Boolean + + @JvmStatic + external fun getString( + layer: Int, + file: String, + section: String, + key: String, + defaultValue: String + ): String + + @JvmStatic + external fun getBoolean( + layer: Int, + file: String, + section: String, + key: String, + defaultValue: Boolean + ): Boolean + + @JvmStatic + external fun getInt( + layer: Int, + file: String, + section: String, + key: String, + defaultValue: Int + ): Int + + @JvmStatic + external fun getFloat( + layer: Int, + file: String, + section: String, + key: String, + defaultValue: Float + ): Float + + @JvmStatic + external fun setString( + layer: Int, + file: String, + section: String, + key: String, + value: String + ) + + @JvmStatic + external fun setBoolean( + layer: Int, + file: String, + section: String, + key: String, + value: Boolean + ) + + @JvmStatic + external fun setInt( + layer: Int, + file: String, + section: String, + key: String, + value: Int + ) + + @JvmStatic + external fun setFloat( + layer: Int, + file: String, + section: String, + key: String, + value: Float + ) +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/PostProcessing.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/PostProcessing.kt new file mode 100644 index 000000000..04fe2734b --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/PostProcessing.kt @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.settings.model + +object PostProcessing { + @JvmStatic + val shaderList: Array + external get + + @JvmStatic + val anaglyphShaderList: Array + external get + + @JvmStatic + val passiveShaderList: Array + external get +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/ScaledIntSetting.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/ScaledIntSetting.kt new file mode 100644 index 000000000..4eef9ed6c --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/ScaledIntSetting.kt @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.settings.model + +class ScaledIntSetting( + private val scale: Int, + private val setting: AbstractIntSetting +) : AbstractIntSetting { + override val isOverridden: Boolean + get() = setting.isOverridden + + override val isRuntimeEditable: Boolean + get() = setting.isRuntimeEditable + + override fun delete(settings: Settings): Boolean { + return setting.delete(settings) + } + + override val int: Int + get() = setting.int / scale + + override fun setInt(settings: Settings, newValue: Int) { + return setting.setInt(settings, newValue * scale) + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/Settings.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/Settings.kt new file mode 100644 index 000000000..da54d8125 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/Settings.kt @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.settings.model + +import android.text.TextUtils +import org.dolphinemu.dolphinemu.NativeLibrary +import org.dolphinemu.dolphinemu.features.input.model.MappingCommon +import java.io.Closeable + +/** + * Represents a set of settings stored in the native part of Dolphin. + * + * A set of settings can be either the global settings, or game settings for a particular game. + */ +class Settings : Closeable { + private var gameId: String = "" + private var revision = 0 + + var isWii = false + private set + + private var settingsLoaded = false + + private val isGameSpecific: Boolean + get() = !TextUtils.isEmpty(gameId) + + val writeLayer: Int + get() = if (isGameSpecific) NativeConfig.LAYER_LOCAL_GAME else NativeConfig.LAYER_BASE_OR_CURRENT + + fun areSettingsLoaded(): Boolean { + return settingsLoaded + } + + @JvmOverloads + fun loadSettings(isWii: Boolean = true) { + this.isWii = isWii + settingsLoaded = true + + if (isGameSpecific) { + // Loading game INIs while the core is running will mess with the game INIs loaded by the core + check(NativeLibrary.IsUninitialized()) { "Attempted to load game INI while emulating" } + NativeConfig.loadGameInis(gameId, revision) + } + } + + fun loadSettings(gameId: String, revision: Int, isWii: Boolean) { + this.gameId = gameId + this.revision = revision + loadSettings(isWii) + } + + fun saveSettings() { + if (!isGameSpecific) { + MappingCommon.save() + + NativeConfig.save(NativeConfig.LAYER_BASE) + + NativeLibrary.ReloadLoggerConfig() + } else { + NativeConfig.save(NativeConfig.LAYER_LOCAL_GAME) + } + } + + fun clearGameSettings() { + NativeConfig.deleteAllKeys(NativeConfig.LAYER_LOCAL_GAME) + } + + fun gameIniContainsJunk(): Boolean { + // Older versions of Android Dolphin would copy the entire contents of most of the global INIs + // into any game INI that got saved (with some of the sections renamed to match the game INI + // section names). The problems with this are twofold: + // + // 1. The user game INIs will contain entries that Dolphin doesn't support reading from + // game INIs. This is annoying when editing game INIs manually but shouldn't really be + // a problem for those who only use the GUI. + // + // 2. Global settings will stick around in user game INIs. For instance, if someone wants to + // change the texture cache accuracy to safe for all games, they have to edit not only the + // global settings but also every single game INI they have created, since the old value of + // the texture cache accuracy Setting has been copied into every user game INI. + // + // These problems are serious enough that we should detect and delete such INI files. + // Problem 1 is easy to detect, but due to the nature of problem 2, it's unfortunately not + // possible to know which lines were added intentionally by the user and which lines were added + // unintentionally, which is why we have to delete the whole file in order to fix everything. + return if (!isGameSpecific) false else NativeConfig.exists( + NativeConfig.LAYER_LOCAL_GAME, + FILE_DOLPHIN, + SECTION_INI_INTERFACE, + "ThemeName" + ) + } + + override fun close() { + if (isGameSpecific) { + NativeConfig.unloadGameInis() + } + } + + companion object { + const val FILE_DOLPHIN = "Dolphin" + const val FILE_SYSCONF = "SYSCONF" + const val FILE_GFX = "GFX" + const val FILE_LOGGER = "Logger" + const val FILE_WIIMOTE = "WiimoteNew" + const val FILE_ACHIEVEMENTS = "RetroAchievements" + const val FILE_GAME_SETTINGS_ONLY = "GameSettingsOnly" + const val SECTION_INI_ANDROID = "Android" + const val SECTION_INI_ANDROID_OVERLAY_BUTTONS = "AndroidOverlayButtons" + const val SECTION_INI_GENERAL = "General" + const val SECTION_INI_CORE = "Core" + const val SECTION_INI_INTERFACE = "Interface" + const val SECTION_INI_DSP = "DSP" + const val SECTION_INI_GBA = "GBA" + const val SECTION_INI_NETPLAY = "NetPlay" + const val SECTION_LOGGER_LOGS = "Logs" + const val SECTION_LOGGER_OPTIONS = "Options" + const val SECTION_GFX_HARDWARE = "Hardware" + const val SECTION_GFX_SETTINGS = "Settings" + const val SECTION_GFX_ENHANCEMENTS = "Enhancements" + const val SECTION_GFX_COLOR_CORRECTION = "ColorCorrection" + const val SECTION_GFX_HACKS = "Hacks" + const val SECTION_DEBUG = "Debug" + const val SECTION_EMULATED_USB_DEVICES = "EmulatedUSBDevices" + const val SECTION_STEREOSCOPY = "Stereoscopy" + const val SECTION_ANALYTICS = "Analytics" + const val SECTION_ACHIEVEMENTS = "Achievements" + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/StringSetting.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/StringSetting.kt new file mode 100644 index 000000000..72877429a --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/settings/model/StringSetting.kt @@ -0,0 +1,159 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.settings.model + +import org.dolphinemu.dolphinemu.NativeLibrary +import java.util.* + +enum class StringSetting( + private val file: String, + private val section: String, + private val key: String, + private val defaultValue: String +) : AbstractStringSetting { + // These entries have the same names and order as in C++, just for consistency. + MAIN_DEFAULT_ISO(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "DefaultISO", ""), + MAIN_BBA_MAC(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "BBA_MAC", ""), + MAIN_BBA_XLINK_IP(Settings.FILE_DOLPHIN, Settings.SECTION_INI_CORE, "BBA_XLINK_IP", ""), + + // Schthack PSO Server - https://schtserv.com/ + MAIN_BBA_BUILTIN_DNS( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_CORE, + "BBA_BUILTIN_DNS", + "3.18.217.27" + ), + MAIN_BBA_TAPSERVER_DESTINATION( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_CORE, + "BBA_TAPSERVER_DESTINATION", + "/tmp/dolphin-tap" + ), + MAIN_MODEM_TAPSERVER_DESTINATION( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_CORE, + "MODEM_TAPSERVER_DESTINATION", + "/tmp/dolphin-modem-tap" + ), + MAIN_CUSTOM_RTC_VALUE( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_CORE, + "CustomRTCValue", + "0x386d4380" + ), + MAIN_GFX_BACKEND( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_CORE, + "GFXBackend", + NativeLibrary.GetDefaultGraphicsBackendConfigName() + ), + MAIN_DUMP_PATH(Settings.FILE_DOLPHIN, Settings.SECTION_INI_GENERAL, "DumpPath", ""), + MAIN_LOAD_PATH(Settings.FILE_DOLPHIN, Settings.SECTION_INI_GENERAL, "LoadPath", ""), + MAIN_RESOURCEPACK_PATH( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_GENERAL, + "ResourcePackPath", + "" + ), + MAIN_FS_PATH(Settings.FILE_DOLPHIN, Settings.SECTION_INI_GENERAL, "NANDRootPath", ""), + MAIN_WII_SD_CARD_IMAGE_PATH( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_GENERAL, + "WiiSDCardPath", + "" + ), + MAIN_WII_SD_CARD_SYNC_FOLDER_PATH( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_GENERAL, + "WiiSDCardSyncFolder", + "" + ), + MAIN_WFS_PATH(Settings.FILE_DOLPHIN, Settings.SECTION_INI_GENERAL, "WFSPath", ""), + MAIN_GBA_BIOS_PATH(Settings.FILE_DOLPHIN, Settings.SECTION_INI_GBA, "BIOS", ""), + MAIN_GB_PLAYER_ROM(Settings.FILE_DOLPHIN, Settings.SECTION_INI_GBA, "GBPlayerRom", ""), + MAIN_GBA_SAVES_PATH(Settings.FILE_DOLPHIN, Settings.SECTION_INI_GBA, "SavesPath", ""), + MAIN_TRIFORCE_IP_REDIRECTIONS( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_CORE, + "TriforceIPRedirections", + "0.0.0.0/0=127.0.0.1" + ), + GFX_ENHANCE_POST_SHADER( + Settings.FILE_GFX, + Settings.SECTION_GFX_ENHANCEMENTS, + "PostProcessingShader", + "" + ), + GFX_DRIVER_LIB_NAME( + Settings.FILE_GFX, + Settings.SECTION_GFX_SETTINGS, + "DriverLibName", + "" + ), + ACHIEVEMENTS_USERNAME( + Settings.FILE_ACHIEVEMENTS, + Settings.SECTION_ACHIEVEMENTS, + "Username", + "" + ), + ACHIEVEMENTS_API_TOKEN( + Settings.FILE_ACHIEVEMENTS, + Settings.SECTION_ACHIEVEMENTS, + "ApiToken", + "" + ), + NETPLAY_TRAVERSAL_CHOICE( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_NETPLAY, + "TraversalChoice", + "direct" + ), + NETPLAY_HOST_CODE( + Settings.FILE_DOLPHIN, + Settings.SECTION_INI_NETPLAY, + "HostCode", + "" + ), + NETPLAY_ADDRESS(Settings.FILE_DOLPHIN, Settings.SECTION_INI_NETPLAY, "Address", "127.0.0.1"), + NETPLAY_NICKNAME(Settings.FILE_DOLPHIN, Settings.SECTION_INI_NETPLAY, "Nickname", "Player"), + NETPLAY_GAME(Settings.FILE_DOLPHIN, Settings.SECTION_INI_NETPLAY, "Game", ""), + NETPLAY_NETWORK_MODE(Settings.FILE_DOLPHIN, Settings.SECTION_INI_NETPLAY, "NetworkMode", "fixeddelay"); + + override val isOverridden: Boolean + get() = NativeConfig.isOverridden(file, section, key) + + override val isRuntimeEditable: Boolean + get() { + for (setting in NOT_RUNTIME_EDITABLE) { + if (setting == this) return false + } + return NativeConfig.isSettingSaveable(file, section, key) + } + + override fun delete(settings: Settings): Boolean { + return NativeConfig.deleteKey(settings.writeLayer, file, section, key) + } + + override val string: String + get() = if (!NativeConfig.isSettingSaveable(file, section, key)) { + throw UnsupportedOperationException("Unsupported setting: $file, $section, $key") + } else NativeConfig.getString(NativeConfig.LAYER_ACTIVE, file, section, key, defaultValue) + + override fun setString(settings: Settings, newValue: String) { + NativeConfig.setString(settings.writeLayer, file, section, key, newValue) + } + + fun setString(layer: Int, newValue: String) { + NativeConfig.setString(layer, file, section, key, newValue) + } + + companion object { + private val NOT_RUNTIME_EDITABLE_ARRAY = arrayOf( + MAIN_CUSTOM_RTC_VALUE, + MAIN_GFX_BACKEND + ) + + private val NOT_RUNTIME_EDITABLE: Set = + HashSet(listOf(*NOT_RUNTIME_EDITABLE_ARRAY)) + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/skylanders/SkylanderConfig.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/skylanders/SkylanderConfig.kt new file mode 100644 index 000000000..b8cf8a475 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/skylanders/SkylanderConfig.kt @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.skylanders + +import android.util.Pair +import org.dolphinemu.dolphinemu.features.skylanders.model.SkylanderPair + +object SkylanderConfig { + var LIST_SKYLANDERS: Map = getSkylanderMap() + var REVERSE_LIST_SKYLANDERS: Map = getInverseSkylanderMap() + + private external fun getSkylanderMap(): Map + private external fun getInverseSkylanderMap(): Map + + @JvmStatic + external fun removeSkylander(slot: Int): Boolean + + @JvmStatic + external fun loadSkylander(slot: Int, fileName: String?): Pair? + + @JvmStatic + external fun createSkylander( + id: Int, + variant: Int, + fileName: String, + slot: Int + ): Pair +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/skylanders/model/Skylander.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/skylanders/model/Skylander.kt new file mode 100644 index 000000000..021607bae --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/skylanders/model/Skylander.kt @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.skylanders.model + +class Skylander(id: Int, variant: Int, var name: String) { + private val pair: SkylanderPair = SkylanderPair(id, variant) + + val id: Int get() = pair.id + val variant: Int get() = pair.variant + + companion object { + @JvmField + val BLANK_SKYLANDER = Skylander(-1, -1, "Blank") + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/skylanders/model/SkylanderPair.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/skylanders/model/SkylanderPair.kt new file mode 100644 index 000000000..6b20567bb --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/features/skylanders/model/SkylanderPair.kt @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.features.skylanders.model + +class SkylanderPair(var id: Int, var variant: Int) { + override fun hashCode(): Int { + return (id shl 16) + variant + } + + override fun equals(other: Any?): Boolean { + if (other !is SkylanderPair) return false + if (other.id != id) return false + return other.variant == variant + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/model/GameFile.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/model/GameFile.kt new file mode 100644 index 000000000..26da17428 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/model/GameFile.kt @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.model + +import androidx.annotation.Keep +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +@Keep +class GameFile private constructor(private val pointer: Long) { + external fun finalize() + + external fun getPlatform(): Int + + external fun getTitle(): String + + external fun getDescription(): String + + external fun getCompany(): String + + external fun getCountry(): Int + + external fun getRegion(): Int + + external fun getPath(): String + + external fun getGameId(): String + + external fun getGameTdbId(): String + + external fun getDiscNumber(): Int + + external fun getRevision(): Int + + external fun getBlobType(): Int + + external fun getFileFormatName(): String + + external fun getBlockSize(): Long + + external fun getCompressionMethod(): String + + external fun shouldShowFileFormatDetails(): Boolean + + external fun shouldAllowConversion(): Boolean + + external fun getFileSize(): Long + + external fun isDatelDisc(): Boolean + + external fun isNKit(): Boolean + + external fun getBanner(): IntArray + + external fun getBannerWidth(): Int + + external fun getBannerHeight(): Int + + suspend fun getTimePlayedMs(): Long { + // getTimePlayedMsInternal reads from disk, so let's use coroutines. + return withContext(Dispatchers.IO) { + getTimePlayedMsInternal() + } + } + + external private fun getTimePlayedMsInternal(): Long + + val customCoverPath: String + get() = "${getPath().substring(0, getPath().lastIndexOf("."))}.cover.png" + + companion object { + var REGION_NTSC_J = 0 + var REGION_NTSC_U = 1 + var REGION_PAL = 2 + var REGION_NTSC_K = 4 + + @JvmStatic + external fun parse(path: String): GameFile? + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/model/GameFileCache.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/model/GameFileCache.kt new file mode 100644 index 000000000..97064f552 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/model/GameFileCache.kt @@ -0,0 +1,102 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.model + +import androidx.annotation.Keep +import org.dolphinemu.dolphinemu.features.settings.model.BooleanSetting +import org.dolphinemu.dolphinemu.features.settings.model.NativeConfig +import org.dolphinemu.dolphinemu.utils.ContentHandler +import java.io.File + +class GameFileCache { + @Keep + private val pointer: Long = newGameFileCache() + + external fun finalize() + + @Synchronized + external fun getSize(): Int + + @Synchronized + external fun getAllGames(): Array + + @Synchronized + external fun addOrGet(gamePath: String): GameFile? + + /** + * Sets the list of games to cache. + * + * Games which are in the passed-in list but not in the cache are scanned and added to the cache, + * and games which are in the cache but not in the passed-in list are removed from the cache. + * + * @return true if the cache was modified + */ + @Synchronized + external fun update(gamePaths: Array): Boolean + + /** + * For each game that already is in the cache, scans the folder that contains the game + * for additional metadata files (PNG/XML). + * + * @return true if the cache was modified + */ + @Synchronized + external fun updateAdditionalMetadata(): Boolean + + @Synchronized + external fun load(): Boolean + + @Synchronized + external fun save(): Boolean + + companion object { + @JvmStatic + private external fun newGameFileCache(): Long + + fun addGameFolder(path: String) { + val paths = getIsoPaths() + + if (!paths.contains(path)) { + setIsoPaths(paths + path) + NativeConfig.save(NativeConfig.LAYER_BASE) + } + } + + private fun getFolderPaths(removeNonExistentFolders: Boolean): Array { + val paths = getIsoPaths() + + val filteredPaths = paths.filter {path -> + if (ContentHandler.isContentUri(path)) + ContentHandler.exists(path) + else + File(path).exists() + }.toTypedArray() + + if (removeNonExistentFolders && paths.size > filteredPaths.size) { + setIsoPaths(filteredPaths) + NativeConfig.save(NativeConfig.LAYER_BASE) + } + + return filteredPaths + } + + @JvmStatic + fun getAllGamePaths(): Array { + val recursiveScan = BooleanSetting.MAIN_RECURSIVE_ISO_PATHS.boolean + val folderPaths = getFolderPaths(true) + return getAllGamePaths(folderPaths, recursiveScan) + } + + @JvmStatic + external fun getAllGamePaths( + folderPaths: Array, + recursiveScan: Boolean + ): Array + + @JvmStatic + external fun getIsoPaths(): Array + + @JvmStatic + external fun setIsoPaths(paths: Array) + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/services/USBPermService.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/services/USBPermService.kt new file mode 100644 index 000000000..2c52cd54f --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/services/USBPermService.kt @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +@file:Suppress("DEPRECATION", "OVERRIDE_DEPRECATION") + +package org.dolphinemu.dolphinemu.services + +import android.app.IntentService +import android.content.Intent + +class USBPermService : IntentService("USBPermService") { + // Needed when extending IntentService. + // We don't care about the results of the intent handler for this. + override fun onHandleIntent(intent: Intent?) { + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/AudioUtils.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/AudioUtils.kt new file mode 100644 index 000000000..68e3573fa --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/AudioUtils.kt @@ -0,0 +1,28 @@ +package org.dolphinemu.dolphinemu.utils + +import android.content.Context +import android.media.AudioManager +import androidx.annotation.Keep +import org.dolphinemu.dolphinemu.DolphinApplication + +object AudioUtils { + @JvmStatic @Keep + fun getSampleRate(): Int = + getAudioServiceProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE, 48000) + + @JvmStatic @Keep + fun getFramesPerBuffer(): Int = + getAudioServiceProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER, 256) + + private fun getAudioServiceProperty(property: String, fallback: Int): Int { + return try { + val context = DolphinApplication.getAppContext() + val am = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager + Integer.parseUnsignedInt(am.getProperty(property)) + } catch (e: NullPointerException) { + fallback + } catch (e: NumberFormatException) { + fallback + } + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/BooleanSupplier.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/BooleanSupplier.kt new file mode 100644 index 000000000..b7dcd196e --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/BooleanSupplier.kt @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.utils + +import androidx.annotation.Keep + +/** + * java.util.function.BooleanSupplier is only provided starting with API 24, while Dolphin still supports API + * 21. API desugaring lets Kotlin/Java code use it on older Android versions, but JNI `FindClass("java/util/ + * function/BooleanSupplier")` isn’t desugared, so native code can’t look up that type reliably on API 23 and + * below. Because of that limitation, we keep our own interface instead of relying on the platform type. + */ +@Keep +fun interface BooleanSupplier { + fun get(): Boolean +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/CompressCallback.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/CompressCallback.kt new file mode 100644 index 000000000..498c9a518 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/CompressCallback.kt @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.utils + +import androidx.annotation.Keep + +@Keep +fun interface CompressCallback { + fun run(text: String, completion: Float): Boolean +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/ContentHandler.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/ContentHandler.kt new file mode 100644 index 000000000..b5e445683 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/ContentHandler.kt @@ -0,0 +1,331 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.utils + +import android.content.ContentResolver +import android.net.Uri +import android.provider.DocumentsContract +import android.provider.DocumentsContract.Document +import androidx.annotation.Keep +import androidx.core.net.toUri +import org.dolphinemu.dolphinemu.DolphinApplication +import java.io.FileNotFoundException + +/* + We use a lot of "catch (Exception e)" in this class. This is for two reasons: + + 1. We don't want any exceptions to escape to native code, as this leads to nasty crashes + that often don't have stack traces that make sense. + + 2. The sheer number of different exceptions, both documented and undocumented. These include: + - FileNotFoundException when a file doesn't exist + - FileNotFoundException when using an invalid open mode (according to the documentation) + - IllegalArgumentException when using an invalid open mode (in practice with FileProvider) + - IllegalArgumentException when providing a tree where a document was expected and vice versa + - SecurityException when trying to access something the user hasn't granted us permission to + - UnsupportedOperationException when a URI specifies a storage provider that doesn't exist + */ +object ContentHandler { + @JvmStatic + fun isContentUri(pathOrUri: String): Boolean { + return pathOrUri.startsWith("content://") + } + + @Keep + @JvmStatic + fun openFd(uri: String, mode: String): Int { + try { + return getContentResolver().openFileDescriptor(unmangle(uri), mode)!!.detachFd() + } catch (_: SecurityException) { + Log.error("Tried to open $uri without permission") + } catch (_: Exception) { + } + + return -1 + } + + @Keep + @JvmStatic + fun delete(uri: String): Boolean { + try { + return DocumentsContract.deleteDocument(getContentResolver(), unmangle(uri)) + } catch (_: FileNotFoundException) { + // Return true because we care about the file not being there, not the actual delete. + return true + } catch (_: SecurityException) { + Log.error("Tried to delete $uri without permission") + } catch (_: Exception) { + } + + return false + } + + @JvmStatic + fun exists(uri: String): Boolean { + try { + val documentUri = treeToDocument(unmangle(uri)) + val projection = arrayOf(Document.COLUMN_MIME_TYPE, Document.COLUMN_SIZE) + getContentResolver().query(documentUri, projection, null, null, null)?.use { cursor -> + return cursor.count > 0 + } + } catch (_: SecurityException) { + Log.error("Tried to check if $uri exists without permission") + } catch (_: Exception) { + } + + return false + } + + /** + * @return -1 if not found, -2 if directory, file size otherwise + */ + @Keep + @JvmStatic + fun getSizeAndIsDirectory(uri: String): Long { + try { + val documentUri = treeToDocument(unmangle(uri)) + val projection = arrayOf(Document.COLUMN_MIME_TYPE, Document.COLUMN_SIZE) + getContentResolver().query(documentUri, projection, null, null, null)?.use { cursor -> + if (cursor.moveToFirst()) { + return if (Document.MIME_TYPE_DIR == cursor.getString(0)) { + -2 + } else { + if (cursor.isNull(1)) 0 else cursor.getLong(1) + } + } + } + } catch (_: SecurityException) { + Log.error("Tried to get metadata for $uri without permission") + } catch (_: Exception) { + } + + return -1 + } + + @Keep + @JvmStatic + fun getDisplayName(uri: String): String? { + try { + return getDisplayName(unmangle(uri)) + } catch (_: Exception) { + } + + return null + } + + @JvmStatic + fun getDisplayName(uri: Uri): String? { + val projection = arrayOf(Document.COLUMN_DISPLAY_NAME) + val documentUri = treeToDocument(uri) + try { + getContentResolver().query(documentUri, projection, null, null, null)?.use { cursor -> + if (cursor.moveToFirst()) { + return cursor.getString(0) + } + } + } catch (_: SecurityException) { + Log.error("Tried to get display name of $uri without permission") + } catch (_: Exception) { + } + + return null + } + + @Keep + @JvmStatic + fun getChildNames(uri: String, recursive: Boolean): Array { + try { + return getChildNames(unmangle(uri), recursive) + } catch (_: Exception) { + } + + return emptyArray() + } + + @JvmStatic + fun getChildNames(uri: Uri, recursive: Boolean): Array { + val result = ArrayList() + fun addChildren(documentId: String) { + forEachChild(uri, documentId) { displayName, childDocumentId, isDirectory -> + if (recursive && isDirectory) { + addChildren(childDocumentId) + } else { + result.add(displayName) + } + } + } + + addChildren(DocumentsContract.getDocumentId(treeToDocument(uri))) + return result.toTypedArray() + } + + @Keep + @JvmStatic + fun doFileSearch( + directory: String, extensions: Array, recursive: Boolean + ): Array { + val result = ArrayList() + + try { + val uri = unmangle(directory) + val documentId = DocumentsContract.getDocumentId(treeToDocument(uri)) + val acceptAll = extensions.isEmpty() + val extensionCheck: (String) -> Boolean = { displayName -> + val extension = FileBrowserHelper.getExtension(displayName, true) + extension != null && extensions.any { it.equals(extension, ignoreCase = true) } + } + + fun addChildren(path: String, parentDocumentId: String) { + forEachChild(uri, parentDocumentId) { displayName, childDocumentId, isDirectory -> + val childPath = "$path/$displayName" + if (acceptAll || (!isDirectory && extensionCheck(displayName))) { + result.add(childPath) + } + if (recursive && isDirectory) { + addChildren(childPath, childDocumentId) + } + } + } + + addChildren(directory, documentId) + } catch (_: Exception) { + } + + return result.toTypedArray() + } + + private fun forEachChild( + uri: Uri, + documentId: String, + callback: (displayName: String, documentId: String, isDirectory: Boolean) -> Unit + ) { + try { + val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(uri, documentId) + val projection = arrayOf( + Document.COLUMN_DISPLAY_NAME, Document.COLUMN_MIME_TYPE, Document.COLUMN_DOCUMENT_ID + ) + getContentResolver().query(childrenUri, projection, null, null, null)?.use { cursor -> + while (cursor.moveToNext()) { + callback( + cursor.getString(0), + cursor.getString(2), + Document.MIME_TYPE_DIR == cursor.getString(1) + ) + } + } + } catch (_: SecurityException) { + Log.error("Tried to get children of $uri without permission") + } catch (_: Exception) { + } + } + + @Throws(FileNotFoundException::class, SecurityException::class) + private fun getChild(parentUri: Uri, childName: String): Uri { + val parentId = DocumentsContract.getDocumentId(treeToDocument(parentUri)) + val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(parentUri, parentId) + + val projection = arrayOf(Document.COLUMN_DISPLAY_NAME, Document.COLUMN_DOCUMENT_ID) + val selection = Document.COLUMN_DISPLAY_NAME + "=?" + val selectionArgs = arrayOf(childName) + try { + getContentResolver().query(childrenUri, projection, selection, selectionArgs, null) + ?.use { cursor -> + while (cursor.moveToNext()) { + // FileProvider seemingly doesn't support selections, so we have to manually filter here + if (childName == cursor.getString(0)) { + return DocumentsContract.buildDocumentUriUsingTree( + parentUri, cursor.getString(1) + ) + } + } + } + } catch (_: SecurityException) { + Log.error("Tried to get child $childName of $parentUri without permission") + } catch (_: Exception) { + } + + throw FileNotFoundException("$parentUri/$childName") + } + + /** + * Since our C++ code was written under the assumption that it would be running under a filesystem + * which supports normal paths, it appends a slash followed by a file name when it wants to access + * a file in a directory. This function translates that into the type of URI that SAF requires. + * + * In order to detect whether a URI is mangled or not, we make the assumption that an + * unmangled URI contains at least one % and does not contain any slashes after the last %. + * This seems to hold for all common storage providers, but it is theoretically possible for a + * storage provider to use URIs without any % characters. + */ + @Throws(FileNotFoundException::class, SecurityException::class) + @JvmStatic + fun unmangle(uri: String): Uri { + val lastComponentEnd = getLastComponentEnd(uri) + val lastComponentStart = getLastComponentStart(uri, lastComponentEnd) + + return if (lastComponentStart == 0) { + uri.substring(0, lastComponentEnd).toUri() + } else { + val parentUri = unmangle(uri.substring(0, lastComponentStart)) + val childName = uri.substring(lastComponentStart, lastComponentEnd) + getChild(parentUri, childName) + } + } + + /** + * Returns the last character which is not a slash. + */ + private fun getLastComponentEnd(uri: String): Int { + var i = uri.length + while (i > 0 && uri[i - 1] == '/') { + i-- + } + return i + } + + /** + * Scans backwards starting from lastComponentEnd and returns the index after the first slash + * it finds, but only if there is a % before that slash and there is no % after it. + */ + private fun getLastComponentStart(uri: String, lastComponentEnd: Int): Int { + var i = lastComponentEnd + while (i > 0 && uri[i - 1] != '/') { + i-- + if (uri[i] == '%') { + return 0 + } + } + + var j = i + while (j > 0) { + j-- + if (uri[j] == '%') { + return i + } + } + + return 0 + } + + private fun treeToDocument(uri: Uri): Uri { + return if (isTreeUri(uri)) { + val documentId = DocumentsContract.getTreeDocumentId(uri) + DocumentsContract.buildDocumentUriUsingTree(uri, documentId) + } else { + uri + } + } + + /** + * This is like DocumentsContract.isTreeUri, except it doesn't return true for URIs like + * content://com.example/tree/12/document/24/. We want to treat those as documents, not trees. + */ + private fun isTreeUri(uri: Uri): Boolean { + val pathSegments = uri.pathSegments + return pathSegments.size == 2 && pathSegments[0] == "tree" + } + + private fun getContentResolver(): ContentResolver { + return DolphinApplication.getAppContext().contentResolver + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/GCAdapter.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/GCAdapter.kt new file mode 100644 index 000000000..a123810e2 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/GCAdapter.kt @@ -0,0 +1,235 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.utils + +import android.app.PendingIntent +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.hardware.usb.UsbConfiguration +import android.hardware.usb.UsbConstants +import android.hardware.usb.UsbDevice +import android.hardware.usb.UsbDeviceConnection +import android.hardware.usb.UsbEndpoint +import android.hardware.usb.UsbInterface +import android.hardware.usb.UsbManager +import android.widget.Toast +import androidx.annotation.Keep +import androidx.core.content.ContextCompat +import org.dolphinemu.dolphinemu.BuildConfig +import org.dolphinemu.dolphinemu.DolphinApplication +import org.dolphinemu.dolphinemu.R + +object GCAdapter { + lateinit var manager: UsbManager + + @Keep + @JvmField + var controllerPayload = ByteArray(37) + + private var usbConnection: UsbDeviceConnection? = null + private var usbInterface: UsbInterface? = null + private var usbIn: UsbEndpoint? = null + private var usbOut: UsbEndpoint? = null + + private val ACTION_GC_ADAPTER_PERMISSION_GRANTED = + BuildConfig.APPLICATION_ID + ".GC_ADAPTER_PERMISSION_GRANTED" + + private val hotplugCallbackLock = Any() + private var hotplugCallbackEnabled = false + private var adapterDevice: UsbDevice? = null + private val hotplugBroadcastReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + onUsbDevicesChanged() + } + } + + private fun requestPermission() { + val devices = manager.deviceList + for (dev in devices.values) { + if (dev.productId == 0x0337 && dev.vendorId == 0x057e) { + if (!manager.hasPermission(dev)) { + val context = DolphinApplication.getAppContext() + + val pendingIntent = PendingIntent.getBroadcast( + context, + 0, + Intent(ACTION_GC_ADAPTER_PERMISSION_GRANTED), + PendingIntent.FLAG_IMMUTABLE + ) + + manager.requestPermission(dev, pendingIntent) + } + } + } + } + + @JvmStatic + fun shutdown() { + usbConnection!!.close() + } + + @Keep + @JvmStatic + fun getFd(): Int { + return usbConnection!!.fileDescriptor + } + + @Keep + @JvmStatic + fun isUsbDeviceAvailable(): Boolean { + synchronized(hotplugCallbackLock) { + return adapterDevice != null + } + } + + private fun queryAdapter(): UsbDevice? { + val devices = manager.deviceList + for (dev in devices.values) { + if (dev.productId == 0x0337 && dev.vendorId == 0x057e) { + if (manager.hasPermission(dev)) { + return dev + } else { + requestPermission() + } + } + } + return null + } + + @JvmStatic + fun initAdapter() { + val init = byteArrayOf(0x13) + usbConnection!!.bulkTransfer(usbOut, init, init.size, 0) + } + + @Keep + @JvmStatic + fun input(): Int { + return usbConnection!!.bulkTransfer(usbIn, controllerPayload, controllerPayload.size, 16) + } + + @Keep + @JvmStatic + fun output(rumble: ByteArray): Int { + return usbConnection!!.bulkTransfer(usbOut, rumble, 5, 16) + } + + @Keep + @JvmStatic + fun openAdapter(): Boolean { + val dev: UsbDevice? + synchronized(hotplugCallbackLock) { + dev = adapterDevice + } + if (dev == null) { + return false + } + + usbConnection = manager.openDevice(dev) + if (usbConnection == null) { + return false + } + + Log.info("GCAdapter: Number of configurations: " + dev.configurationCount) + Log.info("GCAdapter: Number of interfaces: " + dev.interfaceCount) + + if (dev.configurationCount > 0 && dev.interfaceCount > 0) { + val conf: UsbConfiguration = dev.getConfiguration(0) + usbInterface = conf.getInterface(0) + usbConnection!!.claimInterface(usbInterface, true) + + Log.info("GCAdapter: Number of endpoints: " + usbInterface!!.endpointCount) + + if (usbInterface!!.endpointCount == 2) { + for (i in 0 until usbInterface!!.endpointCount) { + if (usbInterface!!.getEndpoint(i).direction == UsbConstants.USB_DIR_IN) { + usbIn = usbInterface!!.getEndpoint(i) + } else { + usbOut = usbInterface!!.getEndpoint(i) + } + } + + initAdapter() + return true + } else { + usbConnection!!.releaseInterface(usbInterface) + } + } + + Toast.makeText( + DolphinApplication.getAppContext(), R.string.replug_gc_adapter, Toast.LENGTH_LONG + ).show() + usbConnection!!.close() + return false + } + + @Keep + @JvmStatic + fun enableHotplugCallback() { + synchronized(hotplugCallbackLock) { + if (hotplugCallbackEnabled) { + throw IllegalStateException("enableHotplugCallback was called when already enabled") + } + + val filter = IntentFilter() + filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED) + filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED) + filter.addAction(ACTION_GC_ADAPTER_PERMISSION_GRANTED) + + ContextCompat.registerReceiver( + DolphinApplication.getAppContext(), + hotplugBroadcastReceiver, + filter, + ContextCompat.RECEIVER_EXPORTED + ) + + hotplugCallbackEnabled = true + + onUsbDevicesChanged() + } + } + + @Keep + @JvmStatic + fun disableHotplugCallback() { + synchronized(hotplugCallbackLock) { + if (hotplugCallbackEnabled) { + DolphinApplication.getAppContext().unregisterReceiver(hotplugBroadcastReceiver) + hotplugCallbackEnabled = false + adapterDevice = null + } + } + } + + @JvmStatic + fun onUsbDevicesChanged() { + synchronized(hotplugCallbackLock) { + if (adapterDevice != null) { + val adapterStillConnected = manager.deviceList.values.any { + it.deviceId == adapterDevice!!.deviceId + } + + if (!adapterStillConnected) { + adapterDevice = null + onAdapterDisconnected() + } + } + + if (adapterDevice == null) { + val newAdapter = queryAdapter() + if (newAdapter != null) { + adapterDevice = newAdapter + onAdapterConnected() + } + } + } + } + + @JvmStatic + private external fun onAdapterConnected() + + @JvmStatic + private external fun onAdapterDisconnected() +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/Log.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/Log.kt new file mode 100644 index 000000000..28a661ffd --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/Log.kt @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.utils + +import org.dolphinemu.dolphinemu.BuildConfig +import android.util.Log as AndroidLog + +/** + * Contains methods that call through to [android.util.Log], but + * with the same TAG automatically provided. Also no-ops VERBOSE and DEBUG log + * levels in release builds. + */ +object Log { + private const val TAG = "Dolphin" + + @JvmStatic + fun verbose(message: String) { + if (BuildConfig.DEBUG) { + AndroidLog.v(TAG, message) + } + } + + @JvmStatic + fun debug(message: String) { + if (BuildConfig.DEBUG) { + AndroidLog.d(TAG, message) + } + } + + @JvmStatic + fun info(message: String) { + AndroidLog.i(TAG, message) + } + + @JvmStatic + fun warning(message: String) { + AndroidLog.w(TAG, message) + } + + @JvmStatic + fun error(message: String) { + AndroidLog.e(TAG, message) + } + + @JvmStatic + fun wtf(message: String) { + AndroidLog.wtf(TAG, message) + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/NetworkHelper.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/NetworkHelper.kt new file mode 100644 index 000000000..231f15fda --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/NetworkHelper.kt @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.utils + +import android.content.Context +import android.net.ConnectivityManager +import android.net.LinkAddress +import androidx.annotation.Keep +import org.dolphinemu.dolphinemu.DolphinApplication +import java.net.Inet4Address +import java.net.InetAddress +import java.net.UnknownHostException + +@Keep +object NetworkHelper { + private fun getConnectivityManager(): ConnectivityManager? { + val context = DolphinApplication.getAppContext() + val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager + if (manager == null) { + Log.warning("Cannot get network link as ConnectivityManager is null.") + } + return manager + } + + private fun getIPv4Link(): LinkAddress? { + val manager = getConnectivityManager() ?: return null + val activeNetwork = manager.activeNetwork + if (activeNetwork == null) { + Log.warning("Active network is null.") + return null + } + val properties = manager.getLinkProperties(activeNetwork) + if (properties == null) { + Log.warning("Link properties is null.") + return null + } + return properties.linkAddresses.firstOrNull { it.address is Inet4Address } ?: run { + Log.warning("No IPv4 link found.") + null + } + } + + private fun InetAddress.inetAddressToInt(): Int { + return address.foldIndexed(0) { index, acc, byte -> + acc or ((byte.toInt() and 0xFF) shl (8 * index)) + } + } + + @Keep + @JvmStatic + fun getNetworkIpAddress(): Int { + return getIPv4Link()?.address?.inetAddressToInt() ?: 0 + } + + @Keep + @JvmStatic + fun getNetworkPrefixLength(): Int { + return getIPv4Link()?.prefixLength ?: 0 + } + + @Keep + @JvmStatic + fun getNetworkGateway(): Int { + val manager = getConnectivityManager() ?: return 0 + val activeNetwork = manager.activeNetwork ?: return 0 + val properties = manager.getLinkProperties(activeNetwork) ?: return 0 + val gatewayAddress = try { + val target = InetAddress.getByName("8.8.8.8") + properties.routes.firstOrNull { it.matches(target) }?.gateway + } catch (ignored: UnknownHostException) { + null + } + return gatewayAddress?.inetAddressToInt() ?: run { + Log.warning("No valid gateway found.") + 0 + } + } + + @JvmStatic + fun getLocalIpString(): String? { + return getIPv4Link()?.address?.hostAddress + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/RateLimiter.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/RateLimiter.kt new file mode 100644 index 000000000..498e12887 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/RateLimiter.kt @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.utils + +import android.os.Handler +import android.os.SystemClock + +class RateLimiter( + private val handler: Handler, + private val delayBetweenRunsMs: Int, + private val runnable: Runnable +) { + private var nextAllowedRun = 0L + private var pendingRun = false + + fun run() { + if (!pendingRun) { + val time = SystemClock.uptimeMillis() + if (time >= nextAllowedRun) { + runnable.run() + nextAllowedRun = time + delayBetweenRunsMs + } else { + pendingRun = true + handler.postAtTime({ + runnable.run() + nextAllowedRun = SystemClock.uptimeMillis() + delayBetweenRunsMs + pendingRun = false + }, nextAllowedRun) + } + } + } +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/WiiUpdateCallback.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/WiiUpdateCallback.kt new file mode 100644 index 000000000..f310b012e --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/WiiUpdateCallback.kt @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.utils + +import androidx.annotation.Keep + +@Keep +fun interface WiiUpdateCallback { + fun run(processed: Int, total: Int, titleId: Long): Boolean +} diff --git a/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/WiimoteAdapter.kt b/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/WiimoteAdapter.kt new file mode 100644 index 000000000..5f7c2bcb9 --- /dev/null +++ b/dolphin/vendored/java/org/dolphinemu/dolphinemu/utils/WiimoteAdapter.kt @@ -0,0 +1,153 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.dolphinemu.dolphinemu.utils + +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.hardware.usb.UsbConfiguration +import android.hardware.usb.UsbDeviceConnection +import android.hardware.usb.UsbEndpoint +import android.hardware.usb.UsbInterface +import android.hardware.usb.UsbManager +import androidx.annotation.Keep +import org.dolphinemu.dolphinemu.DolphinApplication +import org.dolphinemu.dolphinemu.services.USBPermService +import java.util.Arrays + +object WiimoteAdapter { + private const val MAX_PAYLOAD = 23 + private const val MAX_WIIMOTES = 4 + private const val TIMEOUT = 200 + private const val NINTENDO_VENDOR_ID = 0x057e + private const val NINTENDO_WIIMOTE_PRODUCT_ID = 0x0306 + + lateinit var manager: UsbManager + + private var usbConnection: UsbDeviceConnection? = null + private val usbInterface = arrayOfNulls(MAX_WIIMOTES) + private val usbIn = arrayOfNulls(MAX_WIIMOTES) + + @Keep + @JvmField + val wiimotePayload: Array = Array(MAX_WIIMOTES) { ByteArray(MAX_PAYLOAD) } + + private fun requestPermission() { + val devices = manager.deviceList + for (dev in devices.values) { + if (dev.productId == NINTENDO_WIIMOTE_PRODUCT_ID && dev.vendorId == NINTENDO_VENDOR_ID) { + if (!manager.hasPermission(dev)) { + Log.warning("Requesting permission for Wii Remote adapter") + + val context: Context = DolphinApplication.getAppContext() + val intent = Intent(context, USBPermService::class.java) + + val pendingIntent = + PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_IMMUTABLE) + + manager.requestPermission(dev, pendingIntent) + } + } + } + } + + @Keep + @JvmStatic + fun queryAdapter(): Boolean { + val devices = manager.deviceList + for (dev in devices.values) { + if (dev.productId == NINTENDO_WIIMOTE_PRODUCT_ID && dev.vendorId == NINTENDO_VENDOR_ID) { + if (manager.hasPermission(dev)) { + return true + } else { + requestPermission() + } + } + } + return false + } + + @Keep + @JvmStatic + fun input(index: Int): Int { + return usbConnection!!.bulkTransfer( + usbIn[index], wiimotePayload[index], MAX_PAYLOAD, TIMEOUT + ) + } + + @Keep + @JvmStatic + fun output(index: Int, buf: ByteArray, size: Int): Int { + val reportNumber = buf[0] + + // Remove the report number from the buffer + val outputBuffer = Arrays.copyOfRange(buf, 1, buf.size) + val outputSize = size - 1 + + val libusbRequestTypeClass = 1 shl 5 + val libusbRecipientInterface = 0x1 + val libusbEndpointOut = 0 + + val hidSetReport = 0x9 + val hidOutput = 2 shl 8 + + val write = usbConnection!!.controlTransfer( + libusbRequestTypeClass or libusbRecipientInterface or libusbEndpointOut, + hidSetReport, + hidOutput or reportNumber.toInt(), + index, + outputBuffer, + outputSize, + 1000 + ) + + if (write < 0) { + return 0 + } + + return write + 1 + } + + @Keep + @JvmStatic + fun openAdapter(): Boolean { + // If the adapter is already open. Don't attempt to do it again + if (usbConnection != null && usbConnection!!.fileDescriptor != -1) { + return true + } + + val devices = manager.deviceList + for (dev in devices.values) { + if (dev.productId == NINTENDO_WIIMOTE_PRODUCT_ID && dev.vendorId == NINTENDO_VENDOR_ID) { + if (manager.hasPermission(dev)) { + usbConnection = manager.openDevice(dev) + val conf: UsbConfiguration = dev.getConfiguration(0) + + Log.info("Number of configurations: " + dev.configurationCount) + Log.info("Number of Interfaces: " + dev.interfaceCount) + Log.info("Number of Interfaces from conf: " + conf.interfaceCount) + + // Sometimes the interface count is returned as zero. + // Means the device needs to be unplugged and plugged back in again + if (dev.interfaceCount > 0) { + for (i in 0 until MAX_WIIMOTES) { + // One interface per Wii Remote + usbInterface[i] = dev.getInterface(i) + usbConnection!!.claimInterface(usbInterface[i], true) + + // One endpoint per Wii Remote. Input only + // Output reports go through the control channel. + usbIn[i] = usbInterface[i]!!.getEndpoint(0) + Log.info("Interface " + i + " endpoint count:" + usbInterface[i]!!.endpointCount) + } + return true + } else { + // XXX: Message that the device was found, but it needs to be unplugged and plugged back in? + usbConnection!!.close() + } + } + } + } + return false + } +} diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 614327ea6..9e3bff92b 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -13,6 +13,8 @@ activity = "1.10.1" navigationCompose = "2.8.9" lifecycleCompose = "2.10.0" coilCompose = "2.7.0" +composeIcons = "1.1.1" +documentfile = "1.1.0" coroutinesAndroid = "1.10.1" timber = "5.0.1" zxing = "3.5.4" @@ -55,6 +57,13 @@ navigationCompose = { module = "androidx.navigation:navigation-compose", version lifecycleViewmodelCompose = { module = "androidx.lifecycle:lifecycle-viewmodel-compose", version.ref = "lifecycleCompose" } composeUiTextGoogleFonts = { module = "androidx.compose.ui:ui-text-google-fonts" } coilCompose = { module = "io.coil-kt:coil-compose", version.ref = "coilCompose" } +coilGif = { module = "io.coil-kt:coil-gif", version.ref = "coilCompose" } +composeFoundation = { module = "androidx.compose.foundation:foundation" } +lifecycleRuntimeCompose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "lifecycleCompose" } +kotlinReflect = { module = "org.jetbrains.kotlin:kotlin-reflect", version.ref = "kotlin" } +documentfile = { module = "androidx.documentfile:documentfile", version.ref = "documentfile" } +composeIconsFontAwesome = { module = "br.com.devsrsouza.compose.icons:font-awesome", version.ref = "composeIcons" } +composeIconsLineAwesome = { module = "br.com.devsrsouza.compose.icons:line-awesome", version.ref = "composeIcons" } coroutinesAndroid = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "coroutinesAndroid" } timber = { module = "com.jakewharton.timber:timber", version.ref = "timber" } zxingCore = { module = "com.google.zxing:core", version.ref = "zxing" } @@ -75,6 +84,7 @@ workRuntimeKtx = { module = "androidx.work:work-runtime-ktx", version.ref = "wor [plugins] androidApplication = { id = "com.android.application", version.ref = "agp" } +androidLibrary = { id = "com.android.library", version.ref = "agp" } kotlinAndroid = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" } kotlinCompose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" } diff --git a/libretrodroid/.gitignore b/libretrodroid/.gitignore new file mode 100644 index 000000000..796b96d1c --- /dev/null +++ b/libretrodroid/.gitignore @@ -0,0 +1 @@ +/build diff --git a/libretrodroid/build.gradle b/libretrodroid/build.gradle new file mode 100644 index 000000000..ab9410149 --- /dev/null +++ b/libretrodroid/build.gradle @@ -0,0 +1,56 @@ +plugins { + alias(libs.plugins.androidLibrary) + alias(libs.plugins.kotlinAndroid) +} + +android { + namespace = "com.swordfish.libretrodroid" + compileSdk 35 + ndkVersion '27.3.13750724' + + defaultConfig { + minSdk 26 + + consumerProguardFiles 'consumer-rules.pro' + + externalNativeBuild { + cmake { + arguments '-DANDROID_STL=c++_static', + "-DCMAKE_SHARED_LINKER_FLAGS=-Wl,-z,max-page-size=16384" + } + } + + ndk { + abiFilters 'arm64-v8a' + } + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + + externalNativeBuild { + cmake { + version '3.22.1' + path 'src/main/cpp/CMakeLists.txt' + } + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = "17" + } +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar']) + implementation libs.coreKtx + implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.5.1' +} diff --git a/libretrodroid/consumer-rules.pro b/libretrodroid/consumer-rules.pro new file mode 100644 index 000000000..e69de29bb diff --git a/libretrodroid/proguard-rules.pro b/libretrodroid/proguard-rules.pro new file mode 100644 index 000000000..f1b424510 --- /dev/null +++ b/libretrodroid/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/libretrodroid/src/main/AndroidManifest.xml b/libretrodroid/src/main/AndroidManifest.xml new file mode 100644 index 000000000..f47302e5f --- /dev/null +++ b/libretrodroid/src/main/AndroidManifest.xml @@ -0,0 +1,4 @@ + + + diff --git a/libretrodroid/src/main/cpp/CMakeLists.txt b/libretrodroid/src/main/cpp/CMakeLists.txt new file mode 100644 index 000000000..9b6c2c242 --- /dev/null +++ b/libretrodroid/src/main/cpp/CMakeLists.txt @@ -0,0 +1,175 @@ +cmake_minimum_required(VERSION 3.13.2) + +# now build app's shared lib +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17 -Wall") + +add_definitions("-DVFS_FRONTEND -DHAVE_STRL -DHAVE_CHD") + +# Let's include oboe +set (OBOE_DIR oboe) +add_subdirectory (${OBOE_DIR} oboe) +include_directories (${OBOE_DIR}/include) +include_directories (${OBOE_DIR}/src) + +include_directories("libretro/libretro-common/include") + +set (LIBRETRO_COMMON + libretro/libretro-common/vfs/vfs_implementation.c + libretro/libretro-common/string/stdstring.c + libretro/libretro-common/encodings/encoding_utf.c + libretro/libretro-common/file/file_path.c + libretro/libretro-common/time/rtime.c + libretro/libretro-common/streams/chd_stream.c + libretro/libretro-common/streams/file_stream.c + libretro/libretro-common/streams/interface_stream.c + libretro/libretro-common/streams/memory_stream.c + libretro/libretro-common/encodings/encoding_crc32.c + libretro/libretro-common/formats/cdfs/cdfs.c +) + +# Vendored libchdr (from beetle-psx) so RetroAchievements can hash .chd discs. +include_directories("libchdr/include") +set (LIBCHDR + libchdr/deps/lzma-25.01/src/LzmaDec.c + libchdr/deps/zstd-1.5.7/zstddeclib.c + libchdr/src/libchdr_bitstream.c + libchdr/src/libchdr_cdrom.c + libchdr/src/libchdr_chd.c + libchdr/src/libchdr_codec_cdfl.c + libchdr/src/libchdr_codec_cdlz.c + libchdr/src/libchdr_codec_cdzl.c + libchdr/src/libchdr_codec_cdzs.c + libchdr/src/libchdr_codec_flac.c + libchdr/src/libchdr_codec_huff.c + libchdr/src/libchdr_codec_lzma.c + libchdr/src/libchdr_codec_zlib.c + libchdr/src/libchdr_codec_zstd.c + libchdr/src/libchdr_flac.c + libchdr/src/libchdr_huffman.c +) + +add_definitions("-DRC_CLIENT_SUPPORTS_HASH") +include_directories("rcheevos/include") +include_directories("rcheevos/src") + +set (RCHEEVOS + rcheevos/src/rc_client.c + rcheevos/src/rc_client_external.c + rcheevos/src/rc_compat.c + rcheevos/src/rc_libretro.c + rcheevos/src/rc_util.c + rcheevos/src/rc_version.c + rcheevos/src/rapi/rc_api_common.c + rcheevos/src/rapi/rc_api_editor.c + rcheevos/src/rapi/rc_api_info.c + rcheevos/src/rapi/rc_api_runtime.c + rcheevos/src/rapi/rc_api_user.c + rcheevos/src/rcheevos/alloc.c + rcheevos/src/rcheevos/condition.c + rcheevos/src/rcheevos/condset.c + rcheevos/src/rcheevos/consoleinfo.c + rcheevos/src/rcheevos/format.c + rcheevos/src/rcheevos/lboard.c + rcheevos/src/rcheevos/memref.c + rcheevos/src/rcheevos/operand.c + rcheevos/src/rcheevos/rc_validate.c + rcheevos/src/rcheevos/richpresence.c + rcheevos/src/rcheevos/runtime.c + rcheevos/src/rcheevos/runtime_progress.c + rcheevos/src/rcheevos/trigger.c + rcheevos/src/rcheevos/value.c + rcheevos/src/rhash/aes.c + rcheevos/src/rhash/cdreader.c + rcheevos/src/rhash/hash.c + rcheevos/src/rhash/hash_disc.c + rcheevos/src/rhash/hash_encrypted.c + rcheevos/src/rhash/hash_rom.c + rcheevos/src/rhash/hash_zip.c + rcheevos/src/rhash/md5.c +) + +add_library(libretrodroid SHARED + libretrodroidjni.h + libretrodroidjni.cpp + libretrodroid.h + libretrodroid.cpp + log.h + core.h + core.cpp + video.h + video.cpp + immersivemode.h + immersivemode.cpp + videolayout.h + videolayout.cpp + renderers/renderer.h + renderers/renderer.cpp + renderers/es3/es3utils.h + renderers/es3/es3utils.cpp + renderers/es3/framebufferrenderer.h + renderers/es3/framebufferrenderer.cpp + renderers/es2/imagerendereres2.h + renderers/es2/imagerendereres2.cpp + renderers/es3/imagerendereres3.h + renderers/es3/imagerendereres3.cpp + audio.h + audio.cpp + resamplers/resampler.h + resamplers/linearresampler.h + resamplers/linearresampler.cpp + resamplers/sincresampler.h + resamplers/sincresampler.cpp + fpssync.h + fpssync.cpp + environment.h + environment.cpp + netpacket.h + netpacket.cpp + input.h + input.cpp + shadermanager.h + shadermanager.cpp + rumble.h + rumble.cpp + rumblestate.h + rumblestate.cpp + utils/javautils.h + utils/javautils.cpp + utils/utils.cpp + utils/utils.h + utils/jnistring.h + utils/jnistring.cpp + utils/libretrodroidexception.h + utils/libretrodroidexception.cpp + utils/rect.h + utils/rect.cpp + errorcodes.h + errorcodes.cpp + vfs/vfs.h + vfs/vfs.cpp + vfs/vfsfile.h + vfs/vfsfile.cpp + vfs/fdwrapper.h + vfs/fdwrapper.cpp + microphone/microphone.h + microphone/microphone.cpp + microphone/microphoneinterface.h + microphone/microphoneinterface.cpp + retroachievements.cpp + ${LIBRETRO_COMMON} + ${LIBCHDR} + ${RCHEEVOS} +) + +# Support 16k pages for Android 15 +target_link_options(libretrodroid PRIVATE "-Wl,-z,max-page-size=16384") + +# add lib dependencies +target_link_libraries(libretrodroid + android + log + EGL + oboe + GLESv3 + z +) diff --git a/libretrodroid/src/main/cpp/SGSR_LICENSE b/libretrodroid/src/main/cpp/SGSR_LICENSE new file mode 100644 index 000000000..d9d513c75 --- /dev/null +++ b/libretrodroid/src/main/cpp/SGSR_LICENSE @@ -0,0 +1,29 @@ +Copyright (c) 2023, Qualcomm Innovation Center, Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +SPDX-License-Identifier: BSD-3-Clause \ No newline at end of file diff --git a/libretrodroid/src/main/cpp/audio.cpp b/libretrodroid/src/main/cpp/audio.cpp new file mode 100644 index 000000000..c6e721a8e --- /dev/null +++ b/libretrodroid/src/main/cpp/audio.cpp @@ -0,0 +1,171 @@ +/* + * Copyright (C) 2019 Filippo Scognamiglio + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "log.h" + +#include "audio.h" +#include +#include + +namespace libretrodroid { + +Audio::Audio(int32_t sampleRate, double refreshRate, bool preferLowLatencyAudio) { + LOGI("Audio initialization has been called with input sample rate %d", sampleRate); + + contentRefreshRate = refreshRate; + inputSampleRate = sampleRate; + audioLatencySettings = findBestLatencySettings(preferLowLatencyAudio); + initializeStream(); +} + +bool Audio::initializeStream() { + LOGI("Using low latency stream: %d", audioLatencySettings->useLowLatencyStream); + + int32_t audioBufferSize = computeAudioBufferSize(); + + oboe::AudioStreamBuilder builder; + builder.setChannelCount(2); + builder.setDirection(oboe::Direction::Output); + builder.setFormat(oboe::AudioFormat::I16); + builder.setDataCallback(this); + builder.setErrorCallback(this); + + if (audioLatencySettings->useLowLatencyStream) { + builder.setPerformanceMode(oboe::PerformanceMode::LowLatency); + } else { + builder.setFramesPerCallback(audioBufferSize / 10); + } + + oboe::Result result = builder.openManagedStream(stream); + if (result == oboe::Result::OK) { + baseConversionFactor = (double) inputSampleRate / stream->getSampleRate(); + fifoBuffer = std::make_unique(2, audioBufferSize); + temporaryAudioBuffer = std::unique_ptr(new int16_t[audioBufferSize]); + latencyTuner = std::make_unique(*stream); + return true; + } else { + LOGE("Failed to create stream. Error: %s", oboe::convertToText(result)); + stream = nullptr; + latencyTuner = nullptr; + return false; + } +} + +std::unique_ptr Audio::findBestLatencySettings(bool preferLowLatencyAudio) { + if (oboe::AudioStreamBuilder::isAAudioRecommended() && preferLowLatencyAudio) { + return std::make_unique(LOW_LATENCY_SETTINGS); + } else { + return std::make_unique(DEFAULT_LATENCY_SETTINGS); + } +} + +int32_t Audio::computeAudioBufferSize() { + double maxLatency = computeMaximumLatency(); + LOGI("Average audio latency set to: %f ms", maxLatency * 0.5); + double sampleRateDivisor = 500.0 / maxLatency; + return roundToEven(inputSampleRate / sampleRateDivisor); +} + +double Audio::computeMaximumLatency() const { + double maxLatency = (audioLatencySettings->bufferSizeInVideoFrames / contentRefreshRate) * 1000; + return std::max(maxLatency, 32.0); +} + +void Audio::start() { + startRequested = true; + if (stream != nullptr) + stream->requestStart(); +} + +void Audio::stop() { + startRequested = false; + if (stream != nullptr) + stream->requestStop(); +} + +void Audio::write(const int16_t *data, size_t frames) { + fifoBuffer->write(data, frames * 2); +} + +void Audio::setPlaybackSpeed(const double newPlaybackSpeed) { + playbackSpeed = newPlaybackSpeed; +} + +oboe::DataCallbackResult Audio::onAudioReady(oboe::AudioStream *oboeStream, void *audioData, int32_t numFrames) { + double dynamicBufferFactor = computeDynamicBufferConversionFactor(0.001 * numFrames); + double finalConversionFactor = baseConversionFactor * dynamicBufferFactor * playbackSpeed; + + // When using low-latency stream, numFrames is very low (~100) and the dynamic buffer scaling doesn't work with rounding. + // By keeping track of the "fractional" frames we can keep the error smaller. + framesToSubmit += numFrames * finalConversionFactor; + int32_t currentFramesToSubmit = std::round(framesToSubmit); + framesToSubmit -= currentFramesToSubmit; + + fifoBuffer->readNow(temporaryAudioBuffer.get(), currentFramesToSubmit * 2); + + auto outputArray = reinterpret_cast(audioData); + resampler.resample(temporaryAudioBuffer.get(), currentFramesToSubmit, outputArray, numFrames); + + latencyTuner->tune(); + + return oboe::DataCallbackResult::Continue; +} + +// To prevent audio buffer overruns or underruns we set up a PI controller. The idea is to run the +// audio slower when the buffer is empty and faster when it's full. +double Audio::computeDynamicBufferConversionFactor(double dt) { + double framesCapacityInBuffer = fifoBuffer->getBufferCapacityInFrames(); + double framesAvailableInBuffer = fifoBuffer->getFullFramesAvailable(); + + // Error is represented by normalized distance to half buffer utilization. Range [-1.0, 1.0] + double errorMeasure = (framesCapacityInBuffer - 2.0f * framesAvailableInBuffer) / framesCapacityInBuffer; + + errorIntegral += errorMeasure * dt; + + // Wikipedia states that human ear resolution is around 3.6 Hz within the octave of 1000–2000 Hz. + // This changes continuously, so we should try to keep it a very low value. + double proportionalAdjustment = std::clamp(kp * errorMeasure, -maxp, maxp); + + // Ki is a lot lower, so it's safe if it exceeds the ear threshold. Hopefully convergence will + // be slow enough to be not perceptible. We need to battle test this value. + double integralAdjustment = std::clamp(ki * errorIntegral, -maxi, maxi); + + double finalAdjustment = proportionalAdjustment + integralAdjustment; + + LOGD("Audio speed adjustments (p: %f) (i: %f)", proportionalAdjustment, integralAdjustment); + + return 1.0 - (finalAdjustment); +} + +int32_t Audio::roundToEven(int32_t x) { + return (x / 2) * 2; +} + +void Audio::onErrorAfterClose(oboe::AudioStream* oldStream, oboe::Result result) { + AudioStreamErrorCallback::onErrorAfterClose(oldStream, result); + LOGI("Stream error in oboe::onErrorAfterClose %s", oboe::convertToText(result)); + + if (result != oboe::Result::ErrorDisconnected) + return; + + initializeStream(); + if (startRequested) { + start(); + } +} + +} //namespace libretrodroid diff --git a/libretrodroid/src/main/cpp/audio.h b/libretrodroid/src/main/cpp/audio.h new file mode 100644 index 000000000..b0cb5ed28 --- /dev/null +++ b/libretrodroid/src/main/cpp/audio.h @@ -0,0 +1,96 @@ +/* + * Copyright (C) 2019 Filippo Scognamiglio + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef LIBRETRODROID_AUDIO_H +#define LIBRETRODROID_AUDIO_H + +#include +#include +#include +#include + +#include "resamplers/linearresampler.h" + +namespace libretrodroid { + +class Audio: public oboe::AudioStreamDataCallback, oboe::AudioStreamErrorCallback { +private: + struct AudioLatencySettings { + unsigned bufferSizeInVideoFrames; + bool useLowLatencyStream; + }; + + const AudioLatencySettings DEFAULT_LATENCY_SETTINGS { 8, false }; + const AudioLatencySettings LOW_LATENCY_SETTINGS { 4, true }; + +public: + Audio(int32_t sampleRate, double refreshRate, bool preferLowLatencyAudio); + ~Audio() override = default; + + void start(); + void stop(); + + oboe::DataCallbackResult onAudioReady( + oboe::AudioStream *oboeStream, + void *audioData, + int32_t numFrames + ) override; + + void onErrorAfterClose(oboe::AudioStream *oldStream, oboe::Result result) override; + +public: + void write(const int16_t *data, size_t frames); + void setPlaybackSpeed(const double newPlaybackSpeed); + +private: + static int32_t roundToEven(int32_t x); + double computeDynamicBufferConversionFactor(double dt); + int32_t computeAudioBufferSize(); + bool initializeStream(); + std::unique_ptr findBestLatencySettings(bool preferLowLatencyAudio); + double computeMaximumLatency() const; + +private: + const double kp = 0.006; + const double ki = 0.00002; + const double maxp = 0.003; + const double maxi = 0.02; + + LinearResampler resampler; + std::unique_ptr fifoBuffer = nullptr; + std::unique_ptr temporaryAudioBuffer = nullptr; + + oboe::ManagedStream stream = nullptr; + std::unique_ptr latencyTuner = nullptr; + + bool startRequested = false; + int32_t inputSampleRate; + double contentRefreshRate = 60.0; + + double baseConversionFactor = 1.0; + + double framesToSubmit = 0.0; + double errorIntegral = 0.0; + + double playbackSpeed = 1.0; + + std::unique_ptr audioLatencySettings; +}; + +} // namespace libretrodroid + +#endif //LIBRETRODROID_AUDIO_H diff --git a/libretrodroid/src/main/cpp/core.cpp b/libretrodroid/src/main/cpp/core.cpp new file mode 100644 index 000000000..f72d78d2a --- /dev/null +++ b/libretrodroid/src/main/cpp/core.cpp @@ -0,0 +1,80 @@ +/* + * Copyright (C) 2019 Filippo Scognamiglio + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include "core.h" + +#include "log.h" + +namespace libretrodroid { + +Core::Core(const std::string& soCorePath) { + open(soCorePath); +} + +void* get_symbol(void* handle, const char* symbol) { + void* result = dlsym(handle, symbol); + if (!result) { + LOGE("Cannot get symbol %s... Quitting", symbol); + throw std::runtime_error("Missing libretro core symbol"); + } + return result; +} + +void Core::open(const std::string& soCorePath) { + libHandle = dlopen(soCorePath.c_str(), RTLD_LOCAL | RTLD_LAZY); + if (!libHandle) { + LOGE("Cannot dlopen library, closing"); + throw std::runtime_error("Cannot dlopen library"); + } + retro_cheat_reset = (void (*)()) get_symbol(libHandle, "retro_cheat_reset"); + retro_cheat_set = (void (*)(unsigned, bool, const char*)) get_symbol(libHandle, "retro_cheat_set"); + retro_init = (void (*)()) get_symbol(libHandle, "retro_init"); + retro_deinit = (void (*)()) get_symbol(libHandle, "retro_deinit"); + retro_api_version = (unsigned (*)()) get_symbol(libHandle, "retro_api_version"); + retro_get_system_info = (void (*)(struct retro_system_info*)) get_symbol(libHandle, "retro_get_system_info"); + retro_get_system_av_info = (void (*)(struct retro_system_av_info*)) get_symbol(libHandle, "retro_get_system_av_info"); + retro_set_controller_port_device = (void (*)(unsigned, unsigned)) get_symbol(libHandle, "retro_set_controller_port_device"); + retro_reset = (void (*)()) get_symbol(libHandle, "retro_reset"); + retro_run = (void (*)()) get_symbol(libHandle, "retro_run"); + retro_serialize_size = (size_t (*)()) get_symbol(libHandle, "retro_serialize_size"); + retro_serialize = (bool (*)(void*, size_t)) get_symbol(libHandle, "retro_serialize"); + retro_unserialize = (bool (*)(const void*, size_t)) get_symbol(libHandle, "retro_unserialize"); + retro_get_memory_size = (size_t (*)(unsigned)) get_symbol(libHandle, "retro_get_memory_size"); + retro_get_memory_data = (void* (*)(unsigned)) get_symbol(libHandle, "retro_get_memory_data"); + retro_load_game = (bool (*)(const struct retro_game_info*)) get_symbol(libHandle, "retro_load_game"); + retro_unload_game = (void (*)()) get_symbol(libHandle, "retro_unload_game"); + retro_set_video_refresh = (void (*)(retro_video_refresh_t)) get_symbol(libHandle, "retro_set_video_refresh"); + retro_set_environment = (void (*)(retro_environment_t)) get_symbol(libHandle, "retro_set_environment"); + retro_set_audio_sample = (void (*)(retro_audio_sample_t)) get_symbol(libHandle, "retro_set_audio_sample"); + retro_set_audio_sample_batch = (void (*)(retro_audio_sample_batch_t)) get_symbol(libHandle, "retro_set_audio_sample_batch"); + retro_set_input_poll = (void (*)(retro_input_poll_t)) get_symbol(libHandle, "retro_set_input_poll"); + retro_set_input_state = (void (*)(retro_input_state_t)) get_symbol(libHandle, "retro_set_input_state"); +} + +void Core::close() { + if (libHandle) { + dlclose(libHandle); + libHandle = nullptr; + } +} + +Core::~Core() { + close(); +} + +} //namespace libretrodroid diff --git a/libretrodroid/src/main/cpp/core.h b/libretrodroid/src/main/cpp/core.h new file mode 100644 index 000000000..2957566e5 --- /dev/null +++ b/libretrodroid/src/main/cpp/core.h @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2019 Filippo Scognamiglio + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef LIBRETRODROID_CORE_H +#define LIBRETRODROID_CORE_H + +#include + +#include "../../libretro-common/include/libretro.h" + +namespace libretrodroid { + +class Core { +public: + void (*retro_init)(void); + void (*retro_deinit)(void); + unsigned (*retro_api_version)(void); + void (*retro_cheat_reset)(void); + void (*retro_cheat_set)(unsigned index, bool enabled, const char *code); + void (*retro_get_system_info)(struct retro_system_info *info); + void (*retro_get_system_av_info)(struct retro_system_av_info *info); + void (*retro_set_controller_port_device)(unsigned port, unsigned device); + void (*retro_reset)(void); + void (*retro_run)(void); + size_t (*retro_serialize_size)(void); + bool (*retro_serialize)(void *data, size_t size); + bool (*retro_unserialize)(const void *data, size_t size); + size_t (*retro_get_memory_size)(unsigned id); + void* (*retro_get_memory_data)(unsigned id); + bool (*retro_load_game)(const struct retro_game_info *game); + void (*retro_unload_game)(void); + void (*retro_set_video_refresh)(retro_video_refresh_t); + void (*retro_set_environment)(retro_environment_t); + void (*retro_set_audio_sample)(retro_audio_sample_t); + void (*retro_set_audio_sample_batch)(retro_audio_sample_batch_t); + void (*retro_set_input_poll)(retro_input_poll_t); + void (*retro_set_input_state)(retro_input_state_t); + + Core(const std::string& soCorePath); + ~Core(); + +private: + void open(const std::string& soCorePath); + void close(); + + void* libHandle = nullptr; +}; + +} + + + +#endif //LIBRETRODROID_CORE_H diff --git a/libretrodroid/src/main/cpp/environment.cpp b/libretrodroid/src/main/cpp/environment.cpp new file mode 100644 index 000000000..cdab06494 --- /dev/null +++ b/libretrodroid/src/main/cpp/environment.cpp @@ -0,0 +1,507 @@ +/* + * Copyright (C) 2020 Filippo Scognamiglio + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#define MODULE_NAME_CORE "Libretro Core" + +#include +#include +#include +#include +#include +#include +#include + +#include "retro_netpacket_api.h" +#include "log.h" +#include "environment.h" +#include "vfs/vfs.h" +#include "microphone/microphoneinterface.h" +#include "netpacket.h" + +void Environment::initialize( + const std::string &requiredSystemDirectory, + const std::string &requiredSavesDirectory, + retro_hw_get_current_framebuffer_t required_callback_get_current_framebuffer +) { + callback_get_current_framebuffer = required_callback_get_current_framebuffer; + systemDirectory = requiredSystemDirectory; + savesDirectory = requiredSavesDirectory; +} + +void Environment::deinitialize() { + callback_get_current_framebuffer = nullptr; + hw_context_reset = nullptr; + hw_context_destroy = nullptr; + + retro_disk_control_callback = nullptr; + + memoryDescriptors.clear(); + memoryMap = {}; + hasMemoryMap = false; + + savesDirectory = std::string(); + systemDirectory = std::string(); + language = RETRO_LANGUAGE_ENGLISH; + + pixelFormat = RETRO_PIXEL_FORMAT_RGB565; + useHWAcceleration = false; + useDepth = false; + useStencil = false; + bottomLeftOrigin = false; + screenRotation = 0; + + gameGeometryUpdated = false; + gameGeometryWidth = 0; + gameGeometryHeight = 0; + gameGeometryAspectRatio = -1.0f; + + rumbleStates.fill(libretrodroid::RumbleState {}); +} + +void Environment::updateVariable(const std::string& key, const std::string& value) { + auto current = variables[key]; + current.key = key; + + if (value != current.value) { + current.value = value; + variables[key] = current; + dirtyVariables = true; + } +} + +bool Environment::environment_handle_set_variables(const struct retro_variable* received) { + unsigned count = 0; + while (received[count].key != nullptr) { + LOGD("Received variable %s: %s", received[count].key, received[count].value); + + std::string key(received[count].key); + std::string description(received[count].value); + std::string value(received[count].value); + + auto firstValueStart = value.find(';') + 2; + auto firstValueEnd = value.find('|', firstValueStart); + value = value.substr(firstValueStart, firstValueEnd - firstValueStart); + + auto currentVariable = variables[key]; + currentVariable.key = key; + currentVariable.description = description; + + if (currentVariable.value.empty()) { + currentVariable.value = value; + } + + variables[key] = currentVariable; + LOGD("Assigning variable %s: %s", currentVariable.key.c_str(), currentVariable.value.c_str()); + + count++; + } + + return true; +} + +bool Environment::environment_handle_get_variable(struct retro_variable* requested) { + LOGD("Variable requested %s", requested->key); + auto foundVariable = variables.find(std::string(requested->key)); + + if (foundVariable == variables.end()) { + return false; + } + + requested->value = foundVariable->second.value.c_str(); + return true; +} + +bool Environment::environment_handle_set_controller_info(const struct retro_controller_info* received) { + controllers.clear(); + + unsigned player = 0; + while (received[player].types != nullptr) { + + auto currentPlayer = received[player]; + + controllers.emplace_back(); + + unsigned controller = 0; + while (controller < currentPlayer.num_types && currentPlayer.types[controller].desc != nullptr) { + auto currentController = currentPlayer.types[controller]; + LOGD("Received controller for player %d: %d %s", player, currentController.id, currentController.desc); + + controllers[player].push_back(Controller { currentController.id, currentController.desc }); + controller++; + } + + player++; + } + + return true; +} + +bool Environment::environment_handle_set_hw_render(struct retro_hw_render_callback* hw_render_callback) { + useHWAcceleration = true; + useDepth = hw_render_callback->depth; + useStencil = hw_render_callback->stencil; + bottomLeftOrigin = hw_render_callback->bottom_left_origin; + + hw_context_destroy = hw_render_callback->context_destroy; + hw_context_reset = hw_render_callback->context_reset; + hw_render_callback->get_current_framebuffer = callback_get_current_framebuffer; + hw_render_callback->get_proc_address = &eglGetProcAddress; + + return true; +} + +bool Environment::environment_handle_get_vfs_interface(struct retro_vfs_interface_info* vfsInterfaceInfo) { + if (!useVirtualFileSystem) { + return false; + } + + vfsInterfaceInfo->required_interface_version = libretrodroid::VFS::SUPPORTED_VERSION; + vfsInterfaceInfo->iface = libretrodroid::VFS::getInterface(); + return true; +} + +bool Environment::environment_handle_get_microphone_interface(struct retro_microphone_interface* microphone_interface) { + if (!enableMicrophone) { + return false; + } + + *microphone_interface = *libretrodroid::MicrophoneInterface::getInterface(); + return true; +} + +void Environment::callback_retro_log(enum retro_log_level level, const char *fmt, ...) { + va_list argptr; + va_start(argptr, fmt); + + switch (level) { +#if VERBOSE_LOGGING + case RETRO_LOG_DEBUG: + __android_log_vprint(ANDROID_LOG_DEBUG, MODULE_NAME_CORE, fmt, argptr); + break; +#endif + case RETRO_LOG_INFO: + __android_log_vprint(ANDROID_LOG_INFO, MODULE_NAME_CORE, fmt, argptr); + break; + case RETRO_LOG_WARN: + __android_log_vprint(ANDROID_LOG_WARN, MODULE_NAME_CORE, fmt, argptr); + break; + case RETRO_LOG_ERROR: + __android_log_vprint(ANDROID_LOG_ERROR, MODULE_NAME_CORE, fmt, argptr); + break; + default: + // Log nothing in here. + break; + } +} + +bool Environment::callback_set_rumble_state(unsigned port, enum retro_rumble_effect effect, uint16_t strength) { + return Environment::getInstance().handle_callback_set_rumble_state(port, effect, strength); +} + +bool Environment::handle_callback_set_rumble_state(unsigned port, enum retro_rumble_effect effect, uint16_t strength) { + LOGV("Setting rumble strength for port %i to %i", port, strength); + if (port < 0 || port > 3) return false; + + if (effect == RETRO_RUMBLE_STRONG) { + rumbleStates[port].strengthStrong = strength; + } else if (effect == RETRO_RUMBLE_WEAK) { + rumbleStates[port].strengthWeak = strength; + } + + return true; +} + +bool Environment::callback_environment(unsigned cmd, void *data) { + return Environment::getInstance().handle_callback_environment(cmd, data); +} + +bool Environment::handle_callback_environment(unsigned cmd, void *data) { + switch (cmd) { + case RETRO_ENVIRONMENT_GET_CAN_DUPE: + *((bool*) data) = true; + return true; + + case RETRO_ENVIRONMENT_SET_PIXEL_FORMAT: { + LOGD("Called SET_PIXEL_FORMAT"); + pixelFormat = *static_cast(data); + return true; + } + + case RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS: + LOGD("Called SET_INPUT_DESCRIPTORS"); + return false; + + case RETRO_ENVIRONMENT_GET_VARIABLE: + LOGD("Called RETRO_ENVIRONMENT_GET_VARIABLE"); + return environment_handle_get_variable(static_cast(data)); + + case RETRO_ENVIRONMENT_SET_VARIABLES: + LOGD("Called RETRO_ENVIRONMENT_SET_VARIABLES"); + return environment_handle_set_variables(static_cast(data)); + + case RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE: { + LOGD("Called RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE. Is dirty?: %d", dirtyVariables); + *((bool*) data) = dirtyVariables; + dirtyVariables = false; + return true; + } + + case RETRO_ENVIRONMENT_GET_PREFERRED_HW_RENDER: { + LOGD("Called RETRO_ENVIRONMENT_GET_PREFERRED_HW_RENDER"); + *((unsigned*) data) = retro_hw_context_type::RETRO_HW_CONTEXT_OPENGLES3; + return true; + } + + case RETRO_ENVIRONMENT_SET_HW_RENDER: + LOGD("Called RETRO_ENVIRONMENT_SET_HW_RENDER"); + return environment_handle_set_hw_render(static_cast(data)); + + case RETRO_ENVIRONMENT_GET_RUMBLE_INTERFACE: + LOGD("Called RETRO_ENVIRONMENT_GET_RUMBLE_INTERFACE"); + ((struct retro_rumble_interface*) data)->set_rumble_state = &callback_set_rumble_state; + return true; + + case RETRO_ENVIRONMENT_GET_LOG_INTERFACE: + LOGD("Called RETRO_ENVIRONMENT_GET_LOG_INTERFACE"); + ((struct retro_log_callback*) data)->log = &callback_retro_log; + return true; + + case RETRO_ENVIRONMENT_GET_SAVE_DIRECTORY: + LOGD("Called RETRO_ENVIRONMENT_GET_SAVE_DIRECTORY"); + *(const char**) data = savesDirectory.c_str(); + return !savesDirectory.empty(); + + case RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY: + LOGD("Called RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY"); + *(const char**) data = systemDirectory.c_str(); + return !systemDirectory.empty(); + + case RETRO_ENVIRONMENT_SET_ROTATION: { + LOGD("Called RETRO_ENVIRONMENT_SET_ROTATION"); + unsigned screenRotationIndex = (*static_cast(data)); + screenRotation = screenRotationIndex * (float) (-M_PI / 2.0); + screenRotationUpdated = true; + return true; + } + + case RETRO_ENVIRONMENT_SET_DISK_CONTROL_INTERFACE: { + LOGD("Called RETRO_ENVIRONMENT_SET_ROTATION"); + retro_disk_control_callback = static_cast(data); + return true; + } + + case RETRO_ENVIRONMENT_GET_PERF_INTERFACE: + LOGD("Called RETRO_ENVIRONMENT_GET_PERF_INTERFACE"); + return false; + + case RETRO_ENVIRONMENT_SET_MEMORY_MAPS: { + auto *received = static_cast(data); + memoryDescriptors.assign(received->descriptors, received->descriptors + received->num_descriptors); + memoryMap.descriptors = memoryDescriptors.data(); + memoryMap.num_descriptors = static_cast(memoryDescriptors.size()); + hasMemoryMap = !memoryDescriptors.empty(); + return true; + } + + // TODO... RETRO_ENVIRONMENT_SET_SYSTEM_AV_INFO can also change frame-rate + case RETRO_ENVIRONMENT_SET_SYSTEM_AV_INFO: + case RETRO_ENVIRONMENT_SET_GEOMETRY: { + struct retro_game_geometry *geometry = static_cast(data); + gameGeometryHeight = geometry->base_height; + gameGeometryWidth = geometry->base_width; + gameGeometryAspectRatio = geometry->aspect_ratio; + gameGeometryUpdated = true; + return true; + } + + case RETRO_ENVIRONMENT_SET_CONTROLLER_INFO: + LOGD("Called RETRO_ENVIRONMENT_SET_CONTROLLER_INFO"); + return environment_handle_set_controller_info(static_cast(data)); + + case RETRO_ENVIRONMENT_GET_AUDIO_VIDEO_ENABLE: + LOGD("Called RETRO_ENVIRONMENT_GET_AUDIO_VIDEO_ENABLE"); + return false; + + case RETRO_ENVIRONMENT_GET_LANGUAGE: + LOGD("Called RETRO_ENVIRONMENT_GET_LANGUAGE"); + *((unsigned*) data) = language; + return true; + + case RETRO_ENVIRONMENT_GET_VFS_INTERFACE: + LOGD("Called RETRO_ENVIRONMENT_GET_VFS_INTERFACE"); + return environment_handle_get_vfs_interface(static_cast(data)); + + case RETRO_ENVIRONMENT_GET_MICROPHONE_INTERFACE: + LOGD("Called RETRO_ENVIRONMENT_GET_MICROPHONE_INTERFACE"); + return environment_handle_get_microphone_interface(static_cast(data)); + + case RETRO_ENVIRONMENT_SET_NETPACKET_INTERFACE: + LOGI("Called RETRO_ENVIRONMENT_SET_NETPACKET_INTERFACE"); + libretrodroid::NetpacketBridge::getInstance().setCoreInterface( + static_cast(data) + ); + return true; + + default: + LOGD("callback environment has been called: %u", cmd); + return false; + } +} + +void Environment::setLanguage(const std::string& androidLanguage) { + std::unordered_map languages { + { "en", RETRO_LANGUAGE_ENGLISH }, + { "jp", RETRO_LANGUAGE_JAPANESE }, + { "fr", RETRO_LANGUAGE_FRENCH }, + { "es", RETRO_LANGUAGE_SPANISH }, + { "de", RETRO_LANGUAGE_GERMAN }, + { "it", RETRO_LANGUAGE_ITALIAN }, + { "nl", RETRO_LANGUAGE_DUTCH }, + { "pt", RETRO_LANGUAGE_PORTUGUESE_PORTUGAL }, + { "ru", RETRO_LANGUAGE_RUSSIAN }, + { "ko", RETRO_LANGUAGE_KOREAN }, + { "zh", RETRO_LANGUAGE_CHINESE_TRADITIONAL }, + { "eo", RETRO_LANGUAGE_ESPERANTO }, + { "pl", RETRO_LANGUAGE_POLISH }, + { "vi", RETRO_LANGUAGE_VIETNAMESE }, + { "ar", RETRO_LANGUAGE_ARABIC }, + { "el", RETRO_LANGUAGE_GREEK }, + { "tr", RETRO_LANGUAGE_TURKISH } + }; + + if (languages.find(androidLanguage) != languages.end()) { + language = languages[androidLanguage]; + } +} + +retro_hw_context_reset_t Environment::getHwContextReset() const { + return hw_context_reset; +} + +retro_hw_context_reset_t Environment::getHwContextDestroy() const { + return hw_context_destroy; +} + +struct retro_disk_control_callback* Environment::getRetroDiskControlCallback() const { + return retro_disk_control_callback; +} + +const struct retro_memory_map* Environment::getMemoryMap() const { + return hasMemoryMap ? &memoryMap : nullptr; +} + +int Environment::getPixelFormat() const { + return pixelFormat; +} + +bool Environment::isUseHwAcceleration() const { + return useHWAcceleration; +} + +bool Environment::isUseDepth() const { + return useDepth; +} + +bool Environment::isUseStencil() const { + return useStencil; +} + +bool Environment::isBottomLeftOrigin() const { + return bottomLeftOrigin; +} + +float Environment::getScreenRotation() const { + return screenRotation; +} + +bool Environment::isGameGeometryUpdated() const { + return gameGeometryUpdated; +} + +void Environment::clearGameGeometryUpdated() { + gameGeometryUpdated = false; +} + +unsigned int Environment::getGameGeometryWidth() const { + return gameGeometryWidth; +} + +unsigned int Environment::getGameGeometryHeight() const { + return gameGeometryHeight; +} + +float Environment::getGameGeometryAspectRatio() const { + return gameGeometryAspectRatio; +} + +const std::vector Environment::getVariables() const { + std::vector result; + + std::for_each( + variables.begin(), + variables.end(), + [&](std::pair item) { + result.push_back(item.second); + } + ); + + std::sort( + result.begin(), + result.end(), + [](struct Variable v1, struct Variable v2) { + return v1.key < v2.key; + } + ); + + return result; +} + +const std::vector> &Environment::getControllers() const { + return controllers; +} + +float Environment::retrieveGameSpecificAspectRatio() { + if (getGameGeometryAspectRatio() > 0) { + return getGameGeometryAspectRatio(); + } + + if (getGameGeometryWidth() > 0 && getGameGeometryHeight() > 0) { + return (float) getGameGeometryWidth() / (float) getGameGeometryHeight(); + } + + return -1.0f; +} + +bool Environment::isScreenRotationUpdated() const { + return screenRotationUpdated; +} + +void Environment::clearScreenRotationUpdated() { + screenRotationUpdated = false; +} + +std::array& Environment::getLastRumbleStates() { + return rumbleStates; +} + +void Environment::setEnableVirtualFileSystem(bool value) { + this->useVirtualFileSystem = value; +} + +void Environment::setEnableMicrophone(bool value) { + this->enableMicrophone = value; +} diff --git a/libretrodroid/src/main/cpp/environment.h b/libretrodroid/src/main/cpp/environment.h new file mode 100644 index 000000000..ee147777f --- /dev/null +++ b/libretrodroid/src/main/cpp/environment.h @@ -0,0 +1,173 @@ +/* + * Copyright (C) 2020 Filippo Scognamiglio + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef LIBRETRODROID_ENVIRONMENT_H +#define LIBRETRODROID_ENVIRONMENT_H + +#define MODULE_NAME_CORE "Libretro Core" + +#include +#include +#include +#include +#include +#include +#include + +#include "../../libretro-common/include/libretro.h" +#include "log.h" +#include "rumblestate.h" + +class Environment { +public: + static Environment& getInstance() + { + static Environment instance; + return instance; + } + Environment(Environment const&) = delete; + void operator=(Environment const&) = delete; + + static void callback_retro_log(enum retro_log_level level, const char *fmt, ...); + + static bool callback_set_rumble_state( + unsigned port, + enum retro_rumble_effect effect, + uint16_t strength + ); + + static bool callback_environment(unsigned cmd, void *data); + + void setEnableVirtualFileSystem(bool value); + void setEnableMicrophone(bool value); + +private: + Environment() {} + +public: + void initialize( + const std::string &requiredSystemDirectory, + const std::string &requiredSavesDirectory, + retro_hw_get_current_framebuffer_t required_callback_get_current_framebuffer + ); + + void deinitialize(); + + void updateVariable(const std::string &key, const std::string &value); + + void setLanguage(const std::string &androidLanguage); + + float retrieveGameSpecificAspectRatio(); + + bool handle_callback_set_rumble_state( + unsigned port, + enum retro_rumble_effect effect, + uint16_t strength + ); + + bool handle_callback_environment(unsigned cmd, void *data); + + retro_hw_context_reset_t getHwContextReset() const; + retro_hw_context_reset_t getHwContextDestroy() const; + + struct retro_disk_control_callback* getRetroDiskControlCallback() const; + + const struct retro_memory_map* getMemoryMap() const; + + int getPixelFormat() const; + bool isUseHwAcceleration() const; + bool isUseDepth() const; + bool isUseStencil() const; + bool isBottomLeftOrigin() const; + + float getScreenRotation() const; + bool isScreenRotationUpdated() const; + void clearScreenRotationUpdated(); + + unsigned int getGameGeometryWidth() const; + unsigned int getGameGeometryHeight() const; + float getGameGeometryAspectRatio() const; + bool isGameGeometryUpdated() const; + void clearGameGeometryUpdated(); + + std::array & getLastRumbleStates(); + + const std::vector getVariables() const; + + const std::vector> &getControllers() const; + +private: + bool environment_handle_set_variables(const struct retro_variable* received); + bool environment_handle_get_variable(struct retro_variable* requested); + bool environment_handle_set_controller_info(const struct retro_controller_info* received); + bool environment_handle_set_hw_render(struct retro_hw_render_callback* hw_render_callback); + bool environment_handle_get_vfs_interface(struct retro_vfs_interface_info* vfs_interface_info); + bool environment_handle_get_microphone_interface(struct retro_microphone_interface* microphone_interface); + +private: + retro_hw_context_reset_t hw_context_reset = nullptr; + retro_hw_context_reset_t hw_context_destroy = nullptr; + struct retro_disk_control_callback *retro_disk_control_callback = nullptr; + + std::vector memoryDescriptors; + struct retro_memory_map memoryMap {}; + bool hasMemoryMap = false; + + std::string savesDirectory; + std::string systemDirectory; + retro_hw_get_current_framebuffer_t callback_get_current_framebuffer = nullptr; + unsigned language = RETRO_LANGUAGE_ENGLISH; + bool useVirtualFileSystem = false; + bool enableMicrophone = false; + + int pixelFormat = RETRO_PIXEL_FORMAT_RGB565; + bool useHWAcceleration = false; + bool useDepth = false; + bool useStencil = false; + bool bottomLeftOrigin = false; + + float screenRotation = 0; + bool screenRotationUpdated = false; + + bool gameGeometryUpdated = false; + unsigned gameGeometryWidth = 0; + unsigned gameGeometryHeight = 0; + float gameGeometryAspectRatio = -1.0f; + + std::array rumbleStates; + + std::unordered_map variables; + bool dirtyVariables = false; + + std::vector> controllers; +}; + +struct Variable { +public: + std::string key; + std::string value; + std::string description; +}; + +struct Controller { +public: + unsigned id; + std::string description; +}; + +#endif //LIBRETRODROID_ENVIRONMENT_H + diff --git a/libretrodroid/src/main/cpp/errorcodes.cpp b/libretrodroid/src/main/cpp/errorcodes.cpp new file mode 100644 index 000000000..264069b22 --- /dev/null +++ b/libretrodroid/src/main/cpp/errorcodes.cpp @@ -0,0 +1,30 @@ +/* + * Copyright (C) 2019 Filippo Scognamiglio + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef LIBRETRODROID_ERRORCODES_H +#define LIBRETRODROID_ERRORCODES_H + +namespace libretrodroid { + int ERROR_LOAD_LIBRARY = 0; + int ERROR_LOAD_GAME = 1; + int ERROR_GL_NOT_COMPATIBLE = 2; + int ERROR_SERIALIZATION = 3; + int ERROR_CHEAT = 4; + int ERROR_GENERIC = -1; +} + +#endif //LIBRETRODROID_ERRORCODES_H diff --git a/libretrodroid/src/main/cpp/errorcodes.h b/libretrodroid/src/main/cpp/errorcodes.h new file mode 100644 index 000000000..3524a7fc6 --- /dev/null +++ b/libretrodroid/src/main/cpp/errorcodes.h @@ -0,0 +1,30 @@ +/* + * Copyright (C) 2019 Filippo Scognamiglio + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef LIBRETRODROID_ERRORCODES_H +#define LIBRETRODROID_ERRORCODES_H + +namespace libretrodroid { + extern int ERROR_LOAD_LIBRARY; + extern int ERROR_LOAD_GAME; + extern int ERROR_GL_NOT_COMPATIBLE; + extern int ERROR_SERIALIZATION; + extern int ERROR_CHEAT; + extern int ERROR_GENERIC; +} + +#endif //LIBRETRODROID_ERRORCODES_H diff --git a/libretrodroid/src/main/cpp/fpssync.cpp b/libretrodroid/src/main/cpp/fpssync.cpp new file mode 100644 index 000000000..f0ab777d8 --- /dev/null +++ b/libretrodroid/src/main/cpp/fpssync.cpp @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2019 Filippo Scognamiglio + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include "fpssync.h" +#include "log.h" + +namespace libretrodroid { + +unsigned FPSSync::advanceFrames() { + if (useVSync) { + if (vsyncMultiple <= 1) return 1; + tickCounter = (tickCounter + 1) % vsyncMultiple; + return tickCounter == 0 ? 1 : 0; + } + + if (lastFrame == MIN_TIME) { + start(); + } + + auto now = std::chrono::steady_clock::now(); + auto frames = std::max((now - lastFrame) / sampleInterval, (long long) 1); + lastFrame = lastFrame + sampleInterval * frames; + + return frames; +} + +FPSSync::FPSSync(double contentRefreshRate, double screenRefreshRate) { + this->contentRefreshRate = contentRefreshRate; + this->screenRefreshRate = screenRefreshRate; + this->useVSync = std::abs(contentRefreshRate - screenRefreshRate) < FPS_TOLERANCE; + if (!useVSync && contentRefreshRate > 0) { + auto multiple = (unsigned) std::lround(screenRefreshRate / contentRefreshRate); + if (multiple >= 2 && + std::abs(screenRefreshRate - multiple * contentRefreshRate) < FPS_TOLERANCE * multiple) { + this->useVSync = true; + this->vsyncMultiple = multiple; + } + } + this->sampleInterval = std::chrono::microseconds((long) ((1000000L / contentRefreshRate))); + LOGI("FPS sync: content %f screen %f vsync: %d multiple: %d", contentRefreshRate, screenRefreshRate, useVSync, vsyncMultiple); + reset(); +} + +void FPSSync::start() { + LOGI("Starting game with fps %f on a screen with refresh rate %f. Using vsync: %d multiple: %d", contentRefreshRate, screenRefreshRate, useVSync, vsyncMultiple); + lastFrame = std::chrono::steady_clock::now(); +} + +void FPSSync::reset() { + lastFrame = MIN_TIME; +} + +double FPSSync::getTimeStretchFactor() { + return useVSync ? (contentRefreshRate * vsyncMultiple) / screenRefreshRate : 1.0; +} + +void FPSSync::wait() { + if (useVSync) return; + std::this_thread::sleep_until(lastFrame); +} + +} //namespace libretrodroid diff --git a/libretrodroid/src/main/cpp/fpssync.h b/libretrodroid/src/main/cpp/fpssync.h new file mode 100644 index 000000000..118c422ab --- /dev/null +++ b/libretrodroid/src/main/cpp/fpssync.h @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2019 Filippo Scognamiglio + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef LIBRETRODROID_FPSSYNC_H +#define LIBRETRODROID_FPSSYNC_H + +#include +#include + +namespace libretrodroid { + +typedef std::chrono::steady_clock::time_point TimePoint; +typedef std::chrono::duration Duration; + +class FPSSync { +public: + FPSSync(double contentRefreshRate, double screenRefreshRate); + ~FPSSync() { } + + void reset(); + unsigned advanceFrames(); + void wait(); + double getTimeStretchFactor(); +private: + + double screenRefreshRate; + double contentRefreshRate; + bool useVSync; + unsigned vsyncMultiple = 1; + unsigned tickCounter = 0; + const double FPS_TOLERANCE = 5; + + const TimePoint MIN_TIME = TimePoint::min(); + void start(); + + TimePoint lastFrame = MIN_TIME; + Duration sampleInterval; +}; + +} + + +#endif //LIBRETRODROID_FPSSYNC_H diff --git a/libretrodroid/src/main/cpp/immersivemode.cpp b/libretrodroid/src/main/cpp/immersivemode.cpp new file mode 100644 index 000000000..af9235010 --- /dev/null +++ b/libretrodroid/src/main/cpp/immersivemode.cpp @@ -0,0 +1,286 @@ +/* + * Copyright (C) 2025 Filippo Scognamiglio + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "immersivemode.h" + +#include +#include + +#include "log.h" + +namespace libretrodroid { + +void ImmersiveMode::initializeShaders() { + if (blendShaderProgram != 0) return; + + GLuint blendingVertexShader = glCreateShader(GL_VERTEX_SHADER); + glShaderSource(blendingVertexShader, 1, &blendingVertexShaderSource, nullptr); + glCompileShader(blendingVertexShader); + + GLuint blendingFragmentShader = glCreateShader(GL_FRAGMENT_SHADER); + glShaderSource(blendingFragmentShader, 1, &blendingFragmentShaderSource, nullptr); + glCompileShader(blendingFragmentShader); + + blendShaderProgram = glCreateProgram(); + glAttachShader(blendShaderProgram, blendingVertexShader); + glAttachShader(blendShaderProgram, blendingFragmentShader); + glBindAttribLocation(blendShaderProgram, 0, "aPosition"); + glBindAttribLocation(blendShaderProgram, 1, "aTexCoord"); + glLinkProgram(blendShaderProgram); + + glDeleteShader(blendingVertexShader); + glDeleteShader(blendingFragmentShader); + + blendTextureHandle = glGetUniformLocation(blendShaderProgram, "currentFrame"); + blendPrevTextureHandle = glGetUniformLocation(blendShaderProgram, "previousFrame"); + blendFactorHandle = glGetUniformLocation(blendShaderProgram, "blendFactor"); + + std::string fragmentShaderSource = generateBlurShader(); + + GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); + glShaderSource(vertexShader, 1, &defaultVertexShaderSource, nullptr); + glCompileShader(vertexShader); + + GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); + const char* c_str = fragmentShaderSource.c_str(); + glShaderSource(fragmentShader, 1, &c_str, nullptr); + glCompileShader(fragmentShader); + + blurShaderProgram = glCreateProgram(); + glAttachShader(blurShaderProgram, vertexShader); + glAttachShader(blurShaderProgram, fragmentShader); + glBindAttribLocation(blurShaderProgram, 0, "aPosition"); + glBindAttribLocation(blurShaderProgram, 1, "aTexCoord"); + glLinkProgram(blurShaderProgram); + + glDeleteShader(vertexShader); + glDeleteShader(fragmentShader); + + blurPositionHandle = glGetAttribLocation(blurShaderProgram, "aPosition"); + blurTextureCoordinatesHandle = glGetAttribLocation(blurShaderProgram, "aTexCoord"); + blurTextureHandle = glGetUniformLocation(blurShaderProgram, "texture"); + blurDirectionHandle = glGetUniformLocation(blurShaderProgram, "direction"); + + GLuint displayVertexShader = glCreateShader(GL_VERTEX_SHADER); + glShaderSource(displayVertexShader, 1, &defaultVertexShaderSource, nullptr); + glCompileShader(displayVertexShader); + + GLuint displayFragmentShader = glCreateShader(GL_FRAGMENT_SHADER); + glShaderSource(displayFragmentShader, 1, &displayFragmentShaderSource, nullptr); + glCompileShader(displayFragmentShader); + + displayShaderProgram = glCreateProgram(); + glAttachShader(displayShaderProgram, displayVertexShader); + glAttachShader(displayShaderProgram, displayFragmentShader); + glBindAttribLocation(displayShaderProgram, 0, "aPosition"); + glBindAttribLocation(displayShaderProgram, 1, "aTexCoord"); + glLinkProgram(displayShaderProgram); + + glDeleteShader(displayVertexShader); + glDeleteShader(displayFragmentShader); + + displayPositionHandle = glGetAttribLocation(blurShaderProgram, "aPosition"); + displayForegroundBoundsHandle = glGetUniformLocation(displayShaderProgram, "foregroundBounds"); + displayTextureCoordinatesHandle = glGetAttribLocation(blurShaderProgram, "aTexCoord"); + displayTextureHandle = glGetUniformLocation(displayShaderProgram, "texture"); +} + +void ImmersiveMode::initializeFramebuffers() { + if (!blurFramebuffers.empty()) return; + + for (int i = 0; i < 3; i++) { + blurFramebuffers.push_back( + ES3Utils::createFramebuffer( + downscaledWidth, downscaledHeight, true, false, false, false + ) + ); + } + + // Last framebuffer needs GL_MIRROR_REPEAT + blurFramebuffers.push_back( + ES3Utils::createFramebuffer( + downscaledWidth, downscaledHeight, true, true, false, false + ) + ); +} + +void ImmersiveMode::renderToFramebuffer(uintptr_t texture, GLfloat* gBackgroundVertices) { + int blendFramebufferReadIndex = (blendFramebufferWriteIndex + 1) % 2; + + glViewport(0, 0, downscaledWidth, downscaledHeight); + + glVertexAttribPointer(blurPositionHandle, 2, GL_FLOAT, GL_FALSE, 0, gBackgroundVertices); + glEnableVertexAttribArray(blurPositionHandle); + + glVertexAttribPointer(blurTextureCoordinatesHandle, 2, GL_FLOAT, GL_FALSE, 0, gTextureCoords); + glEnableVertexAttribArray(blurTextureCoordinatesHandle); + + glBindFramebuffer(GL_FRAMEBUFFER, blurFramebuffers[blendFramebufferWriteIndex]->framebuffer); + + glClear(GL_COLOR_BUFFER_BIT); + + glUseProgram(blendShaderProgram); + glUniform1f(blendFactorHandle, blendFactor); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, texture); + glUniform1i(blendTextureHandle, 0); + + glActiveTexture(GL_TEXTURE1); + glBindTexture(GL_TEXTURE_2D, blurFramebuffers[blendFramebufferReadIndex]->texture); + glUniform1i(blendPrevTextureHandle, 1); + + glDrawArrays(GL_TRIANGLES, 0, 6); + + glUseProgram(blurShaderProgram); + + glBindFramebuffer(GL_FRAMEBUFFER, blurFramebuffers[2]->framebuffer); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, blurFramebuffers[blendFramebufferWriteIndex]->texture); + glUniform1i(blurTextureHandle, 0); + glUniform2f(blurDirectionHandle, 1.0 / downscaledWidth, 0.0); + + glDrawArrays(GL_TRIANGLES, 0, 6); + + glBindFramebuffer(GL_FRAMEBUFFER, blurFramebuffers[3]->framebuffer); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, blurFramebuffers[2]->texture); + glUniform1i(blurTextureHandle, 0); + glUniform2f(blurDirectionHandle, 0.0, 1.0 / downscaledHeight); + + glDrawArrays(GL_TRIANGLES, 0, 6); + + blendFramebufferWriteIndex = blendFramebufferReadIndex; +} + +void ImmersiveMode::renderToFinalOutput( + unsigned screenWidth, + unsigned screenHeight, + std::array backgroundVertices, + std::array foregroundBounds +) { + glBindFramebuffer(GL_FRAMEBUFFER, 0); + glViewport(0, 0, screenWidth, screenHeight); + glUseProgram(displayShaderProgram); + + glVertexAttribPointer(displayPositionHandle, 2, GL_FLOAT, GL_FALSE, 0, backgroundVertices.data()); + glEnableVertexAttribArray(displayPositionHandle); + + glVertexAttribPointer(displayTextureCoordinatesHandle, 2, GL_FLOAT, GL_FALSE, 0, gTextureCoords); + glEnableVertexAttribArray(displayTextureCoordinatesHandle); + + glUniform4f( + displayForegroundBoundsHandle, + foregroundBounds[0], + foregroundBounds[1], + foregroundBounds[2], + foregroundBounds[3] + ); + + glUniform1i(displayTextureHandle, 0); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, blurFramebuffers[3]->texture); + glUniform1i(displayTextureHandle, 0); + glDrawArrays(GL_TRIANGLES, 0, 6); + + glDisableVertexAttribArray(displayPositionHandle); + glDisableVertexAttribArray(displayTextureCoordinatesHandle); + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindTexture(GL_TEXTURE_2D, 0); + glUseProgram(0); +} + +void ImmersiveMode::renderBackground( + unsigned screenWidth, + unsigned screenHeight, + std::array backgroundVertices, + std::array foregroundBounds, + GLfloat* framebufferVertices, + uintptr_t texture +) { + initializeShaders(); + initializeFramebuffers(); + + if (blendFramebufferCurrent == 0) { + renderToFramebuffer(texture, framebufferVertices); + } + + // Let's update the blurred texture every other frame. + blendFramebufferCurrent = (blendFramebufferCurrent + 1) % blurSkipUpdate; + + renderToFinalOutput(screenWidth, screenHeight, backgroundVertices, foregroundBounds); +} + +std::vector ImmersiveMode::generateSmoothingWeights(int size, float brightness) { + std::vector kernel(size); + float sigma = size / 3.0f; + float sum = 0.0f; + int halfSize = size / 2; + + for (int i = 0; i < size; i++) { + int x = i - halfSize; + kernel[i] = exp(-(x * x) / (2 * sigma * sigma)); + sum += kernel[i]; + } + + for (int i = 0; i < size; i++) { + kernel[i] = (kernel[i] / sum) * brightness; + } + + return kernel; +} + +std::string ImmersiveMode::generateBlurShader() { + if (blurMaskSize % 2 == 0) { + LOGE("Error: maskSize should be an odd number!"); + return ""; + } + + std::vector kernel = generateSmoothingWeights(blurMaskSize, sqrt(blurBrightness)); + + std::ostringstream result; + result << R"( + precision mediump float; + varying vec2 vTexCoord; + uniform sampler2D texture; + uniform vec2 direction; + + void main() { + lowp vec4 result = vec4(0.0); + lowp float kernel[)" << blurMaskSize << R"(]; + + )"; + + for (int i = 0; i < blurMaskSize; i++) { + result << " kernel[" << i << "] = " << kernel[i] << ";\n"; + } + + int halfMask = blurMaskSize / 2; + result << R"( + for (int i = -)" << halfMask << "; i <= " << halfMask << R"(; i++) { + lowp vec2 offset = vec2(float(i)) * direction; + result += texture2D(texture, vTexCoord + offset) * kernel[i + )" << halfMask << R"(]; + } + gl_FragColor = result; + } + )"; + + return result.str(); +} + +} // namespace libretrodroid diff --git a/libretrodroid/src/main/cpp/immersivemode.h b/libretrodroid/src/main/cpp/immersivemode.h new file mode 100644 index 000000000..50f066ee8 --- /dev/null +++ b/libretrodroid/src/main/cpp/immersivemode.h @@ -0,0 +1,200 @@ +/* + * Copyright (C) 2025 Filippo Scognamiglio + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +#ifndef LIBRETRODROID_IMMERSIVEMODE_H +#define LIBRETRODROID_IMMERSIVEMODE_H + +#include +#include +#include +#include +#include + +#include "renderers/es3/es3utils.h" + +namespace libretrodroid { + +class ImmersiveMode { +public: + struct Config { + Config( + int downscaledWidth = 8, + int downscaledHeight = 8, + int blurMaskSize = 5, + float blurBrightness = 0.5F, + int blurSkipUpdate = 2, + float blendFactor = 0.1F + ) : + downscaledWidth(downscaledWidth), + downscaledHeight(downscaledHeight), + blurMaskSize(blurMaskSize), + blurBrightness(blurBrightness), + blurSkipUpdate(blurSkipUpdate), + blendFactor(blendFactor) + {} + + int downscaledWidth; + int downscaledHeight; + int blurMaskSize; + float blurBrightness; + int blurSkipUpdate; + float blendFactor; + }; + + explicit ImmersiveMode(const Config& config = Config()) : + downscaledWidth(config.downscaledWidth), + downscaledHeight(config.downscaledHeight), + blurMaskSize(config.blurMaskSize), + blurBrightness(config.blurBrightness), + blurSkipUpdate(config.blurSkipUpdate > 0 ? config.blurSkipUpdate : 1), + blendFactor(config.blendFactor) + {} + + void renderBackground( + unsigned screenWidth, + unsigned screenHeight, + std::array backgroundVertices, + std::array foregroundBounds, + GLfloat* framebufferVertices, + uintptr_t texture + ); + +private: + std::string generateBlurShader(); + static std::vector generateSmoothingWeights(int size, float brightness); + + void initializeShaders(); + + void initializeFramebuffers(); + + void renderToFramebuffer(uintptr_t texture, GLfloat* gBackgroundVertices); + + void renderToFinalOutput( + unsigned screenWidth, + unsigned screenHeight, + std::array backgroundVertices, + std::array foregroundBounds + ); + +private: + const char* defaultVertexShaderSource = R"( + attribute mediump vec2 aPosition; + attribute mediump vec2 aTexCoord; + varying mediump vec2 vTexCoord; + void main() { + gl_Position = vec4(aPosition, 0.0, 1.0); + vTexCoord = aTexCoord; + } + )"; + + const char* displayFragmentShaderSource = R"( + precision mediump float; + varying mediump vec2 vTexCoord; + uniform lowp sampler2D texture; + uniform vec4 foregroundBounds; // (minX, minY, maxX, maxY) + + void main() { + mediump vec2 normalizedCoords = (vTexCoord - foregroundBounds.xy) / abs(foregroundBounds.zw - foregroundBounds.xy); + lowp vec2 speed = abs(foregroundBounds.zw - foregroundBounds.xy); + + mediump vec2 adjustedCoords = vec2(0.0); + adjustedCoords -= speed * normalizedCoords; + adjustedCoords += (1.0 + speed) * step(vec2(0.0), normalizedCoords) * normalizedCoords; + adjustedCoords -= (1.0 - speed) * step(vec2(1.0), normalizedCoords) * (normalizedCoords - 1.0); + + gl_FragColor = texture2D(texture, adjustedCoords); + } + )"; + + const char* blendingVertexShaderSource = R"( + attribute mediump vec2 aPosition; + attribute mediump vec2 aTexCoord; + varying mediump vec2 vTexCoord; + void main() { + gl_Position = vec4(aPosition, 0.0, 1.0); + vTexCoord = aTexCoord; + } + )"; + + const char* blendingFragmentShaderSource = R"( + precision mediump float; + varying mediump vec2 vTexCoord; + uniform lowp sampler2D currentFrame; + uniform lowp sampler2D previousFrame; + uniform float blendFactor; + + void main() { + lowp float margin = -0.125; + mediump vec2 adjustedCoord = vTexCoord * (1.0 - 2.0 * margin) + margin; + lowp vec4 currentColor = texture2D(currentFrame, adjustedCoord); + lowp vec4 prevColor = texture2D(previousFrame, vTexCoord); + gl_FragColor = mix(prevColor, currentColor, blendFactor); + } + )"; + + GLfloat gTextureCoords[12] = { + 0.0F, + 0.0F, + + 0.0F, + 1.0F, + + 1.0F, + 0.0F, + + 1.0F, + 0.0F, + + 0.0F, + 1.0F, + + 1.0F, + 1.0F, + }; + + GLuint blurShaderProgram = 0; + std::vector> blurFramebuffers; + + GLint blurPositionHandle = -1; + GLint blurTextureCoordinatesHandle = -1; + GLint blurTextureHandle = -1; + + GLint blurDirectionHandle = -1; + + GLuint displayShaderProgram = 0; + GLint displayTextureHandle = -1; + GLint displayPositionHandle = -1; + GLint displayForegroundBoundsHandle = -1; + GLint displayTextureCoordinatesHandle = -1; + + int downscaledWidth; + int downscaledHeight; + int blurMaskSize; + float blurBrightness; + int blurSkipUpdate; + float blendFactor; + + GLuint blendShaderProgram = 0; + GLint blendTextureHandle = -1; + GLint blendPrevTextureHandle = -1; + GLint blendFactorHandle = -1; + int blendFramebufferWriteIndex = 0; + int blendFramebufferCurrent = 0; +}; + +} // libretrodroid + +#endif //LIBRETRODROID_IMMERSIVEMODE_H diff --git a/libretrodroid/src/main/cpp/input.cpp b/libretrodroid/src/main/cpp/input.cpp new file mode 100644 index 000000000..2808f2b57 --- /dev/null +++ b/libretrodroid/src/main/cpp/input.cpp @@ -0,0 +1,241 @@ +/* + * Copyright (C) 2019 Filippo Scognamiglio + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "input.h" + +#include + +#include +#include + +#include "../../libretro-common/include/libretro.h" + +namespace libretrodroid { + +int16_t Input::getInputState(unsigned port, unsigned device, unsigned index, unsigned id) { + if (port >= 4 || port < 0) return 0; + + switch (device) { + case RETRO_DEVICE_JOYPAD: { + if (id == RETRO_DEVICE_ID_JOYPAD_MASK) { + int16_t mask = 0; + for (int i = 0; i < 16; i++) { + if (getInputState(port, RETRO_DEVICE_JOYPAD, 0, i)) { + mask |= (1 << i); + } + } + return mask; + } + switch (id) { + case RETRO_DEVICE_ID_JOYPAD_LEFT: { + bool axis = pads[port].dpadXAxis == -1; + bool buttons = anyPressed( + port, + RETRO_DEVICE_ID_JOYPAD_LEFT, + Input::RETRO_DEVICE_ID_JOYPAD_DOWN_LEFT, + Input::RETRO_DEVICE_ID_JOYPAD_UP_LEFT + ); + return axis || buttons; + } + case RETRO_DEVICE_ID_JOYPAD_RIGHT: { + bool axis = pads[port].dpadXAxis == 1; + bool buttons = anyPressed( + port, + RETRO_DEVICE_ID_JOYPAD_RIGHT, + Input::RETRO_DEVICE_ID_JOYPAD_UP_RIGHT, + Input::RETRO_DEVICE_ID_JOYPAD_DOWN_RIGHT + ); + return axis || buttons; + } + case RETRO_DEVICE_ID_JOYPAD_UP: { + bool axis = pads[port].dpadYAxis == -1; + bool buttons = anyPressed( + port, + RETRO_DEVICE_ID_JOYPAD_UP, + Input::RETRO_DEVICE_ID_JOYPAD_UP_LEFT, + Input::RETRO_DEVICE_ID_JOYPAD_UP_RIGHT + ); + return axis || buttons; + } + case RETRO_DEVICE_ID_JOYPAD_DOWN: { + bool axis = pads[port].dpadYAxis == 1; + bool buttons = anyPressed( + port, + RETRO_DEVICE_ID_JOYPAD_DOWN, + Input::RETRO_DEVICE_ID_JOYPAD_DOWN_LEFT, + Input::RETRO_DEVICE_ID_JOYPAD_DOWN_RIGHT + ); + return axis || buttons; + } + default: + return anyPressed(port, id); + } + } + + case RETRO_DEVICE_ANALOG: { + switch (index) { + case RETRO_DEVICE_INDEX_ANALOG_LEFT: + switch (id) { + case RETRO_DEVICE_ID_ANALOG_X: + return (int16_t) (pads[port].joypadLeftXAxis * MAX_RANGE_MOTION); + case RETRO_DEVICE_ID_ANALOG_Y: + return (int16_t) (pads[port].joypadLeftYAxis * MAX_RANGE_MOTION); + default: + return 0; + } + case RETRO_DEVICE_INDEX_ANALOG_RIGHT: + switch (id) { + case RETRO_DEVICE_ID_ANALOG_X: + return (int16_t) (pads[port].joypadRightXAxis * MAX_RANGE_MOTION); + case RETRO_DEVICE_ID_ANALOG_Y: + return (int16_t) (pads[port].joypadRightYAxis * MAX_RANGE_MOTION); + default: + return 0; + } + case RETRO_DEVICE_INDEX_ANALOG_BUTTON: + if (anyPressed(port, id)) { + return MAX_RANGE_MOTION; + } + return 0; + default: + return 0; + } + } + + case RETRO_DEVICE_POINTER: { + // TODO... Here we should hanlde multitouch... + if (index > 0) { + return 0; + } + + switch (id) { + case RETRO_DEVICE_ID_POINTER_PRESSED: { + bool isXActive = pads[port].pointerScreenXAxis >= 0; + bool isYActive = pads[port].pointerScreenYAxis >= 0; + return (int16_t) (isXActive && isYActive ? 1 : 0); + } + + case RETRO_DEVICE_ID_POINTER_X: + return (int16_t) (2.0 * (pads[port].pointerScreenXAxis - 0.5f) * MAX_RANGE_MOTION); + + case RETRO_DEVICE_ID_POINTER_Y: + return (int16_t) (2.0 * (pads[port].pointerScreenYAxis - 0.5f) * MAX_RANGE_MOTION); + + default: + return 0; + } + } + + default: + return 0; + } +} + +int Input::convertAndroidToLibretroKey(int keyCode) const { + switch (keyCode) { + case AKEYCODE_BUTTON_START: + return RETRO_DEVICE_ID_JOYPAD_START; + case AKEYCODE_BUTTON_SELECT: + return RETRO_DEVICE_ID_JOYPAD_SELECT; + case AKEYCODE_BUTTON_A: + return RETRO_DEVICE_ID_JOYPAD_A; + case AKEYCODE_BUTTON_X: + return RETRO_DEVICE_ID_JOYPAD_X; + case AKEYCODE_BUTTON_Y: + return RETRO_DEVICE_ID_JOYPAD_Y; + case AKEYCODE_BUTTON_B: + return RETRO_DEVICE_ID_JOYPAD_B; + case AKEYCODE_BUTTON_L1: + return RETRO_DEVICE_ID_JOYPAD_L; + case AKEYCODE_BUTTON_L2: + return RETRO_DEVICE_ID_JOYPAD_L2; + case AKEYCODE_BUTTON_R1: + return RETRO_DEVICE_ID_JOYPAD_R; + case AKEYCODE_BUTTON_R2: + return RETRO_DEVICE_ID_JOYPAD_R2; + case AKEYCODE_BUTTON_THUMBL: + return RETRO_DEVICE_ID_JOYPAD_L3; + case AKEYCODE_BUTTON_THUMBR: + return RETRO_DEVICE_ID_JOYPAD_R3; + case AKEYCODE_DPAD_UP: + return RETRO_DEVICE_ID_JOYPAD_UP; + case AKEYCODE_DPAD_DOWN: + return RETRO_DEVICE_ID_JOYPAD_DOWN; + case AKEYCODE_DPAD_LEFT: + return RETRO_DEVICE_ID_JOYPAD_LEFT; + case AKEYCODE_DPAD_RIGHT: + return RETRO_DEVICE_ID_JOYPAD_RIGHT; + case AKEYCODE_DPAD_UP_RIGHT: + return Input::RETRO_DEVICE_ID_JOYPAD_UP_RIGHT; + case AKEYCODE_DPAD_UP_LEFT: + return Input::RETRO_DEVICE_ID_JOYPAD_UP_LEFT; + case AKEYCODE_DPAD_DOWN_RIGHT: + return Input::RETRO_DEVICE_ID_JOYPAD_DOWN_RIGHT; + case AKEYCODE_DPAD_DOWN_LEFT: + return Input::RETRO_DEVICE_ID_JOYPAD_DOWN_LEFT; + default: + return UNKNOWN_KEY; + } +} + +void Input::onKeyEvent(unsigned int port, int action, int keyCode) { + int retroKeyCode = convertAndroidToLibretroKey(keyCode); + if (retroKeyCode == UNKNOWN_KEY) { + return; + } + + if (action == AKEY_EVENT_ACTION_DOWN) { + pads[port].pressedKeys.insert(retroKeyCode); + } else if (action == AKEY_EVENT_ACTION_UP) { + pads[port].pressedKeys.erase(retroKeyCode); + } +} + +void Input::onMotionEvent(int port, int motionSource, float xAxis, float yAxis) { + switch (motionSource) { + case Input::MOTION_SOURCE_DPAD: + pads[port].dpadXAxis = (int) round(xAxis); + pads[port].dpadYAxis = (int) round(yAxis); + break; + + case Input::MOTION_SOURCE_ANALOG_LEFT: + pads[port].joypadLeftXAxis = xAxis; + pads[port].joypadLeftYAxis = yAxis; + break; + + case Input::MOTION_SOURCE_ANALOG_RIGHT: + pads[port].joypadRightXAxis = xAxis; + pads[port].joypadRightYAxis = yAxis; + break; + + case Input::MOTION_SOURCE_POINTER: + pads[port].pointerScreenXAxis = xAxis; + pads[port].pointerScreenYAxis = yAxis; + break; + } +} + +template +bool Input::anyPressed(unsigned int port, unsigned int id, T &... args) const { + return anyPressed(port, id) || anyPressed(port, args...); +} + +bool Input::anyPressed(unsigned int port, unsigned int id) const { + return pads[port].pressedKeys.count(id) > 0; +} + +} //namespace libretrodroid diff --git a/libretrodroid/src/main/cpp/input.h b/libretrodroid/src/main/cpp/input.h new file mode 100644 index 000000000..9d7c44b1e --- /dev/null +++ b/libretrodroid/src/main/cpp/input.h @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2019 Filippo Scognamiglio + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef LIBRETRODROID_INPUT_H +#define LIBRETRODROID_INPUT_H + +#include +#include +#include + +namespace libretrodroid { + +class Input { + +private: + struct GamePadState { + std::unordered_set pressedKeys; + + int dpadXAxis = 0; + int dpadYAxis = 0; + float joypadLeftXAxis = 0; + float joypadLeftYAxis = 0; + float joypadRightXAxis = 0; + float joypadRightYAxis = 0; + float pointerScreenXAxis = -1; + float pointerScreenYAxis = -1; + }; + +public: + static constexpr int MOTION_SOURCE_DPAD = 0; + static constexpr int MOTION_SOURCE_ANALOG_LEFT = 1; + static constexpr int MOTION_SOURCE_ANALOG_RIGHT = 2; + static constexpr int MOTION_SOURCE_POINTER = 3; + static constexpr int MAX_RANGE_MOTION = 0x7fff; + + static constexpr int RETRO_DEVICE_ID_JOYPAD_UP_LEFT = 50; + static constexpr int RETRO_DEVICE_ID_JOYPAD_UP_RIGHT = 51; + static constexpr int RETRO_DEVICE_ID_JOYPAD_DOWN_LEFT = 52; + static constexpr int RETRO_DEVICE_ID_JOYPAD_DOWN_RIGHT = 53; + + int16_t getInputState(unsigned port, unsigned device, unsigned index, unsigned id); + + void onKeyEvent(unsigned int port, int action, int keyCode); + void onMotionEvent(int port, int motionSource, float xAxis, float yAxis); + +private: + const int UNKNOWN_KEY = -1; + + template + bool anyPressed(unsigned int port, unsigned int id, T&... args) const; + bool anyPressed(unsigned int port, unsigned int id) const; + int convertAndroidToLibretroKey(int keyCode) const; + + GamePadState pads[4]; +}; + +} + +#endif //LIBRETRODROID_INPUT_H diff --git a/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/Asm/arm64/7zAsm.S b/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/Asm/arm64/7zAsm.S new file mode 100644 index 000000000..12e950b4c --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/Asm/arm64/7zAsm.S @@ -0,0 +1,181 @@ +// 7zAsm.S -- ASM macros for arm64 +// 2021-04-25 : Igor Pavlov : Public domain + +#define r0 x0 +#define r1 x1 +#define r2 x2 +#define r3 x3 +#define r4 x4 +#define r5 x5 +#define r6 x6 +#define r7 x7 +#define r8 x8 +#define r9 x9 +#define r10 x10 +#define r11 x11 +#define r12 x12 +#define r13 x13 +#define r14 x14 +#define r15 x15 +#define r16 x16 +#define r17 x17 +#define r18 x18 +#define r19 x19 +#define r20 x20 +#define r21 x21 +#define r22 x22 +#define r23 x23 +#define r24 x24 +#define r25 x25 +#define r26 x26 +#define r27 x27 +#define r28 x28 +#define r29 x29 +#define r30 x30 + +#define REG_ABI_PARAM_0 r0 +#define REG_ABI_PARAM_1 r1 +#define REG_ABI_PARAM_2 r2 + + +.macro p2_add reg:req, param:req + add \reg, \reg, \param +.endm + +.macro p2_sub reg:req, param:req + sub \reg, \reg, \param +.endm + +.macro p2_sub_s reg:req, param:req + subs \reg, \reg, \param +.endm + +.macro p2_and reg:req, param:req + and \reg, \reg, \param +.endm + +.macro xor reg:req, param:req + eor \reg, \reg, \param +.endm + +.macro or reg:req, param:req + orr \reg, \reg, \param +.endm + +.macro shl reg:req, param:req + lsl \reg, \reg, \param +.endm + +.macro shr reg:req, param:req + lsr \reg, \reg, \param +.endm + +.macro sar reg:req, param:req + asr \reg, \reg, \param +.endm + +.macro p1_neg reg:req + neg \reg, \reg +.endm + +.macro dec reg:req + sub \reg, \reg, 1 +.endm + +.macro dec_s reg:req + subs \reg, \reg, 1 +.endm + +.macro inc reg:req + add \reg, \reg, 1 +.endm + +.macro inc_s reg:req + adds \reg, \reg, 1 +.endm + + +.macro imul reg:req, param:req + mul \reg, \reg, \param +.endm + +/* +arm64 and arm use reverted c flag after subs/cmp instructions: + arm64-arm : x86 + b.lo / b.cc : jb / jc + b.hs / b.cs : jae / jnc +*/ + +.macro jmp lab:req + b \lab +.endm + +.macro je lab:req + b.eq \lab +.endm + +.macro jz lab:req + b.eq \lab +.endm + +.macro jnz lab:req + b.ne \lab +.endm + +.macro jne lab:req + b.ne \lab +.endm + +.macro jb lab:req + b.lo \lab +.endm + +.macro jbe lab:req + b.ls \lab +.endm + +.macro ja lab:req + b.hi \lab +.endm + +.macro jae lab:req + b.hs \lab +.endm + + +.macro cmove dest:req, srcTrue:req + csel \dest, \srcTrue, \dest, eq +.endm + +.macro cmovne dest:req, srcTrue:req + csel \dest, \srcTrue, \dest, ne +.endm + +.macro cmovs dest:req, srcTrue:req + csel \dest, \srcTrue, \dest, mi +.endm + +.macro cmovns dest:req, srcTrue:req + csel \dest, \srcTrue, \dest, pl +.endm + +.macro cmovb dest:req, srcTrue:req + csel \dest, \srcTrue, \dest, lo +.endm + +.macro cmovae dest:req, srcTrue:req + csel \dest, \srcTrue, \dest, hs +.endm + + +.macro MY_ALIGN_16 macro + .p2align 4,, (1 << 4) - 1 +.endm + +.macro MY_ALIGN_32 macro + .p2align 5,, (1 << 5) - 1 +.endm + +.macro MY_ALIGN_64 macro + .p2align 6,, (1 << 6) - 1 +.endm diff --git a/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/Asm/arm64/LzmaDecOpt.S b/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/Asm/arm64/LzmaDecOpt.S new file mode 100644 index 000000000..10dc47354 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/Asm/arm64/LzmaDecOpt.S @@ -0,0 +1,1487 @@ +// LzmaDecOpt.S -- ARM64-ASM version of LzmaDec_DecodeReal_3() function +// 2021-04-25 : Igor Pavlov : Public domain + +/* +; 3 - is the code compatibility version of LzmaDec_DecodeReal_*() +; function for check at link time. +; That code is tightly coupled with LzmaDec_TryDummy() +; and with another functions in LzmaDec.c file. +; CLzmaDec structure, (probs) array layout, input and output of +; LzmaDec_DecodeReal_*() must be equal in both versions (C / ASM). +*/ + + +#include "7zAsm.S" + + // .arch armv8-a + // .file "LzmaDecOpt.c" + .text + .align 2 + .p2align 4,,15 +#ifdef __APPLE__ + .globl _LzmaDec_DecodeReal_3 +#else + .global LzmaDec_DecodeReal_3 +#endif + // .type LzmaDec_DecodeReal_3, %function + +// #define _LZMA_SIZE_OPT 1 + +#define LZMA_USE_4BYTES_FILL 1 +// #define LZMA_USE_2BYTES_COPY 1 +// #define LZMA_USE_CMOV_LZ_WRAP 1 +// #define _LZMA_PROB32 1 + +#define MY_ALIGN_FOR_ENTRY MY_ALIGN_32 +#define MY_ALIGN_FOR_LOOP MY_ALIGN_32 +#define MY_ALIGN_FOR_LOOP_16 MY_ALIGN_16 + +#ifdef _LZMA_PROB32 + .equ PSHIFT , 2 + .macro PLOAD dest:req, mem:req + ldr \dest, [\mem] + .endm + .macro PLOAD_PREINDEXED dest:req, mem:req, offset:req + ldr \dest, [\mem, \offset]! + .endm + .macro PLOAD_2 dest:req, mem1:req, mem2:req + ldr \dest, [\mem1, \mem2] + .endm + .macro PLOAD_LSL dest:req, mem1:req, mem2:req + ldr \dest, [\mem1, \mem2, lsl #PSHIFT] + .endm + .macro PSTORE src:req, mem:req + str \src, [\mem] + .endm + .macro PSTORE_2 src:req, mem1:req, mem2:req + str \src, [\mem1, \mem2] + .endm + .macro PSTORE_LSL src:req, mem1:req, mem2:req + str \src, [\mem1, \mem2, lsl #PSHIFT] + .endm + .macro PSTORE_LSL_M1 src:req, mem1:req, mem2:req, temp_reg:req + // you must check that temp_reg is free register when macro is used + add \temp_reg, \mem1, \mem2 + str \src, [\temp_reg, \mem2] + .endm +#else + // .equ PSHIFT , 1 + #define PSHIFT 1 + .macro PLOAD dest:req, mem:req + ldrh \dest, [\mem] + .endm + .macro PLOAD_PREINDEXED dest:req, mem:req, offset:req + ldrh \dest, [\mem, \offset]! + .endm + .macro PLOAD_2 dest:req, mem1:req, mem2:req + ldrh \dest, [\mem1, \mem2] + .endm + .macro PLOAD_LSL dest:req, mem1:req, mem2:req + ldrh \dest, [\mem1, \mem2, lsl #PSHIFT] + .endm + .macro PSTORE src:req, mem:req + strh \src, [\mem] + .endm + .macro PSTORE_2 src:req, mem1:req, mem2:req + strh \src, [\mem1, \mem2] + .endm + .macro PSTORE_LSL src:req, mem1:req, mem2:req + strh \src, [\mem1, \mem2, lsl #PSHIFT] + .endm + .macro PSTORE_LSL_M1 src:req, mem1:req, mem2:req, temp_reg:req + strh \src, [\mem1, \mem2] + .endm +#endif + +.equ PMULT , (1 << PSHIFT) +.equ PMULT_2 , (2 << PSHIFT) + +.equ kMatchSpecLen_Error_Data , (1 << 9) + +# x7 t0 : NORM_CALC : prob2 (IF_BIT_1) +# x6 t1 : NORM_CALC : probs_state +# x8 t2 : (LITM) temp : (TREE) temp +# x4 t3 : (LITM) bit : (TREE) temp : UPDATE_0/UPDATE_0 temp +# x10 t4 : (LITM) offs : (TREE) probs_PMULT : numBits +# x9 t5 : (LITM) match : sym2 (ShortDist) +# x1 t6 : (LITM) litm_prob : (TREE) prob_reg : pbPos +# x2 t7 : (LITM) prm : probBranch : cnt +# x3 sym : dist +# x12 len +# x0 range +# x5 cod + + +#define range w0 + +// t6 +#define pbPos w1 +#define pbPos_R r1 +#define prob_reg w1 +#define litm_prob prob_reg + +// t7 +#define probBranch w2 +#define cnt w2 +#define cnt_R r2 +#define prm r2 + +#define sym w3 +#define sym_R r3 +#define dist sym + +#define t3 w4 +#define bit w4 +#define bit_R r4 +#define update_temp_reg r4 + +#define cod w5 + +#define t1 w6 +#define t1_R r6 +#define probs_state t1_R + +#define t0 w7 +#define t0_R r7 +#define prob2 t0 + +#define t2 w8 +#define t2_R r8 + +// t5 +#define match w9 +#define sym2 w9 +#define sym2_R r9 + +#define t4 w10 +#define t4_R r10 + +#define offs w10 +#define offs_R r10 + +#define probs r11 + +#define len w12 +#define len_R x12 + +#define state w13 +#define state_R r13 + +#define dicPos r14 +#define buf r15 +#define bufLimit r16 +#define dicBufSize r17 + +#define limit r19 +#define rep0 w20 +#define rep0_R r20 +#define rep1 w21 +#define rep2 w22 +#define rep3 w23 +#define dic r24 +#define probs_IsMatch r25 +#define probs_Spec r26 +#define checkDicSize w27 +#define processedPos w28 +#define pbMask w29 +#define lc2_lpMask w30 + + +.equ kNumBitModelTotalBits , 11 +.equ kBitModelTotal , (1 << kNumBitModelTotalBits) +.equ kNumMoveBits , 5 +.equ kBitModelOffset , (kBitModelTotal - (1 << kNumMoveBits) + 1) + +.macro NORM_2 macro + ldrb t0, [buf], 1 + shl range, 8 + orr cod, t0, cod, lsl 8 + /* + mov t0, cod + ldrb cod, [buf], 1 + shl range, 8 + bfi cod, t0, #8, #24 + */ +.endm + +.macro TEST_HIGH_BYTE_range macro + tst range, 0xFF000000 +.endm + +.macro NORM macro + TEST_HIGH_BYTE_range + jnz 1f + NORM_2 +1: +.endm + + +# ---------- Branch MACROS ---------- + +.macro UPDATE_0__0 + sub prob2, probBranch, kBitModelOffset +.endm + +.macro UPDATE_0__1 + sub probBranch, probBranch, prob2, asr #(kNumMoveBits) +.endm + +.macro UPDATE_0__2 probsArray:req, probOffset:req, probDisp:req + .if \probDisp == 0 + PSTORE_2 probBranch, \probsArray, \probOffset + .elseif \probOffset == 0 + PSTORE_2 probBranch, \probsArray, \probDisp * PMULT + .else + .error "unsupported" + // add update_temp_reg, \probsArray, \probOffset + PSTORE_2 probBranch, update_temp_reg, \probDisp * PMULT + .endif +.endm + +.macro UPDATE_0 probsArray:req, probOffset:req, probDisp:req + UPDATE_0__0 + UPDATE_0__1 + UPDATE_0__2 \probsArray, \probOffset, \probDisp +.endm + + +.macro UPDATE_1 probsArray:req, probOffset:req, probDisp:req + // sub cod, cod, prob2 + // sub range, range, prob2 + p2_sub cod, range + sub range, prob2, range + sub prob2, probBranch, probBranch, lsr #(kNumMoveBits) + .if \probDisp == 0 + PSTORE_2 prob2, \probsArray, \probOffset + .elseif \probOffset == 0 + PSTORE_2 prob2, \probsArray, \probDisp * PMULT + .else + .error "unsupported" + // add update_temp_reg, \probsArray, \probOffset + PSTORE_2 prob2, update_temp_reg, \probDisp * PMULT + .endif +.endm + + +.macro CMP_COD_BASE + NORM + // lsr prob2, range, kNumBitModelTotalBits + // imul prob2, probBranch + // cmp cod, prob2 + mov prob2, range + shr range, kNumBitModelTotalBits + imul range, probBranch + cmp cod, range +.endm + +.macro CMP_COD_1 probsArray:req + PLOAD probBranch, \probsArray + CMP_COD_BASE +.endm + +.macro CMP_COD_3 probsArray:req, probOffset:req, probDisp:req + .if \probDisp == 0 + PLOAD_2 probBranch, \probsArray, \probOffset + .elseif \probOffset == 0 + PLOAD_2 probBranch, \probsArray, \probDisp * PMULT + .else + .error "unsupported" + add update_temp_reg, \probsArray, \probOffset + PLOAD_2 probBranch, update_temp_reg, \probDisp * PMULT + .endif + CMP_COD_BASE +.endm + + +.macro IF_BIT_1_NOUP probsArray:req, probOffset:req, probDisp:req, toLabel:req + CMP_COD_3 \probsArray, \probOffset, \probDisp + jae \toLabel +.endm + + +.macro IF_BIT_1 probsArray:req, probOffset:req, probDisp:req, toLabel:req + IF_BIT_1_NOUP \probsArray, \probOffset, \probDisp, \toLabel + UPDATE_0 \probsArray, \probOffset, \probDisp +.endm + + +.macro IF_BIT_0_NOUP probsArray:req, probOffset:req, probDisp:req, toLabel:req + CMP_COD_3 \probsArray, \probOffset, \probDisp + jb \toLabel +.endm + +.macro IF_BIT_0_NOUP_1 probsArray:req, toLabel:req + CMP_COD_1 \probsArray + jb \toLabel +.endm + + +# ---------- CMOV MACROS ---------- + +.macro NORM_LSR + NORM + lsr t0, range, #kNumBitModelTotalBits +.endm + +.macro COD_RANGE_SUB + subs t1, cod, t0 + p2_sub range, t0 +.endm + +.macro RANGE_IMUL prob:req + imul t0, \prob +.endm + +.macro NORM_CALC prob:req + NORM_LSR + RANGE_IMUL \prob + COD_RANGE_SUB +.endm + +.macro CMOV_range + cmovb range, t0 +.endm + +.macro CMOV_code + cmovae cod, t1 +.endm + +.macro CMOV_code_Model_Pre prob:req + sub t0, \prob, kBitModelOffset + CMOV_code + cmovae t0, \prob +.endm + + +.macro PUP_BASE_2 prob:req, dest_reg:req + # only sar works for both 16/32 bit prob modes + sub \dest_reg, \prob, \dest_reg, asr #(kNumMoveBits) +.endm + +.macro PUP prob:req, probPtr:req, mem2:req + PUP_BASE_2 \prob, t0 + PSTORE_2 t0, \probPtr, \mem2 +.endm + + + +#define probs_PMULT t4_R + +.macro BIT_01 + add probs_PMULT, probs, PMULT +.endm + + +.macro BIT_0_R prob:req + PLOAD_2 \prob, probs, 1 * PMULT + NORM_LSR + sub t3, \prob, kBitModelOffset + RANGE_IMUL \prob + PLOAD_2 t2, probs, 1 * PMULT_2 + COD_RANGE_SUB + CMOV_range + cmovae t3, \prob + PLOAD_2 t0, probs, 1 * PMULT_2 + PMULT + PUP_BASE_2 \prob, t3 + csel \prob, t2, t0, lo + CMOV_code + mov sym, 2 + PSTORE_2 t3, probs, 1 * PMULT + adc sym, sym, wzr + BIT_01 +.endm + +.macro BIT_1_R prob:req + NORM_LSR + p2_add sym, sym + sub t3, \prob, kBitModelOffset + RANGE_IMUL \prob + PLOAD_LSL t2, probs, sym_R + COD_RANGE_SUB + CMOV_range + cmovae t3, \prob + PLOAD_LSL t0, probs_PMULT, sym_R + PUP_BASE_2 \prob, t3 + csel \prob, t2, t0, lo + CMOV_code + PSTORE_LSL_M1 t3, probs, sym_R, t2_R + adc sym, sym, wzr +.endm + + +.macro BIT_2_R prob:req + NORM_LSR + p2_add sym, sym + sub t3, \prob, kBitModelOffset + RANGE_IMUL \prob + COD_RANGE_SUB + CMOV_range + cmovae t3, \prob + CMOV_code + PUP_BASE_2 \prob, t3 + PSTORE_LSL_M1 t3, probs, sym_R, t2_R + adc sym, sym, wzr +.endm + + +# ---------- MATCHED LITERAL ---------- + +.macro LITM_0 macro + shl match, (PSHIFT + 1) + and bit, match, 256 * PMULT + add prm, probs, 256 * PMULT + 1 * PMULT + p2_add match, match + p2_add prm, bit_R + eor offs, bit, 256 * PMULT + PLOAD litm_prob, prm + + NORM_LSR + sub t2, litm_prob, kBitModelOffset + RANGE_IMUL litm_prob + COD_RANGE_SUB + cmovae offs, bit + CMOV_range + and bit, match, offs + cmovae t2, litm_prob + CMOV_code + mov sym, 2 + PUP_BASE_2 litm_prob, t2 + PSTORE t2, prm + add prm, probs, offs_R + adc sym, sym, wzr +.endm + +.macro LITM macro + p2_add prm, bit_R + xor offs, bit + PLOAD_LSL litm_prob, prm, sym_R + + NORM_LSR + p2_add match, match + sub t2, litm_prob, kBitModelOffset + RANGE_IMUL litm_prob + COD_RANGE_SUB + cmovae offs, bit + CMOV_range + and bit, match, offs + cmovae t2, litm_prob + CMOV_code + PUP_BASE_2 litm_prob, t2 + PSTORE_LSL t2, prm, sym_R + add prm, probs, offs_R + adc sym, sym, sym +.endm + + +.macro LITM_2 macro + p2_add prm, bit_R + PLOAD_LSL litm_prob, prm, sym_R + + NORM_LSR + sub t2, litm_prob, kBitModelOffset + RANGE_IMUL litm_prob + COD_RANGE_SUB + CMOV_range + cmovae t2, litm_prob + CMOV_code + PUP_BASE_2 litm_prob, t2 + PSTORE_LSL t2, prm, sym_R + adc sym, sym, sym +.endm + + +# ---------- REVERSE BITS ---------- + +.macro REV_0 prob:req + NORM_CALC \prob + CMOV_range + PLOAD t2, sym2_R + PLOAD_2 t3, probs, 3 * PMULT + CMOV_code_Model_Pre \prob + add t1_R, probs, 3 * PMULT + cmovae sym2_R, t1_R + PUP \prob, probs, 1 * PMULT + csel \prob, t2, t3, lo +.endm + + +.macro REV_1 prob:req, step:req + NORM_LSR + PLOAD_PREINDEXED t2, sym2_R, (\step * PMULT) + RANGE_IMUL \prob + COD_RANGE_SUB + CMOV_range + PLOAD_2 t3, sym2_R, (\step * PMULT) + sub t0, \prob, kBitModelOffset + CMOV_code + add t1_R, sym2_R, \step * PMULT + cmovae t0, \prob + cmovae sym2_R, t1_R + PUP_BASE_2 \prob, t0 + csel \prob, t2, t3, lo + PSTORE_2 t0, t1_R, 0 - \step * PMULT_2 +.endm + + +.macro REV_2 prob:req, step:req + sub t1_R, sym2_R, probs + NORM_LSR + orr sym, sym, t1, lsr #PSHIFT + RANGE_IMUL \prob + COD_RANGE_SUB + sub t2, sym, \step + CMOV_range + cmovb sym, t2 + CMOV_code_Model_Pre \prob + PUP \prob, sym2_R, 0 +.endm + + +.macro REV_1_VAR prob:req + PLOAD \prob, sym_R + mov probs, sym_R + p2_add sym_R, sym2_R + NORM_LSR + add t2_R, sym_R, sym2_R + RANGE_IMUL \prob + COD_RANGE_SUB + cmovae sym_R, t2_R + CMOV_range + CMOV_code_Model_Pre \prob + p2_add sym2, sym2 + PUP \prob, probs, 0 +.endm + + +.macro add_big dest:req, src:req, param:req + .if (\param) < (1 << 12) + add \dest, \src, \param + .else + #ifndef _LZMA_PROB32 + .error "unexpcted add_big expansion" + #endif + add \dest, \src, (\param) / 2 + add \dest, \dest, (\param) - (\param) / 2 + .endif +.endm + +.macro sub_big dest:req, src:req, param:req + .if (\param) < (1 << 12) + sub \dest, \src, \param + .else + #ifndef _LZMA_PROB32 + .error "unexpcted sub_big expansion" + #endif + sub \dest, \src, (\param) / 2 + sub \dest, \dest, (\param) - (\param) / 2 + .endif +.endm + + +.macro SET_probs offset:req + // add_big probs, probs_Spec, (\offset) * PMULT + add probs, probs_IsMatch, ((\offset) - IsMatch) * PMULT +.endm + + +.macro LIT_PROBS + add sym, sym, processedPos, lsl 8 + inc processedPos + UPDATE_0__0 + shl sym, lc2_lpMask + SET_probs Literal + p2_and sym, lc2_lpMask + // p2_add probs_state, pbPos_R + p2_add probs, sym_R + UPDATE_0__1 + add probs, probs, sym_R, lsl 1 + UPDATE_0__2 probs_state, pbPos_R, 0 +.endm + + + +.equ kNumPosBitsMax , 4 +.equ kNumPosStatesMax , (1 << kNumPosBitsMax) + +.equ kLenNumLowBits , 3 +.equ kLenNumLowSymbols , (1 << kLenNumLowBits) +.equ kLenNumHighBits , 8 +.equ kLenNumHighSymbols , (1 << kLenNumHighBits) +.equ kNumLenProbs , (2 * kLenNumLowSymbols * kNumPosStatesMax + kLenNumHighSymbols) + +.equ LenLow , 0 +.equ LenChoice , LenLow +.equ LenChoice2 , (LenLow + kLenNumLowSymbols) +.equ LenHigh , (LenLow + 2 * kLenNumLowSymbols * kNumPosStatesMax) + +.equ kNumStates , 12 +.equ kNumStates2 , 16 +.equ kNumLitStates , 7 + +.equ kStartPosModelIndex , 4 +.equ kEndPosModelIndex , 14 +.equ kNumFullDistances , (1 << (kEndPosModelIndex >> 1)) + +.equ kNumPosSlotBits , 6 +.equ kNumLenToPosStates , 4 + +.equ kNumAlignBits , 4 +.equ kAlignTableSize , (1 << kNumAlignBits) + +.equ kMatchMinLen , 2 +.equ kMatchSpecLenStart , (kMatchMinLen + kLenNumLowSymbols * 2 + kLenNumHighSymbols) + +// .equ kStartOffset , 1408 +.equ kStartOffset , 0 +.equ SpecPos , (-kStartOffset) +.equ IsRep0Long , (SpecPos + kNumFullDistances) +.equ RepLenCoder , (IsRep0Long + (kNumStates2 << kNumPosBitsMax)) +.equ LenCoder , (RepLenCoder + kNumLenProbs) +.equ IsMatch , (LenCoder + kNumLenProbs) +.equ kAlign , (IsMatch + (kNumStates2 << kNumPosBitsMax)) +.equ IsRep , (kAlign + kAlignTableSize) +.equ IsRepG0 , (IsRep + kNumStates) +.equ IsRepG1 , (IsRepG0 + kNumStates) +.equ IsRepG2 , (IsRepG1 + kNumStates) +.equ PosSlot , (IsRepG2 + kNumStates) +.equ Literal , (PosSlot + (kNumLenToPosStates << kNumPosSlotBits)) +.equ NUM_BASE_PROBS , (Literal + kStartOffset) + +.if kStartOffset != 0 // && IsMatch != 0 + .error "Stop_Compiling_Bad_StartOffset" +.endif + +.if NUM_BASE_PROBS != 1984 + .error "Stop_Compiling_Bad_LZMA_PROBS" +.endif + +.equ offset_lc , 0 +.equ offset_lp , 1 +.equ offset_pb , 2 +.equ offset_dicSize , 4 +.equ offset_probs , 4 + offset_dicSize +.equ offset_probs_1664 , 8 + offset_probs +.equ offset_dic , 8 + offset_probs_1664 +.equ offset_dicBufSize , 8 + offset_dic +.equ offset_dicPos , 8 + offset_dicBufSize +.equ offset_buf , 8 + offset_dicPos +.equ offset_range , 8 + offset_buf +.equ offset_code , 4 + offset_range +.equ offset_processedPos , 4 + offset_code +.equ offset_checkDicSize , 4 + offset_processedPos +.equ offset_rep0 , 4 + offset_checkDicSize +.equ offset_rep1 , 4 + offset_rep0 +.equ offset_rep2 , 4 + offset_rep1 +.equ offset_rep3 , 4 + offset_rep2 +.equ offset_state , 4 + offset_rep3 +.equ offset_remainLen , 4 + offset_state +.equ offset_TOTAL_SIZE , 4 + offset_remainLen + +.if offset_TOTAL_SIZE != 96 + .error "Incorrect offset_TOTAL_SIZE" +.endif + + +.macro IsMatchBranch_Pre + # prob = probs + IsMatch + (state << kNumPosBitsMax) + posState; + and pbPos, pbMask, processedPos, lsl #(kLenNumLowBits + 1 + PSHIFT) + add probs_state, probs_IsMatch, state_R +.endm + + +/* +.macro IsMatchBranch + IsMatchBranch_Pre + IF_BIT_1 probs_state, pbPos_R, (IsMatch - IsMatch), IsMatch_label +.endm +*/ + +.macro CheckLimits + cmp buf, bufLimit + jae fin_OK + cmp dicPos, limit + jae fin_OK +.endm + +#define CheckLimits_lit CheckLimits +/* +.macro CheckLimits_lit + cmp buf, bufLimit + jae fin_OK_lit + cmp dicPos, limit + jae fin_OK_lit +.endm +*/ + + +#define PARAM_lzma REG_ABI_PARAM_0 +#define PARAM_limit REG_ABI_PARAM_1 +#define PARAM_bufLimit REG_ABI_PARAM_2 + + +.macro LOAD_LZMA_VAR reg:req, struct_offs:req + ldr \reg, [PARAM_lzma, \struct_offs] +.endm + +.macro LOAD_LZMA_BYTE reg:req, struct_offs:req + ldrb \reg, [PARAM_lzma, \struct_offs] +.endm + +.macro LOAD_LZMA_PAIR reg0:req, reg1:req, struct_offs:req + ldp \reg0, \reg1, [PARAM_lzma, \struct_offs] +.endm + + +LzmaDec_DecodeReal_3: +_LzmaDec_DecodeReal_3: +/* +.LFB0: + .cfi_startproc +*/ + + stp x19, x20, [sp, -128]! + stp x21, x22, [sp, 16] + stp x23, x24, [sp, 32] + stp x25, x26, [sp, 48] + stp x27, x28, [sp, 64] + stp x29, x30, [sp, 80] + + str PARAM_lzma, [sp, 120] + + mov bufLimit, PARAM_bufLimit + mov limit, PARAM_limit + + LOAD_LZMA_PAIR dic, dicBufSize, offset_dic + LOAD_LZMA_PAIR dicPos, buf, offset_dicPos + LOAD_LZMA_PAIR rep0, rep1, offset_rep0 + LOAD_LZMA_PAIR rep2, rep3, offset_rep2 + + mov t0, 1 << (kLenNumLowBits + 1 + PSHIFT) + LOAD_LZMA_BYTE pbMask, offset_pb + p2_add limit, dic + mov len, wzr // we can set it in all requiread branches instead + lsl pbMask, t0, pbMask + p2_add dicPos, dic + p2_sub pbMask, t0 + + LOAD_LZMA_BYTE lc2_lpMask, offset_lc + mov t0, 256 << PSHIFT + LOAD_LZMA_BYTE t1, offset_lp + p2_add t1, lc2_lpMask + p2_sub lc2_lpMask, (256 << PSHIFT) - PSHIFT + shl t0, t1 + p2_add lc2_lpMask, t0 + + LOAD_LZMA_VAR probs_Spec, offset_probs + LOAD_LZMA_VAR checkDicSize, offset_checkDicSize + LOAD_LZMA_VAR processedPos, offset_processedPos + LOAD_LZMA_VAR state, offset_state + // range is r0 : this load must be last don't move + LOAD_LZMA_PAIR range, cod, offset_range + mov sym, wzr + shl state, PSHIFT + + add_big probs_IsMatch, probs_Spec, ((IsMatch - SpecPos) << PSHIFT) + + // if (processedPos != 0 || checkDicSize != 0) + orr t0, checkDicSize, processedPos + cbz t0, 1f + add t0_R, dicBufSize, dic + cmp dicPos, dic + cmovne t0_R, dicPos + ldrb sym, [t0_R, -1] +1: + IsMatchBranch_Pre + cmp state, 4 * PMULT + jb lit_end + cmp state, kNumLitStates * PMULT + jb lit_matched_end + jmp lz_end + + + +#define BIT_0 BIT_0_R prob_reg +#define BIT_1 BIT_1_R prob_reg +#define BIT_2 BIT_2_R prob_reg + +# ---------- LITERAL ---------- +MY_ALIGN_64 +lit_start: + mov state, wzr +lit_start_2: + LIT_PROBS + + #ifdef _LZMA_SIZE_OPT + + PLOAD_2 prob_reg, probs, 1 * PMULT + mov sym, 1 + BIT_01 +MY_ALIGN_FOR_LOOP +lit_loop: + BIT_1 + tbz sym, 7, lit_loop + + #else + + BIT_0 + BIT_1 + BIT_1 + BIT_1 + BIT_1 + BIT_1 + BIT_1 + + #endif + + BIT_2 + IsMatchBranch_Pre + strb sym, [dicPos], 1 + p2_and sym, 255 + + CheckLimits_lit +lit_end: + IF_BIT_0_NOUP probs_state, pbPos_R, (IsMatch - IsMatch), lit_start + + # jmp IsMatch_label + + +#define FLAG_STATE_BITS (4 + PSHIFT) + +# ---------- MATCHES ---------- +# MY_ALIGN_FOR_ENTRY +IsMatch_label: + UPDATE_1 probs_state, pbPos_R, (IsMatch - IsMatch) + IF_BIT_1 probs_state, 0, (IsRep - IsMatch), IsRep_label + + SET_probs LenCoder + or state, (1 << FLAG_STATE_BITS) + +# ---------- LEN DECODE ---------- +len_decode: + mov len, 8 - kMatchMinLen + IF_BIT_0_NOUP_1 probs, len_mid_0 + UPDATE_1 probs, 0, 0 + p2_add probs, (1 << (kLenNumLowBits + PSHIFT)) + mov len, 0 - kMatchMinLen + IF_BIT_0_NOUP_1 probs, len_mid_0 + UPDATE_1 probs, 0, 0 + p2_add probs, LenHigh * PMULT - (1 << (kLenNumLowBits + PSHIFT)) + + #if 0 == 1 + BIT_0 + BIT_1 + BIT_1 + BIT_1 + BIT_1 + BIT_1 + #else + PLOAD_2 prob_reg, probs, 1 * PMULT + mov sym, 1 + BIT_01 +MY_ALIGN_FOR_LOOP +len8_loop: + BIT_1 + tbz sym, 6, len8_loop + #endif + + mov len, (kLenNumHighSymbols - kLenNumLowSymbols * 2) - kMatchMinLen + jmp len_mid_2 + +MY_ALIGN_FOR_ENTRY +len_mid_0: + UPDATE_0 probs, 0, 0 + p2_add probs, pbPos_R + BIT_0 +len_mid_2: + BIT_1 + BIT_2 + sub len, sym, len + tbz state, FLAG_STATE_BITS, copy_match + +# ---------- DECODE DISTANCE ---------- + // probs + PosSlot + ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << kNumPosSlotBits); + + mov t0, 3 + kMatchMinLen + cmp len, 3 + kMatchMinLen + cmovb t0, len + SET_probs PosSlot - (kMatchMinLen << (kNumPosSlotBits)) + add probs, probs, t0_R, lsl #(kNumPosSlotBits + PSHIFT) + + #ifdef _LZMA_SIZE_OPT + + PLOAD_2 prob_reg, probs, 1 * PMULT + mov sym, 1 + BIT_01 +MY_ALIGN_FOR_LOOP +slot_loop: + BIT_1 + tbz sym, 5, slot_loop + + #else + + BIT_0 + BIT_1 + BIT_1 + BIT_1 + BIT_1 + + #endif + + #define numBits t4 + mov numBits, sym + BIT_2 + // we need only low bits + p2_and sym, 3 + cmp numBits, 32 + kEndPosModelIndex / 2 + jb short_dist + + SET_probs kAlign + + # unsigned numDirectBits = (unsigned)(((distance >> 1) - 1)); + p2_sub numBits, (32 + 1 + kNumAlignBits) + # distance = (2 | (distance & 1)); + or sym, 2 + PLOAD_2 prob_reg, probs, 1 * PMULT + add sym2_R, probs, 2 * PMULT + +# ---------- DIRECT DISTANCE ---------- + +.macro DIRECT_1 + shr range, 1 + subs t0, cod, range + p2_add sym, sym + // add t1, sym, 1 + csel cod, cod, t0, mi + csinc sym, sym, sym, mi + // csel sym, t1, sym, pl + // adc sym, sym, sym // not 100% compatible for "corruptued-allowed" LZMA streams + dec_s numBits + je direct_end +.endm + + #ifdef _LZMA_SIZE_OPT + + jmp direct_norm +MY_ALIGN_FOR_ENTRY +direct_loop: + DIRECT_1 +direct_norm: + TEST_HIGH_BYTE_range + jnz direct_loop + NORM_2 + jmp direct_loop + + #else + +.macro DIRECT_2 + TEST_HIGH_BYTE_range + jz direct_unroll + DIRECT_1 +.endm + + DIRECT_2 + DIRECT_2 + DIRECT_2 + DIRECT_2 + DIRECT_2 + DIRECT_2 + DIRECT_2 + DIRECT_2 + +direct_unroll: + NORM_2 + DIRECT_1 + DIRECT_1 + DIRECT_1 + DIRECT_1 + DIRECT_1 + DIRECT_1 + DIRECT_1 + DIRECT_1 + jmp direct_unroll + + #endif + +MY_ALIGN_FOR_ENTRY +direct_end: + shl sym, kNumAlignBits + REV_0 prob_reg + REV_1 prob_reg, 2 + REV_1 prob_reg, 4 + REV_2 prob_reg, 8 + +decode_dist_end: + + // if (distance >= (checkDicSize == 0 ? processedPos: checkDicSize)) + + tst checkDicSize, checkDicSize + csel t0, processedPos, checkDicSize, eq + cmp sym, t0 + jae end_of_payload + // jmp end_of_payload # for debug + + mov rep3, rep2 + mov rep2, rep1 + mov rep1, rep0 + add rep0, sym, 1 + +.macro STATE_UPDATE_FOR_MATCH + // state = (state < kNumStates + kNumLitStates) ? kNumLitStates : kNumLitStates + 3; + // cmp state, (kNumStates + kNumLitStates) * PMULT + cmp state, kNumLitStates * PMULT + (1 << FLAG_STATE_BITS) + mov state, kNumLitStates * PMULT + mov t0, (kNumLitStates + 3) * PMULT + cmovae state, t0 +.endm + STATE_UPDATE_FOR_MATCH + +# ---------- COPY MATCH ---------- +copy_match: + + // if ((rem = limit - dicPos) == 0) break // return SZ_ERROR_DATA; + subs cnt_R, limit, dicPos + // jz fin_dicPos_LIMIT + jz fin_OK + + // curLen = ((rem < len) ? (unsigned)rem : len); + cmp cnt_R, len_R + cmovae cnt, len + + sub t0_R, dicPos, dic + p2_add dicPos, cnt_R + p2_add processedPos, cnt + p2_sub len, cnt + + // pos = dicPos - rep0 + (dicPos < rep0 ? dicBufSize : 0); + p2_sub_s t0_R, rep0_R + jae 1f + + cmn t0_R, cnt_R + p2_add t0_R, dicBufSize + ja copy_match_cross +1: +# ---------- COPY MATCH FAST ---------- + # t0_R : src_pos + p2_add t0_R, dic + ldrb sym, [t0_R] + p2_add t0_R, cnt_R + p1_neg cnt_R + +copy_common: + dec dicPos + + # dicPos : (ptr_to_last_dest_BYTE) + # t0_R : (src_lim) + # cnt_R : (-curLen) + + IsMatchBranch_Pre + + inc_s cnt_R + jz copy_end + + cmp rep0, 1 + je copy_match_0 + + #ifdef LZMA_USE_2BYTES_COPY + strb sym, [dicPos, cnt_R] + dec dicPos + # dicPos : (ptr_to_last_dest_16bitWORD) + p2_and cnt_R, -2 + ldrh sym, [t0_R, cnt_R] + adds cnt_R, cnt_R, 2 + jz 2f +MY_ALIGN_FOR_LOOP +1: + /* + strh sym, [dicPos, cnt_R] + ldrh sym, [t0_R, cnt_R] + adds cnt_R, cnt_R, 2 + jz 2f + */ + + strh sym, [dicPos, cnt_R] + ldrh sym, [t0_R, cnt_R] + adds cnt_R, cnt_R, 2 + jnz 1b +2: + + /* + // for universal little/big endian code, but slow + strh sym, [dicPos] + inc dicPos + ldrb sym, [t0_R, -1] + */ + + #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ + // we must improve big-endian detection for another compilers + // for big-endian we need to revert bytes + rev16 sym, sym + #endif + + // (sym) must represent as little-endian here: + strb sym, [dicPos], 1 + shr sym, 8 + + #else + +MY_ALIGN_FOR_LOOP +1: + strb sym, [dicPos, cnt_R] + ldrb sym, [t0_R, cnt_R] + inc_s cnt_R + jz copy_end + + strb sym, [dicPos, cnt_R] + ldrb sym, [t0_R, cnt_R] + inc_s cnt_R + jnz 1b + #endif + +copy_end: +lz_end_match: + strb sym, [dicPos], 1 + + # IsMatchBranch_Pre + CheckLimits +lz_end: + IF_BIT_1_NOUP probs_state, pbPos_R, (IsMatch - IsMatch), IsMatch_label + + + +# ---------- LITERAL MATCHED ---------- + + LIT_PROBS + + // matchByte = dic[dicPos - rep0 + (dicPos < rep0 ? dicBufSize : 0)]; + + sub t0_R, dicPos, dic + p2_sub_s t0_R, rep0_R + + #ifdef LZMA_USE_CMOV_LZ_WRAP + add t1_R, t0_R, dicBufSize + cmovb t0_R, t1_R + #else + jae 1f + p2_add t0_R, dicBufSize +1: + #endif + + ldrb match, [dic, t0_R] + + // state -= (state < 10) ? 3 : 6; + sub sym, state, 6 * PMULT + cmp state, 10 * PMULT + p2_sub state, 3 * PMULT + cmovae state, sym + + #ifdef _LZMA_SIZE_OPT + + mov offs, 256 * PMULT + shl match, (PSHIFT + 1) + mov sym, 1 + and bit, match, offs + add prm, probs, offs_R + +MY_ALIGN_FOR_LOOP +litm_loop: + LITM + tbz sym, 8, litm_loop + + #else + + LITM_0 + LITM + LITM + LITM + LITM + LITM + LITM + LITM_2 + + #endif + + IsMatchBranch_Pre + strb sym, [dicPos], 1 + p2_and sym, 255 + + // mov len, wzr // LITM uses same regisetr (len / offs). So we clear it + CheckLimits_lit +lit_matched_end: + IF_BIT_1_NOUP probs_state, pbPos_R, (IsMatch - IsMatch), IsMatch_label + # IsMatchBranch + p2_sub state, 3 * PMULT + jmp lit_start_2 + + + +# ---------- REP 0 LITERAL ---------- +MY_ALIGN_FOR_ENTRY +IsRep0Short_label: + UPDATE_0 probs_state, pbPos_R, 0 + + // dic[dicPos] = dic[dicPos - rep0 + (dicPos < rep0 ? dicBufSize : 0)]; + sub t0_R, dicPos, dic + + // state = state < kNumLitStates ? 9 : 11; + or state, 1 * PMULT + + # the caller doesn't allow (dicPos >= limit) case for REP_SHORT + # so we don't need the following (dicPos == limit) check here: + # cmp dicPos, limit + # jae fin_dicPos_LIMIT_REP_SHORT + # // jmp fin_dicPos_LIMIT_REP_SHORT // for testing/debug puposes + + inc processedPos + + IsMatchBranch_Pre + + p2_sub_s t0_R, rep0_R + #ifdef LZMA_USE_CMOV_LZ_WRAP + add sym_R, t0_R, dicBufSize + cmovb t0_R, sym_R + #else + jae 1f + p2_add t0_R, dicBufSize +1: + #endif + + ldrb sym, [dic, t0_R] + // mov len, wzr + jmp lz_end_match + +MY_ALIGN_FOR_ENTRY +IsRep_label: + UPDATE_1 probs_state, 0, (IsRep - IsMatch) + + # The (checkDicSize == 0 && processedPos == 0) case was checked before in LzmaDec.c with kBadRepCode. + # So we don't check it here. + + # mov t0, processedPos + # or t0, checkDicSize + # jz fin_ERROR_2 + + // state = state < kNumLitStates ? 8 : 11; + cmp state, kNumLitStates * PMULT + mov state, 8 * PMULT + mov probBranch, 11 * PMULT + cmovae state, probBranch + + SET_probs RepLenCoder + + IF_BIT_1 probs_state, 0, (IsRepG0 - IsMatch), IsRepG0_label + sub_big probs_state, probs_state, (IsMatch - IsRep0Long) << PSHIFT + IF_BIT_0_NOUP probs_state, pbPos_R, 0, IsRep0Short_label + UPDATE_1 probs_state, pbPos_R, 0 + jmp len_decode + +MY_ALIGN_FOR_ENTRY +IsRepG0_label: + UPDATE_1 probs_state, 0, (IsRepG0 - IsMatch) + IF_BIT_1 probs_state, 0, (IsRepG1 - IsMatch), IsRepG1_label + mov dist, rep1 + mov rep1, rep0 + mov rep0, dist + jmp len_decode + +# MY_ALIGN_FOR_ENTRY +IsRepG1_label: + UPDATE_1 probs_state, 0, (IsRepG1 - IsMatch) + IF_BIT_1 probs_state, 0, (IsRepG2 - IsMatch), IsRepG2_label + mov dist, rep2 + mov rep2, rep1 + mov rep1, rep0 + mov rep0, dist + jmp len_decode + +# MY_ALIGN_FOR_ENTRY +IsRepG2_label: + UPDATE_1 probs_state, 0, (IsRepG2 - IsMatch) + mov dist, rep3 + mov rep3, rep2 + mov rep2, rep1 + mov rep1, rep0 + mov rep0, dist + jmp len_decode + + + +# ---------- SPEC SHORT DISTANCE ---------- + +MY_ALIGN_FOR_ENTRY +short_dist: + p2_sub_s numBits, 32 + 1 + jbe decode_dist_end + or sym, 2 + shl sym, numBits + add sym_R, probs_Spec, sym_R, lsl #PSHIFT + p2_add sym_R, SpecPos * PMULT + 1 * PMULT + mov sym2, PMULT // # step +MY_ALIGN_FOR_LOOP +spec_loop: + REV_1_VAR prob_reg + dec_s numBits + jnz spec_loop + + p2_add sym2_R, probs_Spec + .if SpecPos != 0 + p2_add sym2_R, SpecPos * PMULT + .endif + p2_sub sym_R, sym2_R + shr sym, PSHIFT + + jmp decode_dist_end + + + +# ---------- COPY MATCH 0 ---------- +MY_ALIGN_FOR_ENTRY +copy_match_0: + #ifdef LZMA_USE_4BYTES_FILL + strb sym, [dicPos, cnt_R] + inc_s cnt_R + jz copy_end + + strb sym, [dicPos, cnt_R] + inc_s cnt_R + jz copy_end + + strb sym, [dicPos, cnt_R] + inc_s cnt_R + jz copy_end + + orr t3, sym, sym, lsl 8 + p2_and cnt_R, -4 + orr t3, t3, t3, lsl 16 +MY_ALIGN_FOR_LOOP_16 +1: + /* + str t3, [dicPos, cnt_R] + adds cnt_R, cnt_R, 4 + jz 2f + */ + + str t3, [dicPos, cnt_R] + adds cnt_R, cnt_R, 4 + jnz 1b +2: + // p2_and sym, 255 + #else + +MY_ALIGN_FOR_LOOP +1: + strb sym, [dicPos, cnt_R] + inc_s cnt_R + jz copy_end + + strb sym, [dicPos, cnt_R] + inc_s cnt_R + jnz 1b + #endif + + jmp copy_end + + +# ---------- COPY MATCH CROSS ---------- +copy_match_cross: + # t0_R - src pos + # cnt_R - total copy len + + p1_neg cnt_R +1: + ldrb sym, [dic, t0_R] + inc t0_R + strb sym, [dicPos, cnt_R] + inc cnt_R + cmp t0_R, dicBufSize + jne 1b + + ldrb sym, [dic] + sub t0_R, dic, cnt_R + jmp copy_common + + + + +/* +fin_dicPos_LIMIT_REP_SHORT: + mov len, 1 + jmp fin_OK +*/ + +/* +fin_dicPos_LIMIT: + jmp fin_OK + # For more strict mode we can stop decoding with error + # mov sym, 1 + # jmp fin +*/ + +fin_ERROR_MATCH_DIST: + # rep0 = distance + 1; + p2_add len, kMatchSpecLen_Error_Data + mov rep3, rep2 + mov rep2, rep1 + mov rep1, rep0 + mov rep0, sym + STATE_UPDATE_FOR_MATCH + # jmp fin_OK + mov sym, 1 + jmp fin + +end_of_payload: + inc_s sym + jnz fin_ERROR_MATCH_DIST + + mov len, kMatchSpecLenStart + xor state, (1 << FLAG_STATE_BITS) + jmp fin_OK + +/* +fin_OK_lit: + mov len, wzr +*/ + +fin_OK: + mov sym, wzr + +fin: + NORM + + #define fin_lzma_reg t0_R + + .macro STORE_LZMA_VAR reg:req, struct_offs:req + str \reg, [fin_lzma_reg, \struct_offs] + .endm + + .macro STORE_LZMA_PAIR reg0:req, reg1:req, struct_offs:req + stp \reg0, \reg1, [fin_lzma_reg, \struct_offs] + .endm + + ldr fin_lzma_reg, [sp, 120] + p2_sub dicPos, dic + shr state, PSHIFT + + STORE_LZMA_PAIR dicPos, buf, offset_dicPos + STORE_LZMA_PAIR range, cod, offset_range + STORE_LZMA_VAR processedPos, offset_processedPos + STORE_LZMA_PAIR rep0, rep1, offset_rep0 + STORE_LZMA_PAIR rep2, rep3, offset_rep2 + STORE_LZMA_PAIR state, len, offset_state + + mov w0, sym + + ldp x29, x30, [sp, 80] + ldp x27, x28, [sp, 64] + ldp x25, x26, [sp, 48] + ldp x23, x24, [sp, 32] + ldp x21, x22, [sp, 16] + ldp x19, x20, [sp], 128 + + ret +/* + .cfi_endproc +.LFE0: + .size LzmaDec_DecodeReal_3, .-LzmaDec_DecodeReal_3 + .ident "TAG_LZMA" + .section .note.GNU-stack,"",@progbits +*/ diff --git a/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/Asm/x86/7zAsm.asm b/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/Asm/x86/7zAsm.asm new file mode 100644 index 000000000..8910d16c6 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/Asm/x86/7zAsm.asm @@ -0,0 +1,341 @@ +; 7zAsm.asm -- ASM macros +; 2023-12-08 : Igor Pavlov : Public domain + + +; UASM can require these changes +; OPTION FRAMEPRESERVEFLAGS:ON +; OPTION PROLOGUE:NONE +; OPTION EPILOGUE:NONE + +ifdef @wordsize +; @wordsize is defined only in JWASM and ASMC and is not defined in MASM +; @wordsize eq 8 for 64-bit x64 +; @wordsize eq 2 for 32-bit x86 +if @wordsize eq 8 + x64 equ 1 +endif +else +ifdef RAX + x64 equ 1 +endif +endif + + +ifdef x64 + IS_X64 equ 1 +else + IS_X64 equ 0 +endif + +ifdef ABI_LINUX + IS_LINUX equ 1 +else + IS_LINUX equ 0 +endif + +ifndef x64 +; Use ABI_CDECL for x86 (32-bit) only +; if ABI_CDECL is not defined, we use fastcall abi +ifdef ABI_CDECL + IS_CDECL equ 1 +else + IS_CDECL equ 0 +endif +endif + +OPTION PROLOGUE:NONE +OPTION EPILOGUE:NONE + +MY_ASM_START macro + ifdef x64 + .code + else + .386 + .model flat + _TEXT$00 SEGMENT PARA PUBLIC 'CODE' + endif +endm + +MY_PROC macro name:req, numParams:req + align 16 + proc_numParams = numParams + if (IS_X64 gt 0) + proc_name equ name + elseif (IS_LINUX gt 0) + proc_name equ name + elseif (IS_CDECL gt 0) + proc_name equ @CatStr(_,name) + else + proc_name equ @CatStr(@,name,@, %numParams * 4) + endif + proc_name PROC +endm + +MY_ENDP macro + if (IS_X64 gt 0) + ret + elseif (IS_CDECL gt 0) + ret + elseif (proc_numParams LT 3) + ret + else + ret (proc_numParams - 2) * 4 + endif + proc_name ENDP +endm + + +ifdef x64 + REG_SIZE equ 8 + REG_LOGAR_SIZE equ 3 +else + REG_SIZE equ 4 + REG_LOGAR_SIZE equ 2 +endif + + x0 equ EAX + x1 equ ECX + x2 equ EDX + x3 equ EBX + x4 equ ESP + x5 equ EBP + x6 equ ESI + x7 equ EDI + + x0_W equ AX + x1_W equ CX + x2_W equ DX + x3_W equ BX + + x5_W equ BP + x6_W equ SI + x7_W equ DI + + x0_L equ AL + x1_L equ CL + x2_L equ DL + x3_L equ BL + + x0_H equ AH + x1_H equ CH + x2_H equ DH + x3_H equ BH + +; r0_L equ AL +; r1_L equ CL +; r2_L equ DL +; r3_L equ BL + +; r0_H equ AH +; r1_H equ CH +; r2_H equ DH +; r3_H equ BH + + +ifdef x64 + x5_L equ BPL + x6_L equ SIL + x7_L equ DIL + x8_L equ r8b + x9_L equ r9b + x10_L equ r10b + x11_L equ r11b + x12_L equ r12b + x13_L equ r13b + x14_L equ r14b + x15_L equ r15b + + r0 equ RAX + r1 equ RCX + r2 equ RDX + r3 equ RBX + r4 equ RSP + r5 equ RBP + r6 equ RSI + r7 equ RDI + x8 equ r8d + x9 equ r9d + x10 equ r10d + x11 equ r11d + x12 equ r12d + x13 equ r13d + x14 equ r14d + x15 equ r15d +else + r0 equ x0 + r1 equ x1 + r2 equ x2 + r3 equ x3 + r4 equ x4 + r5 equ x5 + r6 equ x6 + r7 equ x7 +endif + + x0_R equ r0 + x1_R equ r1 + x2_R equ r2 + x3_R equ r3 + x4_R equ r4 + x5_R equ r5 + x6_R equ r6 + x7_R equ r7 + x8_R equ r8 + x9_R equ r9 + x10_R equ r10 + x11_R equ r11 + x12_R equ r12 + x13_R equ r13 + x14_R equ r14 + x15_R equ r15 + +ifdef x64 +ifdef ABI_LINUX + +MY_PUSH_2_REGS macro + push r3 + push r5 +endm + +MY_POP_2_REGS macro + pop r5 + pop r3 +endm + +endif +endif + + +MY_PUSH_4_REGS macro + push r3 + push r5 + push r6 + push r7 +endm + +MY_POP_4_REGS macro + pop r7 + pop r6 + pop r5 + pop r3 +endm + + +; for fastcall and for WIN-x64 +REG_PARAM_0_x equ x1 +REG_PARAM_0 equ r1 +REG_PARAM_1_x equ x2 +REG_PARAM_1 equ r2 + +ifndef x64 +; for x86-fastcall + +REG_ABI_PARAM_0_x equ REG_PARAM_0_x +REG_ABI_PARAM_0 equ REG_PARAM_0 +REG_ABI_PARAM_1_x equ REG_PARAM_1_x +REG_ABI_PARAM_1 equ REG_PARAM_1 + +MY_PUSH_PRESERVED_ABI_REGS_UP_TO_INCLUDING_R11 macro + MY_PUSH_4_REGS +endm + +MY_POP_PRESERVED_ABI_REGS_UP_TO_INCLUDING_R11 macro + MY_POP_4_REGS +endm + +else +; x64 + +if (IS_LINUX eq 0) + +; for WIN-x64: +REG_PARAM_2_x equ x8 +REG_PARAM_2 equ r8 +REG_PARAM_3 equ r9 + +REG_ABI_PARAM_0_x equ REG_PARAM_0_x +REG_ABI_PARAM_0 equ REG_PARAM_0 +REG_ABI_PARAM_1_x equ REG_PARAM_1_x +REG_ABI_PARAM_1 equ REG_PARAM_1 +REG_ABI_PARAM_2_x equ REG_PARAM_2_x +REG_ABI_PARAM_2 equ REG_PARAM_2 +REG_ABI_PARAM_3 equ REG_PARAM_3 + +else +; for LINUX-x64: +REG_LINUX_PARAM_0_x equ x7 +REG_LINUX_PARAM_0 equ r7 +REG_LINUX_PARAM_1_x equ x6 +REG_LINUX_PARAM_1 equ r6 +REG_LINUX_PARAM_2 equ r2 +REG_LINUX_PARAM_3 equ r1 +REG_LINUX_PARAM_4_x equ x8 +REG_LINUX_PARAM_4 equ r8 +REG_LINUX_PARAM_5 equ r9 + +REG_ABI_PARAM_0_x equ REG_LINUX_PARAM_0_x +REG_ABI_PARAM_0 equ REG_LINUX_PARAM_0 +REG_ABI_PARAM_1_x equ REG_LINUX_PARAM_1_x +REG_ABI_PARAM_1 equ REG_LINUX_PARAM_1 +REG_ABI_PARAM_2 equ REG_LINUX_PARAM_2 +REG_ABI_PARAM_3 equ REG_LINUX_PARAM_3 +REG_ABI_PARAM_4_x equ REG_LINUX_PARAM_4_x +REG_ABI_PARAM_4 equ REG_LINUX_PARAM_4 +REG_ABI_PARAM_5 equ REG_LINUX_PARAM_5 + +MY_ABI_LINUX_TO_WIN_2 macro + mov r2, r6 + mov r1, r7 +endm + +MY_ABI_LINUX_TO_WIN_3 macro + mov r8, r2 + mov r2, r6 + mov r1, r7 +endm + +MY_ABI_LINUX_TO_WIN_4 macro + mov r9, r1 + mov r8, r2 + mov r2, r6 + mov r1, r7 +endm + +endif ; IS_LINUX + + +MY_PUSH_PRESERVED_ABI_REGS_UP_TO_INCLUDING_R11 macro + if (IS_LINUX gt 0) + MY_PUSH_2_REGS + else + MY_PUSH_4_REGS + endif +endm + +MY_POP_PRESERVED_ABI_REGS_UP_TO_INCLUDING_R11 macro + if (IS_LINUX gt 0) + MY_POP_2_REGS + else + MY_POP_4_REGS + endif +endm + + +MY_PUSH_PRESERVED_ABI_REGS macro + MY_PUSH_PRESERVED_ABI_REGS_UP_TO_INCLUDING_R11 + push r12 + push r13 + push r14 + push r15 +endm + + +MY_POP_PRESERVED_ABI_REGS macro + pop r15 + pop r14 + pop r13 + pop r12 + MY_POP_PRESERVED_ABI_REGS_UP_TO_INCLUDING_R11 +endm + +endif ; x64 diff --git a/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/Asm/x86/LzmaDecOpt.asm b/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/Asm/x86/LzmaDecOpt.asm new file mode 100644 index 000000000..7c568df1d --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/Asm/x86/LzmaDecOpt.asm @@ -0,0 +1,1339 @@ +; LzmaDecOpt.asm -- ASM version of LzmaDec_DecodeReal_3() function +; 2024-06-18: Igor Pavlov : Public domain +; +; 3 - is the code compatibility version of LzmaDec_DecodeReal_*() +; function for check at link time. +; That code is tightly coupled with LzmaDec_TryDummy() +; and with another functions in LzmaDec.c file. +; CLzmaDec structure, (probs) array layout, input and output of +; LzmaDec_DecodeReal_*() must be equal in both versions (C / ASM). + +ifndef x64 +; x64=1 +; .err +endif + +include 7zAsm.asm + +MY_ASM_START + +; if Z7_LZMA_DEC_OPT_ASM_USE_SEGMENT is defined, we use additional SEGMENT with 64-byte alignment. +; if Z7_LZMA_DEC_OPT_ASM_USE_SEGMENT is not defined, we use default SEGMENT (where default 16-byte alignment of segment is expected). +; The performance is almost identical in our tests. +; But the performance can depend from position of lzmadec code inside instruction cache +; or micro-op cache line (depending from low address bits in 32-byte/64-byte cache lines). +; And 64-byte alignment provides a more consistent speed regardless +; of the code's position in the executable. +; But also it's possible that code without Z7_LZMA_DEC_OPT_ASM_USE_SEGMENT can be +; slightly faster than 64-bytes aligned code in some cases, if offset of lzmadec +; code in 64-byte block after compilation provides better speed by some reason. +; Note that Z7_LZMA_DEC_OPT_ASM_USE_SEGMENT adds an extra section to the ELF file. +; If you don't want to get that extra section, do not define Z7_LZMA_DEC_OPT_ASM_USE_SEGMENT. + +ifndef Z7_LZMA_DEC_OPT_ASM_USE_SEGMENT +if (IS_LINUX gt 0) + Z7_LZMA_DEC_OPT_ASM_USE_SEGMENT equ 1 +else + Z7_LZMA_DEC_OPT_ASM_USE_SEGMENT equ 1 +endif +endif + +ifdef Z7_LZMA_DEC_OPT_ASM_USE_SEGMENT +_TEXT$LZMADECOPT SEGMENT ALIGN(64) 'CODE' +MY_ALIGN macro num:req + align num + ; align 16 +endm +else +MY_ALIGN macro num:req + ; We expect that ".text" is aligned for 16-bytes. + ; So we don't need large alignment inside out function. + align 16 +endm +endif + + +MY_ALIGN_16 macro + MY_ALIGN 16 +endm + +MY_ALIGN_32 macro + MY_ALIGN 32 +endm + +MY_ALIGN_64 macro + MY_ALIGN 64 +endm + + +; _LZMA_SIZE_OPT equ 1 + +; _LZMA_PROB32 equ 1 + +ifdef _LZMA_PROB32 + PSHIFT equ 2 + PLOAD macro dest, mem + mov dest, dword ptr [mem] + endm + PSTORE macro src, mem + mov dword ptr [mem], src + endm +else + PSHIFT equ 1 + PLOAD macro dest, mem + movzx dest, word ptr [mem] + endm + PSTORE macro src, mem + mov word ptr [mem], @CatStr(src, _W) + endm +endif + +PMULT equ (1 SHL PSHIFT) +PMULT_HALF equ (1 SHL (PSHIFT - 1)) +PMULT_2 equ (1 SHL (PSHIFT + 1)) + +kMatchSpecLen_Error_Data equ (1 SHL 9) + +; x0 range +; x1 pbPos / (prob) TREE +; x2 probBranch / prm (MATCHED) / pbPos / cnt +; x3 sym +;====== r4 === RSP +; x5 cod +; x6 t1 NORM_CALC / probs_state / dist +; x7 t0 NORM_CALC / prob2 IF_BIT_1 +; x8 state +; x9 match (MATCHED) / sym2 / dist2 / lpMask_reg +; x10 kBitModelTotal_reg +; r11 probs +; x12 offs (MATCHED) / dic / len_temp +; x13 processedPos +; x14 bit (MATCHED) / dicPos +; r15 buf + + +cod equ x5 +cod_L equ x5_L +range equ x0 +state equ x8 +state_R equ r8 +buf equ r15 +processedPos equ x13 +kBitModelTotal_reg equ x10 + +probBranch equ x2 +probBranch_R equ r2 +probBranch_W equ x2_W + +pbPos equ x1 +pbPos_R equ r1 + +cnt equ x2 +cnt_R equ r2 + +lpMask_reg equ x9 +dicPos equ r14 + +sym equ x3 +sym_R equ r3 +sym_L equ x3_L + +probs equ r11 +dic equ r12 + +t0 equ x7 +t0_W equ x7_W +t0_R equ r7 + +prob2 equ t0 +prob2_W equ t0_W + +t1 equ x6 +t1_R equ r6 + +probs_state equ t1 +probs_state_R equ t1_R + +prm equ r2 +match equ x9 +match_R equ r9 +offs equ x12 +offs_R equ r12 +bit equ x14 +bit_R equ r14 + +sym2 equ x9 +sym2_R equ r9 + +len_temp equ x12 + +dist equ sym +dist2 equ x9 + + + +kNumBitModelTotalBits equ 11 +kBitModelTotal equ (1 SHL kNumBitModelTotalBits) +kNumMoveBits equ 5 +kBitModelOffset equ ((1 SHL kNumMoveBits) - 1) +kTopValue equ (1 SHL 24) + +NORM_2 macro + ; movzx t0, BYTE PTR [buf] + shl cod, 8 + mov cod_L, BYTE PTR [buf] + shl range, 8 + ; or cod, t0 + inc buf +endm + + +NORM macro + cmp range, kTopValue + jae SHORT @F + NORM_2 +@@: +endm + + +; ---------- Branch MACROS ---------- + +UPDATE_0 macro probsArray:req, probOffset:req, probDisp:req + mov prob2, kBitModelTotal_reg + sub prob2, probBranch + shr prob2, kNumMoveBits + add probBranch, prob2 + PSTORE probBranch, probOffset * 1 + probsArray + probDisp * PMULT +endm + + +UPDATE_1 macro probsArray:req, probOffset:req, probDisp:req + sub prob2, range + sub cod, range + mov range, prob2 + mov prob2, probBranch + shr probBranch, kNumMoveBits + sub prob2, probBranch + PSTORE prob2, probOffset * 1 + probsArray + probDisp * PMULT +endm + + +CMP_COD macro probsArray:req, probOffset:req, probDisp:req + PLOAD probBranch, probOffset * 1 + probsArray + probDisp * PMULT + NORM + mov prob2, range + shr range, kNumBitModelTotalBits + imul range, probBranch + cmp cod, range +endm + + +IF_BIT_1_NOUP macro probsArray:req, probOffset:req, probDisp:req, toLabel:req + CMP_COD probsArray, probOffset, probDisp + jae toLabel +endm + + +IF_BIT_1 macro probsArray:req, probOffset:req, probDisp:req, toLabel:req + IF_BIT_1_NOUP probsArray, probOffset, probDisp, toLabel + UPDATE_0 probsArray, probOffset, probDisp +endm + + +IF_BIT_0_NOUP macro probsArray:req, probOffset:req, probDisp:req, toLabel:req + CMP_COD probsArray, probOffset, probDisp + jb toLabel +endm + + +; ---------- CMOV MACROS ---------- + +NORM_CALC macro prob:req + NORM + mov t0, range + shr range, kNumBitModelTotalBits + imul range, prob + sub t0, range + mov t1, cod + sub cod, range +endm + + +PUP macro prob:req, probPtr:req + sub t0, prob + ; only sar works for both 16/32 bit prob modes + sar t0, kNumMoveBits + add t0, prob + PSTORE t0, probPtr +endm + + +PUP_SUB macro prob:req, probPtr:req, symSub:req + sbb sym, symSub + PUP prob, probPtr +endm + + +PUP_COD macro prob:req, probPtr:req, symSub:req + mov t0, kBitModelOffset + cmovb cod, t1 + mov t1, sym + cmovb t0, kBitModelTotal_reg + PUP_SUB prob, probPtr, symSub +endm + + +BIT_0 macro prob:req, probNext:req + PLOAD prob, probs + 1 * PMULT + PLOAD probNext, probs + 1 * PMULT_2 + + NORM_CALC prob + + cmovae range, t0 + PLOAD t0, probs + 1 * PMULT_2 + PMULT + cmovae probNext, t0 + mov t0, kBitModelOffset + cmovb cod, t1 + cmovb t0, kBitModelTotal_reg + mov sym, 2 + PUP_SUB prob, probs + 1 * PMULT, 0 - 1 +endm + + +BIT_1 macro prob:req, probNext:req + PLOAD probNext, probs + sym_R * PMULT_2 + add sym, sym + + NORM_CALC prob + + cmovae range, t0 + PLOAD t0, probs + sym_R * PMULT + PMULT + cmovae probNext, t0 + PUP_COD prob, probs + t1_R * PMULT_HALF, 0 - 1 +endm + + +BIT_2 macro prob:req, symSub:req + add sym, sym + + NORM_CALC prob + + cmovae range, t0 + PUP_COD prob, probs + t1_R * PMULT_HALF, symSub +endm + + +; ---------- MATCHED LITERAL ---------- + +LITM_0 macro + mov offs, 256 * PMULT + shl match, (PSHIFT + 1) + mov bit, offs + and bit, match + PLOAD x1, probs + 256 * PMULT + bit_R * 1 + 1 * PMULT + lea prm, [probs + 256 * PMULT + bit_R * 1 + 1 * PMULT] + ; lea prm, [probs + 256 * PMULT + 1 * PMULT] + ; add prm, bit_R + xor offs, bit + add match, match + + NORM_CALC x1 + + cmovae offs, bit + mov bit, match + cmovae range, t0 + mov t0, kBitModelOffset + cmovb cod, t1 + cmovb t0, kBitModelTotal_reg + mov sym, 0 + PUP_SUB x1, prm, -2-1 +endm + + +LITM macro + and bit, offs + lea prm, [probs + offs_R * 1] + add prm, bit_R + PLOAD x1, prm + sym_R * PMULT + xor offs, bit + add sym, sym + add match, match + + NORM_CALC x1 + + cmovae offs, bit + mov bit, match + cmovae range, t0 + PUP_COD x1, prm + t1_R * PMULT_HALF, - 1 +endm + + +LITM_2 macro + and bit, offs + lea prm, [probs + offs_R * 1] + add prm, bit_R + PLOAD x1, prm + sym_R * PMULT + add sym, sym + + NORM_CALC x1 + + cmovae range, t0 + PUP_COD x1, prm + t1_R * PMULT_HALF, 256 - 1 +endm + + +; ---------- REVERSE BITS ---------- + +REV_0 macro prob:req, probNext:req + ; PLOAD prob, probs + 1 * PMULT + ; lea sym2_R, [probs + 2 * PMULT] + ; PLOAD probNext, probs + 2 * PMULT + PLOAD probNext, sym2_R + + NORM_CALC prob + + cmovae range, t0 + PLOAD t0, probs + 3 * PMULT + cmovae probNext, t0 + cmovb cod, t1 + mov t0, kBitModelOffset + cmovb t0, kBitModelTotal_reg + lea t1_R, [probs + 3 * PMULT] + cmovae sym2_R, t1_R + PUP prob, probs + 1 * PMULT +endm + + +REV_1 macro prob:req, probNext:req, step:req + add sym2_R, step * PMULT + PLOAD probNext, sym2_R + + NORM_CALC prob + + cmovae range, t0 + PLOAD t0, sym2_R + step * PMULT + cmovae probNext, t0 + cmovb cod, t1 + mov t0, kBitModelOffset + cmovb t0, kBitModelTotal_reg + lea t1_R, [sym2_R + step * PMULT] + cmovae sym2_R, t1_R + PUP prob, t1_R - step * PMULT_2 +endm + + +REV_2 macro prob:req, step:req + sub sym2_R, probs + shr sym2, PSHIFT + or sym, sym2 + + NORM_CALC prob + + cmovae range, t0 + lea t0, [sym - step] + cmovb sym, t0 + cmovb cod, t1 + mov t0, kBitModelOffset + cmovb t0, kBitModelTotal_reg + PUP prob, probs + sym2_R * PMULT +endm + + +REV_1_VAR macro prob:req + PLOAD prob, sym_R + mov probs, sym_R + add sym_R, sym2_R + + NORM_CALC prob + + cmovae range, t0 + lea t0_R, [sym_R + 1 * sym2_R] + cmovae sym_R, t0_R + mov t0, kBitModelOffset + cmovb cod, t1 + ; mov t1, kBitModelTotal + ; cmovb t0, t1 + cmovb t0, kBitModelTotal_reg + add sym2, sym2 + PUP prob, probs +endm + + + + +LIT_PROBS macro lpMaskParam:req + ; prob += (UInt32)3 * ((((processedPos << 8) + dic[(dicPos == 0 ? dicBufSize : dicPos) - 1]) & lpMask) << lc); + mov t0, processedPos + shl t0, 8 + add sym, t0 + and sym, lpMaskParam + add probs_state_R, pbPos_R + mov x1, LOC lc2 + lea sym, dword ptr[sym_R + 2 * sym_R] + add probs, Literal * PMULT + shl sym, x1_L + add probs, sym_R + UPDATE_0 probs_state_R, 0, IsMatch + inc processedPos +endm + + + +kNumPosBitsMax equ 4 +kNumPosStatesMax equ (1 SHL kNumPosBitsMax) + +kLenNumLowBits equ 3 +kLenNumLowSymbols equ (1 SHL kLenNumLowBits) +kLenNumHighBits equ 8 +kLenNumHighSymbols equ (1 SHL kLenNumHighBits) +kNumLenProbs equ (2 * kLenNumLowSymbols * kNumPosStatesMax + kLenNumHighSymbols) + +LenLow equ 0 +LenChoice equ LenLow +LenChoice2 equ (LenLow + kLenNumLowSymbols) +LenHigh equ (LenLow + 2 * kLenNumLowSymbols * kNumPosStatesMax) + +kNumStates equ 12 +kNumStates2 equ 16 +kNumLitStates equ 7 + +kStartPosModelIndex equ 4 +kEndPosModelIndex equ 14 +kNumFullDistances equ (1 SHL (kEndPosModelIndex SHR 1)) + +kNumPosSlotBits equ 6 +kNumLenToPosStates equ 4 + +kNumAlignBits equ 4 +kAlignTableSize equ (1 SHL kNumAlignBits) + +kMatchMinLen equ 2 +kMatchSpecLenStart equ (kMatchMinLen + kLenNumLowSymbols * 2 + kLenNumHighSymbols) + +kStartOffset equ 1664 +SpecPos equ (-kStartOffset) +IsRep0Long equ (SpecPos + kNumFullDistances) +RepLenCoder equ (IsRep0Long + (kNumStates2 SHL kNumPosBitsMax)) +LenCoder equ (RepLenCoder + kNumLenProbs) +IsMatch equ (LenCoder + kNumLenProbs) +kAlign equ (IsMatch + (kNumStates2 SHL kNumPosBitsMax)) +IsRep equ (kAlign + kAlignTableSize) +IsRepG0 equ (IsRep + kNumStates) +IsRepG1 equ (IsRepG0 + kNumStates) +IsRepG2 equ (IsRepG1 + kNumStates) +PosSlot equ (IsRepG2 + kNumStates) +Literal equ (PosSlot + (kNumLenToPosStates SHL kNumPosSlotBits)) +NUM_BASE_PROBS equ (Literal + kStartOffset) + +if kAlign ne 0 + .err +endif + +if NUM_BASE_PROBS ne 1984 + .err +endif + + +PTR_FIELD equ dq ? + +CLzmaDec_Asm struct + lc db ? + lp db ? + pb db ? + _pad_ db ? + dicSize dd ? + + probs_Spec PTR_FIELD + probs_1664 PTR_FIELD + dic_Spec PTR_FIELD + dicBufSize PTR_FIELD + dicPos_Spec PTR_FIELD + buf_Spec PTR_FIELD + + range_Spec dd ? + code_Spec dd ? + processedPos_Spec dd ? + checkDicSize dd ? + rep0 dd ? + rep1 dd ? + rep2 dd ? + rep3 dd ? + state_Spec dd ? + remainLen dd ? +CLzmaDec_Asm ends + + +CLzmaDec_Asm_Loc struct + OLD_RSP PTR_FIELD + lzmaPtr PTR_FIELD + _pad0_ PTR_FIELD + _pad1_ PTR_FIELD + _pad2_ PTR_FIELD + dicBufSize PTR_FIELD + probs_Spec PTR_FIELD + dic_Spec PTR_FIELD + + limit PTR_FIELD + bufLimit PTR_FIELD + lc2 dd ? + lpMask dd ? + pbMask dd ? + checkDicSize dd ? + + _pad_ dd ? + remainLen dd ? + dicPos_Spec PTR_FIELD + rep0 dd ? + rep1 dd ? + rep2 dd ? + rep3 dd ? +CLzmaDec_Asm_Loc ends + + +GLOB_2 equ [sym_R].CLzmaDec_Asm. +GLOB equ [r1].CLzmaDec_Asm. +LOC_0 equ [r0].CLzmaDec_Asm_Loc. +LOC equ [RSP].CLzmaDec_Asm_Loc. + + +COPY_VAR macro name + mov t0, GLOB_2 name + mov LOC_0 name, t0 +endm + + +RESTORE_VAR macro name + mov t0, LOC name + mov GLOB name, t0 +endm + + + +IsMatchBranch_Pre macro reg + ; prob = probs + IsMatch + (state << kNumPosBitsMax) + posState; + mov pbPos, LOC pbMask + and pbPos, processedPos + shl pbPos, (kLenNumLowBits + 1 + PSHIFT) + lea probs_state_R, [probs + 1 * state_R] +endm + + +IsMatchBranch macro reg + IsMatchBranch_Pre + IF_BIT_1 probs_state_R, pbPos_R, IsMatch, IsMatch_label +endm + + +CheckLimits macro reg + cmp buf, LOC bufLimit + jae fin_OK + cmp dicPos, LOC limit + jae fin_OK +endm + + + +; RSP is (16x + 8) bytes aligned in WIN64-x64 +; LocalSize equ ((((SIZEOF CLzmaDec_Asm_Loc) + 7) / 16 * 16) + 8) + +PARAM_lzma equ REG_ABI_PARAM_0 +PARAM_limit equ REG_ABI_PARAM_1 +PARAM_bufLimit equ REG_ABI_PARAM_2 + +ifdef Z7_LZMA_DEC_OPT_ASM_USE_SEGMENT +; MY_ALIGN_64 +else + MY_ALIGN_16 +endif +MY_PROC LzmaDec_DecodeReal_3, 3 +MY_PUSH_PRESERVED_ABI_REGS + + lea r0, [RSP - (SIZEOF CLzmaDec_Asm_Loc)] + and r0, -128 + mov r5, RSP + mov RSP, r0 + mov LOC_0 Old_RSP, r5 + mov LOC_0 lzmaPtr, PARAM_lzma + + mov LOC_0 remainLen, 0 ; remainLen must be ZERO + + mov LOC_0 bufLimit, PARAM_bufLimit + mov sym_R, PARAM_lzma ; CLzmaDec_Asm_Loc pointer for GLOB_2 + mov dic, GLOB_2 dic_Spec + add PARAM_limit, dic + mov LOC_0 limit, PARAM_limit + + COPY_VAR(rep0) + COPY_VAR(rep1) + COPY_VAR(rep2) + COPY_VAR(rep3) + + mov dicPos, GLOB_2 dicPos_Spec + add dicPos, dic + mov LOC_0 dicPos_Spec, dicPos + mov LOC_0 dic_Spec, dic + + mov x1_L, GLOB_2 pb + mov t0, 1 + shl t0, x1_L + dec t0 + mov LOC_0 pbMask, t0 + + ; unsigned pbMask = ((unsigned)1 << (p->prop.pb)) - 1; + ; unsigned lc = p->prop.lc; + ; unsigned lpMask = ((unsigned)0x100 << p->prop.lp) - ((unsigned)0x100 >> lc); + + mov x1_L, GLOB_2 lc + mov x2, 100h + mov t0, x2 + shr x2, x1_L + ; inc x1 + add x1_L, PSHIFT + mov LOC_0 lc2, x1 + mov x1_L, GLOB_2 lp + shl t0, x1_L + sub t0, x2 + mov LOC_0 lpMask, t0 + mov lpMask_reg, t0 + + ; mov probs, GLOB_2 probs_Spec + ; add probs, kStartOffset SHL PSHIFT + mov probs, GLOB_2 probs_1664 + mov LOC_0 probs_Spec, probs + + mov t0_R, GLOB_2 dicBufSize + mov LOC_0 dicBufSize, t0_R + + mov x1, GLOB_2 checkDicSize + mov LOC_0 checkDicSize, x1 + + mov processedPos, GLOB_2 processedPos_Spec + + mov state, GLOB_2 state_Spec + shl state, PSHIFT + + mov buf, GLOB_2 buf_Spec + mov range, GLOB_2 range_Spec + mov cod, GLOB_2 code_Spec + mov kBitModelTotal_reg, kBitModelTotal + xor sym, sym + + ; if (processedPos != 0 || checkDicSize != 0) + or x1, processedPos + jz @f + + add t0_R, dic + cmp dicPos, dic + cmovnz t0_R, dicPos + movzx sym, byte ptr[t0_R - 1] + +@@: + IsMatchBranch_Pre + cmp state, 4 * PMULT + jb lit_end + cmp state, kNumLitStates * PMULT + jb lit_matched_end + jmp lz_end + + + + +; ---------- LITERAL ---------- +MY_ALIGN_64 +lit_start: + xor state, state +lit_start_2: + LIT_PROBS lpMask_reg + + ifdef _LZMA_SIZE_OPT + + PLOAD x1, probs + 1 * PMULT + mov sym, 1 +MY_ALIGN_16 +lit_loop: + BIT_1 x1, x2 + mov x1, x2 + cmp sym, 127 + jbe lit_loop + + else + + BIT_0 x1, x2 + BIT_1 x2, x1 + BIT_1 x1, x2 + BIT_1 x2, x1 + BIT_1 x1, x2 + BIT_1 x2, x1 + BIT_1 x1, x2 + + endif + + BIT_2 x2, 256 - 1 + + ; mov dic, LOC dic_Spec + mov probs, LOC probs_Spec + IsMatchBranch_Pre + mov byte ptr[dicPos], sym_L + inc dicPos + + CheckLimits +lit_end: + IF_BIT_0_NOUP probs_state_R, pbPos_R, IsMatch, lit_start + + ; jmp IsMatch_label + +; ---------- MATCHES ---------- +; MY_ALIGN_32 +IsMatch_label: + UPDATE_1 probs_state_R, pbPos_R, IsMatch + IF_BIT_1 probs_state_R, 0, IsRep, IsRep_label + + add probs, LenCoder * PMULT + add state, kNumStates * PMULT + +; ---------- LEN DECODE ---------- +len_decode: + mov len_temp, 8 - 1 - kMatchMinLen + IF_BIT_0_NOUP probs, 0, 0, len_mid_0 + UPDATE_1 probs, 0, 0 + add probs, (1 SHL (kLenNumLowBits + PSHIFT)) + mov len_temp, -1 - kMatchMinLen + IF_BIT_0_NOUP probs, 0, 0, len_mid_0 + UPDATE_1 probs, 0, 0 + add probs, LenHigh * PMULT - (1 SHL (kLenNumLowBits + PSHIFT)) + mov sym, 1 + PLOAD x1, probs + 1 * PMULT + +MY_ALIGN_32 +len8_loop: + BIT_1 x1, x2 + mov x1, x2 + cmp sym, 64 + jb len8_loop + + mov len_temp, (kLenNumHighSymbols - kLenNumLowSymbols * 2) - 1 - kMatchMinLen + jmp short len_mid_2 ; we use short here for MASM that doesn't optimize that code as another assembler programs + +MY_ALIGN_32 +len_mid_0: + UPDATE_0 probs, 0, 0 + add probs, pbPos_R + BIT_0 x2, x1 +len_mid_2: + BIT_1 x1, x2 + BIT_2 x2, len_temp + mov probs, LOC probs_Spec + cmp state, kNumStates * PMULT + jb copy_match + + +; ---------- DECODE DISTANCE ---------- + ; probs + PosSlot + ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << kNumPosSlotBits); + + mov t0, 3 + kMatchMinLen + cmp sym, 3 + kMatchMinLen + cmovb t0, sym + add probs, PosSlot * PMULT - (kMatchMinLen SHL (kNumPosSlotBits + PSHIFT)) + shl t0, (kNumPosSlotBits + PSHIFT) + add probs, t0_R + + ; sym = Len + ; mov LOC remainLen, sym + mov len_temp, sym + + ifdef _LZMA_SIZE_OPT + + PLOAD x1, probs + 1 * PMULT + mov sym, 1 +MY_ALIGN_16 +slot_loop: + BIT_1 x1, x2 + mov x1, x2 + cmp sym, 32 + jb slot_loop + + else + + BIT_0 x1, x2 + BIT_1 x2, x1 + BIT_1 x1, x2 + BIT_1 x2, x1 + BIT_1 x1, x2 + + endif + + mov x1, sym + BIT_2 x2, 64-1 + + and sym, 3 + mov probs, LOC probs_Spec + cmp x1, 32 + kEndPosModelIndex / 2 + jb short_dist + + ; unsigned numDirectBits = (unsigned)(((distance >> 1) - 1)); + sub x1, (32 + 1 + kNumAlignBits) + ; distance = (2 | (distance & 1)); + or sym, 2 + PLOAD x2, probs + 1 * PMULT + shl sym, kNumAlignBits + 1 + lea sym2_R, [probs + 2 * PMULT] + + jmp direct_norm + ; lea t1, [sym_R + (1 SHL kNumAlignBits)] + ; cmp range, kTopValue + ; jb direct_norm + +; ---------- DIRECT DISTANCE ---------- +MY_ALIGN_32 +direct_loop: + shr range, 1 + mov t0, cod + sub cod, range + cmovs cod, t0 + cmovns sym, t1 + + comment ~ + sub cod, range + mov x2, cod + sar x2, 31 + lea sym, dword ptr [r2 + sym_R * 2 + 1] + and x2, range + add cod, x2 + ~ + dec x1 + je direct_end + + add sym, sym +direct_norm: + lea t1, [sym_R + (1 SHL kNumAlignBits)] + cmp range, kTopValue + jae near ptr direct_loop + ; we align for 32 here with "near ptr" command above + NORM_2 + jmp direct_loop + +MY_ALIGN_32 +direct_end: + ; prob = + kAlign; + ; distance <<= kNumAlignBits; + REV_0 x2, x1 + REV_1 x1, x2, 2 + REV_1 x2, x1, 4 + REV_2 x1, 8 + +decode_dist_end: + + ; if (distance >= (checkDicSize == 0 ? processedPos: checkDicSize)) + + mov t1, LOC rep0 + mov x1, LOC rep1 + mov x2, LOC rep2 + + mov t0, LOC checkDicSize + test t0, t0 + cmove t0, processedPos + cmp sym, t0 + jae end_of_payload + ; jmp end_of_payload ; for debug + + ; rep3 = rep2; + ; rep2 = rep1; + ; rep1 = rep0; + ; rep0 = distance + 1; + + inc sym + mov LOC rep0, sym + ; mov sym, LOC remainLen + mov sym, len_temp + mov LOC rep1, t1 + mov LOC rep2, x1 + mov LOC rep3, x2 + + ; state = (state < kNumStates + kNumLitStates) ? kNumLitStates : kNumLitStates + 3; + cmp state, (kNumStates + kNumLitStates) * PMULT + mov state, kNumLitStates * PMULT + mov t0, (kNumLitStates + 3) * PMULT + cmovae state, t0 + + +; ---------- COPY MATCH ---------- +copy_match: + + ; len += kMatchMinLen; + ; add sym, kMatchMinLen + + ; if ((rem = limit - dicPos) == 0) + ; { + ; p->dicPos = dicPos; + ; return SZ_ERROR_DATA; + ; } + mov cnt_R, LOC limit + sub cnt_R, dicPos + jz fin_dicPos_LIMIT + + ; curLen = ((rem < len) ? (unsigned)rem : len); + cmp cnt_R, sym_R + ; cmovae cnt_R, sym_R ; 64-bit + cmovae cnt, sym ; 32-bit + + mov dic, LOC dic_Spec + mov x1, LOC rep0 + + mov t0_R, dicPos + add dicPos, cnt_R + ; processedPos += curLen; + add processedPos, cnt + ; len -= curLen; + sub sym, cnt + mov LOC remainLen, sym + + sub t0_R, dic + + ; pos = dicPos - rep0 + (dicPos < rep0 ? dicBufSize : 0); + sub t0_R, r1 + jae @f + + mov r1, LOC dicBufSize + add t0_R, r1 + sub r1, t0_R + cmp cnt_R, r1 + ja copy_match_cross +@@: + ; if (curLen <= dicBufSize - pos) + +; ---------- COPY MATCH FAST ---------- + ; Byte *dest = dic + dicPos; + ; mov r1, dic + ; ptrdiff_t src = (ptrdiff_t)pos - (ptrdiff_t)dicPos; + ; sub t0_R, dicPos + ; dicPos += curLen; + + ; const Byte *lim = dest + curLen; + add t0_R, dic + movzx sym, byte ptr[t0_R] + add t0_R, cnt_R + neg cnt_R + ; lea r1, [dicPos - 1] +copy_common: + dec dicPos + ; cmp LOC rep0, 1 + ; je rep0Label + + ; t0_R - src_lim + ; r1 - dest_lim - 1 + ; cnt_R - (-cnt) + + IsMatchBranch_Pre + inc cnt_R + jz copy_end +MY_ALIGN_16 +@@: + mov byte ptr[cnt_R * 1 + dicPos], sym_L + movzx sym, byte ptr[cnt_R * 1 + t0_R] + inc cnt_R + jnz @b + +copy_end: +lz_end_match: + mov byte ptr[dicPos], sym_L + inc dicPos + + ; IsMatchBranch_Pre + CheckLimits +lz_end: + IF_BIT_1_NOUP probs_state_R, pbPos_R, IsMatch, IsMatch_label + + + +; ---------- LITERAL MATCHED ---------- + + LIT_PROBS LOC lpMask + + ; matchByte = dic[dicPos - rep0 + (dicPos < rep0 ? dicBufSize : 0)]; + mov x1, LOC rep0 + ; mov dic, LOC dic_Spec + mov LOC dicPos_Spec, dicPos + + ; state -= (state < 10) ? 3 : 6; + lea t0, [state_R - 6 * PMULT] + sub state, 3 * PMULT + cmp state, 7 * PMULT + cmovae state, t0 + + sub dicPos, dic + sub dicPos, r1 + jae @f + add dicPos, LOC dicBufSize +@@: + comment ~ + xor t0, t0 + sub dicPos, r1 + cmovb t0_R, LOC dicBufSize + ~ + + movzx match, byte ptr[dic + dicPos * 1] + + ifdef _LZMA_SIZE_OPT + + mov offs, 256 * PMULT + shl match, (PSHIFT + 1) + mov bit, match + mov sym, 1 +MY_ALIGN_16 +litm_loop: + LITM + cmp sym, 256 + jb litm_loop + sub sym, 256 + + else + + LITM_0 + LITM + LITM + LITM + LITM + LITM + LITM + LITM_2 + + endif + + mov probs, LOC probs_Spec + IsMatchBranch_Pre + ; mov dic, LOC dic_Spec + mov dicPos, LOC dicPos_Spec + mov byte ptr[dicPos], sym_L + inc dicPos + + CheckLimits +lit_matched_end: + IF_BIT_1_NOUP probs_state_R, pbPos_R, IsMatch, IsMatch_label + ; IsMatchBranch + mov lpMask_reg, LOC lpMask + sub state, 3 * PMULT + jmp lit_start_2 + + + +; ---------- REP 0 LITERAL ---------- +MY_ALIGN_32 +IsRep0Short_label: + UPDATE_0 probs_state_R, pbPos_R, IsRep0Long + + ; dic[dicPos] = dic[dicPos - rep0 + (dicPos < rep0 ? dicBufSize : 0)]; + mov dic, LOC dic_Spec + mov t0_R, dicPos + mov probBranch, LOC rep0 + sub t0_R, dic + + sub probs, RepLenCoder * PMULT + + ; state = state < kNumLitStates ? 9 : 11; + or state, 1 * PMULT + + ; the caller doesn't allow (dicPos >= limit) case for REP_SHORT + ; so we don't need the following (dicPos == limit) check here: + ; cmp dicPos, LOC limit + ; jae fin_dicPos_LIMIT_REP_SHORT + + inc processedPos + + IsMatchBranch_Pre + +; xor sym, sym +; sub t0_R, probBranch_R +; cmovb sym_R, LOC dicBufSize +; add t0_R, sym_R + sub t0_R, probBranch_R + jae @f + add t0_R, LOC dicBufSize +@@: + movzx sym, byte ptr[dic + t0_R * 1] + jmp lz_end_match + + +MY_ALIGN_32 +IsRep_label: + UPDATE_1 probs_state_R, 0, IsRep + + ; The (checkDicSize == 0 && processedPos == 0) case was checked before in LzmaDec.c with kBadRepCode. + ; So we don't check it here. + + ; mov t0, processedPos + ; or t0, LOC checkDicSize + ; jz fin_ERROR_2 + + ; state = state < kNumLitStates ? 8 : 11; + cmp state, kNumLitStates * PMULT + mov state, 8 * PMULT + mov probBranch, 11 * PMULT + cmovae state, probBranch + + ; prob = probs + RepLenCoder; + add probs, RepLenCoder * PMULT + + IF_BIT_1 probs_state_R, 0, IsRepG0, IsRepG0_label + IF_BIT_0_NOUP probs_state_R, pbPos_R, IsRep0Long, IsRep0Short_label + UPDATE_1 probs_state_R, pbPos_R, IsRep0Long + jmp len_decode + +MY_ALIGN_32 +IsRepG0_label: + UPDATE_1 probs_state_R, 0, IsRepG0 + mov dist2, LOC rep0 + mov dist, LOC rep1 + mov LOC rep1, dist2 + + IF_BIT_1 probs_state_R, 0, IsRepG1, IsRepG1_label + mov LOC rep0, dist + jmp len_decode + +; MY_ALIGN_32 +IsRepG1_label: + UPDATE_1 probs_state_R, 0, IsRepG1 + mov dist2, LOC rep2 + mov LOC rep2, dist + + IF_BIT_1 probs_state_R, 0, IsRepG2, IsRepG2_label + mov LOC rep0, dist2 + jmp len_decode + +; MY_ALIGN_32 +IsRepG2_label: + UPDATE_1 probs_state_R, 0, IsRepG2 + mov dist, LOC rep3 + mov LOC rep3, dist2 + mov LOC rep0, dist + jmp len_decode + + + +; ---------- SPEC SHORT DISTANCE ---------- + +MY_ALIGN_32 +short_dist: + sub x1, 32 + 1 + jbe decode_dist_end + or sym, 2 + shl sym, x1_L + lea sym_R, [probs + sym_R * PMULT + SpecPos * PMULT + 1 * PMULT] + mov sym2, PMULT ; step +MY_ALIGN_32 +spec_loop: + REV_1_VAR x2 + dec x1 + jnz spec_loop + + mov probs, LOC probs_Spec + sub sym, sym2 + sub sym, SpecPos * PMULT + sub sym_R, probs + shr sym, PSHIFT + + jmp decode_dist_end + + +; ---------- COPY MATCH CROSS ---------- +copy_match_cross: + ; t0_R - src pos + ; r1 - len to dicBufSize + ; cnt_R - total copy len + + mov t1_R, t0_R ; srcPos + mov t0_R, dic + mov r1, LOC dicBufSize ; + neg cnt_R +@@: + movzx sym, byte ptr[t1_R * 1 + t0_R] + inc t1_R + mov byte ptr[cnt_R * 1 + dicPos], sym_L + inc cnt_R + cmp t1_R, r1 + jne @b + + movzx sym, byte ptr[t0_R] + sub t0_R, cnt_R + jmp copy_common + + + + +; fin_dicPos_LIMIT_REP_SHORT: + ; mov sym, 1 + +fin_dicPos_LIMIT: + mov LOC remainLen, sym + jmp fin_OK + ; For more strict mode we can stop decoding with error + ; mov sym, 1 + ; jmp fin + + +fin_ERROR_MATCH_DIST: + + ; rep3 = rep2; + ; rep2 = rep1; + ; rep1 = rep0; + ; rep0 = distance + 1; + + add len_temp, kMatchSpecLen_Error_Data + mov LOC remainLen, len_temp + + mov LOC rep0, sym + mov LOC rep1, t1 + mov LOC rep2, x1 + mov LOC rep3, x2 + + ; state = (state < kNumStates + kNumLitStates) ? kNumLitStates : kNumLitStates + 3; + cmp state, (kNumStates + kNumLitStates) * PMULT + mov state, kNumLitStates * PMULT + mov t0, (kNumLitStates + 3) * PMULT + cmovae state, t0 + + ; jmp fin_OK + mov sym, 1 + jmp fin + +end_of_payload: + inc sym + jnz fin_ERROR_MATCH_DIST + + mov LOC remainLen, kMatchSpecLenStart + sub state, kNumStates * PMULT + +fin_OK: + xor sym, sym + +fin: + NORM + + mov r1, LOC lzmaPtr + + sub dicPos, LOC dic_Spec + mov GLOB dicPos_Spec, dicPos + mov GLOB buf_Spec, buf + mov GLOB range_Spec, range + mov GLOB code_Spec, cod + shr state, PSHIFT + mov GLOB state_Spec, state + mov GLOB processedPos_Spec, processedPos + + RESTORE_VAR(remainLen) + RESTORE_VAR(rep0) + RESTORE_VAR(rep1) + RESTORE_VAR(rep2) + RESTORE_VAR(rep3) + + mov x0, sym + + mov RSP, LOC Old_RSP + +MY_POP_PRESERVED_ABI_REGS +MY_ENDP + +ifdef Z7_LZMA_DEC_OPT_ASM_USE_SEGMENT +_TEXT$LZMADECOPT ENDS +endif + +end diff --git a/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/CMakeLists.txt b/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/CMakeLists.txt new file mode 100644 index 000000000..8a64210ee --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/CMakeLists.txt @@ -0,0 +1,29 @@ +add_library(chdr-lzma STATIC + include/LzmaDec.h + src/LzmaDec.c +) + +set_target_properties(chdr-lzma PROPERTIES POSITION_INDEPENDENT_CODE ON) + +option(WITH_LZMA_ASM "Use lzma asm" ON) +if(WITH_LZMA_ASM) + if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + include(CheckSymbolExists) + check_symbol_exists("__aarch64__" "" CPU_ARM64) + if(CPU_ARM64) + enable_language(ASM) + set_source_files_properties(src/LzmaDec.c PROPERTIES COMPILE_DEFINITIONS Z7_LZMA_DEC_OPT) + target_sources(chdr-lzma PRIVATE Asm/arm64/LzmaDecOpt.S) + set_source_files_properties(Asm/arm64/LzmaDecOpt.S PROPERTIES LANGUAGE ASM) + endif() + elseif(WIN32) + include(CheckSymbolExists) + check_symbol_exists("_M_AMD64" "" CPU_X64) + if(CPU_X64) + enable_language(ASM_MASM) + set_source_files_properties(src/LzmaDec.c PROPERTIES COMPILE_DEFINITIONS Z7_LZMA_DEC_OPT) + target_sources(chdr-lzma PRIVATE Asm/x86/LzmaDecOpt.asm) + set_source_files_properties(Asm/x86/LzmaDecOpt.asm PROPERTIES LANGUAGE ASM_MASM) + endif() + endif() +endif() diff --git a/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/LICENSE b/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/LICENSE new file mode 100644 index 000000000..5f5705169 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/LICENSE @@ -0,0 +1,3 @@ +LZMA SDK is placed in the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or distribute the original LZMA SDK code, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. \ No newline at end of file diff --git a/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/include/LzmaDec.h b/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/include/LzmaDec.h new file mode 100644 index 000000000..0aeba2d5f --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/include/LzmaDec.h @@ -0,0 +1,13 @@ +/* Namespace some symbols to avoid linker errors in static libretro builds. */ +#define LzmaDec_InitDicAndState CHDR_LzmaDec_InitDicAndState +#define LzmaDec_Init CHDR_LzmaDec_Init +#define LzmaDec_DecodeToDic CHDR_LzmaDec_DecodeToDic +#define LzmaDec_DecodeToBuf CHDR_LzmaDec_DecodeToBuf +#define LzmaDec_FreeProbs CHDR_LzmaDec_FreeProbs +#define LzmaDec_Free CHDR_LzmaDec_Free +#define LzmaProps_Decode CHDR_LzmaProps_Decode +#define LzmaDec_AllocateProbs CHDR_LzmaDec_AllocateProbs +#define LzmaDec_Allocate CHDR_LzmaDec_Allocate +#define LzmaDecode CHDR_LzmaDecode + +#include "real/LzmaDec.h" diff --git a/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/include/real/7zTypes.h b/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/include/real/7zTypes.h new file mode 100644 index 000000000..5d3c74834 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/include/real/7zTypes.h @@ -0,0 +1,597 @@ +/* 7zTypes.h -- Basic types +2024-01-24 : Igor Pavlov : Public domain */ + +#ifndef ZIP7_7Z_TYPES_H +#define ZIP7_7Z_TYPES_H + +#ifdef _WIN32 +/* #include */ +#else +#include +#endif + +#include + +#ifndef EXTERN_C_BEGIN +#ifdef __cplusplus +#define EXTERN_C_BEGIN extern "C" { +#define EXTERN_C_END } +#else +#define EXTERN_C_BEGIN +#define EXTERN_C_END +#endif +#endif + +EXTERN_C_BEGIN + +#define SZ_OK 0 + +#define SZ_ERROR_DATA 1 +#define SZ_ERROR_MEM 2 +#define SZ_ERROR_CRC 3 +#define SZ_ERROR_UNSUPPORTED 4 +#define SZ_ERROR_PARAM 5 +#define SZ_ERROR_INPUT_EOF 6 +#define SZ_ERROR_OUTPUT_EOF 7 +#define SZ_ERROR_READ 8 +#define SZ_ERROR_WRITE 9 +#define SZ_ERROR_PROGRESS 10 +#define SZ_ERROR_FAIL 11 +#define SZ_ERROR_THREAD 12 + +#define SZ_ERROR_ARCHIVE 16 +#define SZ_ERROR_NO_ARCHIVE 17 + +typedef int SRes; + + +#ifdef _MSC_VER + #if _MSC_VER > 1200 + #define MY_ALIGN(n) __declspec(align(n)) + #else + #define MY_ALIGN(n) + #endif +#else + /* + // C11/C++11: + #include + #define MY_ALIGN(n) alignas(n) + */ + #define MY_ALIGN(n) __attribute__ ((aligned(n))) +#endif + + +#ifdef _WIN32 + +/* typedef DWORD WRes; */ +typedef unsigned WRes; +#define MY_SRes_HRESULT_FROM_WRes(x) HRESULT_FROM_WIN32(x) + +// #define MY_HRES_ERROR_INTERNAL_ERROR MY_SRes_HRESULT_FROM_WRes(ERROR_INTERNAL_ERROR) + +#else // _WIN32 + +// #define ENV_HAVE_LSTAT +typedef int WRes; + +// (FACILITY_ERRNO = 0x800) is 7zip's FACILITY constant to represent (errno) errors in HRESULT +#define MY_FACILITY_ERRNO 0x800 +#define MY_FACILITY_WIN32 7 +#define MY_FACILITY_WRes MY_FACILITY_ERRNO + +#define MY_HRESULT_FROM_errno_CONST_ERROR(x) ((HRESULT)( \ + ( (HRESULT)(x) & 0x0000FFFF) \ + | (MY_FACILITY_WRes << 16) \ + | (HRESULT)0x80000000 )) + +#define MY_SRes_HRESULT_FROM_WRes(x) \ + ((HRESULT)(x) <= 0 ? ((HRESULT)(x)) : MY_HRESULT_FROM_errno_CONST_ERROR(x)) + +// we call macro HRESULT_FROM_WIN32 for system errors (WRes) that are (errno) +#define HRESULT_FROM_WIN32(x) MY_SRes_HRESULT_FROM_WRes(x) + +/* +#define ERROR_FILE_NOT_FOUND 2L +#define ERROR_ACCESS_DENIED 5L +#define ERROR_NO_MORE_FILES 18L +#define ERROR_LOCK_VIOLATION 33L +#define ERROR_FILE_EXISTS 80L +#define ERROR_DISK_FULL 112L +#define ERROR_NEGATIVE_SEEK 131L +#define ERROR_ALREADY_EXISTS 183L +#define ERROR_DIRECTORY 267L +#define ERROR_TOO_MANY_POSTS 298L + +#define ERROR_INTERNAL_ERROR 1359L +#define ERROR_INVALID_REPARSE_DATA 4392L +#define ERROR_REPARSE_TAG_INVALID 4393L +#define ERROR_REPARSE_TAG_MISMATCH 4394L +*/ + +// we use errno equivalents for some WIN32 errors: + +#define ERROR_INVALID_PARAMETER EINVAL +#define ERROR_INVALID_FUNCTION EINVAL +#define ERROR_ALREADY_EXISTS EEXIST +#define ERROR_FILE_EXISTS EEXIST +#define ERROR_PATH_NOT_FOUND ENOENT +#define ERROR_FILE_NOT_FOUND ENOENT +#define ERROR_DISK_FULL ENOSPC +// #define ERROR_INVALID_HANDLE EBADF + +// we use FACILITY_WIN32 for errors that has no errno equivalent +// Too many posts were made to a semaphore. +#define ERROR_TOO_MANY_POSTS ((HRESULT)0x8007012AL) +#define ERROR_INVALID_REPARSE_DATA ((HRESULT)0x80071128L) +#define ERROR_REPARSE_TAG_INVALID ((HRESULT)0x80071129L) + +// if (MY_FACILITY_WRes != FACILITY_WIN32), +// we use FACILITY_WIN32 for COM errors: +#define E_OUTOFMEMORY ((HRESULT)0x8007000EL) +#define E_INVALIDARG ((HRESULT)0x80070057L) +#define MY_E_ERROR_NEGATIVE_SEEK ((HRESULT)0x80070083L) + +/* +// we can use FACILITY_ERRNO for some COM errors, that have errno equivalents: +#define E_OUTOFMEMORY MY_HRESULT_FROM_errno_CONST_ERROR(ENOMEM) +#define E_INVALIDARG MY_HRESULT_FROM_errno_CONST_ERROR(EINVAL) +#define MY_E_ERROR_NEGATIVE_SEEK MY_HRESULT_FROM_errno_CONST_ERROR(EINVAL) +*/ + +#define TEXT(quote) quote + +#define FILE_ATTRIBUTE_READONLY 0x0001 +#define FILE_ATTRIBUTE_HIDDEN 0x0002 +#define FILE_ATTRIBUTE_SYSTEM 0x0004 +#define FILE_ATTRIBUTE_DIRECTORY 0x0010 +#define FILE_ATTRIBUTE_ARCHIVE 0x0020 +#define FILE_ATTRIBUTE_DEVICE 0x0040 +#define FILE_ATTRIBUTE_NORMAL 0x0080 +#define FILE_ATTRIBUTE_TEMPORARY 0x0100 +#define FILE_ATTRIBUTE_SPARSE_FILE 0x0200 +#define FILE_ATTRIBUTE_REPARSE_POINT 0x0400 +#define FILE_ATTRIBUTE_COMPRESSED 0x0800 +#define FILE_ATTRIBUTE_OFFLINE 0x1000 +#define FILE_ATTRIBUTE_NOT_CONTENT_INDEXED 0x2000 +#define FILE_ATTRIBUTE_ENCRYPTED 0x4000 + +#define FILE_ATTRIBUTE_UNIX_EXTENSION 0x8000 /* trick for Unix */ + +#endif + + +#ifndef RINOK +#define RINOK(x) { const int _result_ = (x); if (_result_ != 0) return _result_; } +#endif + +#ifndef RINOK_WRes +#define RINOK_WRes(x) { const WRes _result_ = (x); if (_result_ != 0) return _result_; } +#endif + +typedef unsigned char Byte; +typedef short Int16; +typedef unsigned short UInt16; + +#ifdef Z7_DECL_Int32_AS_long +typedef long Int32; +typedef unsigned long UInt32; +#else +typedef int Int32; +typedef unsigned int UInt32; +#endif + + +#ifndef _WIN32 + +typedef int INT; +typedef Int32 INT32; +typedef unsigned int UINT; +typedef UInt32 UINT32; +typedef INT32 LONG; // LONG, ULONG and DWORD must be 32-bit for _WIN32 compatibility +typedef UINT32 ULONG; + +#undef DWORD +typedef UINT32 DWORD; + +#define VOID void + +#define HRESULT LONG + +typedef void *LPVOID; +// typedef void VOID; +// typedef ULONG_PTR DWORD_PTR, *PDWORD_PTR; +// gcc / clang on Unix : sizeof(long==sizeof(void*) in 32 or 64 bits) +typedef long INT_PTR; +typedef unsigned long UINT_PTR; +typedef long LONG_PTR; +typedef unsigned long DWORD_PTR; + +typedef size_t SIZE_T; + +#endif // _WIN32 + + +#define MY_HRES_ERROR_INTERNAL_ERROR ((HRESULT)0x8007054FL) + + +#ifdef Z7_DECL_Int64_AS_long + +typedef long Int64; +typedef unsigned long UInt64; + +#else + +#if (defined(_MSC_VER) || defined(__BORLANDC__)) && !defined(__clang__) +typedef __int64 Int64; +typedef unsigned __int64 UInt64; +#else +#if defined(__clang__) || defined(__GNUC__) +#include +typedef int64_t Int64; +typedef uint64_t UInt64; +#else +typedef long long int Int64; +typedef unsigned long long int UInt64; +// #define UINT64_CONST(n) n ## ULL +#endif +#endif + +#endif + +#define UINT64_CONST(n) n + + +#ifdef Z7_DECL_SizeT_AS_unsigned_int +typedef unsigned int SizeT; +#else +typedef size_t SizeT; +#endif + +/* +#if (defined(_MSC_VER) && _MSC_VER <= 1200) +typedef size_t MY_uintptr_t; +#else +#include +typedef uintptr_t MY_uintptr_t; +#endif +*/ + +typedef int BoolInt; +/* typedef BoolInt Bool; */ +#define True 1 +#define False 0 + + +#ifdef _WIN32 +#define Z7_STDCALL __stdcall +#else +#define Z7_STDCALL +#endif + +#ifdef _MSC_VER + +#if _MSC_VER >= 1300 +#define Z7_NO_INLINE __declspec(noinline) +#else +#define Z7_NO_INLINE +#endif + +#define Z7_FORCE_INLINE __forceinline + +#define Z7_CDECL __cdecl +#define Z7_FASTCALL __fastcall + +#else // _MSC_VER + +#if (defined(__GNUC__) && (__GNUC__ >= 4)) \ + || (defined(__clang__) && (__clang_major__ >= 4)) \ + || defined(__INTEL_COMPILER) \ + || defined(__xlC__) +#define Z7_NO_INLINE __attribute__((noinline)) +#define Z7_FORCE_INLINE __attribute__((always_inline)) inline +#else +#define Z7_NO_INLINE +#define Z7_FORCE_INLINE +#endif + +#define Z7_CDECL + +#if defined(_M_IX86) \ + || defined(__i386__) +// #define Z7_FASTCALL __attribute__((fastcall)) +// #define Z7_FASTCALL __attribute__((cdecl)) +#define Z7_FASTCALL +#elif defined(MY_CPU_AMD64) +// #define Z7_FASTCALL __attribute__((ms_abi)) +#define Z7_FASTCALL +#else +#define Z7_FASTCALL +#endif + +#endif // _MSC_VER + + +/* The following interfaces use first parameter as pointer to structure */ + +// #define Z7_C_IFACE_CONST_QUAL +#define Z7_C_IFACE_CONST_QUAL const + +#define Z7_C_IFACE_DECL(a) \ + struct a ## _; \ + typedef Z7_C_IFACE_CONST_QUAL struct a ## _ * a ## Ptr; \ + typedef struct a ## _ a; \ + struct a ## _ + + +Z7_C_IFACE_DECL (IByteIn) +{ + Byte (*Read)(IByteInPtr p); /* reads one byte, returns 0 in case of EOF or error */ +}; +#define IByteIn_Read(p) (p)->Read(p) + + +Z7_C_IFACE_DECL (IByteOut) +{ + void (*Write)(IByteOutPtr p, Byte b); +}; +#define IByteOut_Write(p, b) (p)->Write(p, b) + + +Z7_C_IFACE_DECL (ISeqInStream) +{ + SRes (*Read)(ISeqInStreamPtr p, void *buf, size_t *size); + /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream. + (output(*size) < input(*size)) is allowed */ +}; +#define ISeqInStream_Read(p, buf, size) (p)->Read(p, buf, size) + +/* try to read as much as avail in stream and limited by (*processedSize) */ +SRes SeqInStream_ReadMax(ISeqInStreamPtr stream, void *buf, size_t *processedSize); +/* it can return SZ_ERROR_INPUT_EOF */ +// SRes SeqInStream_Read(ISeqInStreamPtr stream, void *buf, size_t size); +// SRes SeqInStream_Read2(ISeqInStreamPtr stream, void *buf, size_t size, SRes errorType); +SRes SeqInStream_ReadByte(ISeqInStreamPtr stream, Byte *buf); + + +Z7_C_IFACE_DECL (ISeqOutStream) +{ + size_t (*Write)(ISeqOutStreamPtr p, const void *buf, size_t size); + /* Returns: result - the number of actually written bytes. + (result < size) means error */ +}; +#define ISeqOutStream_Write(p, buf, size) (p)->Write(p, buf, size) + +typedef enum +{ + SZ_SEEK_SET = 0, + SZ_SEEK_CUR = 1, + SZ_SEEK_END = 2 +} ESzSeek; + + +Z7_C_IFACE_DECL (ISeekInStream) +{ + SRes (*Read)(ISeekInStreamPtr p, void *buf, size_t *size); /* same as ISeqInStream::Read */ + SRes (*Seek)(ISeekInStreamPtr p, Int64 *pos, ESzSeek origin); +}; +#define ISeekInStream_Read(p, buf, size) (p)->Read(p, buf, size) +#define ISeekInStream_Seek(p, pos, origin) (p)->Seek(p, pos, origin) + + +Z7_C_IFACE_DECL (ILookInStream) +{ + SRes (*Look)(ILookInStreamPtr p, const void **buf, size_t *size); + /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream. + (output(*size) > input(*size)) is not allowed + (output(*size) < input(*size)) is allowed */ + SRes (*Skip)(ILookInStreamPtr p, size_t offset); + /* offset must be <= output(*size) of Look */ + SRes (*Read)(ILookInStreamPtr p, void *buf, size_t *size); + /* reads directly (without buffer). It's same as ISeqInStream::Read */ + SRes (*Seek)(ILookInStreamPtr p, Int64 *pos, ESzSeek origin); +}; + +#define ILookInStream_Look(p, buf, size) (p)->Look(p, buf, size) +#define ILookInStream_Skip(p, offset) (p)->Skip(p, offset) +#define ILookInStream_Read(p, buf, size) (p)->Read(p, buf, size) +#define ILookInStream_Seek(p, pos, origin) (p)->Seek(p, pos, origin) + + +SRes LookInStream_LookRead(ILookInStreamPtr stream, void *buf, size_t *size); +SRes LookInStream_SeekTo(ILookInStreamPtr stream, UInt64 offset); + +/* reads via ILookInStream::Read */ +SRes LookInStream_Read2(ILookInStreamPtr stream, void *buf, size_t size, SRes errorType); +SRes LookInStream_Read(ILookInStreamPtr stream, void *buf, size_t size); + + +typedef struct +{ + ILookInStream vt; + ISeekInStreamPtr realStream; + + size_t pos; + size_t size; /* it's data size */ + + /* the following variables must be set outside */ + Byte *buf; + size_t bufSize; +} CLookToRead2; + +void LookToRead2_CreateVTable(CLookToRead2 *p, int lookahead); + +#define LookToRead2_INIT(p) { (p)->pos = (p)->size = 0; } + + +typedef struct +{ + ISeqInStream vt; + ILookInStreamPtr realStream; +} CSecToLook; + +void SecToLook_CreateVTable(CSecToLook *p); + + + +typedef struct +{ + ISeqInStream vt; + ILookInStreamPtr realStream; +} CSecToRead; + +void SecToRead_CreateVTable(CSecToRead *p); + + +Z7_C_IFACE_DECL (ICompressProgress) +{ + SRes (*Progress)(ICompressProgressPtr p, UInt64 inSize, UInt64 outSize); + /* Returns: result. (result != SZ_OK) means break. + Value (UInt64)(Int64)-1 for size means unknown value. */ +}; + +#define ICompressProgress_Progress(p, inSize, outSize) (p)->Progress(p, inSize, outSize) + + + +typedef struct ISzAlloc ISzAlloc; +typedef const ISzAlloc * ISzAllocPtr; + +struct ISzAlloc +{ + void *(*Alloc)(ISzAllocPtr p, size_t size); + void (*Free)(ISzAllocPtr p, void *address); /* address can be 0 */ +}; + +#define ISzAlloc_Alloc(p, size) (p)->Alloc(p, size) +#define ISzAlloc_Free(p, a) (p)->Free(p, a) + +/* deprecated */ +#define IAlloc_Alloc(p, size) ISzAlloc_Alloc(p, size) +#define IAlloc_Free(p, a) ISzAlloc_Free(p, a) + + + + + +#ifndef MY_offsetof + #ifdef offsetof + #define MY_offsetof(type, m) offsetof(type, m) + /* + #define MY_offsetof(type, m) FIELD_OFFSET(type, m) + */ + #else + #define MY_offsetof(type, m) ((size_t)&(((type *)0)->m)) + #endif +#endif + + + +#ifndef Z7_container_of + +/* +#define Z7_container_of(ptr, type, m) container_of(ptr, type, m) +#define Z7_container_of(ptr, type, m) CONTAINING_RECORD(ptr, type, m) +#define Z7_container_of(ptr, type, m) ((type *)((char *)(ptr) - offsetof(type, m))) +#define Z7_container_of(ptr, type, m) (&((type *)0)->m == (ptr), ((type *)(((char *)(ptr)) - MY_offsetof(type, m)))) +*/ + +/* + GCC shows warning: "perhaps the 'offsetof' macro was used incorrectly" + GCC 3.4.4 : classes with constructor + GCC 4.8.1 : classes with non-public variable members" +*/ + +#define Z7_container_of(ptr, type, m) \ + ((type *)(void *)((char *)(void *) \ + (1 ? (ptr) : &((type *)NULL)->m) - MY_offsetof(type, m))) + +#define Z7_container_of_CONST(ptr, type, m) \ + ((const type *)(const void *)((const char *)(const void *) \ + (1 ? (ptr) : &((type *)NULL)->m) - MY_offsetof(type, m))) + +/* +#define Z7_container_of_NON_CONST_FROM_CONST(ptr, type, m) \ + ((type *)(void *)(const void *)((const char *)(const void *) \ + (1 ? (ptr) : &((type *)NULL)->m) - MY_offsetof(type, m))) +*/ + +#endif + +#define Z7_CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) ((type *)(void *)(ptr)) + +// #define Z7_CONTAINER_FROM_VTBL(ptr, type, m) Z7_CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) +#define Z7_CONTAINER_FROM_VTBL(ptr, type, m) Z7_container_of(ptr, type, m) +// #define Z7_CONTAINER_FROM_VTBL(ptr, type, m) Z7_container_of_NON_CONST_FROM_CONST(ptr, type, m) + +#define Z7_CONTAINER_FROM_VTBL_CONST(ptr, type, m) Z7_container_of_CONST(ptr, type, m) + +#define Z7_CONTAINER_FROM_VTBL_CLS(ptr, type, m) Z7_CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) +/* +#define Z7_CONTAINER_FROM_VTBL_CLS(ptr, type, m) Z7_CONTAINER_FROM_VTBL(ptr, type, m) +*/ +#if defined (__clang__) || defined(__GNUC__) +#define Z7_DIAGNOSTIC_IGNORE_BEGIN_CAST_QUAL \ + _Pragma("GCC diagnostic push") \ + _Pragma("GCC diagnostic ignored \"-Wcast-qual\"") +#define Z7_DIAGNOSTIC_IGNORE_END_CAST_QUAL \ + _Pragma("GCC diagnostic pop") +#else +#define Z7_DIAGNOSTIC_IGNORE_BEGIN_CAST_QUAL +#define Z7_DIAGNOSTIC_IGNORE_END_CAST_QUAL +#endif + +#define Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR(ptr, type, m, p) \ + Z7_DIAGNOSTIC_IGNORE_BEGIN_CAST_QUAL \ + type *p = Z7_CONTAINER_FROM_VTBL(ptr, type, m); \ + Z7_DIAGNOSTIC_IGNORE_END_CAST_QUAL + +#define Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(type) \ + Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR(pp, type, vt, p) + + +// #define ZIP7_DECLARE_HANDLE(name) typedef void *name; +#define Z7_DECLARE_HANDLE(name) struct name##_dummy{int unused;}; typedef struct name##_dummy *name; + + +#define Z7_memset_0_ARRAY(a) memset((a), 0, sizeof(a)) + +#ifndef Z7_ARRAY_SIZE +#define Z7_ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +#endif + + +#ifdef _WIN32 + +#define CHAR_PATH_SEPARATOR '\\' +#define WCHAR_PATH_SEPARATOR L'\\' +#define STRING_PATH_SEPARATOR "\\" +#define WSTRING_PATH_SEPARATOR L"\\" + +#else + +#define CHAR_PATH_SEPARATOR '/' +#define WCHAR_PATH_SEPARATOR L'/' +#define STRING_PATH_SEPARATOR "/" +#define WSTRING_PATH_SEPARATOR L"/" + +#endif + +#define k_PropVar_TimePrec_0 0 +#define k_PropVar_TimePrec_Unix 1 +#define k_PropVar_TimePrec_DOS 2 +#define k_PropVar_TimePrec_HighPrec 3 +#define k_PropVar_TimePrec_Base 16 +#define k_PropVar_TimePrec_100ns (k_PropVar_TimePrec_Base + 7) +#define k_PropVar_TimePrec_1ns (k_PropVar_TimePrec_Base + 9) + +EXTERN_C_END + +#endif + +/* +#ifndef Z7_ST +#ifdef _7ZIP_ST +#define Z7_ST +#endif +#endif +*/ diff --git a/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/include/real/LzmaDec.h b/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/include/real/LzmaDec.h new file mode 100644 index 000000000..6432f6085 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/include/real/LzmaDec.h @@ -0,0 +1,237 @@ +/* LzmaDec.h -- LZMA Decoder +2023-04-02 : Igor Pavlov : Public domain */ + +#ifndef ZIP7_INC_LZMA_DEC_H +#define ZIP7_INC_LZMA_DEC_H + +#include "7zTypes.h" + +EXTERN_C_BEGIN + +/* #define Z7_LZMA_PROB32 */ +/* Z7_LZMA_PROB32 can increase the speed on some CPUs, + but memory usage for CLzmaDec::probs will be doubled in that case */ + +typedef +#ifdef Z7_LZMA_PROB32 + UInt32 +#else + UInt16 +#endif + CLzmaProb; + + +/* ---------- LZMA Properties ---------- */ + +#define LZMA_PROPS_SIZE 5 + +typedef struct +{ + Byte lc; + Byte lp; + Byte pb; + Byte _pad_; + UInt32 dicSize; +} CLzmaProps; + +/* LzmaProps_Decode - decodes properties +Returns: + SZ_OK + SZ_ERROR_UNSUPPORTED - Unsupported properties +*/ + +SRes LzmaProps_Decode(CLzmaProps *p, const Byte *data, unsigned size); + + +/* ---------- LZMA Decoder state ---------- */ + +/* LZMA_REQUIRED_INPUT_MAX = number of required input bytes for worst case. + Num bits = log2((2^11 / 31) ^ 22) + 26 < 134 + 26 = 160; */ + +#define LZMA_REQUIRED_INPUT_MAX 20 + +typedef struct +{ + /* Don't change this structure. ASM code can use it. */ + CLzmaProps prop; + CLzmaProb *probs; + CLzmaProb *probs_1664; + Byte *dic; + SizeT dicBufSize; + SizeT dicPos; + const Byte *buf; + UInt32 range; + UInt32 code; + UInt32 processedPos; + UInt32 checkDicSize; + UInt32 reps[4]; + UInt32 state; + UInt32 remainLen; + + UInt32 numProbs; + unsigned tempBufSize; + Byte tempBuf[LZMA_REQUIRED_INPUT_MAX]; +} CLzmaDec; + +#define LzmaDec_CONSTRUCT(p) { (p)->dic = NULL; (p)->probs = NULL; } +#define LzmaDec_Construct(p) LzmaDec_CONSTRUCT(p) + +void LzmaDec_Init(CLzmaDec *p); + +/* There are two types of LZMA streams: + - Stream with end mark. That end mark adds about 6 bytes to compressed size. + - Stream without end mark. You must know exact uncompressed size to decompress such stream. */ + +typedef enum +{ + LZMA_FINISH_ANY, /* finish at any point */ + LZMA_FINISH_END /* block must be finished at the end */ +} ELzmaFinishMode; + +/* ELzmaFinishMode has meaning only if the decoding reaches output limit !!! + + You must use LZMA_FINISH_END, when you know that current output buffer + covers last bytes of block. In other cases you must use LZMA_FINISH_ANY. + + If LZMA decoder sees end marker before reaching output limit, it returns SZ_OK, + and output value of destLen will be less than output buffer size limit. + You can check status result also. + + You can use multiple checks to test data integrity after full decompression: + 1) Check Result and "status" variable. + 2) Check that output(destLen) = uncompressedSize, if you know real uncompressedSize. + 3) Check that output(srcLen) = compressedSize, if you know real compressedSize. + You must use correct finish mode in that case. */ + +typedef enum +{ + LZMA_STATUS_NOT_SPECIFIED, /* use main error code instead */ + LZMA_STATUS_FINISHED_WITH_MARK, /* stream was finished with end mark. */ + LZMA_STATUS_NOT_FINISHED, /* stream was not finished */ + LZMA_STATUS_NEEDS_MORE_INPUT, /* you must provide more input bytes */ + LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK /* there is probability that stream was finished without end mark */ +} ELzmaStatus; + +/* ELzmaStatus is used only as output value for function call */ + + +/* ---------- Interfaces ---------- */ + +/* There are 3 levels of interfaces: + 1) Dictionary Interface + 2) Buffer Interface + 3) One Call Interface + You can select any of these interfaces, but don't mix functions from different + groups for same object. */ + + +/* There are two variants to allocate state for Dictionary Interface: + 1) LzmaDec_Allocate / LzmaDec_Free + 2) LzmaDec_AllocateProbs / LzmaDec_FreeProbs + You can use variant 2, if you set dictionary buffer manually. + For Buffer Interface you must always use variant 1. + +LzmaDec_Allocate* can return: + SZ_OK + SZ_ERROR_MEM - Memory allocation error + SZ_ERROR_UNSUPPORTED - Unsupported properties +*/ + +SRes LzmaDec_AllocateProbs(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAllocPtr alloc); +void LzmaDec_FreeProbs(CLzmaDec *p, ISzAllocPtr alloc); + +SRes LzmaDec_Allocate(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAllocPtr alloc); +void LzmaDec_Free(CLzmaDec *p, ISzAllocPtr alloc); + +/* ---------- Dictionary Interface ---------- */ + +/* You can use it, if you want to eliminate the overhead for data copying from + dictionary to some other external buffer. + You must work with CLzmaDec variables directly in this interface. + + STEPS: + LzmaDec_Construct() + LzmaDec_Allocate() + for (each new stream) + { + LzmaDec_Init() + while (it needs more decompression) + { + LzmaDec_DecodeToDic() + use data from CLzmaDec::dic and update CLzmaDec::dicPos + } + } + LzmaDec_Free() +*/ + +/* LzmaDec_DecodeToDic + + The decoding to internal dictionary buffer (CLzmaDec::dic). + You must manually update CLzmaDec::dicPos, if it reaches CLzmaDec::dicBufSize !!! + +finishMode: + It has meaning only if the decoding reaches output limit (dicLimit). + LZMA_FINISH_ANY - Decode just dicLimit bytes. + LZMA_FINISH_END - Stream must be finished after dicLimit. + +Returns: + SZ_OK + status: + LZMA_STATUS_FINISHED_WITH_MARK + LZMA_STATUS_NOT_FINISHED + LZMA_STATUS_NEEDS_MORE_INPUT + LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK + SZ_ERROR_DATA - Data error + SZ_ERROR_FAIL - Some unexpected error: internal error of code, memory corruption or hardware failure +*/ + +SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, + const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status); + + +/* ---------- Buffer Interface ---------- */ + +/* It's zlib-like interface. + See LzmaDec_DecodeToDic description for information about STEPS and return results, + but you must use LzmaDec_DecodeToBuf instead of LzmaDec_DecodeToDic and you don't need + to work with CLzmaDec variables manually. + +finishMode: + It has meaning only if the decoding reaches output limit (*destLen). + LZMA_FINISH_ANY - Decode just destLen bytes. + LZMA_FINISH_END - Stream must be finished after (*destLen). +*/ + +SRes LzmaDec_DecodeToBuf(CLzmaDec *p, Byte *dest, SizeT *destLen, + const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status); + + +/* ---------- One Call Interface ---------- */ + +/* LzmaDecode + +finishMode: + It has meaning only if the decoding reaches output limit (*destLen). + LZMA_FINISH_ANY - Decode just destLen bytes. + LZMA_FINISH_END - Stream must be finished after (*destLen). + +Returns: + SZ_OK + status: + LZMA_STATUS_FINISHED_WITH_MARK + LZMA_STATUS_NOT_FINISHED + LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK + SZ_ERROR_DATA - Data error + SZ_ERROR_MEM - Memory allocation error + SZ_ERROR_UNSUPPORTED - Unsupported properties + SZ_ERROR_INPUT_EOF - It needs more bytes in input buffer (src). + SZ_ERROR_FAIL - Some unexpected error: internal error of code, memory corruption or hardware failure +*/ + +SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, + const Byte *propData, unsigned propSize, ELzmaFinishMode finishMode, + ELzmaStatus *status, ISzAllocPtr alloc); + +EXTERN_C_END + +#endif diff --git a/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/src/LzmaDec.c b/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/src/LzmaDec.c new file mode 100644 index 000000000..4772470af --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/src/LzmaDec.c @@ -0,0 +1,2 @@ +#include "../include/LzmaDec.h" +#include "real/LzmaDec.c" diff --git a/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/src/real/LzmaDec.c b/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/src/real/LzmaDec.c new file mode 100644 index 000000000..7b70a7fd0 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/deps/lzma-25.01/src/real/LzmaDec.c @@ -0,0 +1,1361 @@ +/* LzmaDec.c -- LZMA Decoder +2023-04-07 : Igor Pavlov : Public domain */ + +#include + +/* #include "CpuArch.h" */ +#include "../../include/LzmaDec.h" + +// #define kNumTopBits 24 +#define kTopValue ((UInt32)1 << 24) + +#define kNumBitModelTotalBits 11 +#define kBitModelTotal (1 << kNumBitModelTotalBits) + +#define RC_INIT_SIZE 5 + +#ifndef Z7_LZMA_DEC_OPT + +#define kNumMoveBits 5 +#define NORMALIZE if (range < kTopValue) { range <<= 8; code = (code << 8) | (*buf++); } + +#define IF_BIT_0(p) ttt = *(p); NORMALIZE; bound = (range >> kNumBitModelTotalBits) * (UInt32)ttt; if (code < bound) +#define UPDATE_0(p) range = bound; *(p) = (CLzmaProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits)); +#define UPDATE_1(p) range -= bound; code -= bound; *(p) = (CLzmaProb)(ttt - (ttt >> kNumMoveBits)); +#define GET_BIT2(p, i, A0, A1) IF_BIT_0(p) \ + { UPDATE_0(p) i = (i + i); A0; } else \ + { UPDATE_1(p) i = (i + i) + 1; A1; } + +#define TREE_GET_BIT(probs, i) { GET_BIT2(probs + i, i, ;, ;); } + +#define REV_BIT(p, i, A0, A1) IF_BIT_0(p + i) \ + { UPDATE_0(p + i) A0; } else \ + { UPDATE_1(p + i) A1; } +#define REV_BIT_VAR( p, i, m) REV_BIT(p, i, i += m; m += m, m += m; i += m; ) +#define REV_BIT_CONST(p, i, m) REV_BIT(p, i, i += m; , i += m * 2; ) +#define REV_BIT_LAST( p, i, m) REV_BIT(p, i, i -= m , ; ) + +#define TREE_DECODE(probs, limit, i) \ + { i = 1; do { TREE_GET_BIT(probs, i); } while (i < limit); i -= limit; } + +/* #define Z7_LZMA_SIZE_OPT */ + +#ifdef Z7_LZMA_SIZE_OPT +#define TREE_6_DECODE(probs, i) TREE_DECODE(probs, (1 << 6), i) +#else +#define TREE_6_DECODE(probs, i) \ + { i = 1; \ + TREE_GET_BIT(probs, i) \ + TREE_GET_BIT(probs, i) \ + TREE_GET_BIT(probs, i) \ + TREE_GET_BIT(probs, i) \ + TREE_GET_BIT(probs, i) \ + TREE_GET_BIT(probs, i) \ + i -= 0x40; } +#endif + +#define NORMAL_LITER_DEC TREE_GET_BIT(prob, symbol) +#define MATCHED_LITER_DEC \ + matchByte += matchByte; \ + bit = offs; \ + offs &= matchByte; \ + probLit = prob + (offs + bit + symbol); \ + GET_BIT2(probLit, symbol, offs ^= bit; , ;) + +#endif // Z7_LZMA_DEC_OPT + + +#define NORMALIZE_CHECK if (range < kTopValue) { if (buf >= bufLimit) return DUMMY_INPUT_EOF; range <<= 8; code = (code << 8) | (*buf++); } + +#define IF_BIT_0_CHECK(p) ttt = *(p); NORMALIZE_CHECK bound = (range >> kNumBitModelTotalBits) * (UInt32)ttt; if (code < bound) +#define UPDATE_0_CHECK range = bound; +#define UPDATE_1_CHECK range -= bound; code -= bound; +#define GET_BIT2_CHECK(p, i, A0, A1) IF_BIT_0_CHECK(p) \ + { UPDATE_0_CHECK i = (i + i); A0; } else \ + { UPDATE_1_CHECK i = (i + i) + 1; A1; } +#define GET_BIT_CHECK(p, i) GET_BIT2_CHECK(p, i, ; , ;) +#define TREE_DECODE_CHECK(probs, limit, i) \ + { i = 1; do { GET_BIT_CHECK(probs + i, i) } while (i < limit); i -= limit; } + + +#define REV_BIT_CHECK(p, i, m) IF_BIT_0_CHECK(p + i) \ + { UPDATE_0_CHECK i += m; m += m; } else \ + { UPDATE_1_CHECK m += m; i += m; } + + +#define kNumPosBitsMax 4 +#define kNumPosStatesMax (1 << kNumPosBitsMax) + +#define kLenNumLowBits 3 +#define kLenNumLowSymbols (1 << kLenNumLowBits) +#define kLenNumHighBits 8 +#define kLenNumHighSymbols (1 << kLenNumHighBits) + +#define LenLow 0 +#define LenHigh (LenLow + 2 * (kNumPosStatesMax << kLenNumLowBits)) +#define kNumLenProbs (LenHigh + kLenNumHighSymbols) + +#define LenChoice LenLow +#define LenChoice2 (LenLow + (1 << kLenNumLowBits)) + +#define kNumStates 12 +#define kNumStates2 16 +#define kNumLitStates 7 + +#define kStartPosModelIndex 4 +#define kEndPosModelIndex 14 +#define kNumFullDistances (1 << (kEndPosModelIndex >> 1)) + +#define kNumPosSlotBits 6 +#define kNumLenToPosStates 4 + +#define kNumAlignBits 4 +#define kAlignTableSize (1 << kNumAlignBits) + +#define kMatchMinLen 2 +#define kMatchSpecLenStart (kMatchMinLen + kLenNumLowSymbols * 2 + kLenNumHighSymbols) + +#define kMatchSpecLen_Error_Data (1 << 9) +#define kMatchSpecLen_Error_Fail (kMatchSpecLen_Error_Data - 1) + +/* External ASM code needs same CLzmaProb array layout. So don't change it. */ + +/* (probs_1664) is faster and better for code size at some platforms */ +/* +#ifdef MY_CPU_X86_OR_AMD64 +*/ +#define kStartOffset 1664 +#define GET_PROBS p->probs_1664 +/* +#define GET_PROBS p->probs + kStartOffset +#else +#define kStartOffset 0 +#define GET_PROBS p->probs +#endif +*/ + +#define SpecPos (-kStartOffset) +#define IsRep0Long (SpecPos + kNumFullDistances) +#define RepLenCoder (IsRep0Long + (kNumStates2 << kNumPosBitsMax)) +#define LenCoder (RepLenCoder + kNumLenProbs) +#define IsMatch (LenCoder + kNumLenProbs) +#define Align (IsMatch + (kNumStates2 << kNumPosBitsMax)) +#define IsRep (Align + kAlignTableSize) +#define IsRepG0 (IsRep + kNumStates) +#define IsRepG1 (IsRepG0 + kNumStates) +#define IsRepG2 (IsRepG1 + kNumStates) +#define PosSlot (IsRepG2 + kNumStates) +#define Literal (PosSlot + (kNumLenToPosStates << kNumPosSlotBits)) +#define NUM_BASE_PROBS (Literal + kStartOffset) + +#if Align != 0 && kStartOffset != 0 + #error Stop_Compiling_Bad_LZMA_kAlign +#endif + +#if NUM_BASE_PROBS != 1984 + #error Stop_Compiling_Bad_LZMA_PROBS +#endif + + +#define LZMA_LIT_SIZE 0x300 + +#define LzmaProps_GetNumProbs(p) (NUM_BASE_PROBS + ((UInt32)LZMA_LIT_SIZE << ((p)->lc + (p)->lp))) + + +#define CALC_POS_STATE(processedPos, pbMask) (((processedPos) & (pbMask)) << 4) +#define COMBINED_PS_STATE (posState + state) +#define GET_LEN_STATE (posState) + +#define LZMA_DIC_MIN (1 << 12) + +/* +p->remainLen : shows status of LZMA decoder: + < kMatchSpecLenStart : the number of bytes to be copied with (p->rep0) offset + = kMatchSpecLenStart : the LZMA stream was finished with end mark + = kMatchSpecLenStart + 1 : need init range coder + = kMatchSpecLenStart + 2 : need init range coder and state + = kMatchSpecLen_Error_Fail : Internal Code Failure + = kMatchSpecLen_Error_Data + [0 ... 273] : LZMA Data Error +*/ + +/* ---------- LZMA_DECODE_REAL ---------- */ +/* +LzmaDec_DecodeReal_3() can be implemented in external ASM file. +3 - is the code compatibility version of that function for check at link time. +*/ + +#define LZMA_DECODE_REAL LzmaDec_DecodeReal_3 + +/* +LZMA_DECODE_REAL() +In: + RangeCoder is normalized + if (p->dicPos == limit) + { + LzmaDec_TryDummy() was called before to exclude LITERAL and MATCH-REP cases. + So first symbol can be only MATCH-NON-REP. And if that MATCH-NON-REP symbol + is not END_OF_PAYALOAD_MARKER, then the function doesn't write any byte to dictionary, + the function returns SZ_OK, and the caller can use (p->remainLen) and (p->reps[0]) later. + } + +Processing: + The first LZMA symbol will be decoded in any case. + All main checks for limits are at the end of main loop, + It decodes additional LZMA-symbols while (p->buf < bufLimit && dicPos < limit), + RangeCoder is still without last normalization when (p->buf < bufLimit) is being checked. + But if (p->buf < bufLimit), the caller provided at least (LZMA_REQUIRED_INPUT_MAX + 1) bytes for + next iteration before limit (bufLimit + LZMA_REQUIRED_INPUT_MAX), + that is enough for worst case LZMA symbol with one additional RangeCoder normalization for one bit. + So that function never reads bufLimit [LZMA_REQUIRED_INPUT_MAX] byte. + +Out: + RangeCoder is normalized + Result: + SZ_OK - OK + p->remainLen: + < kMatchSpecLenStart : the number of bytes to be copied with (p->reps[0]) offset + = kMatchSpecLenStart : the LZMA stream was finished with end mark + + SZ_ERROR_DATA - error, when the MATCH-Symbol refers out of dictionary + p->remainLen : undefined + p->reps[*] : undefined +*/ + + +#ifdef Z7_LZMA_DEC_OPT + +int Z7_FASTCALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit); + +#else + +static +int Z7_FASTCALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit) +{ + CLzmaProb *probs = GET_PROBS; + unsigned state = (unsigned)p->state; + UInt32 rep0 = p->reps[0], rep1 = p->reps[1], rep2 = p->reps[2], rep3 = p->reps[3]; + unsigned pbMask = ((unsigned)1 << (p->prop.pb)) - 1; + unsigned lc = p->prop.lc; + unsigned lpMask = ((unsigned)0x100 << p->prop.lp) - ((unsigned)0x100 >> lc); + + Byte *dic = p->dic; + SizeT dicBufSize = p->dicBufSize; + SizeT dicPos = p->dicPos; + + UInt32 processedPos = p->processedPos; + UInt32 checkDicSize = p->checkDicSize; + unsigned len = 0; + + const Byte *buf = p->buf; + UInt32 range = p->range; + UInt32 code = p->code; + + do + { + CLzmaProb *prob; + UInt32 bound; + unsigned ttt; + unsigned posState = CALC_POS_STATE(processedPos, pbMask); + + prob = probs + IsMatch + COMBINED_PS_STATE; + IF_BIT_0(prob) + { + unsigned symbol; + UPDATE_0(prob) + prob = probs + Literal; + if (processedPos != 0 || checkDicSize != 0) + prob += (UInt32)3 * ((((processedPos << 8) + dic[(dicPos == 0 ? dicBufSize : dicPos) - 1]) & lpMask) << lc); + processedPos++; + + if (state < kNumLitStates) + { + state -= (state < 4) ? state : 3; + symbol = 1; + #ifdef Z7_LZMA_SIZE_OPT + do { NORMAL_LITER_DEC } while (symbol < 0x100); + #else + NORMAL_LITER_DEC + NORMAL_LITER_DEC + NORMAL_LITER_DEC + NORMAL_LITER_DEC + NORMAL_LITER_DEC + NORMAL_LITER_DEC + NORMAL_LITER_DEC + NORMAL_LITER_DEC + #endif + } + else + { + unsigned matchByte = dic[dicPos - rep0 + (dicPos < rep0 ? dicBufSize : 0)]; + unsigned offs = 0x100; + state -= (state < 10) ? 3 : 6; + symbol = 1; + #ifdef Z7_LZMA_SIZE_OPT + do + { + unsigned bit; + CLzmaProb *probLit; + MATCHED_LITER_DEC + } + while (symbol < 0x100); + #else + { + unsigned bit; + CLzmaProb *probLit; + MATCHED_LITER_DEC + MATCHED_LITER_DEC + MATCHED_LITER_DEC + MATCHED_LITER_DEC + MATCHED_LITER_DEC + MATCHED_LITER_DEC + MATCHED_LITER_DEC + MATCHED_LITER_DEC + } + #endif + } + + dic[dicPos++] = (Byte)symbol; + continue; + } + + { + UPDATE_1(prob) + prob = probs + IsRep + state; + IF_BIT_0(prob) + { + UPDATE_0(prob) + state += kNumStates; + prob = probs + LenCoder; + } + else + { + UPDATE_1(prob) + prob = probs + IsRepG0 + state; + IF_BIT_0(prob) + { + UPDATE_0(prob) + prob = probs + IsRep0Long + COMBINED_PS_STATE; + IF_BIT_0(prob) + { + UPDATE_0(prob) + + // that case was checked before with kBadRepCode + // if (checkDicSize == 0 && processedPos == 0) { len = kMatchSpecLen_Error_Data + 1; break; } + // The caller doesn't allow (dicPos == limit) case here + // so we don't need the following check: + // if (dicPos == limit) { state = state < kNumLitStates ? 9 : 11; len = 1; break; } + + dic[dicPos] = dic[dicPos - rep0 + (dicPos < rep0 ? dicBufSize : 0)]; + dicPos++; + processedPos++; + state = state < kNumLitStates ? 9 : 11; + continue; + } + UPDATE_1(prob) + } + else + { + UInt32 distance; + UPDATE_1(prob) + prob = probs + IsRepG1 + state; + IF_BIT_0(prob) + { + UPDATE_0(prob) + distance = rep1; + } + else + { + UPDATE_1(prob) + prob = probs + IsRepG2 + state; + IF_BIT_0(prob) + { + UPDATE_0(prob) + distance = rep2; + } + else + { + UPDATE_1(prob) + distance = rep3; + rep3 = rep2; + } + rep2 = rep1; + } + rep1 = rep0; + rep0 = distance; + } + state = state < kNumLitStates ? 8 : 11; + prob = probs + RepLenCoder; + } + + #ifdef Z7_LZMA_SIZE_OPT + { + unsigned lim, offset; + CLzmaProb *probLen = prob + LenChoice; + IF_BIT_0(probLen) + { + UPDATE_0(probLen) + probLen = prob + LenLow + GET_LEN_STATE; + offset = 0; + lim = (1 << kLenNumLowBits); + } + else + { + UPDATE_1(probLen) + probLen = prob + LenChoice2; + IF_BIT_0(probLen) + { + UPDATE_0(probLen) + probLen = prob + LenLow + GET_LEN_STATE + (1 << kLenNumLowBits); + offset = kLenNumLowSymbols; + lim = (1 << kLenNumLowBits); + } + else + { + UPDATE_1(probLen) + probLen = prob + LenHigh; + offset = kLenNumLowSymbols * 2; + lim = (1 << kLenNumHighBits); + } + } + TREE_DECODE(probLen, lim, len) + len += offset; + } + #else + { + CLzmaProb *probLen = prob + LenChoice; + IF_BIT_0(probLen) + { + UPDATE_0(probLen) + probLen = prob + LenLow + GET_LEN_STATE; + len = 1; + TREE_GET_BIT(probLen, len) + TREE_GET_BIT(probLen, len) + TREE_GET_BIT(probLen, len) + len -= 8; + } + else + { + UPDATE_1(probLen) + probLen = prob + LenChoice2; + IF_BIT_0(probLen) + { + UPDATE_0(probLen) + probLen = prob + LenLow + GET_LEN_STATE + (1 << kLenNumLowBits); + len = 1; + TREE_GET_BIT(probLen, len) + TREE_GET_BIT(probLen, len) + TREE_GET_BIT(probLen, len) + } + else + { + UPDATE_1(probLen) + probLen = prob + LenHigh; + TREE_DECODE(probLen, (1 << kLenNumHighBits), len) + len += kLenNumLowSymbols * 2; + } + } + } + #endif + + if (state >= kNumStates) + { + UInt32 distance; + prob = probs + PosSlot + + ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << kNumPosSlotBits); + TREE_6_DECODE(prob, distance) + if (distance >= kStartPosModelIndex) + { + unsigned posSlot = (unsigned)distance; + unsigned numDirectBits = (unsigned)(((distance >> 1) - 1)); + distance = (2 | (distance & 1)); + if (posSlot < kEndPosModelIndex) + { + distance <<= numDirectBits; + prob = probs + SpecPos; + { + UInt32 m = 1; + distance++; + do + { + REV_BIT_VAR(prob, distance, m) + } + while (--numDirectBits); + distance -= m; + } + } + else + { + numDirectBits -= kNumAlignBits; + do + { + NORMALIZE + range >>= 1; + + { + UInt32 t; + code -= range; + t = (0 - ((UInt32)code >> 31)); /* (UInt32)((Int32)code >> 31) */ + distance = (distance << 1) + (t + 1); + code += range & t; + } + /* + distance <<= 1; + if (code >= range) + { + code -= range; + distance |= 1; + } + */ + } + while (--numDirectBits); + prob = probs + Align; + distance <<= kNumAlignBits; + { + unsigned i = 1; + REV_BIT_CONST(prob, i, 1) + REV_BIT_CONST(prob, i, 2) + REV_BIT_CONST(prob, i, 4) + REV_BIT_LAST (prob, i, 8) + distance |= i; + } + if (distance == (UInt32)0xFFFFFFFF) + { + len = kMatchSpecLenStart; + state -= kNumStates; + break; + } + } + } + + rep3 = rep2; + rep2 = rep1; + rep1 = rep0; + rep0 = distance + 1; + state = (state < kNumStates + kNumLitStates) ? kNumLitStates : kNumLitStates + 3; + if (distance >= (checkDicSize == 0 ? processedPos: checkDicSize)) + { + len += kMatchSpecLen_Error_Data + kMatchMinLen; + // len = kMatchSpecLen_Error_Data; + // len += kMatchMinLen; + break; + } + } + + len += kMatchMinLen; + + { + SizeT rem; + unsigned curLen; + SizeT pos; + + if ((rem = limit - dicPos) == 0) + { + /* + We stop decoding and return SZ_OK, and we can resume decoding later. + Any error conditions can be tested later in caller code. + For more strict mode we can stop decoding with error + // len += kMatchSpecLen_Error_Data; + */ + break; + } + + curLen = ((rem < len) ? (unsigned)rem : len); + pos = dicPos - rep0 + (dicPos < rep0 ? dicBufSize : 0); + + processedPos += (UInt32)curLen; + + len -= curLen; + if (curLen <= dicBufSize - pos) + { + Byte *dest = dic + dicPos; + ptrdiff_t src = (ptrdiff_t)pos - (ptrdiff_t)dicPos; + const Byte *lim = dest + curLen; + dicPos += (SizeT)curLen; + do + *(dest) = (Byte)*(dest + src); + while (++dest != lim); + } + else + { + do + { + dic[dicPos++] = dic[pos]; + if (++pos == dicBufSize) + pos = 0; + } + while (--curLen != 0); + } + } + } + } + while (dicPos < limit && buf < bufLimit); + + NORMALIZE + + p->buf = buf; + p->range = range; + p->code = code; + p->remainLen = (UInt32)len; // & (kMatchSpecLen_Error_Data - 1); // we can write real length for error matches too. + p->dicPos = dicPos; + p->processedPos = processedPos; + p->reps[0] = rep0; + p->reps[1] = rep1; + p->reps[2] = rep2; + p->reps[3] = rep3; + p->state = (UInt32)state; + if (len >= kMatchSpecLen_Error_Data) + return SZ_ERROR_DATA; + return SZ_OK; +} +#endif + + + +static void Z7_FASTCALL LzmaDec_WriteRem(CLzmaDec *p, SizeT limit) +{ + unsigned len = (unsigned)p->remainLen; + if (len == 0 /* || len >= kMatchSpecLenStart */) + return; + { + SizeT dicPos = p->dicPos; + Byte *dic; + SizeT dicBufSize; + SizeT rep0; /* we use SizeT to avoid the BUG of VC14 for AMD64 */ + { + SizeT rem = limit - dicPos; + if (rem < len) + { + len = (unsigned)(rem); + if (len == 0) + return; + } + } + + if (p->checkDicSize == 0 && p->prop.dicSize - p->processedPos <= len) + p->checkDicSize = p->prop.dicSize; + + p->processedPos += (UInt32)len; + p->remainLen -= (UInt32)len; + dic = p->dic; + rep0 = p->reps[0]; + dicBufSize = p->dicBufSize; + do + { + dic[dicPos] = dic[dicPos - rep0 + (dicPos < rep0 ? dicBufSize : 0)]; + dicPos++; + } + while (--len); + p->dicPos = dicPos; + } +} + + +/* +At staring of new stream we have one of the following symbols: + - Literal - is allowed + - Non-Rep-Match - is allowed only if it's end marker symbol + - Rep-Match - is not allowed +We use early check of (RangeCoder:Code) over kBadRepCode to simplify main decoding code +*/ + +#define kRange0 0xFFFFFFFF +#define kBound0 ((kRange0 >> kNumBitModelTotalBits) << (kNumBitModelTotalBits - 1)) +#define kBadRepCode (kBound0 + (((kRange0 - kBound0) >> kNumBitModelTotalBits) << (kNumBitModelTotalBits - 1))) +#if kBadRepCode != (0xC0000000 - 0x400) + #error Stop_Compiling_Bad_LZMA_Check +#endif + + +/* +LzmaDec_DecodeReal2(): + It calls LZMA_DECODE_REAL() and it adjusts limit according (p->checkDicSize). + +We correct (p->checkDicSize) after LZMA_DECODE_REAL() and in LzmaDec_WriteRem(), +and we support the following state of (p->checkDicSize): + if (total_processed < p->prop.dicSize) then + { + (total_processed == p->processedPos) + (p->checkDicSize == 0) + } + else + (p->checkDicSize == p->prop.dicSize) +*/ + +static int Z7_FASTCALL LzmaDec_DecodeReal2(CLzmaDec *p, SizeT limit, const Byte *bufLimit) +{ + if (p->checkDicSize == 0) + { + UInt32 rem = p->prop.dicSize - p->processedPos; + if (limit - p->dicPos > rem) + limit = p->dicPos + rem; + } + { + int res = LZMA_DECODE_REAL(p, limit, bufLimit); + if (p->checkDicSize == 0 && p->processedPos >= p->prop.dicSize) + p->checkDicSize = p->prop.dicSize; + return res; + } +} + + + +typedef enum +{ + DUMMY_INPUT_EOF, /* need more input data */ + DUMMY_LIT, + DUMMY_MATCH, + DUMMY_REP +} ELzmaDummy; + + +#define IS_DUMMY_END_MARKER_POSSIBLE(dummyRes) ((dummyRes) == DUMMY_MATCH) + +static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, const Byte **bufOut) +{ + UInt32 range = p->range; + UInt32 code = p->code; + const Byte *bufLimit = *bufOut; + const CLzmaProb *probs = GET_PROBS; + unsigned state = (unsigned)p->state; + ELzmaDummy res; + + for (;;) + { + const CLzmaProb *prob; + UInt32 bound; + unsigned ttt; + unsigned posState = CALC_POS_STATE(p->processedPos, ((unsigned)1 << p->prop.pb) - 1); + + prob = probs + IsMatch + COMBINED_PS_STATE; + IF_BIT_0_CHECK(prob) + { + UPDATE_0_CHECK + + prob = probs + Literal; + if (p->checkDicSize != 0 || p->processedPos != 0) + prob += ((UInt32)LZMA_LIT_SIZE * + ((((p->processedPos) & (((unsigned)1 << (p->prop.lp)) - 1)) << p->prop.lc) + + ((unsigned)p->dic[(p->dicPos == 0 ? p->dicBufSize : p->dicPos) - 1] >> (8 - p->prop.lc)))); + + if (state < kNumLitStates) + { + unsigned symbol = 1; + do { GET_BIT_CHECK(prob + symbol, symbol) } while (symbol < 0x100); + } + else + { + unsigned matchByte = p->dic[p->dicPos - p->reps[0] + + (p->dicPos < p->reps[0] ? p->dicBufSize : 0)]; + unsigned offs = 0x100; + unsigned symbol = 1; + do + { + unsigned bit; + const CLzmaProb *probLit; + matchByte += matchByte; + bit = offs; + offs &= matchByte; + probLit = prob + (offs + bit + symbol); + GET_BIT2_CHECK(probLit, symbol, offs ^= bit; , ; ) + } + while (symbol < 0x100); + } + res = DUMMY_LIT; + } + else + { + unsigned len; + UPDATE_1_CHECK + + prob = probs + IsRep + state; + IF_BIT_0_CHECK(prob) + { + UPDATE_0_CHECK + state = 0; + prob = probs + LenCoder; + res = DUMMY_MATCH; + } + else + { + UPDATE_1_CHECK + res = DUMMY_REP; + prob = probs + IsRepG0 + state; + IF_BIT_0_CHECK(prob) + { + UPDATE_0_CHECK + prob = probs + IsRep0Long + COMBINED_PS_STATE; + IF_BIT_0_CHECK(prob) + { + UPDATE_0_CHECK + break; + } + else + { + UPDATE_1_CHECK + } + } + else + { + UPDATE_1_CHECK + prob = probs + IsRepG1 + state; + IF_BIT_0_CHECK(prob) + { + UPDATE_0_CHECK + } + else + { + UPDATE_1_CHECK + prob = probs + IsRepG2 + state; + IF_BIT_0_CHECK(prob) + { + UPDATE_0_CHECK + } + else + { + UPDATE_1_CHECK + } + } + } + state = kNumStates; + prob = probs + RepLenCoder; + } + { + unsigned limit, offset; + const CLzmaProb *probLen = prob + LenChoice; + IF_BIT_0_CHECK(probLen) + { + UPDATE_0_CHECK + probLen = prob + LenLow + GET_LEN_STATE; + offset = 0; + limit = 1 << kLenNumLowBits; + } + else + { + UPDATE_1_CHECK + probLen = prob + LenChoice2; + IF_BIT_0_CHECK(probLen) + { + UPDATE_0_CHECK + probLen = prob + LenLow + GET_LEN_STATE + (1 << kLenNumLowBits); + offset = kLenNumLowSymbols; + limit = 1 << kLenNumLowBits; + } + else + { + UPDATE_1_CHECK + probLen = prob + LenHigh; + offset = kLenNumLowSymbols * 2; + limit = 1 << kLenNumHighBits; + } + } + TREE_DECODE_CHECK(probLen, limit, len) + len += offset; + } + + if (state < 4) + { + unsigned posSlot; + prob = probs + PosSlot + + ((len < kNumLenToPosStates - 1 ? len : kNumLenToPosStates - 1) << + kNumPosSlotBits); + TREE_DECODE_CHECK(prob, 1 << kNumPosSlotBits, posSlot) + if (posSlot >= kStartPosModelIndex) + { + unsigned numDirectBits = ((posSlot >> 1) - 1); + + if (posSlot < kEndPosModelIndex) + { + prob = probs + SpecPos + ((2 | (posSlot & 1)) << numDirectBits); + } + else + { + numDirectBits -= kNumAlignBits; + do + { + NORMALIZE_CHECK + range >>= 1; + code -= range & (((code - range) >> 31) - 1); + /* if (code >= range) code -= range; */ + } + while (--numDirectBits); + prob = probs + Align; + numDirectBits = kNumAlignBits; + } + { + unsigned i = 1; + unsigned m = 1; + do + { + REV_BIT_CHECK(prob, i, m) + } + while (--numDirectBits); + } + } + } + } + break; + } + NORMALIZE_CHECK + + *bufOut = buf; + return res; +} + +void LzmaDec_InitDicAndState(CLzmaDec *p, BoolInt initDic, BoolInt initState); +void LzmaDec_InitDicAndState(CLzmaDec *p, BoolInt initDic, BoolInt initState) +{ + p->remainLen = kMatchSpecLenStart + 1; + p->tempBufSize = 0; + + if (initDic) + { + p->processedPos = 0; + p->checkDicSize = 0; + p->remainLen = kMatchSpecLenStart + 2; + } + if (initState) + p->remainLen = kMatchSpecLenStart + 2; +} + +void LzmaDec_Init(CLzmaDec *p) +{ + p->dicPos = 0; + LzmaDec_InitDicAndState(p, True, True); +} + + +/* +LZMA supports optional end_marker. +So the decoder can lookahead for one additional LZMA-Symbol to check end_marker. +That additional LZMA-Symbol can require up to LZMA_REQUIRED_INPUT_MAX bytes in input stream. +When the decoder reaches dicLimit, it looks (finishMode) parameter: + if (finishMode == LZMA_FINISH_ANY), the decoder doesn't lookahead + if (finishMode != LZMA_FINISH_ANY), the decoder lookahead, if end_marker is possible for current position + +When the decoder lookahead, and the lookahead symbol is not end_marker, we have two ways: + 1) Strict mode (default) : the decoder returns SZ_ERROR_DATA. + 2) The relaxed mode (alternative mode) : we could return SZ_OK, and the caller + must check (status) value. The caller can show the error, + if the end of stream is expected, and the (status) is noit + LZMA_STATUS_FINISHED_WITH_MARK or LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK. +*/ + + +#define RETURN_NOT_FINISHED_FOR_FINISH \ + *status = LZMA_STATUS_NOT_FINISHED; \ + return SZ_ERROR_DATA; // for strict mode + // return SZ_OK; // for relaxed mode + + +SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, const Byte *src, SizeT *srcLen, + ELzmaFinishMode finishMode, ELzmaStatus *status) +{ + SizeT inSize = *srcLen; + (*srcLen) = 0; + *status = LZMA_STATUS_NOT_SPECIFIED; + + if (p->remainLen > kMatchSpecLenStart) + { + if (p->remainLen > kMatchSpecLenStart + 2) + return p->remainLen == kMatchSpecLen_Error_Fail ? SZ_ERROR_FAIL : SZ_ERROR_DATA; + + for (; inSize > 0 && p->tempBufSize < RC_INIT_SIZE; (*srcLen)++, inSize--) + p->tempBuf[p->tempBufSize++] = *src++; + if (p->tempBufSize != 0 && p->tempBuf[0] != 0) + return SZ_ERROR_DATA; + if (p->tempBufSize < RC_INIT_SIZE) + { + *status = LZMA_STATUS_NEEDS_MORE_INPUT; + return SZ_OK; + } + p->code = + ((UInt32)p->tempBuf[1] << 24) + | ((UInt32)p->tempBuf[2] << 16) + | ((UInt32)p->tempBuf[3] << 8) + | ((UInt32)p->tempBuf[4]); + + if (p->checkDicSize == 0 + && p->processedPos == 0 + && p->code >= kBadRepCode) + return SZ_ERROR_DATA; + + p->range = 0xFFFFFFFF; + p->tempBufSize = 0; + + if (p->remainLen > kMatchSpecLenStart + 1) + { + SizeT numProbs = LzmaProps_GetNumProbs(&p->prop); + SizeT i; + CLzmaProb *probs = p->probs; + for (i = 0; i < numProbs; i++) + probs[i] = kBitModelTotal >> 1; + p->reps[0] = p->reps[1] = p->reps[2] = p->reps[3] = 1; + p->state = 0; + } + + p->remainLen = 0; + } + + for (;;) + { + if (p->remainLen == kMatchSpecLenStart) + { + if (p->code != 0) + return SZ_ERROR_DATA; + *status = LZMA_STATUS_FINISHED_WITH_MARK; + return SZ_OK; + } + + LzmaDec_WriteRem(p, dicLimit); + + { + // (p->remainLen == 0 || p->dicPos == dicLimit) + + int checkEndMarkNow = 0; + + if (p->dicPos >= dicLimit) + { + if (p->remainLen == 0 && p->code == 0) + { + *status = LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK; + return SZ_OK; + } + if (finishMode == LZMA_FINISH_ANY) + { + *status = LZMA_STATUS_NOT_FINISHED; + return SZ_OK; + } + if (p->remainLen != 0) + { + RETURN_NOT_FINISHED_FOR_FINISH + } + checkEndMarkNow = 1; + } + + // (p->remainLen == 0) + + if (p->tempBufSize == 0) + { + const Byte *bufLimit; + int dummyProcessed = -1; + + if (inSize < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow) + { + const Byte *bufOut = src + inSize; + + ELzmaDummy dummyRes = LzmaDec_TryDummy(p, src, &bufOut); + + if (dummyRes == DUMMY_INPUT_EOF) + { + size_t i; + if (inSize >= LZMA_REQUIRED_INPUT_MAX) + break; + (*srcLen) += inSize; + p->tempBufSize = (unsigned)inSize; + for (i = 0; i < inSize; i++) + p->tempBuf[i] = src[i]; + *status = LZMA_STATUS_NEEDS_MORE_INPUT; + return SZ_OK; + } + + dummyProcessed = (int)(bufOut - src); + if ((unsigned)dummyProcessed > LZMA_REQUIRED_INPUT_MAX) + break; + + if (checkEndMarkNow && !IS_DUMMY_END_MARKER_POSSIBLE(dummyRes)) + { + unsigned i; + (*srcLen) += (unsigned)dummyProcessed; + p->tempBufSize = (unsigned)dummyProcessed; + for (i = 0; i < (unsigned)dummyProcessed; i++) + p->tempBuf[i] = src[i]; + // p->remainLen = kMatchSpecLen_Error_Data; + RETURN_NOT_FINISHED_FOR_FINISH + } + + bufLimit = src; + // we will decode only one iteration + } + else + bufLimit = src + inSize - LZMA_REQUIRED_INPUT_MAX; + + p->buf = src; + + { + int res = LzmaDec_DecodeReal2(p, dicLimit, bufLimit); + + SizeT processed = (SizeT)(p->buf - src); + + if (dummyProcessed < 0) + { + if (processed > inSize) + break; + } + else if ((unsigned)dummyProcessed != processed) + break; + + src += processed; + inSize -= processed; + (*srcLen) += processed; + + if (res != SZ_OK) + { + p->remainLen = kMatchSpecLen_Error_Data; + return SZ_ERROR_DATA; + } + } + continue; + } + + { + // we have some data in (p->tempBuf) + // in strict mode: tempBufSize is not enough for one Symbol decoding. + // in relaxed mode: tempBufSize not larger than required for one Symbol decoding. + + unsigned rem = p->tempBufSize; + unsigned ahead = 0; + int dummyProcessed = -1; + + while (rem < LZMA_REQUIRED_INPUT_MAX && ahead < inSize) + p->tempBuf[rem++] = src[ahead++]; + + // ahead - the size of new data copied from (src) to (p->tempBuf) + // rem - the size of temp buffer including new data from (src) + + if (rem < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow) + { + const Byte *bufOut = p->tempBuf + rem; + + ELzmaDummy dummyRes = LzmaDec_TryDummy(p, p->tempBuf, &bufOut); + + if (dummyRes == DUMMY_INPUT_EOF) + { + if (rem >= LZMA_REQUIRED_INPUT_MAX) + break; + p->tempBufSize = rem; + (*srcLen) += (SizeT)ahead; + *status = LZMA_STATUS_NEEDS_MORE_INPUT; + return SZ_OK; + } + + dummyProcessed = (int)(bufOut - p->tempBuf); + + if ((unsigned)dummyProcessed < p->tempBufSize) + break; + + if (checkEndMarkNow && !IS_DUMMY_END_MARKER_POSSIBLE(dummyRes)) + { + (*srcLen) += (unsigned)dummyProcessed - p->tempBufSize; + p->tempBufSize = (unsigned)dummyProcessed; + // p->remainLen = kMatchSpecLen_Error_Data; + RETURN_NOT_FINISHED_FOR_FINISH + } + } + + p->buf = p->tempBuf; + + { + // we decode one symbol from (p->tempBuf) here, so the (bufLimit) is equal to (p->buf) + int res = LzmaDec_DecodeReal2(p, dicLimit, p->buf); + + SizeT processed = (SizeT)(p->buf - p->tempBuf); + rem = p->tempBufSize; + + if (dummyProcessed < 0) + { + if (processed > LZMA_REQUIRED_INPUT_MAX) + break; + if (processed < rem) + break; + } + else if ((unsigned)dummyProcessed != processed) + break; + + processed -= rem; + + src += processed; + inSize -= processed; + (*srcLen) += processed; + p->tempBufSize = 0; + + if (res != SZ_OK) + { + p->remainLen = kMatchSpecLen_Error_Data; + return SZ_ERROR_DATA; + } + } + } + } + } + + /* Some unexpected error: internal error of code, memory corruption or hardware failure */ + p->remainLen = kMatchSpecLen_Error_Fail; + return SZ_ERROR_FAIL; +} + + + +SRes LzmaDec_DecodeToBuf(CLzmaDec *p, Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status) +{ + SizeT outSize = *destLen; + SizeT inSize = *srcLen; + *srcLen = *destLen = 0; + for (;;) + { + SizeT inSizeCur = inSize, outSizeCur, dicPos; + ELzmaFinishMode curFinishMode; + SRes res; + if (p->dicPos == p->dicBufSize) + p->dicPos = 0; + dicPos = p->dicPos; + if (outSize > p->dicBufSize - dicPos) + { + outSizeCur = p->dicBufSize; + curFinishMode = LZMA_FINISH_ANY; + } + else + { + outSizeCur = dicPos + outSize; + curFinishMode = finishMode; + } + + res = LzmaDec_DecodeToDic(p, outSizeCur, src, &inSizeCur, curFinishMode, status); + src += inSizeCur; + inSize -= inSizeCur; + *srcLen += inSizeCur; + outSizeCur = p->dicPos - dicPos; + memcpy(dest, p->dic + dicPos, outSizeCur); + dest += outSizeCur; + outSize -= outSizeCur; + *destLen += outSizeCur; + if (res != 0) + return res; + if (outSizeCur == 0 || outSize == 0) + return SZ_OK; + } +} + +void LzmaDec_FreeProbs(CLzmaDec *p, ISzAllocPtr alloc) +{ + ISzAlloc_Free(alloc, p->probs); + p->probs = NULL; +} + +static void LzmaDec_FreeDict(CLzmaDec *p, ISzAllocPtr alloc) +{ + ISzAlloc_Free(alloc, p->dic); + p->dic = NULL; +} + +void LzmaDec_Free(CLzmaDec *p, ISzAllocPtr alloc) +{ + LzmaDec_FreeProbs(p, alloc); + LzmaDec_FreeDict(p, alloc); +} + +SRes LzmaProps_Decode(CLzmaProps *p, const Byte *data, unsigned size) +{ + UInt32 dicSize; + Byte d; + + if (size < LZMA_PROPS_SIZE) + return SZ_ERROR_UNSUPPORTED; + else + dicSize = data[1] | ((UInt32)data[2] << 8) | ((UInt32)data[3] << 16) | ((UInt32)data[4] << 24); + + if (dicSize < LZMA_DIC_MIN) + dicSize = LZMA_DIC_MIN; + p->dicSize = dicSize; + + d = data[0]; + if (d >= (9 * 5 * 5)) + return SZ_ERROR_UNSUPPORTED; + + p->lc = (Byte)(d % 9); + d /= 9; + p->pb = (Byte)(d / 5); + p->lp = (Byte)(d % 5); + + return SZ_OK; +} + +static SRes LzmaDec_AllocateProbs2(CLzmaDec *p, const CLzmaProps *propNew, ISzAllocPtr alloc) +{ + UInt32 numProbs = LzmaProps_GetNumProbs(propNew); + if (!p->probs || numProbs != p->numProbs) + { + LzmaDec_FreeProbs(p, alloc); + p->probs = (CLzmaProb *)ISzAlloc_Alloc(alloc, numProbs * sizeof(CLzmaProb)); + if (!p->probs) + return SZ_ERROR_MEM; + p->probs_1664 = p->probs + 1664; + p->numProbs = numProbs; + } + return SZ_OK; +} + +SRes LzmaDec_AllocateProbs(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAllocPtr alloc) +{ + CLzmaProps propNew; + RINOK(LzmaProps_Decode(&propNew, props, propsSize)) + RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc)) + p->prop = propNew; + return SZ_OK; +} + +SRes LzmaDec_Allocate(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAllocPtr alloc) +{ + CLzmaProps propNew; + SizeT dicBufSize; + RINOK(LzmaProps_Decode(&propNew, props, propsSize)) + RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc)) + + { + UInt32 dictSize = propNew.dicSize; + SizeT mask = ((UInt32)1 << 12) - 1; + if (dictSize >= ((UInt32)1 << 30)) mask = ((UInt32)1 << 22) - 1; + else if (dictSize >= ((UInt32)1 << 22)) mask = ((UInt32)1 << 20) - 1; + dicBufSize = ((SizeT)dictSize + mask) & ~mask; + if (dicBufSize < dictSize) + dicBufSize = dictSize; + } + + if (!p->dic || dicBufSize != p->dicBufSize) + { + LzmaDec_FreeDict(p, alloc); + p->dic = (Byte *)ISzAlloc_Alloc(alloc, dicBufSize); + if (!p->dic) + { + LzmaDec_FreeProbs(p, alloc); + return SZ_ERROR_MEM; + } + } + p->dicBufSize = dicBufSize; + p->prop = propNew; + return SZ_OK; +} + +SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, + const Byte *propData, unsigned propSize, ELzmaFinishMode finishMode, + ELzmaStatus *status, ISzAllocPtr alloc) +{ + CLzmaDec p; + SRes res; + SizeT outSize = *destLen, inSize = *srcLen; + *destLen = *srcLen = 0; + *status = LZMA_STATUS_NOT_SPECIFIED; + if (inSize < RC_INIT_SIZE) + return SZ_ERROR_INPUT_EOF; + LzmaDec_CONSTRUCT(&p) + RINOK(LzmaDec_AllocateProbs(&p, propData, propSize, alloc)) + p.dic = dest; + p.dicBufSize = outSize; + LzmaDec_Init(&p); + *srcLen = inSize; + res = LzmaDec_DecodeToDic(&p, outSize, src, srcLen, finishMode, status); + *destLen = p.dicPos; + if (res == SZ_OK && *status == LZMA_STATUS_NEEDS_MORE_INPUT) + res = SZ_ERROR_INPUT_EOF; + LzmaDec_FreeProbs(&p, alloc); + return res; +} diff --git a/libretrodroid/src/main/cpp/libchdr/deps/zstd-1.5.7/CMakeLists.txt b/libretrodroid/src/main/cpp/libchdr/deps/zstd-1.5.7/CMakeLists.txt new file mode 100644 index 000000000..0cdbda800 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/deps/zstd-1.5.7/CMakeLists.txt @@ -0,0 +1,7 @@ +add_library(zstd STATIC + zstd.h + zstd_errors.h + zstddeclib.c +) + +set_target_properties(zstd PROPERTIES POSITION_INDEPENDENT_CODE ON) diff --git a/libretrodroid/src/main/cpp/libchdr/deps/zstd-1.5.7/zstd.h b/libretrodroid/src/main/cpp/libchdr/deps/zstd-1.5.7/zstd.h new file mode 100644 index 000000000..5d50584cc --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/deps/zstd-1.5.7/zstd.h @@ -0,0 +1,3198 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTD_H_235446 +#define ZSTD_H_235446 + + +/* ====== Dependencies ======*/ +#include /* size_t */ + +#include "zstd_errors.h" /* list of errors */ +#if defined(ZSTD_STATIC_LINKING_ONLY) && !defined(ZSTD_H_ZSTD_STATIC_LINKING_ONLY) +#include /* INT_MAX */ +#endif /* ZSTD_STATIC_LINKING_ONLY */ + +#if defined (__cplusplus) +extern "C" { +#endif + +/* ===== ZSTDLIB_API : control library symbols visibility ===== */ +#ifndef ZSTDLIB_VISIBLE + /* Backwards compatibility with old macro name */ +# ifdef ZSTDLIB_VISIBILITY +# define ZSTDLIB_VISIBLE ZSTDLIB_VISIBILITY +# elif defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__MINGW32__) +# define ZSTDLIB_VISIBLE __attribute__ ((visibility ("default"))) +# else +# define ZSTDLIB_VISIBLE +# endif +#endif + +#ifndef ZSTDLIB_HIDDEN +# if defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__MINGW32__) +# define ZSTDLIB_HIDDEN __attribute__ ((visibility ("hidden"))) +# else +# define ZSTDLIB_HIDDEN +# endif +#endif + +#if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1) +# define ZSTDLIB_API __declspec(dllexport) ZSTDLIB_VISIBLE +#elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1) +# define ZSTDLIB_API __declspec(dllimport) ZSTDLIB_VISIBLE /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/ +#else +# define ZSTDLIB_API ZSTDLIB_VISIBLE +#endif + +/* Deprecation warnings : + * Should these warnings be a problem, it is generally possible to disable them, + * typically with -Wno-deprecated-declarations for gcc or _CRT_SECURE_NO_WARNINGS in Visual. + * Otherwise, it's also possible to define ZSTD_DISABLE_DEPRECATE_WARNINGS. + */ +#ifdef ZSTD_DISABLE_DEPRECATE_WARNINGS +# define ZSTD_DEPRECATED(message) /* disable deprecation warnings */ +#else +# if defined (__cplusplus) && (__cplusplus >= 201402) /* C++14 or greater */ +# define ZSTD_DEPRECATED(message) [[deprecated(message)]] +# elif (defined(GNUC) && (GNUC > 4 || (GNUC == 4 && GNUC_MINOR >= 5))) || defined(__clang__) || defined(__IAR_SYSTEMS_ICC__) +# define ZSTD_DEPRECATED(message) __attribute__((deprecated(message))) +# elif defined(__GNUC__) && (__GNUC__ >= 3) +# define ZSTD_DEPRECATED(message) __attribute__((deprecated)) +# elif defined(_MSC_VER) +# define ZSTD_DEPRECATED(message) __declspec(deprecated(message)) +# else +# pragma message("WARNING: You need to implement ZSTD_DEPRECATED for this compiler") +# define ZSTD_DEPRECATED(message) +# endif +#endif /* ZSTD_DISABLE_DEPRECATE_WARNINGS */ + + +/******************************************************************************* + Introduction + + zstd, short for Zstandard, is a fast lossless compression algorithm, targeting + real-time compression scenarios at zlib-level and better compression ratios. + The zstd compression library provides in-memory compression and decompression + functions. + + The library supports regular compression levels from 1 up to ZSTD_maxCLevel(), + which is currently 22. Levels >= 20, labeled `--ultra`, should be used with + caution, as they require more memory. The library also offers negative + compression levels, which extend the range of speed vs. ratio preferences. + The lower the level, the faster the speed (at the cost of compression). + + Compression can be done in: + - a single step (described as Simple API) + - a single step, reusing a context (described as Explicit context) + - unbounded multiple steps (described as Streaming compression) + + The compression ratio achievable on small data can be highly improved using + a dictionary. Dictionary compression can be performed in: + - a single step (described as Simple dictionary API) + - a single step, reusing a dictionary (described as Bulk-processing + dictionary API) + + Advanced experimental functions can be accessed using + `#define ZSTD_STATIC_LINKING_ONLY` before including zstd.h. + + Advanced experimental APIs should never be used with a dynamically-linked + library. They are not "stable"; their definitions or signatures may change in + the future. Only static linking is allowed. +*******************************************************************************/ + +/*------ Version ------*/ +#define ZSTD_VERSION_MAJOR 1 +#define ZSTD_VERSION_MINOR 5 +#define ZSTD_VERSION_RELEASE 7 +#define ZSTD_VERSION_NUMBER (ZSTD_VERSION_MAJOR *100*100 + ZSTD_VERSION_MINOR *100 + ZSTD_VERSION_RELEASE) + +/*! ZSTD_versionNumber() : + * Return runtime library version, the value is (MAJOR*100*100 + MINOR*100 + RELEASE). */ +ZSTDLIB_API unsigned ZSTD_versionNumber(void); + +#define ZSTD_LIB_VERSION ZSTD_VERSION_MAJOR.ZSTD_VERSION_MINOR.ZSTD_VERSION_RELEASE +#define ZSTD_QUOTE(str) #str +#define ZSTD_EXPAND_AND_QUOTE(str) ZSTD_QUOTE(str) +#define ZSTD_VERSION_STRING ZSTD_EXPAND_AND_QUOTE(ZSTD_LIB_VERSION) + +/*! ZSTD_versionString() : + * Return runtime library version, like "1.4.5". Requires v1.3.0+. */ +ZSTDLIB_API const char* ZSTD_versionString(void); + +/* ************************************* + * Default constant + ***************************************/ +#ifndef ZSTD_CLEVEL_DEFAULT +# define ZSTD_CLEVEL_DEFAULT 3 +#endif + +/* ************************************* + * Constants + ***************************************/ + +/* All magic numbers are supposed read/written to/from files/memory using little-endian convention */ +#define ZSTD_MAGICNUMBER 0xFD2FB528 /* valid since v0.8.0 */ +#define ZSTD_MAGIC_DICTIONARY 0xEC30A437 /* valid since v0.7.0 */ +#define ZSTD_MAGIC_SKIPPABLE_START 0x184D2A50 /* all 16 values, from 0x184D2A50 to 0x184D2A5F, signal the beginning of a skippable frame */ +#define ZSTD_MAGIC_SKIPPABLE_MASK 0xFFFFFFF0 + +#define ZSTD_BLOCKSIZELOG_MAX 17 +#define ZSTD_BLOCKSIZE_MAX (1<= ZSTD_compressBound(srcSize)` guarantees that zstd will have + * enough space to successfully compress the data. + * @return : compressed size written into `dst` (<= `dstCapacity), + * or an error code if it fails (which can be tested using ZSTD_isError()). */ +ZSTDLIB_API size_t ZSTD_compress( void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + int compressionLevel); + +/*! ZSTD_decompress() : + * `compressedSize` : must be the _exact_ size of some number of compressed and/or skippable frames. + * Multiple compressed frames can be decompressed at once with this method. + * The result will be the concatenation of all decompressed frames, back to back. + * `dstCapacity` is an upper bound of originalSize to regenerate. + * First frame's decompressed size can be extracted using ZSTD_getFrameContentSize(). + * If maximum upper bound isn't known, prefer using streaming mode to decompress data. + * @return : the number of bytes decompressed into `dst` (<= `dstCapacity`), + * or an errorCode if it fails (which can be tested using ZSTD_isError()). */ +ZSTDLIB_API size_t ZSTD_decompress( void* dst, size_t dstCapacity, + const void* src, size_t compressedSize); + + +/*====== Decompression helper functions ======*/ + +/*! ZSTD_getFrameContentSize() : requires v1.3.0+ + * `src` should point to the start of a ZSTD encoded frame. + * `srcSize` must be at least as large as the frame header. + * hint : any size >= `ZSTD_frameHeaderSize_max` is large enough. + * @return : - decompressed size of `src` frame content, if known + * - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined + * - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small) + * note 1 : a 0 return value means the frame is valid but "empty". + * When invoking this method on a skippable frame, it will return 0. + * note 2 : decompressed size is an optional field, it may not be present (typically in streaming mode). + * When `return==ZSTD_CONTENTSIZE_UNKNOWN`, data to decompress could be any size. + * In which case, it's necessary to use streaming mode to decompress data. + * Optionally, application can rely on some implicit limit, + * as ZSTD_decompress() only needs an upper bound of decompressed size. + * (For example, data could be necessarily cut into blocks <= 16 KB). + * note 3 : decompressed size is always present when compression is completed using single-pass functions, + * such as ZSTD_compress(), ZSTD_compressCCtx() ZSTD_compress_usingDict() or ZSTD_compress_usingCDict(). + * note 4 : decompressed size can be very large (64-bits value), + * potentially larger than what local system can handle as a single memory segment. + * In which case, it's necessary to use streaming mode to decompress data. + * note 5 : If source is untrusted, decompressed size could be wrong or intentionally modified. + * Always ensure return value fits within application's authorized limits. + * Each application can set its own limits. + * note 6 : This function replaces ZSTD_getDecompressedSize() */ +#define ZSTD_CONTENTSIZE_UNKNOWN (0ULL - 1) +#define ZSTD_CONTENTSIZE_ERROR (0ULL - 2) +ZSTDLIB_API unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize); + +/*! ZSTD_getDecompressedSize() (obsolete): + * This function is now obsolete, in favor of ZSTD_getFrameContentSize(). + * Both functions work the same way, but ZSTD_getDecompressedSize() blends + * "empty", "unknown" and "error" results to the same return value (0), + * while ZSTD_getFrameContentSize() gives them separate return values. + * @return : decompressed size of `src` frame content _if known and not empty_, 0 otherwise. */ +ZSTD_DEPRECATED("Replaced by ZSTD_getFrameContentSize") +ZSTDLIB_API unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize); + +/*! ZSTD_findFrameCompressedSize() : Requires v1.4.0+ + * `src` should point to the start of a ZSTD frame or skippable frame. + * `srcSize` must be >= first frame size + * @return : the compressed size of the first frame starting at `src`, + * suitable to pass as `srcSize` to `ZSTD_decompress` or similar, + * or an error code if input is invalid + * Note 1: this method is called _find*() because it's not enough to read the header, + * it may have to scan through the frame's content, to reach its end. + * Note 2: this method also works with Skippable Frames. In which case, + * it returns the size of the complete skippable frame, + * which is always equal to its content size + 8 bytes for headers. */ +ZSTDLIB_API size_t ZSTD_findFrameCompressedSize(const void* src, size_t srcSize); + + +/*====== Compression helper functions ======*/ + +/*! ZSTD_compressBound() : + * maximum compressed size in worst case single-pass scenario. + * When invoking `ZSTD_compress()`, or any other one-pass compression function, + * it's recommended to provide @dstCapacity >= ZSTD_compressBound(srcSize) + * as it eliminates one potential failure scenario, + * aka not enough room in dst buffer to write the compressed frame. + * Note : ZSTD_compressBound() itself can fail, if @srcSize >= ZSTD_MAX_INPUT_SIZE . + * In which case, ZSTD_compressBound() will return an error code + * which can be tested using ZSTD_isError(). + * + * ZSTD_COMPRESSBOUND() : + * same as ZSTD_compressBound(), but as a macro. + * It can be used to produce constants, which can be useful for static allocation, + * for example to size a static array on stack. + * Will produce constant value 0 if srcSize is too large. + */ +#define ZSTD_MAX_INPUT_SIZE ((sizeof(size_t)==8) ? 0xFF00FF00FF00FF00ULL : 0xFF00FF00U) +#define ZSTD_COMPRESSBOUND(srcSize) (((size_t)(srcSize) >= ZSTD_MAX_INPUT_SIZE) ? 0 : (srcSize) + ((srcSize)>>8) + (((srcSize) < (128<<10)) ? (((128<<10) - (srcSize)) >> 11) /* margin, from 64 to 0 */ : 0)) /* this formula ensures that bound(A) + bound(B) <= bound(A+B) as long as A and B >= 128 KB */ +ZSTDLIB_API size_t ZSTD_compressBound(size_t srcSize); /*!< maximum compressed size in worst case single-pass scenario */ + + +/*====== Error helper functions ======*/ +/* ZSTD_isError() : + * Most ZSTD_* functions returning a size_t value can be tested for error, + * using ZSTD_isError(). + * @return 1 if error, 0 otherwise + */ +ZSTDLIB_API unsigned ZSTD_isError(size_t result); /*!< tells if a `size_t` function result is an error code */ +ZSTDLIB_API ZSTD_ErrorCode ZSTD_getErrorCode(size_t functionResult); /* convert a result into an error code, which can be compared to error enum list */ +ZSTDLIB_API const char* ZSTD_getErrorName(size_t result); /*!< provides readable string from a function result */ +ZSTDLIB_API int ZSTD_minCLevel(void); /*!< minimum negative compression level allowed, requires v1.4.0+ */ +ZSTDLIB_API int ZSTD_maxCLevel(void); /*!< maximum compression level available */ +ZSTDLIB_API int ZSTD_defaultCLevel(void); /*!< default compression level, specified by ZSTD_CLEVEL_DEFAULT, requires v1.5.0+ */ + + +/*************************************** +* Explicit context +***************************************/ +/*= Compression context + * When compressing many times, + * it is recommended to allocate a compression context just once, + * and reuse it for each successive compression operation. + * This will make the workload easier for system's memory. + * Note : re-using context is just a speed / resource optimization. + * It doesn't change the compression ratio, which remains identical. + * Note 2: For parallel execution in multi-threaded environments, + * use one different context per thread . + */ +typedef struct ZSTD_CCtx_s ZSTD_CCtx; +ZSTDLIB_API ZSTD_CCtx* ZSTD_createCCtx(void); +ZSTDLIB_API size_t ZSTD_freeCCtx(ZSTD_CCtx* cctx); /* compatible with NULL pointer */ + +/*! ZSTD_compressCCtx() : + * Same as ZSTD_compress(), using an explicit ZSTD_CCtx. + * Important : in order to mirror `ZSTD_compress()` behavior, + * this function compresses at the requested compression level, + * __ignoring any other advanced parameter__ . + * If any advanced parameter was set using the advanced API, + * they will all be reset. Only @compressionLevel remains. + */ +ZSTDLIB_API size_t ZSTD_compressCCtx(ZSTD_CCtx* cctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + int compressionLevel); + +/*= Decompression context + * When decompressing many times, + * it is recommended to allocate a context only once, + * and reuse it for each successive compression operation. + * This will make workload friendlier for system's memory. + * Use one context per thread for parallel execution. */ +typedef struct ZSTD_DCtx_s ZSTD_DCtx; +ZSTDLIB_API ZSTD_DCtx* ZSTD_createDCtx(void); +ZSTDLIB_API size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx); /* accept NULL pointer */ + +/*! ZSTD_decompressDCtx() : + * Same as ZSTD_decompress(), + * requires an allocated ZSTD_DCtx. + * Compatible with sticky parameters (see below). + */ +ZSTDLIB_API size_t ZSTD_decompressDCtx(ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize); + + +/********************************************* +* Advanced compression API (Requires v1.4.0+) +**********************************************/ + +/* API design : + * Parameters are pushed one by one into an existing context, + * using ZSTD_CCtx_set*() functions. + * Pushed parameters are sticky : they are valid for next compressed frame, and any subsequent frame. + * "sticky" parameters are applicable to `ZSTD_compress2()` and `ZSTD_compressStream*()` ! + * __They do not apply to one-shot variants such as ZSTD_compressCCtx()__ . + * + * It's possible to reset all parameters to "default" using ZSTD_CCtx_reset(). + * + * This API supersedes all other "advanced" API entry points in the experimental section. + * In the future, we expect to remove API entry points from experimental which are redundant with this API. + */ + + +/* Compression strategies, listed from fastest to strongest */ +typedef enum { ZSTD_fast=1, + ZSTD_dfast=2, + ZSTD_greedy=3, + ZSTD_lazy=4, + ZSTD_lazy2=5, + ZSTD_btlazy2=6, + ZSTD_btopt=7, + ZSTD_btultra=8, + ZSTD_btultra2=9 + /* note : new strategies _might_ be added in the future. + Only the order (from fast to strong) is guaranteed */ +} ZSTD_strategy; + +typedef enum { + + /* compression parameters + * Note: When compressing with a ZSTD_CDict these parameters are superseded + * by the parameters used to construct the ZSTD_CDict. + * See ZSTD_CCtx_refCDict() for more info (superseded-by-cdict). */ + ZSTD_c_compressionLevel=100, /* Set compression parameters according to pre-defined cLevel table. + * Note that exact compression parameters are dynamically determined, + * depending on both compression level and srcSize (when known). + * Default level is ZSTD_CLEVEL_DEFAULT==3. + * Special: value 0 means default, which is controlled by ZSTD_CLEVEL_DEFAULT. + * Note 1 : it's possible to pass a negative compression level. + * Note 2 : setting a level does not automatically set all other compression parameters + * to default. Setting this will however eventually dynamically impact the compression + * parameters which have not been manually set. The manually set + * ones will 'stick'. */ + /* Advanced compression parameters : + * It's possible to pin down compression parameters to some specific values. + * In which case, these values are no longer dynamically selected by the compressor */ + ZSTD_c_windowLog=101, /* Maximum allowed back-reference distance, expressed as power of 2. + * This will set a memory budget for streaming decompression, + * with larger values requiring more memory + * and typically compressing more. + * Must be clamped between ZSTD_WINDOWLOG_MIN and ZSTD_WINDOWLOG_MAX. + * Special: value 0 means "use default windowLog". + * Note: Using a windowLog greater than ZSTD_WINDOWLOG_LIMIT_DEFAULT + * requires explicitly allowing such size at streaming decompression stage. */ + ZSTD_c_hashLog=102, /* Size of the initial probe table, as a power of 2. + * Resulting memory usage is (1 << (hashLog+2)). + * Must be clamped between ZSTD_HASHLOG_MIN and ZSTD_HASHLOG_MAX. + * Larger tables improve compression ratio of strategies <= dFast, + * and improve speed of strategies > dFast. + * Special: value 0 means "use default hashLog". */ + ZSTD_c_chainLog=103, /* Size of the multi-probe search table, as a power of 2. + * Resulting memory usage is (1 << (chainLog+2)). + * Must be clamped between ZSTD_CHAINLOG_MIN and ZSTD_CHAINLOG_MAX. + * Larger tables result in better and slower compression. + * This parameter is useless for "fast" strategy. + * It's still useful when using "dfast" strategy, + * in which case it defines a secondary probe table. + * Special: value 0 means "use default chainLog". */ + ZSTD_c_searchLog=104, /* Number of search attempts, as a power of 2. + * More attempts result in better and slower compression. + * This parameter is useless for "fast" and "dFast" strategies. + * Special: value 0 means "use default searchLog". */ + ZSTD_c_minMatch=105, /* Minimum size of searched matches. + * Note that Zstandard can still find matches of smaller size, + * it just tweaks its search algorithm to look for this size and larger. + * Larger values increase compression and decompression speed, but decrease ratio. + * Must be clamped between ZSTD_MINMATCH_MIN and ZSTD_MINMATCH_MAX. + * Note that currently, for all strategies < btopt, effective minimum is 4. + * , for all strategies > fast, effective maximum is 6. + * Special: value 0 means "use default minMatchLength". */ + ZSTD_c_targetLength=106, /* Impact of this field depends on strategy. + * For strategies btopt, btultra & btultra2: + * Length of Match considered "good enough" to stop search. + * Larger values make compression stronger, and slower. + * For strategy fast: + * Distance between match sampling. + * Larger values make compression faster, and weaker. + * Special: value 0 means "use default targetLength". */ + ZSTD_c_strategy=107, /* See ZSTD_strategy enum definition. + * The higher the value of selected strategy, the more complex it is, + * resulting in stronger and slower compression. + * Special: value 0 means "use default strategy". */ + + ZSTD_c_targetCBlockSize=130, /* v1.5.6+ + * Attempts to fit compressed block size into approximately targetCBlockSize. + * Bound by ZSTD_TARGETCBLOCKSIZE_MIN and ZSTD_TARGETCBLOCKSIZE_MAX. + * Note that it's not a guarantee, just a convergence target (default:0). + * No target when targetCBlockSize == 0. + * This is helpful in low bandwidth streaming environments to improve end-to-end latency, + * when a client can make use of partial documents (a prominent example being Chrome). + * Note: this parameter is stable since v1.5.6. + * It was present as an experimental parameter in earlier versions, + * but it's not recommended using it with earlier library versions + * due to massive performance regressions. + */ + /* LDM mode parameters */ + ZSTD_c_enableLongDistanceMatching=160, /* Enable long distance matching. + * This parameter is designed to improve compression ratio + * for large inputs, by finding large matches at long distance. + * It increases memory usage and window size. + * Note: enabling this parameter increases default ZSTD_c_windowLog to 128 MB + * except when expressly set to a different value. + * Note: will be enabled by default if ZSTD_c_windowLog >= 128 MB and + * compression strategy >= ZSTD_btopt (== compression level 16+) */ + ZSTD_c_ldmHashLog=161, /* Size of the table for long distance matching, as a power of 2. + * Larger values increase memory usage and compression ratio, + * but decrease compression speed. + * Must be clamped between ZSTD_HASHLOG_MIN and ZSTD_HASHLOG_MAX + * default: windowlog - 7. + * Special: value 0 means "automatically determine hashlog". */ + ZSTD_c_ldmMinMatch=162, /* Minimum match size for long distance matcher. + * Larger/too small values usually decrease compression ratio. + * Must be clamped between ZSTD_LDM_MINMATCH_MIN and ZSTD_LDM_MINMATCH_MAX. + * Special: value 0 means "use default value" (default: 64). */ + ZSTD_c_ldmBucketSizeLog=163, /* Log size of each bucket in the LDM hash table for collision resolution. + * Larger values improve collision resolution but decrease compression speed. + * The maximum value is ZSTD_LDM_BUCKETSIZELOG_MAX. + * Special: value 0 means "use default value" (default: 3). */ + ZSTD_c_ldmHashRateLog=164, /* Frequency of inserting/looking up entries into the LDM hash table. + * Must be clamped between 0 and (ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN). + * Default is MAX(0, (windowLog - ldmHashLog)), optimizing hash table usage. + * Larger values improve compression speed. + * Deviating far from default value will likely result in a compression ratio decrease. + * Special: value 0 means "automatically determine hashRateLog". */ + + /* frame parameters */ + ZSTD_c_contentSizeFlag=200, /* Content size will be written into frame header _whenever known_ (default:1) + * Content size must be known at the beginning of compression. + * This is automatically the case when using ZSTD_compress2(), + * For streaming scenarios, content size must be provided with ZSTD_CCtx_setPledgedSrcSize() */ + ZSTD_c_checksumFlag=201, /* A 32-bits checksum of content is written at end of frame (default:0) */ + ZSTD_c_dictIDFlag=202, /* When applicable, dictionary's ID is written into frame header (default:1) */ + + /* multi-threading parameters */ + /* These parameters are only active if multi-threading is enabled (compiled with build macro ZSTD_MULTITHREAD). + * Otherwise, trying to set any other value than default (0) will be a no-op and return an error. + * In a situation where it's unknown if the linked library supports multi-threading or not, + * setting ZSTD_c_nbWorkers to any value >= 1 and consulting the return value provides a quick way to check this property. + */ + ZSTD_c_nbWorkers=400, /* Select how many threads will be spawned to compress in parallel. + * When nbWorkers >= 1, triggers asynchronous mode when invoking ZSTD_compressStream*() : + * ZSTD_compressStream*() consumes input and flush output if possible, but immediately gives back control to caller, + * while compression is performed in parallel, within worker thread(s). + * (note : a strong exception to this rule is when first invocation of ZSTD_compressStream2() sets ZSTD_e_end : + * in which case, ZSTD_compressStream2() delegates to ZSTD_compress2(), which is always a blocking call). + * More workers improve speed, but also increase memory usage. + * Default value is `0`, aka "single-threaded mode" : no worker is spawned, + * compression is performed inside Caller's thread, and all invocations are blocking */ + ZSTD_c_jobSize=401, /* Size of a compression job. This value is enforced only when nbWorkers >= 1. + * Each compression job is completed in parallel, so this value can indirectly impact the nb of active threads. + * 0 means default, which is dynamically determined based on compression parameters. + * Job size must be a minimum of overlap size, or ZSTDMT_JOBSIZE_MIN (= 512 KB), whichever is largest. + * The minimum size is automatically and transparently enforced. */ + ZSTD_c_overlapLog=402, /* Control the overlap size, as a fraction of window size. + * The overlap size is an amount of data reloaded from previous job at the beginning of a new job. + * It helps preserve compression ratio, while each job is compressed in parallel. + * This value is enforced only when nbWorkers >= 1. + * Larger values increase compression ratio, but decrease speed. + * Possible values range from 0 to 9 : + * - 0 means "default" : value will be determined by the library, depending on strategy + * - 1 means "no overlap" + * - 9 means "full overlap", using a full window size. + * Each intermediate rank increases/decreases load size by a factor 2 : + * 9: full window; 8: w/2; 7: w/4; 6: w/8; 5:w/16; 4: w/32; 3:w/64; 2:w/128; 1:no overlap; 0:default + * default value varies between 6 and 9, depending on strategy */ + + /* note : additional experimental parameters are also available + * within the experimental section of the API. + * At the time of this writing, they include : + * ZSTD_c_rsyncable + * ZSTD_c_format + * ZSTD_c_forceMaxWindow + * ZSTD_c_forceAttachDict + * ZSTD_c_literalCompressionMode + * ZSTD_c_srcSizeHint + * ZSTD_c_enableDedicatedDictSearch + * ZSTD_c_stableInBuffer + * ZSTD_c_stableOutBuffer + * ZSTD_c_blockDelimiters + * ZSTD_c_validateSequences + * ZSTD_c_blockSplitterLevel + * ZSTD_c_splitAfterSequences + * ZSTD_c_useRowMatchFinder + * ZSTD_c_prefetchCDictTables + * ZSTD_c_enableSeqProducerFallback + * ZSTD_c_maxBlockSize + * Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them. + * note : never ever use experimentalParam? names directly; + * also, the enums values themselves are unstable and can still change. + */ + ZSTD_c_experimentalParam1=500, + ZSTD_c_experimentalParam2=10, + ZSTD_c_experimentalParam3=1000, + ZSTD_c_experimentalParam4=1001, + ZSTD_c_experimentalParam5=1002, + /* was ZSTD_c_experimentalParam6=1003; is now ZSTD_c_targetCBlockSize */ + ZSTD_c_experimentalParam7=1004, + ZSTD_c_experimentalParam8=1005, + ZSTD_c_experimentalParam9=1006, + ZSTD_c_experimentalParam10=1007, + ZSTD_c_experimentalParam11=1008, + ZSTD_c_experimentalParam12=1009, + ZSTD_c_experimentalParam13=1010, + ZSTD_c_experimentalParam14=1011, + ZSTD_c_experimentalParam15=1012, + ZSTD_c_experimentalParam16=1013, + ZSTD_c_experimentalParam17=1014, + ZSTD_c_experimentalParam18=1015, + ZSTD_c_experimentalParam19=1016, + ZSTD_c_experimentalParam20=1017 +} ZSTD_cParameter; + +typedef struct { + size_t error; + int lowerBound; + int upperBound; +} ZSTD_bounds; + +/*! ZSTD_cParam_getBounds() : + * All parameters must belong to an interval with lower and upper bounds, + * otherwise they will either trigger an error or be automatically clamped. + * @return : a structure, ZSTD_bounds, which contains + * - an error status field, which must be tested using ZSTD_isError() + * - lower and upper bounds, both inclusive + */ +ZSTDLIB_API ZSTD_bounds ZSTD_cParam_getBounds(ZSTD_cParameter cParam); + +/*! ZSTD_CCtx_setParameter() : + * Set one compression parameter, selected by enum ZSTD_cParameter. + * All parameters have valid bounds. Bounds can be queried using ZSTD_cParam_getBounds(). + * Providing a value beyond bound will either clamp it, or trigger an error (depending on parameter). + * Setting a parameter is generally only possible during frame initialization (before starting compression). + * Exception : when using multi-threading mode (nbWorkers >= 1), + * the following parameters can be updated _during_ compression (within same frame): + * => compressionLevel, hashLog, chainLog, searchLog, minMatch, targetLength and strategy. + * new parameters will be active for next job only (after a flush()). + * @return : an error code (which can be tested using ZSTD_isError()). + */ +ZSTDLIB_API size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int value); + +/*! ZSTD_CCtx_setPledgedSrcSize() : + * Total input data size to be compressed as a single frame. + * Value will be written in frame header, unless if explicitly forbidden using ZSTD_c_contentSizeFlag. + * This value will also be controlled at end of frame, and trigger an error if not respected. + * @result : 0, or an error code (which can be tested with ZSTD_isError()). + * Note 1 : pledgedSrcSize==0 actually means zero, aka an empty frame. + * In order to mean "unknown content size", pass constant ZSTD_CONTENTSIZE_UNKNOWN. + * ZSTD_CONTENTSIZE_UNKNOWN is default value for any new frame. + * Note 2 : pledgedSrcSize is only valid once, for the next frame. + * It's discarded at the end of the frame, and replaced by ZSTD_CONTENTSIZE_UNKNOWN. + * Note 3 : Whenever all input data is provided and consumed in a single round, + * for example with ZSTD_compress2(), + * or invoking immediately ZSTD_compressStream2(,,,ZSTD_e_end), + * this value is automatically overridden by srcSize instead. + */ +ZSTDLIB_API size_t ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx* cctx, unsigned long long pledgedSrcSize); + +typedef enum { + ZSTD_reset_session_only = 1, + ZSTD_reset_parameters = 2, + ZSTD_reset_session_and_parameters = 3 +} ZSTD_ResetDirective; + +/*! ZSTD_CCtx_reset() : + * There are 2 different things that can be reset, independently or jointly : + * - The session : will stop compressing current frame, and make CCtx ready to start a new one. + * Useful after an error, or to interrupt any ongoing compression. + * Any internal data not yet flushed is cancelled. + * Compression parameters and dictionary remain unchanged. + * They will be used to compress next frame. + * Resetting session never fails. + * - The parameters : changes all parameters back to "default". + * This also removes any reference to any dictionary or external sequence producer. + * Parameters can only be changed between 2 sessions (i.e. no compression is currently ongoing) + * otherwise the reset fails, and function returns an error value (which can be tested using ZSTD_isError()) + * - Both : similar to resetting the session, followed by resetting parameters. + */ +ZSTDLIB_API size_t ZSTD_CCtx_reset(ZSTD_CCtx* cctx, ZSTD_ResetDirective reset); + +/*! ZSTD_compress2() : + * Behave the same as ZSTD_compressCCtx(), but compression parameters are set using the advanced API. + * (note that this entry point doesn't even expose a compression level parameter). + * ZSTD_compress2() always starts a new frame. + * Should cctx hold data from a previously unfinished frame, everything about it is forgotten. + * - Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_set*() + * - The function is always blocking, returns when compression is completed. + * NOTE: Providing `dstCapacity >= ZSTD_compressBound(srcSize)` guarantees that zstd will have + * enough space to successfully compress the data, though it is possible it fails for other reasons. + * @return : compressed size written into `dst` (<= `dstCapacity), + * or an error code if it fails (which can be tested using ZSTD_isError()). + */ +ZSTDLIB_API size_t ZSTD_compress2( ZSTD_CCtx* cctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize); + + +/*********************************************** +* Advanced decompression API (Requires v1.4.0+) +************************************************/ + +/* The advanced API pushes parameters one by one into an existing DCtx context. + * Parameters are sticky, and remain valid for all following frames + * using the same DCtx context. + * It's possible to reset parameters to default values using ZSTD_DCtx_reset(). + * Note : This API is compatible with existing ZSTD_decompressDCtx() and ZSTD_decompressStream(). + * Therefore, no new decompression function is necessary. + */ + +typedef enum { + + ZSTD_d_windowLogMax=100, /* Select a size limit (in power of 2) beyond which + * the streaming API will refuse to allocate memory buffer + * in order to protect the host from unreasonable memory requirements. + * This parameter is only useful in streaming mode, since no internal buffer is allocated in single-pass mode. + * By default, a decompression context accepts window sizes <= (1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT). + * Special: value 0 means "use default maximum windowLog". */ + + /* note : additional experimental parameters are also available + * within the experimental section of the API. + * At the time of this writing, they include : + * ZSTD_d_format + * ZSTD_d_stableOutBuffer + * ZSTD_d_forceIgnoreChecksum + * ZSTD_d_refMultipleDDicts + * ZSTD_d_disableHuffmanAssembly + * ZSTD_d_maxBlockSize + * Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them. + * note : never ever use experimentalParam? names directly + */ + ZSTD_d_experimentalParam1=1000, + ZSTD_d_experimentalParam2=1001, + ZSTD_d_experimentalParam3=1002, + ZSTD_d_experimentalParam4=1003, + ZSTD_d_experimentalParam5=1004, + ZSTD_d_experimentalParam6=1005 + +} ZSTD_dParameter; + +/*! ZSTD_dParam_getBounds() : + * All parameters must belong to an interval with lower and upper bounds, + * otherwise they will either trigger an error or be automatically clamped. + * @return : a structure, ZSTD_bounds, which contains + * - an error status field, which must be tested using ZSTD_isError() + * - both lower and upper bounds, inclusive + */ +ZSTDLIB_API ZSTD_bounds ZSTD_dParam_getBounds(ZSTD_dParameter dParam); + +/*! ZSTD_DCtx_setParameter() : + * Set one compression parameter, selected by enum ZSTD_dParameter. + * All parameters have valid bounds. Bounds can be queried using ZSTD_dParam_getBounds(). + * Providing a value beyond bound will either clamp it, or trigger an error (depending on parameter). + * Setting a parameter is only possible during frame initialization (before starting decompression). + * @return : 0, or an error code (which can be tested using ZSTD_isError()). + */ +ZSTDLIB_API size_t ZSTD_DCtx_setParameter(ZSTD_DCtx* dctx, ZSTD_dParameter param, int value); + +/*! ZSTD_DCtx_reset() : + * Return a DCtx to clean state. + * Session and parameters can be reset jointly or separately. + * Parameters can only be reset when no active frame is being decompressed. + * @return : 0, or an error code, which can be tested with ZSTD_isError() + */ +ZSTDLIB_API size_t ZSTD_DCtx_reset(ZSTD_DCtx* dctx, ZSTD_ResetDirective reset); + + +/**************************** +* Streaming +****************************/ + +typedef struct ZSTD_inBuffer_s { + const void* src; /**< start of input buffer */ + size_t size; /**< size of input buffer */ + size_t pos; /**< position where reading stopped. Will be updated. Necessarily 0 <= pos <= size */ +} ZSTD_inBuffer; + +typedef struct ZSTD_outBuffer_s { + void* dst; /**< start of output buffer */ + size_t size; /**< size of output buffer */ + size_t pos; /**< position where writing stopped. Will be updated. Necessarily 0 <= pos <= size */ +} ZSTD_outBuffer; + + + +/*-*********************************************************************** +* Streaming compression - HowTo +* +* A ZSTD_CStream object is required to track streaming operation. +* Use ZSTD_createCStream() and ZSTD_freeCStream() to create/release resources. +* ZSTD_CStream objects can be reused multiple times on consecutive compression operations. +* It is recommended to reuse ZSTD_CStream since it will play nicer with system's memory, by re-using already allocated memory. +* +* For parallel execution, use one separate ZSTD_CStream per thread. +* +* note : since v1.3.0, ZSTD_CStream and ZSTD_CCtx are the same thing. +* +* Parameters are sticky : when starting a new compression on the same context, +* it will reuse the same sticky parameters as previous compression session. +* When in doubt, it's recommended to fully initialize the context before usage. +* Use ZSTD_CCtx_reset() to reset the context and ZSTD_CCtx_setParameter(), +* ZSTD_CCtx_setPledgedSrcSize(), or ZSTD_CCtx_loadDictionary() and friends to +* set more specific parameters, the pledged source size, or load a dictionary. +* +* Use ZSTD_compressStream2() with ZSTD_e_continue as many times as necessary to +* consume input stream. The function will automatically update both `pos` +* fields within `input` and `output`. +* Note that the function may not consume the entire input, for example, because +* the output buffer is already full, in which case `input.pos < input.size`. +* The caller must check if input has been entirely consumed. +* If not, the caller must make some room to receive more compressed data, +* and then present again remaining input data. +* note: ZSTD_e_continue is guaranteed to make some forward progress when called, +* but doesn't guarantee maximal forward progress. This is especially relevant +* when compressing with multiple threads. The call won't block if it can +* consume some input, but if it can't it will wait for some, but not all, +* output to be flushed. +* @return : provides a minimum amount of data remaining to be flushed from internal buffers +* or an error code, which can be tested using ZSTD_isError(). +* +* At any moment, it's possible to flush whatever data might remain stuck within internal buffer, +* using ZSTD_compressStream2() with ZSTD_e_flush. `output->pos` will be updated. +* Note that, if `output->size` is too small, a single invocation with ZSTD_e_flush might not be enough (return code > 0). +* In which case, make some room to receive more compressed data, and call again ZSTD_compressStream2() with ZSTD_e_flush. +* You must continue calling ZSTD_compressStream2() with ZSTD_e_flush until it returns 0, at which point you can change the +* operation. +* note: ZSTD_e_flush will flush as much output as possible, meaning when compressing with multiple threads, it will +* block until the flush is complete or the output buffer is full. +* @return : 0 if internal buffers are entirely flushed, +* >0 if some data still present within internal buffer (the value is minimal estimation of remaining size), +* or an error code, which can be tested using ZSTD_isError(). +* +* Calling ZSTD_compressStream2() with ZSTD_e_end instructs to finish a frame. +* It will perform a flush and write frame epilogue. +* The epilogue is required for decoders to consider a frame completed. +* flush operation is the same, and follows same rules as calling ZSTD_compressStream2() with ZSTD_e_flush. +* You must continue calling ZSTD_compressStream2() with ZSTD_e_end until it returns 0, at which point you are free to +* start a new frame. +* note: ZSTD_e_end will flush as much output as possible, meaning when compressing with multiple threads, it will +* block until the flush is complete or the output buffer is full. +* @return : 0 if frame fully completed and fully flushed, +* >0 if some data still present within internal buffer (the value is minimal estimation of remaining size), +* or an error code, which can be tested using ZSTD_isError(). +* +* *******************************************************************/ + +typedef ZSTD_CCtx ZSTD_CStream; /**< CCtx and CStream are now effectively same object (>= v1.3.0) */ + /* Continue to distinguish them for compatibility with older versions <= v1.2.0 */ +/*===== ZSTD_CStream management functions =====*/ +ZSTDLIB_API ZSTD_CStream* ZSTD_createCStream(void); +ZSTDLIB_API size_t ZSTD_freeCStream(ZSTD_CStream* zcs); /* accept NULL pointer */ + +/*===== Streaming compression functions =====*/ +typedef enum { + ZSTD_e_continue=0, /* collect more data, encoder decides when to output compressed result, for optimal compression ratio */ + ZSTD_e_flush=1, /* flush any data provided so far, + * it creates (at least) one new block, that can be decoded immediately on reception; + * frame will continue: any future data can still reference previously compressed data, improving compression. + * note : multithreaded compression will block to flush as much output as possible. */ + ZSTD_e_end=2 /* flush any remaining data _and_ close current frame. + * note that frame is only closed after compressed data is fully flushed (return value == 0). + * After that point, any additional data starts a new frame. + * note : each frame is independent (does not reference any content from previous frame). + : note : multithreaded compression will block to flush as much output as possible. */ +} ZSTD_EndDirective; + +/*! ZSTD_compressStream2() : Requires v1.4.0+ + * Behaves about the same as ZSTD_compressStream, with additional control on end directive. + * - Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_set*() + * - Compression parameters cannot be changed once compression is started (save a list of exceptions in multi-threading mode) + * - output->pos must be <= dstCapacity, input->pos must be <= srcSize + * - output->pos and input->pos will be updated. They are guaranteed to remain below their respective limit. + * - endOp must be a valid directive + * - When nbWorkers==0 (default), function is blocking : it completes its job before returning to caller. + * - When nbWorkers>=1, function is non-blocking : it copies a portion of input, distributes jobs to internal worker threads, flush to output whatever is available, + * and then immediately returns, just indicating that there is some data remaining to be flushed. + * The function nonetheless guarantees forward progress : it will return only after it reads or write at least 1+ byte. + * - Exception : if the first call requests a ZSTD_e_end directive and provides enough dstCapacity, the function delegates to ZSTD_compress2() which is always blocking. + * - @return provides a minimum amount of data remaining to be flushed from internal buffers + * or an error code, which can be tested using ZSTD_isError(). + * if @return != 0, flush is not fully completed, there is still some data left within internal buffers. + * This is useful for ZSTD_e_flush, since in this case more flushes are necessary to empty all buffers. + * For ZSTD_e_end, @return == 0 when internal buffers are fully flushed and frame is completed. + * - after a ZSTD_e_end directive, if internal buffer is not fully flushed (@return != 0), + * only ZSTD_e_end or ZSTD_e_flush operations are allowed. + * Before starting a new compression job, or changing compression parameters, + * it is required to fully flush internal buffers. + * - note: if an operation ends with an error, it may leave @cctx in an undefined state. + * Therefore, it's UB to invoke ZSTD_compressStream2() of ZSTD_compressStream() on such a state. + * In order to be re-employed after an error, a state must be reset, + * which can be done explicitly (ZSTD_CCtx_reset()), + * or is sometimes implied by methods starting a new compression job (ZSTD_initCStream(), ZSTD_compressCCtx()) + */ +ZSTDLIB_API size_t ZSTD_compressStream2( ZSTD_CCtx* cctx, + ZSTD_outBuffer* output, + ZSTD_inBuffer* input, + ZSTD_EndDirective endOp); + + +/* These buffer sizes are softly recommended. + * They are not required : ZSTD_compressStream*() happily accepts any buffer size, for both input and output. + * Respecting the recommended size just makes it a bit easier for ZSTD_compressStream*(), + * reducing the amount of memory shuffling and buffering, resulting in minor performance savings. + * + * However, note that these recommendations are from the perspective of a C caller program. + * If the streaming interface is invoked from some other language, + * especially managed ones such as Java or Go, through a foreign function interface such as jni or cgo, + * a major performance rule is to reduce crossing such interface to an absolute minimum. + * It's not rare that performance ends being spent more into the interface, rather than compression itself. + * In which cases, prefer using large buffers, as large as practical, + * for both input and output, to reduce the nb of roundtrips. + */ +ZSTDLIB_API size_t ZSTD_CStreamInSize(void); /**< recommended size for input buffer */ +ZSTDLIB_API size_t ZSTD_CStreamOutSize(void); /**< recommended size for output buffer. Guarantee to successfully flush at least one complete compressed block. */ + + +/* ***************************************************************************** + * This following is a legacy streaming API, available since v1.0+ . + * It can be replaced by ZSTD_CCtx_reset() and ZSTD_compressStream2(). + * It is redundant, but remains fully supported. + ******************************************************************************/ + +/*! + * Equivalent to: + * + * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); + * ZSTD_CCtx_refCDict(zcs, NULL); // clear the dictionary (if any) + * ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel); + * + * Note that ZSTD_initCStream() clears any previously set dictionary. Use the new API + * to compress with a dictionary. + */ +ZSTDLIB_API size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel); +/*! + * Alternative for ZSTD_compressStream2(zcs, output, input, ZSTD_e_continue). + * NOTE: The return value is different. ZSTD_compressStream() returns a hint for + * the next read size (if non-zero and not an error). ZSTD_compressStream2() + * returns the minimum nb of bytes left to flush (if non-zero and not an error). + */ +ZSTDLIB_API size_t ZSTD_compressStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output, ZSTD_inBuffer* input); +/*! Equivalent to ZSTD_compressStream2(zcs, output, &emptyInput, ZSTD_e_flush). */ +ZSTDLIB_API size_t ZSTD_flushStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output); +/*! Equivalent to ZSTD_compressStream2(zcs, output, &emptyInput, ZSTD_e_end). */ +ZSTDLIB_API size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output); + + +/*-*************************************************************************** +* Streaming decompression - HowTo +* +* A ZSTD_DStream object is required to track streaming operations. +* Use ZSTD_createDStream() and ZSTD_freeDStream() to create/release resources. +* ZSTD_DStream objects can be re-employed multiple times. +* +* Use ZSTD_initDStream() to start a new decompression operation. +* @return : recommended first input size +* Alternatively, use advanced API to set specific properties. +* +* Use ZSTD_decompressStream() repetitively to consume your input. +* The function will update both `pos` fields. +* If `input.pos < input.size`, some input has not been consumed. +* It's up to the caller to present again remaining data. +* +* The function tries to flush all data decoded immediately, respecting output buffer size. +* If `output.pos < output.size`, decoder has flushed everything it could. +* +* However, when `output.pos == output.size`, it's more difficult to know. +* If @return > 0, the frame is not complete, meaning +* either there is still some data left to flush within internal buffers, +* or there is more input to read to complete the frame (or both). +* In which case, call ZSTD_decompressStream() again to flush whatever remains in the buffer. +* Note : with no additional input provided, amount of data flushed is necessarily <= ZSTD_BLOCKSIZE_MAX. +* @return : 0 when a frame is completely decoded and fully flushed, +* or an error code, which can be tested using ZSTD_isError(), +* or any other value > 0, which means there is still some decoding or flushing to do to complete current frame : +* the return value is a suggested next input size (just a hint for better latency) +* that will never request more than the remaining content of the compressed frame. +* *******************************************************************************/ + +typedef ZSTD_DCtx ZSTD_DStream; /**< DCtx and DStream are now effectively same object (>= v1.3.0) */ + /* For compatibility with versions <= v1.2.0, prefer differentiating them. */ +/*===== ZSTD_DStream management functions =====*/ +ZSTDLIB_API ZSTD_DStream* ZSTD_createDStream(void); +ZSTDLIB_API size_t ZSTD_freeDStream(ZSTD_DStream* zds); /* accept NULL pointer */ + +/*===== Streaming decompression functions =====*/ + +/*! ZSTD_initDStream() : + * Initialize/reset DStream state for new decompression operation. + * Call before new decompression operation using same DStream. + * + * Note : This function is redundant with the advanced API and equivalent to: + * ZSTD_DCtx_reset(zds, ZSTD_reset_session_only); + * ZSTD_DCtx_refDDict(zds, NULL); + */ +ZSTDLIB_API size_t ZSTD_initDStream(ZSTD_DStream* zds); + +/*! ZSTD_decompressStream() : + * Streaming decompression function. + * Call repetitively to consume full input updating it as necessary. + * Function will update both input and output `pos` fields exposing current state via these fields: + * - `input.pos < input.size`, some input remaining and caller should provide remaining input + * on the next call. + * - `output.pos < output.size`, decoder flushed internal output buffer. + * - `output.pos == output.size`, unflushed data potentially present in the internal buffers, + * check ZSTD_decompressStream() @return value, + * if > 0, invoke it again to flush remaining data to output. + * Note : with no additional input, amount of data flushed <= ZSTD_BLOCKSIZE_MAX. + * + * @return : 0 when a frame is completely decoded and fully flushed, + * or an error code, which can be tested using ZSTD_isError(), + * or any other value > 0, which means there is some decoding or flushing to do to complete current frame. + * + * Note: when an operation returns with an error code, the @zds state may be left in undefined state. + * It's UB to invoke `ZSTD_decompressStream()` on such a state. + * In order to re-use such a state, it must be first reset, + * which can be done explicitly (`ZSTD_DCtx_reset()`), + * or is implied for operations starting some new decompression job (`ZSTD_initDStream`, `ZSTD_decompressDCtx()`, `ZSTD_decompress_usingDict()`) + */ +ZSTDLIB_API size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input); + +ZSTDLIB_API size_t ZSTD_DStreamInSize(void); /*!< recommended size for input buffer */ +ZSTDLIB_API size_t ZSTD_DStreamOutSize(void); /*!< recommended size for output buffer. Guarantee to successfully flush at least one complete block in all circumstances. */ + + +/************************** +* Simple dictionary API +***************************/ +/*! ZSTD_compress_usingDict() : + * Compression at an explicit compression level using a Dictionary. + * A dictionary can be any arbitrary data segment (also called a prefix), + * or a buffer with specified information (see zdict.h). + * Note : This function loads the dictionary, resulting in significant startup delay. + * It's intended for a dictionary used only once. + * Note 2 : When `dict == NULL || dictSize < 8` no dictionary is used. */ +ZSTDLIB_API size_t ZSTD_compress_usingDict(ZSTD_CCtx* ctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const void* dict,size_t dictSize, + int compressionLevel); + +/*! ZSTD_decompress_usingDict() : + * Decompression using a known Dictionary. + * Dictionary must be identical to the one used during compression. + * Note : This function loads the dictionary, resulting in significant startup delay. + * It's intended for a dictionary used only once. + * Note : When `dict == NULL || dictSize < 8` no dictionary is used. */ +ZSTDLIB_API size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const void* dict,size_t dictSize); + + +/*********************************** + * Bulk processing dictionary API + **********************************/ +typedef struct ZSTD_CDict_s ZSTD_CDict; + +/*! ZSTD_createCDict() : + * When compressing multiple messages or blocks using the same dictionary, + * it's recommended to digest the dictionary only once, since it's a costly operation. + * ZSTD_createCDict() will create a state from digesting a dictionary. + * The resulting state can be used for future compression operations with very limited startup cost. + * ZSTD_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only. + * @dictBuffer can be released after ZSTD_CDict creation, because its content is copied within CDict. + * Note 1 : Consider experimental function `ZSTD_createCDict_byReference()` if you prefer to not duplicate @dictBuffer content. + * Note 2 : A ZSTD_CDict can be created from an empty @dictBuffer, + * in which case the only thing that it transports is the @compressionLevel. + * This can be useful in a pipeline featuring ZSTD_compress_usingCDict() exclusively, + * expecting a ZSTD_CDict parameter with any data, including those without a known dictionary. */ +ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict(const void* dictBuffer, size_t dictSize, + int compressionLevel); + +/*! ZSTD_freeCDict() : + * Function frees memory allocated by ZSTD_createCDict(). + * If a NULL pointer is passed, no operation is performed. */ +ZSTDLIB_API size_t ZSTD_freeCDict(ZSTD_CDict* CDict); + +/*! ZSTD_compress_usingCDict() : + * Compression using a digested Dictionary. + * Recommended when same dictionary is used multiple times. + * Note : compression level is _decided at dictionary creation time_, + * and frame parameters are hardcoded (dictID=yes, contentSize=yes, checksum=no) */ +ZSTDLIB_API size_t ZSTD_compress_usingCDict(ZSTD_CCtx* cctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const ZSTD_CDict* cdict); + + +typedef struct ZSTD_DDict_s ZSTD_DDict; + +/*! ZSTD_createDDict() : + * Create a digested dictionary, ready to start decompression operation without startup delay. + * dictBuffer can be released after DDict creation, as its content is copied inside DDict. */ +ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict(const void* dictBuffer, size_t dictSize); + +/*! ZSTD_freeDDict() : + * Function frees memory allocated with ZSTD_createDDict() + * If a NULL pointer is passed, no operation is performed. */ +ZSTDLIB_API size_t ZSTD_freeDDict(ZSTD_DDict* ddict); + +/*! ZSTD_decompress_usingDDict() : + * Decompression using a digested Dictionary. + * Recommended when same dictionary is used multiple times. */ +ZSTDLIB_API size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const ZSTD_DDict* ddict); + + +/******************************** + * Dictionary helper functions + *******************************/ + +/*! ZSTD_getDictID_fromDict() : Requires v1.4.0+ + * Provides the dictID stored within dictionary. + * if @return == 0, the dictionary is not conformant with Zstandard specification. + * It can still be loaded, but as a content-only dictionary. */ +ZSTDLIB_API unsigned ZSTD_getDictID_fromDict(const void* dict, size_t dictSize); + +/*! ZSTD_getDictID_fromCDict() : Requires v1.5.0+ + * Provides the dictID of the dictionary loaded into `cdict`. + * If @return == 0, the dictionary is not conformant to Zstandard specification, or empty. + * Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */ +ZSTDLIB_API unsigned ZSTD_getDictID_fromCDict(const ZSTD_CDict* cdict); + +/*! ZSTD_getDictID_fromDDict() : Requires v1.4.0+ + * Provides the dictID of the dictionary loaded into `ddict`. + * If @return == 0, the dictionary is not conformant to Zstandard specification, or empty. + * Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */ +ZSTDLIB_API unsigned ZSTD_getDictID_fromDDict(const ZSTD_DDict* ddict); + +/*! ZSTD_getDictID_fromFrame() : Requires v1.4.0+ + * Provides the dictID required to decompressed the frame stored within `src`. + * If @return == 0, the dictID could not be decoded. + * This could for one of the following reasons : + * - The frame does not require a dictionary to be decoded (most common case). + * - The frame was built with dictID intentionally removed. Whatever dictionary is necessary is a hidden piece of information. + * Note : this use case also happens when using a non-conformant dictionary. + * - `srcSize` is too small, and as a result, the frame header could not be decoded (only possible if `srcSize < ZSTD_FRAMEHEADERSIZE_MAX`). + * - This is not a Zstandard frame. + * When identifying the exact failure cause, it's possible to use ZSTD_getFrameHeader(), which will provide a more precise error code. */ +ZSTDLIB_API unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize); + + +/******************************************************************************* + * Advanced dictionary and prefix API (Requires v1.4.0+) + * + * This API allows dictionaries to be used with ZSTD_compress2(), + * ZSTD_compressStream2(), and ZSTD_decompressDCtx(). + * Dictionaries are sticky, they remain valid when same context is reused, + * they only reset when the context is reset + * with ZSTD_reset_parameters or ZSTD_reset_session_and_parameters. + * In contrast, Prefixes are single-use. + ******************************************************************************/ + + +/*! ZSTD_CCtx_loadDictionary() : Requires v1.4.0+ + * Create an internal CDict from `dict` buffer. + * Decompression will have to use same dictionary. + * @result : 0, or an error code (which can be tested with ZSTD_isError()). + * Special: Loading a NULL (or 0-size) dictionary invalidates previous dictionary, + * meaning "return to no-dictionary mode". + * Note 1 : Dictionary is sticky, it will be used for all future compressed frames, + * until parameters are reset, a new dictionary is loaded, or the dictionary + * is explicitly invalidated by loading a NULL dictionary. + * Note 2 : Loading a dictionary involves building tables. + * It's also a CPU consuming operation, with non-negligible impact on latency. + * Tables are dependent on compression parameters, and for this reason, + * compression parameters can no longer be changed after loading a dictionary. + * Note 3 :`dict` content will be copied internally. + * Use experimental ZSTD_CCtx_loadDictionary_byReference() to reference content instead. + * In such a case, dictionary buffer must outlive its users. + * Note 4 : Use ZSTD_CCtx_loadDictionary_advanced() + * to precisely select how dictionary content must be interpreted. + * Note 5 : This method does not benefit from LDM (long distance mode). + * If you want to employ LDM on some large dictionary content, + * prefer employing ZSTD_CCtx_refPrefix() described below. + */ +ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary(ZSTD_CCtx* cctx, const void* dict, size_t dictSize); + +/*! ZSTD_CCtx_refCDict() : Requires v1.4.0+ + * Reference a prepared dictionary, to be used for all future compressed frames. + * Note that compression parameters are enforced from within CDict, + * and supersede any compression parameter previously set within CCtx. + * The parameters ignored are labelled as "superseded-by-cdict" in the ZSTD_cParameter enum docs. + * The ignored parameters will be used again if the CCtx is returned to no-dictionary mode. + * The dictionary will remain valid for future compressed frames using same CCtx. + * @result : 0, or an error code (which can be tested with ZSTD_isError()). + * Special : Referencing a NULL CDict means "return to no-dictionary mode". + * Note 1 : Currently, only one dictionary can be managed. + * Referencing a new dictionary effectively "discards" any previous one. + * Note 2 : CDict is just referenced, its lifetime must outlive its usage within CCtx. */ +ZSTDLIB_API size_t ZSTD_CCtx_refCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict); + +/*! ZSTD_CCtx_refPrefix() : Requires v1.4.0+ + * Reference a prefix (single-usage dictionary) for next compressed frame. + * A prefix is **only used once**. Tables are discarded at end of frame (ZSTD_e_end). + * Decompression will need same prefix to properly regenerate data. + * Compressing with a prefix is similar in outcome as performing a diff and compressing it, + * but performs much faster, especially during decompression (compression speed is tunable with compression level). + * This method is compatible with LDM (long distance mode). + * @result : 0, or an error code (which can be tested with ZSTD_isError()). + * Special: Adding any prefix (including NULL) invalidates any previous prefix or dictionary + * Note 1 : Prefix buffer is referenced. It **must** outlive compression. + * Its content must remain unmodified during compression. + * Note 2 : If the intention is to diff some large src data blob with some prior version of itself, + * ensure that the window size is large enough to contain the entire source. + * See ZSTD_c_windowLog. + * Note 3 : Referencing a prefix involves building tables, which are dependent on compression parameters. + * It's a CPU consuming operation, with non-negligible impact on latency. + * If there is a need to use the same prefix multiple times, consider loadDictionary instead. + * Note 4 : By default, the prefix is interpreted as raw content (ZSTD_dct_rawContent). + * Use experimental ZSTD_CCtx_refPrefix_advanced() to alter dictionary interpretation. */ +ZSTDLIB_API size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx, + const void* prefix, size_t prefixSize); + +/*! ZSTD_DCtx_loadDictionary() : Requires v1.4.0+ + * Create an internal DDict from dict buffer, to be used to decompress all future frames. + * The dictionary remains valid for all future frames, until explicitly invalidated, or + * a new dictionary is loaded. + * @result : 0, or an error code (which can be tested with ZSTD_isError()). + * Special : Adding a NULL (or 0-size) dictionary invalidates any previous dictionary, + * meaning "return to no-dictionary mode". + * Note 1 : Loading a dictionary involves building tables, + * which has a non-negligible impact on CPU usage and latency. + * It's recommended to "load once, use many times", to amortize the cost + * Note 2 :`dict` content will be copied internally, so `dict` can be released after loading. + * Use ZSTD_DCtx_loadDictionary_byReference() to reference dictionary content instead. + * Note 3 : Use ZSTD_DCtx_loadDictionary_advanced() to take control of + * how dictionary content is loaded and interpreted. + */ +ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize); + +/*! ZSTD_DCtx_refDDict() : Requires v1.4.0+ + * Reference a prepared dictionary, to be used to decompress next frames. + * The dictionary remains active for decompression of future frames using same DCtx. + * + * If called with ZSTD_d_refMultipleDDicts enabled, repeated calls of this function + * will store the DDict references in a table, and the DDict used for decompression + * will be determined at decompression time, as per the dict ID in the frame. + * The memory for the table is allocated on the first call to refDDict, and can be + * freed with ZSTD_freeDCtx(). + * + * If called with ZSTD_d_refMultipleDDicts disabled (the default), only one dictionary + * will be managed, and referencing a dictionary effectively "discards" any previous one. + * + * @result : 0, or an error code (which can be tested with ZSTD_isError()). + * Special: referencing a NULL DDict means "return to no-dictionary mode". + * Note 2 : DDict is just referenced, its lifetime must outlive its usage from DCtx. + */ +ZSTDLIB_API size_t ZSTD_DCtx_refDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict); + +/*! ZSTD_DCtx_refPrefix() : Requires v1.4.0+ + * Reference a prefix (single-usage dictionary) to decompress next frame. + * This is the reverse operation of ZSTD_CCtx_refPrefix(), + * and must use the same prefix as the one used during compression. + * Prefix is **only used once**. Reference is discarded at end of frame. + * End of frame is reached when ZSTD_decompressStream() returns 0. + * @result : 0, or an error code (which can be tested with ZSTD_isError()). + * Note 1 : Adding any prefix (including NULL) invalidates any previously set prefix or dictionary + * Note 2 : Prefix buffer is referenced. It **must** outlive decompression. + * Prefix buffer must remain unmodified up to the end of frame, + * reached when ZSTD_decompressStream() returns 0. + * Note 3 : By default, the prefix is treated as raw content (ZSTD_dct_rawContent). + * Use ZSTD_CCtx_refPrefix_advanced() to alter dictMode (Experimental section) + * Note 4 : Referencing a raw content prefix has almost no cpu nor memory cost. + * A full dictionary is more costly, as it requires building tables. + */ +ZSTDLIB_API size_t ZSTD_DCtx_refPrefix(ZSTD_DCtx* dctx, + const void* prefix, size_t prefixSize); + +/* === Memory management === */ + +/*! ZSTD_sizeof_*() : Requires v1.4.0+ + * These functions give the _current_ memory usage of selected object. + * Note that object memory usage can evolve (increase or decrease) over time. */ +ZSTDLIB_API size_t ZSTD_sizeof_CCtx(const ZSTD_CCtx* cctx); +ZSTDLIB_API size_t ZSTD_sizeof_DCtx(const ZSTD_DCtx* dctx); +ZSTDLIB_API size_t ZSTD_sizeof_CStream(const ZSTD_CStream* zcs); +ZSTDLIB_API size_t ZSTD_sizeof_DStream(const ZSTD_DStream* zds); +ZSTDLIB_API size_t ZSTD_sizeof_CDict(const ZSTD_CDict* cdict); +ZSTDLIB_API size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict); + +#if defined (__cplusplus) +} +#endif + +#endif /* ZSTD_H_235446 */ + + +/* ************************************************************************************** + * ADVANCED AND EXPERIMENTAL FUNCTIONS + **************************************************************************************** + * The definitions in the following section are considered experimental. + * They are provided for advanced scenarios. + * They should never be used with a dynamic library, as prototypes may change in the future. + * Use them only in association with static linking. + * ***************************************************************************************/ + +#if defined(ZSTD_STATIC_LINKING_ONLY) && !defined(ZSTD_H_ZSTD_STATIC_LINKING_ONLY) +#define ZSTD_H_ZSTD_STATIC_LINKING_ONLY + +#if defined (__cplusplus) +extern "C" { +#endif + +/* This can be overridden externally to hide static symbols. */ +#ifndef ZSTDLIB_STATIC_API +# if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1) +# define ZSTDLIB_STATIC_API __declspec(dllexport) ZSTDLIB_VISIBLE +# elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1) +# define ZSTDLIB_STATIC_API __declspec(dllimport) ZSTDLIB_VISIBLE +# else +# define ZSTDLIB_STATIC_API ZSTDLIB_VISIBLE +# endif +#endif + +/**************************************************************************************** + * experimental API (static linking only) + **************************************************************************************** + * The following symbols and constants + * are not planned to join "stable API" status in the near future. + * They can still change in future versions. + * Some of them are planned to remain in the static_only section indefinitely. + * Some of them might be removed in the future (especially when redundant with existing stable functions) + * ***************************************************************************************/ + +#define ZSTD_FRAMEHEADERSIZE_PREFIX(format) ((format) == ZSTD_f_zstd1 ? 5 : 1) /* minimum input size required to query frame header size */ +#define ZSTD_FRAMEHEADERSIZE_MIN(format) ((format) == ZSTD_f_zstd1 ? 6 : 2) +#define ZSTD_FRAMEHEADERSIZE_MAX 18 /* can be useful for static allocation */ +#define ZSTD_SKIPPABLEHEADERSIZE 8 + +/* compression parameter bounds */ +#define ZSTD_WINDOWLOG_MAX_32 30 +#define ZSTD_WINDOWLOG_MAX_64 31 +#define ZSTD_WINDOWLOG_MAX ((int)(sizeof(size_t) == 4 ? ZSTD_WINDOWLOG_MAX_32 : ZSTD_WINDOWLOG_MAX_64)) +#define ZSTD_WINDOWLOG_MIN 10 +#define ZSTD_HASHLOG_MAX ((ZSTD_WINDOWLOG_MAX < 30) ? ZSTD_WINDOWLOG_MAX : 30) +#define ZSTD_HASHLOG_MIN 6 +#define ZSTD_CHAINLOG_MAX_32 29 +#define ZSTD_CHAINLOG_MAX_64 30 +#define ZSTD_CHAINLOG_MAX ((int)(sizeof(size_t) == 4 ? ZSTD_CHAINLOG_MAX_32 : ZSTD_CHAINLOG_MAX_64)) +#define ZSTD_CHAINLOG_MIN ZSTD_HASHLOG_MIN +#define ZSTD_SEARCHLOG_MAX (ZSTD_WINDOWLOG_MAX-1) +#define ZSTD_SEARCHLOG_MIN 1 +#define ZSTD_MINMATCH_MAX 7 /* only for ZSTD_fast, other strategies are limited to 6 */ +#define ZSTD_MINMATCH_MIN 3 /* only for ZSTD_btopt+, faster strategies are limited to 4 */ +#define ZSTD_TARGETLENGTH_MAX ZSTD_BLOCKSIZE_MAX +#define ZSTD_TARGETLENGTH_MIN 0 /* note : comparing this constant to an unsigned results in a tautological test */ +#define ZSTD_STRATEGY_MIN ZSTD_fast +#define ZSTD_STRATEGY_MAX ZSTD_btultra2 +#define ZSTD_BLOCKSIZE_MAX_MIN (1 << 10) /* The minimum valid max blocksize. Maximum blocksizes smaller than this make compressBound() inaccurate. */ + + +#define ZSTD_OVERLAPLOG_MIN 0 +#define ZSTD_OVERLAPLOG_MAX 9 + +#define ZSTD_WINDOWLOG_LIMIT_DEFAULT 27 /* by default, the streaming decoder will refuse any frame + * requiring larger than (1< 0: + * If litLength != 0: + * rep == 1 --> offset == repeat_offset_1 + * rep == 2 --> offset == repeat_offset_2 + * rep == 3 --> offset == repeat_offset_3 + * If litLength == 0: + * rep == 1 --> offset == repeat_offset_2 + * rep == 2 --> offset == repeat_offset_3 + * rep == 3 --> offset == repeat_offset_1 - 1 + * + * Note: This field is optional. ZSTD_generateSequences() will calculate the value of + * 'rep', but repeat offsets do not necessarily need to be calculated from an external + * sequence provider perspective. For example, ZSTD_compressSequences() does not + * use this 'rep' field at all (as of now). + */ +} ZSTD_Sequence; + +typedef struct { + unsigned windowLog; /**< largest match distance : larger == more compression, more memory needed during decompression */ + unsigned chainLog; /**< fully searched segment : larger == more compression, slower, more memory (useless for fast) */ + unsigned hashLog; /**< dispatch table : larger == faster, more memory */ + unsigned searchLog; /**< nb of searches : larger == more compression, slower */ + unsigned minMatch; /**< match length searched : larger == faster decompression, sometimes less compression */ + unsigned targetLength; /**< acceptable match size for optimal parser (only) : larger == more compression, slower */ + ZSTD_strategy strategy; /**< see ZSTD_strategy definition above */ +} ZSTD_compressionParameters; + +typedef struct { + int contentSizeFlag; /**< 1: content size will be in frame header (when known) */ + int checksumFlag; /**< 1: generate a 32-bits checksum using XXH64 algorithm at end of frame, for error detection */ + int noDictIDFlag; /**< 1: no dictID will be saved into frame header (dictID is only useful for dictionary compression) */ +} ZSTD_frameParameters; + +typedef struct { + ZSTD_compressionParameters cParams; + ZSTD_frameParameters fParams; +} ZSTD_parameters; + +typedef enum { + ZSTD_dct_auto = 0, /* dictionary is "full" when starting with ZSTD_MAGIC_DICTIONARY, otherwise it is "rawContent" */ + ZSTD_dct_rawContent = 1, /* ensures dictionary is always loaded as rawContent, even if it starts with ZSTD_MAGIC_DICTIONARY */ + ZSTD_dct_fullDict = 2 /* refuses to load a dictionary if it does not respect Zstandard's specification, starting with ZSTD_MAGIC_DICTIONARY */ +} ZSTD_dictContentType_e; + +typedef enum { + ZSTD_dlm_byCopy = 0, /**< Copy dictionary content internally */ + ZSTD_dlm_byRef = 1 /**< Reference dictionary content -- the dictionary buffer must outlive its users. */ +} ZSTD_dictLoadMethod_e; + +typedef enum { + ZSTD_f_zstd1 = 0, /* zstd frame format, specified in zstd_compression_format.md (default) */ + ZSTD_f_zstd1_magicless = 1 /* Variant of zstd frame format, without initial 4-bytes magic number. + * Useful to save 4 bytes per generated frame. + * Decoder cannot recognise automatically this format, requiring this instruction. */ +} ZSTD_format_e; + +typedef enum { + /* Note: this enum controls ZSTD_d_forceIgnoreChecksum */ + ZSTD_d_validateChecksum = 0, + ZSTD_d_ignoreChecksum = 1 +} ZSTD_forceIgnoreChecksum_e; + +typedef enum { + /* Note: this enum controls ZSTD_d_refMultipleDDicts */ + ZSTD_rmd_refSingleDDict = 0, + ZSTD_rmd_refMultipleDDicts = 1 +} ZSTD_refMultipleDDicts_e; + +typedef enum { + /* Note: this enum and the behavior it controls are effectively internal + * implementation details of the compressor. They are expected to continue + * to evolve and should be considered only in the context of extremely + * advanced performance tuning. + * + * Zstd currently supports the use of a CDict in three ways: + * + * - The contents of the CDict can be copied into the working context. This + * means that the compression can search both the dictionary and input + * while operating on a single set of internal tables. This makes + * the compression faster per-byte of input. However, the initial copy of + * the CDict's tables incurs a fixed cost at the beginning of the + * compression. For small compressions (< 8 KB), that copy can dominate + * the cost of the compression. + * + * - The CDict's tables can be used in-place. In this model, compression is + * slower per input byte, because the compressor has to search two sets of + * tables. However, this model incurs no start-up cost (as long as the + * working context's tables can be reused). For small inputs, this can be + * faster than copying the CDict's tables. + * + * - The CDict's tables are not used at all, and instead we use the working + * context alone to reload the dictionary and use params based on the source + * size. See ZSTD_compress_insertDictionary() and ZSTD_compress_usingDict(). + * This method is effective when the dictionary sizes are very small relative + * to the input size, and the input size is fairly large to begin with. + * + * Zstd has a simple internal heuristic that selects which strategy to use + * at the beginning of a compression. However, if experimentation shows that + * Zstd is making poor choices, it is possible to override that choice with + * this enum. + */ + ZSTD_dictDefaultAttach = 0, /* Use the default heuristic. */ + ZSTD_dictForceAttach = 1, /* Never copy the dictionary. */ + ZSTD_dictForceCopy = 2, /* Always copy the dictionary. */ + ZSTD_dictForceLoad = 3 /* Always reload the dictionary */ +} ZSTD_dictAttachPref_e; + +typedef enum { + ZSTD_lcm_auto = 0, /**< Automatically determine the compression mode based on the compression level. + * Negative compression levels will be uncompressed, and positive compression + * levels will be compressed. */ + ZSTD_lcm_huffman = 1, /**< Always attempt Huffman compression. Uncompressed literals will still be + * emitted if Huffman compression is not profitable. */ + ZSTD_lcm_uncompressed = 2 /**< Always emit uncompressed literals. */ +} ZSTD_literalCompressionMode_e; + +typedef enum { + /* Note: This enum controls features which are conditionally beneficial. + * Zstd can take a decision on whether or not to enable the feature (ZSTD_ps_auto), + * but setting the switch to ZSTD_ps_enable or ZSTD_ps_disable force enable/disable the feature. + */ + ZSTD_ps_auto = 0, /* Let the library automatically determine whether the feature shall be enabled */ + ZSTD_ps_enable = 1, /* Force-enable the feature */ + ZSTD_ps_disable = 2 /* Do not use the feature */ +} ZSTD_ParamSwitch_e; +#define ZSTD_paramSwitch_e ZSTD_ParamSwitch_e /* old name */ + +/*************************************** +* Frame header and size functions +***************************************/ + +/*! ZSTD_findDecompressedSize() : + * `src` should point to the start of a series of ZSTD encoded and/or skippable frames + * `srcSize` must be the _exact_ size of this series + * (i.e. there should be a frame boundary at `src + srcSize`) + * @return : - decompressed size of all data in all successive frames + * - if the decompressed size cannot be determined: ZSTD_CONTENTSIZE_UNKNOWN + * - if an error occurred: ZSTD_CONTENTSIZE_ERROR + * + * note 1 : decompressed size is an optional field, that may not be present, especially in streaming mode. + * When `return==ZSTD_CONTENTSIZE_UNKNOWN`, data to decompress could be any size. + * In which case, it's necessary to use streaming mode to decompress data. + * note 2 : decompressed size is always present when compression is done with ZSTD_compress() + * note 3 : decompressed size can be very large (64-bits value), + * potentially larger than what local system can handle as a single memory segment. + * In which case, it's necessary to use streaming mode to decompress data. + * note 4 : If source is untrusted, decompressed size could be wrong or intentionally modified. + * Always ensure result fits within application's authorized limits. + * Each application can set its own limits. + * note 5 : ZSTD_findDecompressedSize handles multiple frames, and so it must traverse the input to + * read each contained frame header. This is fast as most of the data is skipped, + * however it does mean that all frame data must be present and valid. */ +ZSTDLIB_STATIC_API unsigned long long ZSTD_findDecompressedSize(const void* src, size_t srcSize); + +/*! ZSTD_decompressBound() : + * `src` should point to the start of a series of ZSTD encoded and/or skippable frames + * `srcSize` must be the _exact_ size of this series + * (i.e. there should be a frame boundary at `src + srcSize`) + * @return : - upper-bound for the decompressed size of all data in all successive frames + * - if an error occurred: ZSTD_CONTENTSIZE_ERROR + * + * note 1 : an error can occur if `src` contains an invalid or incorrectly formatted frame. + * note 2 : the upper-bound is exact when the decompressed size field is available in every ZSTD encoded frame of `src`. + * in this case, `ZSTD_findDecompressedSize` and `ZSTD_decompressBound` return the same value. + * note 3 : when the decompressed size field isn't available, the upper-bound for that frame is calculated by: + * upper-bound = # blocks * min(128 KB, Window_Size) + */ +ZSTDLIB_STATIC_API unsigned long long ZSTD_decompressBound(const void* src, size_t srcSize); + +/*! ZSTD_frameHeaderSize() : + * srcSize must be large enough, aka >= ZSTD_FRAMEHEADERSIZE_PREFIX. + * @return : size of the Frame Header, + * or an error code (if srcSize is too small) */ +ZSTDLIB_STATIC_API size_t ZSTD_frameHeaderSize(const void* src, size_t srcSize); + +typedef enum { ZSTD_frame, ZSTD_skippableFrame } ZSTD_FrameType_e; +#define ZSTD_frameType_e ZSTD_FrameType_e /* old name */ +typedef struct { + unsigned long long frameContentSize; /* if == ZSTD_CONTENTSIZE_UNKNOWN, it means this field is not available. 0 means "empty" */ + unsigned long long windowSize; /* can be very large, up to <= frameContentSize */ + unsigned blockSizeMax; + ZSTD_FrameType_e frameType; /* if == ZSTD_skippableFrame, frameContentSize is the size of skippable content */ + unsigned headerSize; + unsigned dictID; /* for ZSTD_skippableFrame, contains the skippable magic variant [0-15] */ + unsigned checksumFlag; + unsigned _reserved1; + unsigned _reserved2; +} ZSTD_FrameHeader; +#define ZSTD_frameHeader ZSTD_FrameHeader /* old name */ + +/*! ZSTD_getFrameHeader() : + * decode Frame Header into `zfhPtr`, or requires larger `srcSize`. + * @return : 0 => header is complete, `zfhPtr` is correctly filled, + * >0 => `srcSize` is too small, @return value is the wanted `srcSize` amount, `zfhPtr` is not filled, + * or an error code, which can be tested using ZSTD_isError() */ +ZSTDLIB_STATIC_API size_t ZSTD_getFrameHeader(ZSTD_FrameHeader* zfhPtr, const void* src, size_t srcSize); +/*! ZSTD_getFrameHeader_advanced() : + * same as ZSTD_getFrameHeader(), + * with added capability to select a format (like ZSTD_f_zstd1_magicless) */ +ZSTDLIB_STATIC_API size_t ZSTD_getFrameHeader_advanced(ZSTD_FrameHeader* zfhPtr, const void* src, size_t srcSize, ZSTD_format_e format); + +/*! ZSTD_decompressionMargin() : + * Zstd supports in-place decompression, where the input and output buffers overlap. + * In this case, the output buffer must be at least (Margin + Output_Size) bytes large, + * and the input buffer must be at the end of the output buffer. + * + * _______________________ Output Buffer ________________________ + * | | + * | ____ Input Buffer ____| + * | | | + * v v v + * |---------------------------------------|-----------|----------| + * ^ ^ ^ + * |___________________ Output_Size ___________________|_ Margin _| + * + * NOTE: See also ZSTD_DECOMPRESSION_MARGIN(). + * NOTE: This applies only to single-pass decompression through ZSTD_decompress() or + * ZSTD_decompressDCtx(). + * NOTE: This function supports multi-frame input. + * + * @param src The compressed frame(s) + * @param srcSize The size of the compressed frame(s) + * @returns The decompression margin or an error that can be checked with ZSTD_isError(). + */ +ZSTDLIB_STATIC_API size_t ZSTD_decompressionMargin(const void* src, size_t srcSize); + +/*! ZSTD_DECOMPRESS_MARGIN() : + * Similar to ZSTD_decompressionMargin(), but instead of computing the margin from + * the compressed frame, compute it from the original size and the blockSizeLog. + * See ZSTD_decompressionMargin() for details. + * + * WARNING: This macro does not support multi-frame input, the input must be a single + * zstd frame. If you need that support use the function, or implement it yourself. + * + * @param originalSize The original uncompressed size of the data. + * @param blockSize The block size == MIN(windowSize, ZSTD_BLOCKSIZE_MAX). + * Unless you explicitly set the windowLog smaller than + * ZSTD_BLOCKSIZELOG_MAX you can just use ZSTD_BLOCKSIZE_MAX. + */ +#define ZSTD_DECOMPRESSION_MARGIN(originalSize, blockSize) ((size_t)( \ + ZSTD_FRAMEHEADERSIZE_MAX /* Frame header */ + \ + 4 /* checksum */ + \ + ((originalSize) == 0 ? 0 : 3 * (((originalSize) + (blockSize) - 1) / blockSize)) /* 3 bytes per block */ + \ + (blockSize) /* One block of margin */ \ + )) + +typedef enum { + ZSTD_sf_noBlockDelimiters = 0, /* ZSTD_Sequence[] has no block delimiters, just sequences */ + ZSTD_sf_explicitBlockDelimiters = 1 /* ZSTD_Sequence[] contains explicit block delimiters */ +} ZSTD_SequenceFormat_e; +#define ZSTD_sequenceFormat_e ZSTD_SequenceFormat_e /* old name */ + +/*! ZSTD_sequenceBound() : + * `srcSize` : size of the input buffer + * @return : upper-bound for the number of sequences that can be generated + * from a buffer of srcSize bytes + * + * note : returns number of sequences - to get bytes, multiply by sizeof(ZSTD_Sequence). + */ +ZSTDLIB_STATIC_API size_t ZSTD_sequenceBound(size_t srcSize); + +/*! ZSTD_generateSequences() : + * WARNING: This function is meant for debugging and informational purposes ONLY! + * Its implementation is flawed, and it will be deleted in a future version. + * It is not guaranteed to succeed, as there are several cases where it will give + * up and fail. You should NOT use this function in production code. + * + * This function is deprecated, and will be removed in a future version. + * + * Generate sequences using ZSTD_compress2(), given a source buffer. + * + * @param zc The compression context to be used for ZSTD_compress2(). Set any + * compression parameters you need on this context. + * @param outSeqs The output sequences buffer of size @p outSeqsSize + * @param outSeqsCapacity The size of the output sequences buffer. + * ZSTD_sequenceBound(srcSize) is an upper bound on the number + * of sequences that can be generated. + * @param src The source buffer to generate sequences from of size @p srcSize. + * @param srcSize The size of the source buffer. + * + * Each block will end with a dummy sequence + * with offset == 0, matchLength == 0, and litLength == length of last literals. + * litLength may be == 0, and if so, then the sequence of (of: 0 ml: 0 ll: 0) + * simply acts as a block delimiter. + * + * @returns The number of sequences generated, necessarily less than + * ZSTD_sequenceBound(srcSize), or an error code that can be checked + * with ZSTD_isError(). + */ +ZSTD_DEPRECATED("For debugging only, will be replaced by ZSTD_extractSequences()") +ZSTDLIB_STATIC_API size_t +ZSTD_generateSequences(ZSTD_CCtx* zc, + ZSTD_Sequence* outSeqs, size_t outSeqsCapacity, + const void* src, size_t srcSize); + +/*! ZSTD_mergeBlockDelimiters() : + * Given an array of ZSTD_Sequence, remove all sequences that represent block delimiters/last literals + * by merging them into the literals of the next sequence. + * + * As such, the final generated result has no explicit representation of block boundaries, + * and the final last literals segment is not represented in the sequences. + * + * The output of this function can be fed into ZSTD_compressSequences() with CCtx + * setting of ZSTD_c_blockDelimiters as ZSTD_sf_noBlockDelimiters + * @return : number of sequences left after merging + */ +ZSTDLIB_STATIC_API size_t ZSTD_mergeBlockDelimiters(ZSTD_Sequence* sequences, size_t seqsSize); + +/*! ZSTD_compressSequences() : + * Compress an array of ZSTD_Sequence, associated with @src buffer, into dst. + * @src contains the entire input (not just the literals). + * If @srcSize > sum(sequence.length), the remaining bytes are considered all literals + * If a dictionary is included, then the cctx should reference the dict (see: ZSTD_CCtx_refCDict(), ZSTD_CCtx_loadDictionary(), etc.). + * The entire source is compressed into a single frame. + * + * The compression behavior changes based on cctx params. In particular: + * If ZSTD_c_blockDelimiters == ZSTD_sf_noBlockDelimiters, the array of ZSTD_Sequence is expected to contain + * no block delimiters (defined in ZSTD_Sequence). Block boundaries are roughly determined based on + * the block size derived from the cctx, and sequences may be split. This is the default setting. + * + * If ZSTD_c_blockDelimiters == ZSTD_sf_explicitBlockDelimiters, the array of ZSTD_Sequence is expected to contain + * valid block delimiters (defined in ZSTD_Sequence). Behavior is undefined if no block delimiters are provided. + * + * When ZSTD_c_blockDelimiters == ZSTD_sf_explicitBlockDelimiters, it's possible to decide generating repcodes + * using the advanced parameter ZSTD_c_repcodeResolution. Repcodes will improve compression ratio, though the benefit + * can vary greatly depending on Sequences. On the other hand, repcode resolution is an expensive operation. + * By default, it's disabled at low (<10) compression levels, and enabled above the threshold (>=10). + * ZSTD_c_repcodeResolution makes it possible to directly manage this processing in either direction. + * + * If ZSTD_c_validateSequences == 0, this function blindly accepts the Sequences provided. Invalid Sequences cause undefined + * behavior. If ZSTD_c_validateSequences == 1, then the function will detect invalid Sequences (see doc/zstd_compression_format.md for + * specifics regarding offset/matchlength requirements) and then bail out and return an error. + * + * In addition to the two adjustable experimental params, there are other important cctx params. + * - ZSTD_c_minMatch MUST be set as less than or equal to the smallest match generated by the match finder. It has a minimum value of ZSTD_MINMATCH_MIN. + * - ZSTD_c_compressionLevel accordingly adjusts the strength of the entropy coder, as it would in typical compression. + * - ZSTD_c_windowLog affects offset validation: this function will return an error at higher debug levels if a provided offset + * is larger than what the spec allows for a given window log and dictionary (if present). See: doc/zstd_compression_format.md + * + * Note: Repcodes are, as of now, always re-calculated within this function, ZSTD_Sequence.rep is effectively unused. + * Dev Note: Once ability to ingest repcodes become available, the explicit block delims mode must respect those repcodes exactly, + * and cannot emit an RLE block that disagrees with the repcode history. + * @return : final compressed size, or a ZSTD error code. + */ +ZSTDLIB_STATIC_API size_t +ZSTD_compressSequences(ZSTD_CCtx* cctx, + void* dst, size_t dstCapacity, + const ZSTD_Sequence* inSeqs, size_t inSeqsSize, + const void* src, size_t srcSize); + + +/*! ZSTD_compressSequencesAndLiterals() : + * This is a variant of ZSTD_compressSequences() which, + * instead of receiving (src,srcSize) as input parameter, receives (literals,litSize), + * aka all the literals, already extracted and laid out into a single continuous buffer. + * This can be useful if the process generating the sequences also happens to generate the buffer of literals, + * thus skipping an extraction + caching stage. + * It's a speed optimization, useful when the right conditions are met, + * but it also features the following limitations: + * - Only supports explicit delimiter mode + * - Currently does not support Sequences validation (so input Sequences are trusted) + * - Not compatible with frame checksum, which must be disabled + * - If any block is incompressible, will fail and return an error + * - @litSize must be == sum of all @.litLength fields in @inSeqs. Any discrepancy will generate an error. + * - @litBufCapacity is the size of the underlying buffer into which literals are written, starting at address @literals. + * @litBufCapacity must be at least 8 bytes larger than @litSize. + * - @decompressedSize must be correct, and correspond to the sum of all Sequences. Any discrepancy will generate an error. + * @return : final compressed size, or a ZSTD error code. + */ +ZSTDLIB_STATIC_API size_t +ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, + void* dst, size_t dstCapacity, + const ZSTD_Sequence* inSeqs, size_t nbSequences, + const void* literals, size_t litSize, size_t litBufCapacity, + size_t decompressedSize); + + +/*! ZSTD_writeSkippableFrame() : + * Generates a zstd skippable frame containing data given by src, and writes it to dst buffer. + * + * Skippable frames begin with a 4-byte magic number. There are 16 possible choices of magic number, + * ranging from ZSTD_MAGIC_SKIPPABLE_START to ZSTD_MAGIC_SKIPPABLE_START+15. + * As such, the parameter magicVariant controls the exact skippable frame magic number variant used, + * so the magic number used will be ZSTD_MAGIC_SKIPPABLE_START + magicVariant. + * + * Returns an error if destination buffer is not large enough, if the source size is not representable + * with a 4-byte unsigned int, or if the parameter magicVariant is greater than 15 (and therefore invalid). + * + * @return : number of bytes written or a ZSTD error. + */ +ZSTDLIB_STATIC_API size_t ZSTD_writeSkippableFrame(void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + unsigned magicVariant); + +/*! ZSTD_readSkippableFrame() : + * Retrieves the content of a zstd skippable frame starting at @src, and writes it to @dst buffer. + * + * The parameter @magicVariant will receive the magicVariant that was supplied when the frame was written, + * i.e. magicNumber - ZSTD_MAGIC_SKIPPABLE_START. + * This can be NULL if the caller is not interested in the magicVariant. + * + * Returns an error if destination buffer is not large enough, or if the frame is not skippable. + * + * @return : number of bytes written or a ZSTD error. + */ +ZSTDLIB_STATIC_API size_t ZSTD_readSkippableFrame(void* dst, size_t dstCapacity, + unsigned* magicVariant, + const void* src, size_t srcSize); + +/*! ZSTD_isSkippableFrame() : + * Tells if the content of `buffer` starts with a valid Frame Identifier for a skippable frame. + */ +ZSTDLIB_STATIC_API unsigned ZSTD_isSkippableFrame(const void* buffer, size_t size); + + + +/*************************************** +* Memory management +***************************************/ + +/*! ZSTD_estimate*() : + * These functions make it possible to estimate memory usage + * of a future {D,C}Ctx, before its creation. + * This is useful in combination with ZSTD_initStatic(), + * which makes it possible to employ a static buffer for ZSTD_CCtx* state. + * + * ZSTD_estimateCCtxSize() will provide a memory budget large enough + * to compress data of any size using one-shot compression ZSTD_compressCCtx() or ZSTD_compress2() + * associated with any compression level up to max specified one. + * The estimate will assume the input may be arbitrarily large, + * which is the worst case. + * + * Note that the size estimation is specific for one-shot compression, + * it is not valid for streaming (see ZSTD_estimateCStreamSize*()) + * nor other potential ways of using a ZSTD_CCtx* state. + * + * When srcSize can be bound by a known and rather "small" value, + * this knowledge can be used to provide a tighter budget estimation + * because the ZSTD_CCtx* state will need less memory for small inputs. + * This tighter estimation can be provided by employing more advanced functions + * ZSTD_estimateCCtxSize_usingCParams(), which can be used in tandem with ZSTD_getCParams(), + * and ZSTD_estimateCCtxSize_usingCCtxParams(), which can be used in tandem with ZSTD_CCtxParams_setParameter(). + * Both can be used to estimate memory using custom compression parameters and arbitrary srcSize limits. + * + * Note : only single-threaded compression is supported. + * ZSTD_estimateCCtxSize_usingCCtxParams() will return an error code if ZSTD_c_nbWorkers is >= 1. + */ +ZSTDLIB_STATIC_API size_t ZSTD_estimateCCtxSize(int maxCompressionLevel); +ZSTDLIB_STATIC_API size_t ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams); +ZSTDLIB_STATIC_API size_t ZSTD_estimateCCtxSize_usingCCtxParams(const ZSTD_CCtx_params* params); +ZSTDLIB_STATIC_API size_t ZSTD_estimateDCtxSize(void); + +/*! ZSTD_estimateCStreamSize() : + * ZSTD_estimateCStreamSize() will provide a memory budget large enough for streaming compression + * using any compression level up to the max specified one. + * It will also consider src size to be arbitrarily "large", which is a worst case scenario. + * If srcSize is known to always be small, ZSTD_estimateCStreamSize_usingCParams() can provide a tighter estimation. + * ZSTD_estimateCStreamSize_usingCParams() can be used in tandem with ZSTD_getCParams() to create cParams from compressionLevel. + * ZSTD_estimateCStreamSize_usingCCtxParams() can be used in tandem with ZSTD_CCtxParams_setParameter(). Only single-threaded compression is supported. This function will return an error code if ZSTD_c_nbWorkers is >= 1. + * Note : CStream size estimation is only correct for single-threaded compression. + * ZSTD_estimateCStreamSize_usingCCtxParams() will return an error code if ZSTD_c_nbWorkers is >= 1. + * Note 2 : ZSTD_estimateCStreamSize* functions are not compatible with the Block-Level Sequence Producer API at this time. + * Size estimates assume that no external sequence producer is registered. + * + * ZSTD_DStream memory budget depends on frame's window Size. + * This information can be passed manually, using ZSTD_estimateDStreamSize, + * or deducted from a valid frame Header, using ZSTD_estimateDStreamSize_fromFrame(); + * Any frame requesting a window size larger than max specified one will be rejected. + * Note : if streaming is init with function ZSTD_init?Stream_usingDict(), + * an internal ?Dict will be created, which additional size is not estimated here. + * In this case, get total size by adding ZSTD_estimate?DictSize + */ +ZSTDLIB_STATIC_API size_t ZSTD_estimateCStreamSize(int maxCompressionLevel); +ZSTDLIB_STATIC_API size_t ZSTD_estimateCStreamSize_usingCParams(ZSTD_compressionParameters cParams); +ZSTDLIB_STATIC_API size_t ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params* params); +ZSTDLIB_STATIC_API size_t ZSTD_estimateDStreamSize(size_t maxWindowSize); +ZSTDLIB_STATIC_API size_t ZSTD_estimateDStreamSize_fromFrame(const void* src, size_t srcSize); + +/*! ZSTD_estimate?DictSize() : + * ZSTD_estimateCDictSize() will bet that src size is relatively "small", and content is copied, like ZSTD_createCDict(). + * ZSTD_estimateCDictSize_advanced() makes it possible to control compression parameters precisely, like ZSTD_createCDict_advanced(). + * Note : dictionaries created by reference (`ZSTD_dlm_byRef`) are logically smaller. + */ +ZSTDLIB_STATIC_API size_t ZSTD_estimateCDictSize(size_t dictSize, int compressionLevel); +ZSTDLIB_STATIC_API size_t ZSTD_estimateCDictSize_advanced(size_t dictSize, ZSTD_compressionParameters cParams, ZSTD_dictLoadMethod_e dictLoadMethod); +ZSTDLIB_STATIC_API size_t ZSTD_estimateDDictSize(size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod); + +/*! ZSTD_initStatic*() : + * Initialize an object using a pre-allocated fixed-size buffer. + * workspace: The memory area to emplace the object into. + * Provided pointer *must be 8-bytes aligned*. + * Buffer must outlive object. + * workspaceSize: Use ZSTD_estimate*Size() to determine + * how large workspace must be to support target scenario. + * @return : pointer to object (same address as workspace, just different type), + * or NULL if error (size too small, incorrect alignment, etc.) + * Note : zstd will never resize nor malloc() when using a static buffer. + * If the object requires more memory than available, + * zstd will just error out (typically ZSTD_error_memory_allocation). + * Note 2 : there is no corresponding "free" function. + * Since workspace is allocated externally, it must be freed externally too. + * Note 3 : cParams : use ZSTD_getCParams() to convert a compression level + * into its associated cParams. + * Limitation 1 : currently not compatible with internal dictionary creation, triggered by + * ZSTD_CCtx_loadDictionary(), ZSTD_initCStream_usingDict() or ZSTD_initDStream_usingDict(). + * Limitation 2 : static cctx currently not compatible with multi-threading. + * Limitation 3 : static dctx is incompatible with legacy support. + */ +ZSTDLIB_STATIC_API ZSTD_CCtx* ZSTD_initStaticCCtx(void* workspace, size_t workspaceSize); +ZSTDLIB_STATIC_API ZSTD_CStream* ZSTD_initStaticCStream(void* workspace, size_t workspaceSize); /**< same as ZSTD_initStaticCCtx() */ + +ZSTDLIB_STATIC_API ZSTD_DCtx* ZSTD_initStaticDCtx(void* workspace, size_t workspaceSize); +ZSTDLIB_STATIC_API ZSTD_DStream* ZSTD_initStaticDStream(void* workspace, size_t workspaceSize); /**< same as ZSTD_initStaticDCtx() */ + +ZSTDLIB_STATIC_API const ZSTD_CDict* ZSTD_initStaticCDict( + void* workspace, size_t workspaceSize, + const void* dict, size_t dictSize, + ZSTD_dictLoadMethod_e dictLoadMethod, + ZSTD_dictContentType_e dictContentType, + ZSTD_compressionParameters cParams); + +ZSTDLIB_STATIC_API const ZSTD_DDict* ZSTD_initStaticDDict( + void* workspace, size_t workspaceSize, + const void* dict, size_t dictSize, + ZSTD_dictLoadMethod_e dictLoadMethod, + ZSTD_dictContentType_e dictContentType); + + +/*! Custom memory allocation : + * These prototypes make it possible to pass your own allocation/free functions. + * ZSTD_customMem is provided at creation time, using ZSTD_create*_advanced() variants listed below. + * All allocation/free operations will be completed using these custom variants instead of regular ones. + */ +typedef void* (*ZSTD_allocFunction) (void* opaque, size_t size); +typedef void (*ZSTD_freeFunction) (void* opaque, void* address); +typedef struct { ZSTD_allocFunction customAlloc; ZSTD_freeFunction customFree; void* opaque; } ZSTD_customMem; +static +#ifdef __GNUC__ +__attribute__((__unused__)) +#endif + +#if defined(__clang__) && __clang_major__ >= 5 +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" +#endif +ZSTD_customMem const ZSTD_defaultCMem = { NULL, NULL, NULL }; /**< this constant defers to stdlib's functions */ +#if defined(__clang__) && __clang_major__ >= 5 +#pragma clang diagnostic pop +#endif + +ZSTDLIB_STATIC_API ZSTD_CCtx* ZSTD_createCCtx_advanced(ZSTD_customMem customMem); +ZSTDLIB_STATIC_API ZSTD_CStream* ZSTD_createCStream_advanced(ZSTD_customMem customMem); +ZSTDLIB_STATIC_API ZSTD_DCtx* ZSTD_createDCtx_advanced(ZSTD_customMem customMem); +ZSTDLIB_STATIC_API ZSTD_DStream* ZSTD_createDStream_advanced(ZSTD_customMem customMem); + +ZSTDLIB_STATIC_API ZSTD_CDict* ZSTD_createCDict_advanced(const void* dict, size_t dictSize, + ZSTD_dictLoadMethod_e dictLoadMethod, + ZSTD_dictContentType_e dictContentType, + ZSTD_compressionParameters cParams, + ZSTD_customMem customMem); + +/*! Thread pool : + * These prototypes make it possible to share a thread pool among multiple compression contexts. + * This can limit resources for applications with multiple threads where each one uses + * a threaded compression mode (via ZSTD_c_nbWorkers parameter). + * ZSTD_createThreadPool creates a new thread pool with a given number of threads. + * Note that the lifetime of such pool must exist while being used. + * ZSTD_CCtx_refThreadPool assigns a thread pool to a context (use NULL argument value + * to use an internal thread pool). + * ZSTD_freeThreadPool frees a thread pool, accepts NULL pointer. + */ +typedef struct POOL_ctx_s ZSTD_threadPool; +ZSTDLIB_STATIC_API ZSTD_threadPool* ZSTD_createThreadPool(size_t numThreads); +ZSTDLIB_STATIC_API void ZSTD_freeThreadPool (ZSTD_threadPool* pool); /* accept NULL pointer */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtx_refThreadPool(ZSTD_CCtx* cctx, ZSTD_threadPool* pool); + + +/* + * This API is temporary and is expected to change or disappear in the future! + */ +ZSTDLIB_STATIC_API ZSTD_CDict* ZSTD_createCDict_advanced2( + const void* dict, size_t dictSize, + ZSTD_dictLoadMethod_e dictLoadMethod, + ZSTD_dictContentType_e dictContentType, + const ZSTD_CCtx_params* cctxParams, + ZSTD_customMem customMem); + +ZSTDLIB_STATIC_API ZSTD_DDict* ZSTD_createDDict_advanced( + const void* dict, size_t dictSize, + ZSTD_dictLoadMethod_e dictLoadMethod, + ZSTD_dictContentType_e dictContentType, + ZSTD_customMem customMem); + + +/*************************************** +* Advanced compression functions +***************************************/ + +/*! ZSTD_createCDict_byReference() : + * Create a digested dictionary for compression + * Dictionary content is just referenced, not duplicated. + * As a consequence, `dictBuffer` **must** outlive CDict, + * and its content must remain unmodified throughout the lifetime of CDict. + * note: equivalent to ZSTD_createCDict_advanced(), with dictLoadMethod==ZSTD_dlm_byRef */ +ZSTDLIB_STATIC_API ZSTD_CDict* ZSTD_createCDict_byReference(const void* dictBuffer, size_t dictSize, int compressionLevel); + +/*! ZSTD_getCParams() : + * @return ZSTD_compressionParameters structure for a selected compression level and estimated srcSize. + * `estimatedSrcSize` value is optional, select 0 if not known */ +ZSTDLIB_STATIC_API ZSTD_compressionParameters ZSTD_getCParams(int compressionLevel, unsigned long long estimatedSrcSize, size_t dictSize); + +/*! ZSTD_getParams() : + * same as ZSTD_getCParams(), but @return a full `ZSTD_parameters` object instead of sub-component `ZSTD_compressionParameters`. + * All fields of `ZSTD_frameParameters` are set to default : contentSize=1, checksum=0, noDictID=0 */ +ZSTDLIB_STATIC_API ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long estimatedSrcSize, size_t dictSize); + +/*! ZSTD_checkCParams() : + * Ensure param values remain within authorized range. + * @return 0 on success, or an error code (can be checked with ZSTD_isError()) */ +ZSTDLIB_STATIC_API size_t ZSTD_checkCParams(ZSTD_compressionParameters params); + +/*! ZSTD_adjustCParams() : + * optimize params for a given `srcSize` and `dictSize`. + * `srcSize` can be unknown, in which case use ZSTD_CONTENTSIZE_UNKNOWN. + * `dictSize` must be `0` when there is no dictionary. + * cPar can be invalid : all parameters will be clamped within valid range in the @return struct. + * This function never fails (wide contract) */ +ZSTDLIB_STATIC_API ZSTD_compressionParameters ZSTD_adjustCParams(ZSTD_compressionParameters cPar, unsigned long long srcSize, size_t dictSize); + +/*! ZSTD_CCtx_setCParams() : + * Set all parameters provided within @p cparams into the working @p cctx. + * Note : if modifying parameters during compression (MT mode only), + * note that changes to the .windowLog parameter will be ignored. + * @return 0 on success, or an error code (can be checked with ZSTD_isError()). + * On failure, no parameters are updated. + */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtx_setCParams(ZSTD_CCtx* cctx, ZSTD_compressionParameters cparams); + +/*! ZSTD_CCtx_setFParams() : + * Set all parameters provided within @p fparams into the working @p cctx. + * @return 0 on success, or an error code (can be checked with ZSTD_isError()). + */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtx_setFParams(ZSTD_CCtx* cctx, ZSTD_frameParameters fparams); + +/*! ZSTD_CCtx_setParams() : + * Set all parameters provided within @p params into the working @p cctx. + * @return 0 on success, or an error code (can be checked with ZSTD_isError()). + */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtx_setParams(ZSTD_CCtx* cctx, ZSTD_parameters params); + +/*! ZSTD_compress_advanced() : + * Note : this function is now DEPRECATED. + * It can be replaced by ZSTD_compress2(), in combination with ZSTD_CCtx_setParameter() and other parameter setters. + * This prototype will generate compilation warnings. */ +ZSTD_DEPRECATED("use ZSTD_compress2") +ZSTDLIB_STATIC_API +size_t ZSTD_compress_advanced(ZSTD_CCtx* cctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const void* dict,size_t dictSize, + ZSTD_parameters params); + +/*! ZSTD_compress_usingCDict_advanced() : + * Note : this function is now DEPRECATED. + * It can be replaced by ZSTD_compress2(), in combination with ZSTD_CCtx_loadDictionary() and other parameter setters. + * This prototype will generate compilation warnings. */ +ZSTD_DEPRECATED("use ZSTD_compress2 with ZSTD_CCtx_loadDictionary") +ZSTDLIB_STATIC_API +size_t ZSTD_compress_usingCDict_advanced(ZSTD_CCtx* cctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const ZSTD_CDict* cdict, + ZSTD_frameParameters fParams); + + +/*! ZSTD_CCtx_loadDictionary_byReference() : + * Same as ZSTD_CCtx_loadDictionary(), but dictionary content is referenced, instead of being copied into CCtx. + * It saves some memory, but also requires that `dict` outlives its usage within `cctx` */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtx_loadDictionary_byReference(ZSTD_CCtx* cctx, const void* dict, size_t dictSize); + +/*! ZSTD_CCtx_loadDictionary_advanced() : + * Same as ZSTD_CCtx_loadDictionary(), but gives finer control over + * how to load the dictionary (by copy ? by reference ?) + * and how to interpret it (automatic ? force raw mode ? full mode only ?) */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtx_loadDictionary_advanced(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType); + +/*! ZSTD_CCtx_refPrefix_advanced() : + * Same as ZSTD_CCtx_refPrefix(), but gives finer control over + * how to interpret prefix content (automatic ? force raw mode (default) ? full mode only ?) */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtx_refPrefix_advanced(ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType); + +/* === experimental parameters === */ +/* these parameters can be used with ZSTD_setParameter() + * they are not guaranteed to remain supported in the future */ + + /* Enables rsyncable mode, + * which makes compressed files more rsync friendly + * by adding periodic synchronization points to the compressed data. + * The target average block size is ZSTD_c_jobSize / 2. + * It's possible to modify the job size to increase or decrease + * the granularity of the synchronization point. + * Once the jobSize is smaller than the window size, + * it will result in compression ratio degradation. + * NOTE 1: rsyncable mode only works when multithreading is enabled. + * NOTE 2: rsyncable performs poorly in combination with long range mode, + * since it will decrease the effectiveness of synchronization points, + * though mileage may vary. + * NOTE 3: Rsyncable mode limits maximum compression speed to ~400 MB/s. + * If the selected compression level is already running significantly slower, + * the overall speed won't be significantly impacted. + */ + #define ZSTD_c_rsyncable ZSTD_c_experimentalParam1 + +/* Select a compression format. + * The value must be of type ZSTD_format_e. + * See ZSTD_format_e enum definition for details */ +#define ZSTD_c_format ZSTD_c_experimentalParam2 + +/* Force back-reference distances to remain < windowSize, + * even when referencing into Dictionary content (default:0) */ +#define ZSTD_c_forceMaxWindow ZSTD_c_experimentalParam3 + +/* Controls whether the contents of a CDict + * are used in place, or copied into the working context. + * Accepts values from the ZSTD_dictAttachPref_e enum. + * See the comments on that enum for an explanation of the feature. */ +#define ZSTD_c_forceAttachDict ZSTD_c_experimentalParam4 + +/* Controlled with ZSTD_ParamSwitch_e enum. + * Default is ZSTD_ps_auto. + * Set to ZSTD_ps_disable to never compress literals. + * Set to ZSTD_ps_enable to always compress literals. (Note: uncompressed literals + * may still be emitted if huffman is not beneficial to use.) + * + * By default, in ZSTD_ps_auto, the library will decide at runtime whether to use + * literals compression based on the compression parameters - specifically, + * negative compression levels do not use literal compression. + */ +#define ZSTD_c_literalCompressionMode ZSTD_c_experimentalParam5 + +/* User's best guess of source size. + * Hint is not valid when srcSizeHint == 0. + * There is no guarantee that hint is close to actual source size, + * but compression ratio may regress significantly if guess considerably underestimates */ +#define ZSTD_c_srcSizeHint ZSTD_c_experimentalParam7 + +/* Controls whether the new and experimental "dedicated dictionary search + * structure" can be used. This feature is still rough around the edges, be + * prepared for surprising behavior! + * + * How to use it: + * + * When using a CDict, whether to use this feature or not is controlled at + * CDict creation, and it must be set in a CCtxParams set passed into that + * construction (via ZSTD_createCDict_advanced2()). A compression will then + * use the feature or not based on how the CDict was constructed; the value of + * this param, set in the CCtx, will have no effect. + * + * However, when a dictionary buffer is passed into a CCtx, such as via + * ZSTD_CCtx_loadDictionary(), this param can be set on the CCtx to control + * whether the CDict that is created internally can use the feature or not. + * + * What it does: + * + * Normally, the internal data structures of the CDict are analogous to what + * would be stored in a CCtx after compressing the contents of a dictionary. + * To an approximation, a compression using a dictionary can then use those + * data structures to simply continue what is effectively a streaming + * compression where the simulated compression of the dictionary left off. + * Which is to say, the search structures in the CDict are normally the same + * format as in the CCtx. + * + * It is possible to do better, since the CDict is not like a CCtx: the search + * structures are written once during CDict creation, and then are only read + * after that, while the search structures in the CCtx are both read and + * written as the compression goes along. This means we can choose a search + * structure for the dictionary that is read-optimized. + * + * This feature enables the use of that different structure. + * + * Note that some of the members of the ZSTD_compressionParameters struct have + * different semantics and constraints in the dedicated search structure. It is + * highly recommended that you simply set a compression level in the CCtxParams + * you pass into the CDict creation call, and avoid messing with the cParams + * directly. + * + * Effects: + * + * This will only have any effect when the selected ZSTD_strategy + * implementation supports this feature. Currently, that's limited to + * ZSTD_greedy, ZSTD_lazy, and ZSTD_lazy2. + * + * Note that this means that the CDict tables can no longer be copied into the + * CCtx, so the dict attachment mode ZSTD_dictForceCopy will no longer be + * usable. The dictionary can only be attached or reloaded. + * + * In general, you should expect compression to be faster--sometimes very much + * so--and CDict creation to be slightly slower. Eventually, we will probably + * make this mode the default. + */ +#define ZSTD_c_enableDedicatedDictSearch ZSTD_c_experimentalParam8 + +/* ZSTD_c_stableInBuffer + * Experimental parameter. + * Default is 0 == disabled. Set to 1 to enable. + * + * Tells the compressor that input data presented with ZSTD_inBuffer + * will ALWAYS be the same between calls. + * Technically, the @src pointer must never be changed, + * and the @pos field can only be updated by zstd. + * However, it's possible to increase the @size field, + * allowing scenarios where more data can be appended after compressions starts. + * These conditions are checked by the compressor, + * and compression will fail if they are not respected. + * Also, data in the ZSTD_inBuffer within the range [src, src + pos) + * MUST not be modified during compression or it will result in data corruption. + * + * When this flag is enabled zstd won't allocate an input window buffer, + * because the user guarantees it can reference the ZSTD_inBuffer until + * the frame is complete. But, it will still allocate an output buffer + * large enough to fit a block (see ZSTD_c_stableOutBuffer). This will also + * avoid the memcpy() from the input buffer to the input window buffer. + * + * NOTE: So long as the ZSTD_inBuffer always points to valid memory, using + * this flag is ALWAYS memory safe, and will never access out-of-bounds + * memory. However, compression WILL fail if conditions are not respected. + * + * WARNING: The data in the ZSTD_inBuffer in the range [src, src + pos) MUST + * not be modified during compression or it will result in data corruption. + * This is because zstd needs to reference data in the ZSTD_inBuffer to find + * matches. Normally zstd maintains its own window buffer for this purpose, + * but passing this flag tells zstd to rely on user provided buffer instead. + */ +#define ZSTD_c_stableInBuffer ZSTD_c_experimentalParam9 + +/* ZSTD_c_stableOutBuffer + * Experimental parameter. + * Default is 0 == disabled. Set to 1 to enable. + * + * Tells he compressor that the ZSTD_outBuffer will not be resized between + * calls. Specifically: (out.size - out.pos) will never grow. This gives the + * compressor the freedom to say: If the compressed data doesn't fit in the + * output buffer then return ZSTD_error_dstSizeTooSmall. This allows us to + * always decompress directly into the output buffer, instead of decompressing + * into an internal buffer and copying to the output buffer. + * + * When this flag is enabled zstd won't allocate an output buffer, because + * it can write directly to the ZSTD_outBuffer. It will still allocate the + * input window buffer (see ZSTD_c_stableInBuffer). + * + * Zstd will check that (out.size - out.pos) never grows and return an error + * if it does. While not strictly necessary, this should prevent surprises. + */ +#define ZSTD_c_stableOutBuffer ZSTD_c_experimentalParam10 + +/* ZSTD_c_blockDelimiters + * Default is 0 == ZSTD_sf_noBlockDelimiters. + * + * For use with sequence compression API: ZSTD_compressSequences(). + * + * Designates whether or not the given array of ZSTD_Sequence contains block delimiters + * and last literals, which are defined as sequences with offset == 0 and matchLength == 0. + * See the definition of ZSTD_Sequence for more specifics. + */ +#define ZSTD_c_blockDelimiters ZSTD_c_experimentalParam11 + +/* ZSTD_c_validateSequences + * Default is 0 == disabled. Set to 1 to enable sequence validation. + * + * For use with sequence compression API: ZSTD_compressSequences*(). + * Designates whether or not provided sequences are validated within ZSTD_compressSequences*() + * during function execution. + * + * When Sequence validation is disabled (default), Sequences are compressed as-is, + * so they must correct, otherwise it would result in a corruption error. + * + * Sequence validation adds some protection, by ensuring that all values respect boundary conditions. + * If a Sequence is detected invalid (see doc/zstd_compression_format.md for + * specifics regarding offset/matchlength requirements) then the function will bail out and + * return an error. + */ +#define ZSTD_c_validateSequences ZSTD_c_experimentalParam12 + +/* ZSTD_c_blockSplitterLevel + * note: this parameter only influences the first splitter stage, + * which is active before producing the sequences. + * ZSTD_c_splitAfterSequences controls the next splitter stage, + * which is active after sequence production. + * Note that both can be combined. + * Allowed values are between 0 and ZSTD_BLOCKSPLITTER_LEVEL_MAX included. + * 0 means "auto", which will select a value depending on current ZSTD_c_strategy. + * 1 means no splitting. + * Then, values from 2 to 6 are sorted in increasing cpu load order. + * + * Note that currently the first block is never split, + * to ensure expansion guarantees in presence of incompressible data. + */ +#define ZSTD_BLOCKSPLITTER_LEVEL_MAX 6 +#define ZSTD_c_blockSplitterLevel ZSTD_c_experimentalParam20 + +/* ZSTD_c_splitAfterSequences + * This is a stronger splitter algorithm, + * based on actual sequences previously produced by the selected parser. + * It's also slower, and as a consequence, mostly used for high compression levels. + * While the post-splitter does overlap with the pre-splitter, + * both can nonetheless be combined, + * notably with ZSTD_c_blockSplitterLevel at ZSTD_BLOCKSPLITTER_LEVEL_MAX, + * resulting in higher compression ratio than just one of them. + * + * Default is ZSTD_ps_auto. + * Set to ZSTD_ps_disable to never use block splitter. + * Set to ZSTD_ps_enable to always use block splitter. + * + * By default, in ZSTD_ps_auto, the library will decide at runtime whether to use + * block splitting based on the compression parameters. + */ +#define ZSTD_c_splitAfterSequences ZSTD_c_experimentalParam13 + +/* ZSTD_c_useRowMatchFinder + * Controlled with ZSTD_ParamSwitch_e enum. + * Default is ZSTD_ps_auto. + * Set to ZSTD_ps_disable to never use row-based matchfinder. + * Set to ZSTD_ps_enable to force usage of row-based matchfinder. + * + * By default, in ZSTD_ps_auto, the library will decide at runtime whether to use + * the row-based matchfinder based on support for SIMD instructions and the window log. + * Note that this only pertains to compression strategies: greedy, lazy, and lazy2 + */ +#define ZSTD_c_useRowMatchFinder ZSTD_c_experimentalParam14 + +/* ZSTD_c_deterministicRefPrefix + * Default is 0 == disabled. Set to 1 to enable. + * + * Zstd produces different results for prefix compression when the prefix is + * directly adjacent to the data about to be compressed vs. when it isn't. + * This is because zstd detects that the two buffers are contiguous and it can + * use a more efficient match finding algorithm. However, this produces different + * results than when the two buffers are non-contiguous. This flag forces zstd + * to always load the prefix in non-contiguous mode, even if it happens to be + * adjacent to the data, to guarantee determinism. + * + * If you really care about determinism when using a dictionary or prefix, + * like when doing delta compression, you should select this option. It comes + * at a speed penalty of about ~2.5% if the dictionary and data happened to be + * contiguous, and is free if they weren't contiguous. We don't expect that + * intentionally making the dictionary and data contiguous will be worth the + * cost to memcpy() the data. + */ +#define ZSTD_c_deterministicRefPrefix ZSTD_c_experimentalParam15 + +/* ZSTD_c_prefetchCDictTables + * Controlled with ZSTD_ParamSwitch_e enum. Default is ZSTD_ps_auto. + * + * In some situations, zstd uses CDict tables in-place rather than copying them + * into the working context. (See docs on ZSTD_dictAttachPref_e above for details). + * In such situations, compression speed is seriously impacted when CDict tables are + * "cold" (outside CPU cache). This parameter instructs zstd to prefetch CDict tables + * when they are used in-place. + * + * For sufficiently small inputs, the cost of the prefetch will outweigh the benefit. + * For sufficiently large inputs, zstd will by default memcpy() CDict tables + * into the working context, so there is no need to prefetch. This parameter is + * targeted at a middle range of input sizes, where a prefetch is cheap enough to be + * useful but memcpy() is too expensive. The exact range of input sizes where this + * makes sense is best determined by careful experimentation. + * + * Note: for this parameter, ZSTD_ps_auto is currently equivalent to ZSTD_ps_disable, + * but in the future zstd may conditionally enable this feature via an auto-detection + * heuristic for cold CDicts. + * Use ZSTD_ps_disable to opt out of prefetching under any circumstances. + */ +#define ZSTD_c_prefetchCDictTables ZSTD_c_experimentalParam16 + +/* ZSTD_c_enableSeqProducerFallback + * Allowed values are 0 (disable) and 1 (enable). The default setting is 0. + * + * Controls whether zstd will fall back to an internal sequence producer if an + * external sequence producer is registered and returns an error code. This fallback + * is block-by-block: the internal sequence producer will only be called for blocks + * where the external sequence producer returns an error code. Fallback parsing will + * follow any other cParam settings, such as compression level, the same as in a + * normal (fully-internal) compression operation. + * + * The user is strongly encouraged to read the full Block-Level Sequence Producer API + * documentation (below) before setting this parameter. */ +#define ZSTD_c_enableSeqProducerFallback ZSTD_c_experimentalParam17 + +/* ZSTD_c_maxBlockSize + * Allowed values are between 1KB and ZSTD_BLOCKSIZE_MAX (128KB). + * The default is ZSTD_BLOCKSIZE_MAX, and setting to 0 will set to the default. + * + * This parameter can be used to set an upper bound on the blocksize + * that overrides the default ZSTD_BLOCKSIZE_MAX. It cannot be used to set upper + * bounds greater than ZSTD_BLOCKSIZE_MAX or bounds lower than 1KB (will make + * compressBound() inaccurate). Only currently meant to be used for testing. + */ +#define ZSTD_c_maxBlockSize ZSTD_c_experimentalParam18 + +/* ZSTD_c_repcodeResolution + * This parameter only has an effect if ZSTD_c_blockDelimiters is + * set to ZSTD_sf_explicitBlockDelimiters (may change in the future). + * + * This parameter affects how zstd parses external sequences, + * provided via the ZSTD_compressSequences*() API + * or from an external block-level sequence producer. + * + * If set to ZSTD_ps_enable, the library will check for repeated offsets within + * external sequences, even if those repcodes are not explicitly indicated in + * the "rep" field. Note that this is the only way to exploit repcode matches + * while using compressSequences*() or an external sequence producer, since zstd + * currently ignores the "rep" field of external sequences. + * + * If set to ZSTD_ps_disable, the library will not exploit repeated offsets in + * external sequences, regardless of whether the "rep" field has been set. This + * reduces sequence compression overhead by about 25% while sacrificing some + * compression ratio. + * + * The default value is ZSTD_ps_auto, for which the library will enable/disable + * based on compression level (currently: level<10 disables, level>=10 enables). + */ +#define ZSTD_c_repcodeResolution ZSTD_c_experimentalParam19 +#define ZSTD_c_searchForExternalRepcodes ZSTD_c_experimentalParam19 /* older name */ + + +/*! ZSTD_CCtx_getParameter() : + * Get the requested compression parameter value, selected by enum ZSTD_cParameter, + * and store it into int* value. + * @return : 0, or an error code (which can be tested with ZSTD_isError()). + */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtx_getParameter(const ZSTD_CCtx* cctx, ZSTD_cParameter param, int* value); + + +/*! ZSTD_CCtx_params : + * Quick howto : + * - ZSTD_createCCtxParams() : Create a ZSTD_CCtx_params structure + * - ZSTD_CCtxParams_setParameter() : Push parameters one by one into + * an existing ZSTD_CCtx_params structure. + * This is similar to + * ZSTD_CCtx_setParameter(). + * - ZSTD_CCtx_setParametersUsingCCtxParams() : Apply parameters to + * an existing CCtx. + * These parameters will be applied to + * all subsequent frames. + * - ZSTD_compressStream2() : Do compression using the CCtx. + * - ZSTD_freeCCtxParams() : Free the memory, accept NULL pointer. + * + * This can be used with ZSTD_estimateCCtxSize_advanced_usingCCtxParams() + * for static allocation of CCtx for single-threaded compression. + */ +ZSTDLIB_STATIC_API ZSTD_CCtx_params* ZSTD_createCCtxParams(void); +ZSTDLIB_STATIC_API size_t ZSTD_freeCCtxParams(ZSTD_CCtx_params* params); /* accept NULL pointer */ + +/*! ZSTD_CCtxParams_reset() : + * Reset params to default values. + */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtxParams_reset(ZSTD_CCtx_params* params); + +/*! ZSTD_CCtxParams_init() : + * Initializes the compression parameters of cctxParams according to + * compression level. All other parameters are reset to their default values. + */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtxParams_init(ZSTD_CCtx_params* cctxParams, int compressionLevel); + +/*! ZSTD_CCtxParams_init_advanced() : + * Initializes the compression and frame parameters of cctxParams according to + * params. All other parameters are reset to their default values. + */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtxParams_init_advanced(ZSTD_CCtx_params* cctxParams, ZSTD_parameters params); + +/*! ZSTD_CCtxParams_setParameter() : Requires v1.4.0+ + * Similar to ZSTD_CCtx_setParameter. + * Set one compression parameter, selected by enum ZSTD_cParameter. + * Parameters must be applied to a ZSTD_CCtx using + * ZSTD_CCtx_setParametersUsingCCtxParams(). + * @result : a code representing success or failure (which can be tested with + * ZSTD_isError()). + */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* params, ZSTD_cParameter param, int value); + +/*! ZSTD_CCtxParams_getParameter() : + * Similar to ZSTD_CCtx_getParameter. + * Get the requested value of one compression parameter, selected by enum ZSTD_cParameter. + * @result : 0, or an error code (which can be tested with ZSTD_isError()). + */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtxParams_getParameter(const ZSTD_CCtx_params* params, ZSTD_cParameter param, int* value); + +/*! ZSTD_CCtx_setParametersUsingCCtxParams() : + * Apply a set of ZSTD_CCtx_params to the compression context. + * This can be done even after compression is started, + * if nbWorkers==0, this will have no impact until a new compression is started. + * if nbWorkers>=1, new parameters will be picked up at next job, + * with a few restrictions (windowLog, pledgedSrcSize, nbWorkers, jobSize, and overlapLog are not updated). + */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtx_setParametersUsingCCtxParams( + ZSTD_CCtx* cctx, const ZSTD_CCtx_params* params); + +/*! ZSTD_compressStream2_simpleArgs() : + * Same as ZSTD_compressStream2(), + * but using only integral types as arguments. + * This variant might be helpful for binders from dynamic languages + * which have troubles handling structures containing memory pointers. + */ +ZSTDLIB_STATIC_API size_t ZSTD_compressStream2_simpleArgs ( + ZSTD_CCtx* cctx, + void* dst, size_t dstCapacity, size_t* dstPos, + const void* src, size_t srcSize, size_t* srcPos, + ZSTD_EndDirective endOp); + + +/*************************************** +* Advanced decompression functions +***************************************/ + +/*! ZSTD_isFrame() : + * Tells if the content of `buffer` starts with a valid Frame Identifier. + * Note : Frame Identifier is 4 bytes. If `size < 4`, @return will always be 0. + * Note 2 : Legacy Frame Identifiers are considered valid only if Legacy Support is enabled. + * Note 3 : Skippable Frame Identifiers are considered valid. */ +ZSTDLIB_STATIC_API unsigned ZSTD_isFrame(const void* buffer, size_t size); + +/*! ZSTD_createDDict_byReference() : + * Create a digested dictionary, ready to start decompression operation without startup delay. + * Dictionary content is referenced, and therefore stays in dictBuffer. + * It is important that dictBuffer outlives DDict, + * it must remain read accessible throughout the lifetime of DDict */ +ZSTDLIB_STATIC_API ZSTD_DDict* ZSTD_createDDict_byReference(const void* dictBuffer, size_t dictSize); + +/*! ZSTD_DCtx_loadDictionary_byReference() : + * Same as ZSTD_DCtx_loadDictionary(), + * but references `dict` content instead of copying it into `dctx`. + * This saves memory if `dict` remains around., + * However, it's imperative that `dict` remains accessible (and unmodified) while being used, so it must outlive decompression. */ +ZSTDLIB_STATIC_API size_t ZSTD_DCtx_loadDictionary_byReference(ZSTD_DCtx* dctx, const void* dict, size_t dictSize); + +/*! ZSTD_DCtx_loadDictionary_advanced() : + * Same as ZSTD_DCtx_loadDictionary(), + * but gives direct control over + * how to load the dictionary (by copy ? by reference ?) + * and how to interpret it (automatic ? force raw mode ? full mode only ?). */ +ZSTDLIB_STATIC_API size_t ZSTD_DCtx_loadDictionary_advanced(ZSTD_DCtx* dctx, const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType); + +/*! ZSTD_DCtx_refPrefix_advanced() : + * Same as ZSTD_DCtx_refPrefix(), but gives finer control over + * how to interpret prefix content (automatic ? force raw mode (default) ? full mode only ?) */ +ZSTDLIB_STATIC_API size_t ZSTD_DCtx_refPrefix_advanced(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType); + +/*! ZSTD_DCtx_setMaxWindowSize() : + * Refuses allocating internal buffers for frames requiring a window size larger than provided limit. + * This protects a decoder context from reserving too much memory for itself (potential attack scenario). + * This parameter is only useful in streaming mode, since no internal buffer is allocated in single-pass mode. + * By default, a decompression context accepts all window sizes <= (1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT) + * @return : 0, or an error code (which can be tested using ZSTD_isError()). + */ +ZSTDLIB_STATIC_API size_t ZSTD_DCtx_setMaxWindowSize(ZSTD_DCtx* dctx, size_t maxWindowSize); + +/*! ZSTD_DCtx_getParameter() : + * Get the requested decompression parameter value, selected by enum ZSTD_dParameter, + * and store it into int* value. + * @return : 0, or an error code (which can be tested with ZSTD_isError()). + */ +ZSTDLIB_STATIC_API size_t ZSTD_DCtx_getParameter(ZSTD_DCtx* dctx, ZSTD_dParameter param, int* value); + +/* ZSTD_d_format + * experimental parameter, + * allowing selection between ZSTD_format_e input compression formats + */ +#define ZSTD_d_format ZSTD_d_experimentalParam1 +/* ZSTD_d_stableOutBuffer + * Experimental parameter. + * Default is 0 == disabled. Set to 1 to enable. + * + * Tells the decompressor that the ZSTD_outBuffer will ALWAYS be the same + * between calls, except for the modifications that zstd makes to pos (the + * caller must not modify pos). This is checked by the decompressor, and + * decompression will fail if it ever changes. Therefore the ZSTD_outBuffer + * MUST be large enough to fit the entire decompressed frame. This will be + * checked when the frame content size is known. The data in the ZSTD_outBuffer + * in the range [dst, dst + pos) MUST not be modified during decompression + * or you will get data corruption. + * + * When this flag is enabled zstd won't allocate an output buffer, because + * it can write directly to the ZSTD_outBuffer, but it will still allocate + * an input buffer large enough to fit any compressed block. This will also + * avoid the memcpy() from the internal output buffer to the ZSTD_outBuffer. + * If you need to avoid the input buffer allocation use the buffer-less + * streaming API. + * + * NOTE: So long as the ZSTD_outBuffer always points to valid memory, using + * this flag is ALWAYS memory safe, and will never access out-of-bounds + * memory. However, decompression WILL fail if you violate the preconditions. + * + * WARNING: The data in the ZSTD_outBuffer in the range [dst, dst + pos) MUST + * not be modified during decompression or you will get data corruption. This + * is because zstd needs to reference data in the ZSTD_outBuffer to regenerate + * matches. Normally zstd maintains its own buffer for this purpose, but passing + * this flag tells zstd to use the user provided buffer. + */ +#define ZSTD_d_stableOutBuffer ZSTD_d_experimentalParam2 + +/* ZSTD_d_forceIgnoreChecksum + * Experimental parameter. + * Default is 0 == disabled. Set to 1 to enable + * + * Tells the decompressor to skip checksum validation during decompression, regardless + * of whether checksumming was specified during compression. This offers some + * slight performance benefits, and may be useful for debugging. + * Param has values of type ZSTD_forceIgnoreChecksum_e + */ +#define ZSTD_d_forceIgnoreChecksum ZSTD_d_experimentalParam3 + +/* ZSTD_d_refMultipleDDicts + * Experimental parameter. + * Default is 0 == disabled. Set to 1 to enable + * + * If enabled and dctx is allocated on the heap, then additional memory will be allocated + * to store references to multiple ZSTD_DDict. That is, multiple calls of ZSTD_refDDict() + * using a given ZSTD_DCtx, rather than overwriting the previous DDict reference, will instead + * store all references. At decompression time, the appropriate dictID is selected + * from the set of DDicts based on the dictID in the frame. + * + * Usage is simply calling ZSTD_refDDict() on multiple dict buffers. + * + * Param has values of byte ZSTD_refMultipleDDicts_e + * + * WARNING: Enabling this parameter and calling ZSTD_DCtx_refDDict(), will trigger memory + * allocation for the hash table. ZSTD_freeDCtx() also frees this memory. + * Memory is allocated as per ZSTD_DCtx::customMem. + * + * Although this function allocates memory for the table, the user is still responsible for + * memory management of the underlying ZSTD_DDict* themselves. + */ +#define ZSTD_d_refMultipleDDicts ZSTD_d_experimentalParam4 + +/* ZSTD_d_disableHuffmanAssembly + * Set to 1 to disable the Huffman assembly implementation. + * The default value is 0, which allows zstd to use the Huffman assembly + * implementation if available. + * + * This parameter can be used to disable Huffman assembly at runtime. + * If you want to disable it at compile time you can define the macro + * ZSTD_DISABLE_ASM. + */ +#define ZSTD_d_disableHuffmanAssembly ZSTD_d_experimentalParam5 + +/* ZSTD_d_maxBlockSize + * Allowed values are between 1KB and ZSTD_BLOCKSIZE_MAX (128KB). + * The default is ZSTD_BLOCKSIZE_MAX, and setting to 0 will set to the default. + * + * Forces the decompressor to reject blocks whose content size is + * larger than the configured maxBlockSize. When maxBlockSize is + * larger than the windowSize, the windowSize is used instead. + * This saves memory on the decoder when you know all blocks are small. + * + * This option is typically used in conjunction with ZSTD_c_maxBlockSize. + * + * WARNING: This causes the decoder to reject otherwise valid frames + * that have block sizes larger than the configured maxBlockSize. + */ +#define ZSTD_d_maxBlockSize ZSTD_d_experimentalParam6 + + +/*! ZSTD_DCtx_setFormat() : + * This function is REDUNDANT. Prefer ZSTD_DCtx_setParameter(). + * Instruct the decoder context about what kind of data to decode next. + * This instruction is mandatory to decode data without a fully-formed header, + * such ZSTD_f_zstd1_magicless for example. + * @return : 0, or an error code (which can be tested using ZSTD_isError()). */ +ZSTD_DEPRECATED("use ZSTD_DCtx_setParameter() instead") +ZSTDLIB_STATIC_API +size_t ZSTD_DCtx_setFormat(ZSTD_DCtx* dctx, ZSTD_format_e format); + +/*! ZSTD_decompressStream_simpleArgs() : + * Same as ZSTD_decompressStream(), + * but using only integral types as arguments. + * This can be helpful for binders from dynamic languages + * which have troubles handling structures containing memory pointers. + */ +ZSTDLIB_STATIC_API size_t ZSTD_decompressStream_simpleArgs ( + ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, size_t* dstPos, + const void* src, size_t srcSize, size_t* srcPos); + + +/******************************************************************** +* Advanced streaming functions +* Warning : most of these functions are now redundant with the Advanced API. +* Once Advanced API reaches "stable" status, +* redundant functions will be deprecated, and then at some point removed. +********************************************************************/ + +/*===== Advanced Streaming compression functions =====*/ + +/*! ZSTD_initCStream_srcSize() : + * This function is DEPRECATED, and equivalent to: + * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); + * ZSTD_CCtx_refCDict(zcs, NULL); // clear the dictionary (if any) + * ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel); + * ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize); + * + * pledgedSrcSize must be correct. If it is not known at init time, use + * ZSTD_CONTENTSIZE_UNKNOWN. Note that, for compatibility with older programs, + * "0" also disables frame content size field. It may be enabled in the future. + * This prototype will generate compilation warnings. + */ +ZSTD_DEPRECATED("use ZSTD_CCtx_reset, see zstd.h for detailed instructions") +ZSTDLIB_STATIC_API +size_t ZSTD_initCStream_srcSize(ZSTD_CStream* zcs, + int compressionLevel, + unsigned long long pledgedSrcSize); + +/*! ZSTD_initCStream_usingDict() : + * This function is DEPRECATED, and is equivalent to: + * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); + * ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel); + * ZSTD_CCtx_loadDictionary(zcs, dict, dictSize); + * + * Creates of an internal CDict (incompatible with static CCtx), except if + * dict == NULL or dictSize < 8, in which case no dict is used. + * Note: dict is loaded with ZSTD_dct_auto (treated as a full zstd dictionary if + * it begins with ZSTD_MAGIC_DICTIONARY, else as raw content) and ZSTD_dlm_byCopy. + * This prototype will generate compilation warnings. + */ +ZSTD_DEPRECATED("use ZSTD_CCtx_reset, see zstd.h for detailed instructions") +ZSTDLIB_STATIC_API +size_t ZSTD_initCStream_usingDict(ZSTD_CStream* zcs, + const void* dict, size_t dictSize, + int compressionLevel); + +/*! ZSTD_initCStream_advanced() : + * This function is DEPRECATED, and is equivalent to: + * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); + * ZSTD_CCtx_setParams(zcs, params); + * ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize); + * ZSTD_CCtx_loadDictionary(zcs, dict, dictSize); + * + * dict is loaded with ZSTD_dct_auto and ZSTD_dlm_byCopy. + * pledgedSrcSize must be correct. + * If srcSize is not known at init time, use value ZSTD_CONTENTSIZE_UNKNOWN. + * This prototype will generate compilation warnings. + */ +ZSTD_DEPRECATED("use ZSTD_CCtx_reset, see zstd.h for detailed instructions") +ZSTDLIB_STATIC_API +size_t ZSTD_initCStream_advanced(ZSTD_CStream* zcs, + const void* dict, size_t dictSize, + ZSTD_parameters params, + unsigned long long pledgedSrcSize); + +/*! ZSTD_initCStream_usingCDict() : + * This function is DEPRECATED, and equivalent to: + * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); + * ZSTD_CCtx_refCDict(zcs, cdict); + * + * note : cdict will just be referenced, and must outlive compression session + * This prototype will generate compilation warnings. + */ +ZSTD_DEPRECATED("use ZSTD_CCtx_reset and ZSTD_CCtx_refCDict, see zstd.h for detailed instructions") +ZSTDLIB_STATIC_API +size_t ZSTD_initCStream_usingCDict(ZSTD_CStream* zcs, const ZSTD_CDict* cdict); + +/*! ZSTD_initCStream_usingCDict_advanced() : + * This function is DEPRECATED, and is equivalent to: + * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); + * ZSTD_CCtx_setFParams(zcs, fParams); + * ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize); + * ZSTD_CCtx_refCDict(zcs, cdict); + * + * same as ZSTD_initCStream_usingCDict(), with control over frame parameters. + * pledgedSrcSize must be correct. If srcSize is not known at init time, use + * value ZSTD_CONTENTSIZE_UNKNOWN. + * This prototype will generate compilation warnings. + */ +ZSTD_DEPRECATED("use ZSTD_CCtx_reset and ZSTD_CCtx_refCDict, see zstd.h for detailed instructions") +ZSTDLIB_STATIC_API +size_t ZSTD_initCStream_usingCDict_advanced(ZSTD_CStream* zcs, + const ZSTD_CDict* cdict, + ZSTD_frameParameters fParams, + unsigned long long pledgedSrcSize); + +/*! ZSTD_resetCStream() : + * This function is DEPRECATED, and is equivalent to: + * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); + * ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize); + * Note: ZSTD_resetCStream() interprets pledgedSrcSize == 0 as ZSTD_CONTENTSIZE_UNKNOWN, but + * ZSTD_CCtx_setPledgedSrcSize() does not do the same, so ZSTD_CONTENTSIZE_UNKNOWN must be + * explicitly specified. + * + * start a new frame, using same parameters from previous frame. + * This is typically useful to skip dictionary loading stage, since it will reuse it in-place. + * Note that zcs must be init at least once before using ZSTD_resetCStream(). + * If pledgedSrcSize is not known at reset time, use macro ZSTD_CONTENTSIZE_UNKNOWN. + * If pledgedSrcSize > 0, its value must be correct, as it will be written in header, and controlled at the end. + * For the time being, pledgedSrcSize==0 is interpreted as "srcSize unknown" for compatibility with older programs, + * but it will change to mean "empty" in future version, so use macro ZSTD_CONTENTSIZE_UNKNOWN instead. + * @return : 0, or an error code (which can be tested using ZSTD_isError()) + * This prototype will generate compilation warnings. + */ +ZSTD_DEPRECATED("use ZSTD_CCtx_reset, see zstd.h for detailed instructions") +ZSTDLIB_STATIC_API +size_t ZSTD_resetCStream(ZSTD_CStream* zcs, unsigned long long pledgedSrcSize); + + +typedef struct { + unsigned long long ingested; /* nb input bytes read and buffered */ + unsigned long long consumed; /* nb input bytes actually compressed */ + unsigned long long produced; /* nb of compressed bytes generated and buffered */ + unsigned long long flushed; /* nb of compressed bytes flushed : not provided; can be tracked from caller side */ + unsigned currentJobID; /* MT only : latest started job nb */ + unsigned nbActiveWorkers; /* MT only : nb of workers actively compressing at probe time */ +} ZSTD_frameProgression; + +/* ZSTD_getFrameProgression() : + * tells how much data has been ingested (read from input) + * consumed (input actually compressed) and produced (output) for current frame. + * Note : (ingested - consumed) is amount of input data buffered internally, not yet compressed. + * Aggregates progression inside active worker threads. + */ +ZSTDLIB_STATIC_API ZSTD_frameProgression ZSTD_getFrameProgression(const ZSTD_CCtx* cctx); + +/*! ZSTD_toFlushNow() : + * Tell how many bytes are ready to be flushed immediately. + * Useful for multithreading scenarios (nbWorkers >= 1). + * Probe the oldest active job, defined as oldest job not yet entirely flushed, + * and check its output buffer. + * @return : amount of data stored in oldest job and ready to be flushed immediately. + * if @return == 0, it means either : + * + there is no active job (could be checked with ZSTD_frameProgression()), or + * + oldest job is still actively compressing data, + * but everything it has produced has also been flushed so far, + * therefore flush speed is limited by production speed of oldest job + * irrespective of the speed of concurrent (and newer) jobs. + */ +ZSTDLIB_STATIC_API size_t ZSTD_toFlushNow(ZSTD_CCtx* cctx); + + +/*===== Advanced Streaming decompression functions =====*/ + +/*! + * This function is deprecated, and is equivalent to: + * + * ZSTD_DCtx_reset(zds, ZSTD_reset_session_only); + * ZSTD_DCtx_loadDictionary(zds, dict, dictSize); + * + * note: no dictionary will be used if dict == NULL or dictSize < 8 + */ +ZSTD_DEPRECATED("use ZSTD_DCtx_reset + ZSTD_DCtx_loadDictionary, see zstd.h for detailed instructions") +ZSTDLIB_STATIC_API size_t ZSTD_initDStream_usingDict(ZSTD_DStream* zds, const void* dict, size_t dictSize); + +/*! + * This function is deprecated, and is equivalent to: + * + * ZSTD_DCtx_reset(zds, ZSTD_reset_session_only); + * ZSTD_DCtx_refDDict(zds, ddict); + * + * note : ddict is referenced, it must outlive decompression session + */ +ZSTD_DEPRECATED("use ZSTD_DCtx_reset + ZSTD_DCtx_refDDict, see zstd.h for detailed instructions") +ZSTDLIB_STATIC_API size_t ZSTD_initDStream_usingDDict(ZSTD_DStream* zds, const ZSTD_DDict* ddict); + +/*! + * This function is deprecated, and is equivalent to: + * + * ZSTD_DCtx_reset(zds, ZSTD_reset_session_only); + * + * reuse decompression parameters from previous init; saves dictionary loading + */ +ZSTD_DEPRECATED("use ZSTD_DCtx_reset, see zstd.h for detailed instructions") +ZSTDLIB_STATIC_API size_t ZSTD_resetDStream(ZSTD_DStream* zds); + + +/* ********************* BLOCK-LEVEL SEQUENCE PRODUCER API ********************* + * + * *** OVERVIEW *** + * The Block-Level Sequence Producer API allows users to provide their own custom + * sequence producer which libzstd invokes to process each block. The produced list + * of sequences (literals and matches) is then post-processed by libzstd to produce + * valid compressed blocks. + * + * This block-level offload API is a more granular complement of the existing + * frame-level offload API compressSequences() (introduced in v1.5.1). It offers + * an easier migration story for applications already integrated with libzstd: the + * user application continues to invoke the same compression functions + * ZSTD_compress2() or ZSTD_compressStream2() as usual, and transparently benefits + * from the specific advantages of the external sequence producer. For example, + * the sequence producer could be tuned to take advantage of known characteristics + * of the input, to offer better speed / ratio, or could leverage hardware + * acceleration not available within libzstd itself. + * + * See contrib/externalSequenceProducer for an example program employing the + * Block-Level Sequence Producer API. + * + * *** USAGE *** + * The user is responsible for implementing a function of type + * ZSTD_sequenceProducer_F. For each block, zstd will pass the following + * arguments to the user-provided function: + * + * - sequenceProducerState: a pointer to a user-managed state for the sequence + * producer. + * + * - outSeqs, outSeqsCapacity: an output buffer for the sequence producer. + * outSeqsCapacity is guaranteed >= ZSTD_sequenceBound(srcSize). The memory + * backing outSeqs is managed by the CCtx. + * + * - src, srcSize: an input buffer for the sequence producer to parse. + * srcSize is guaranteed to be <= ZSTD_BLOCKSIZE_MAX. + * + * - dict, dictSize: a history buffer, which may be empty, which the sequence + * producer may reference as it parses the src buffer. Currently, zstd will + * always pass dictSize == 0 into external sequence producers, but this will + * change in the future. + * + * - compressionLevel: a signed integer representing the zstd compression level + * set by the user for the current operation. The sequence producer may choose + * to use this information to change its compression strategy and speed/ratio + * tradeoff. Note: the compression level does not reflect zstd parameters set + * through the advanced API. + * + * - windowSize: a size_t representing the maximum allowed offset for external + * sequences. Note that sequence offsets are sometimes allowed to exceed the + * windowSize if a dictionary is present, see doc/zstd_compression_format.md + * for details. + * + * The user-provided function shall return a size_t representing the number of + * sequences written to outSeqs. This return value will be treated as an error + * code if it is greater than outSeqsCapacity. The return value must be non-zero + * if srcSize is non-zero. The ZSTD_SEQUENCE_PRODUCER_ERROR macro is provided + * for convenience, but any value greater than outSeqsCapacity will be treated as + * an error code. + * + * If the user-provided function does not return an error code, the sequences + * written to outSeqs must be a valid parse of the src buffer. Data corruption may + * occur if the parse is not valid. A parse is defined to be valid if the + * following conditions hold: + * - The sum of matchLengths and literalLengths must equal srcSize. + * - All sequences in the parse, except for the final sequence, must have + * matchLength >= ZSTD_MINMATCH_MIN. The final sequence must have + * matchLength >= ZSTD_MINMATCH_MIN or matchLength == 0. + * - All offsets must respect the windowSize parameter as specified in + * doc/zstd_compression_format.md. + * - If the final sequence has matchLength == 0, it must also have offset == 0. + * + * zstd will only validate these conditions (and fail compression if they do not + * hold) if the ZSTD_c_validateSequences cParam is enabled. Note that sequence + * validation has a performance cost. + * + * If the user-provided function returns an error, zstd will either fall back + * to an internal sequence producer or fail the compression operation. The user can + * choose between the two behaviors by setting the ZSTD_c_enableSeqProducerFallback + * cParam. Fallback compression will follow any other cParam settings, such as + * compression level, the same as in a normal compression operation. + * + * The user shall instruct zstd to use a particular ZSTD_sequenceProducer_F + * function by calling + * ZSTD_registerSequenceProducer(cctx, + * sequenceProducerState, + * sequenceProducer) + * This setting will persist until the next parameter reset of the CCtx. + * + * The sequenceProducerState must be initialized by the user before calling + * ZSTD_registerSequenceProducer(). The user is responsible for destroying the + * sequenceProducerState. + * + * *** LIMITATIONS *** + * This API is compatible with all zstd compression APIs which respect advanced parameters. + * However, there are three limitations: + * + * First, the ZSTD_c_enableLongDistanceMatching cParam is not currently supported. + * COMPRESSION WILL FAIL if it is enabled and the user tries to compress with a block-level + * external sequence producer. + * - Note that ZSTD_c_enableLongDistanceMatching is auto-enabled by default in some + * cases (see its documentation for details). Users must explicitly set + * ZSTD_c_enableLongDistanceMatching to ZSTD_ps_disable in such cases if an external + * sequence producer is registered. + * - As of this writing, ZSTD_c_enableLongDistanceMatching is disabled by default + * whenever ZSTD_c_windowLog < 128MB, but that's subject to change. Users should + * check the docs on ZSTD_c_enableLongDistanceMatching whenever the Block-Level Sequence + * Producer API is used in conjunction with advanced settings (like ZSTD_c_windowLog). + * + * Second, history buffers are not currently supported. Concretely, zstd will always pass + * dictSize == 0 to the external sequence producer (for now). This has two implications: + * - Dictionaries are not currently supported. Compression will *not* fail if the user + * references a dictionary, but the dictionary won't have any effect. + * - Stream history is not currently supported. All advanced compression APIs, including + * streaming APIs, work with external sequence producers, but each block is treated as + * an independent chunk without history from previous blocks. + * + * Third, multi-threading within a single compression is not currently supported. In other words, + * COMPRESSION WILL FAIL if ZSTD_c_nbWorkers > 0 and an external sequence producer is registered. + * Multi-threading across compressions is fine: simply create one CCtx per thread. + * + * Long-term, we plan to overcome all three limitations. There is no technical blocker to + * overcoming them. It is purely a question of engineering effort. + */ + +#define ZSTD_SEQUENCE_PRODUCER_ERROR ((size_t)(-1)) + +typedef size_t (*ZSTD_sequenceProducer_F) ( + void* sequenceProducerState, + ZSTD_Sequence* outSeqs, size_t outSeqsCapacity, + const void* src, size_t srcSize, + const void* dict, size_t dictSize, + int compressionLevel, + size_t windowSize +); + +/*! ZSTD_registerSequenceProducer() : + * Instruct zstd to use a block-level external sequence producer function. + * + * The sequenceProducerState must be initialized by the caller, and the caller is + * responsible for managing its lifetime. This parameter is sticky across + * compressions. It will remain set until the user explicitly resets compression + * parameters. + * + * Sequence producer registration is considered to be an "advanced parameter", + * part of the "advanced API". This means it will only have an effect on compression + * APIs which respect advanced parameters, such as compress2() and compressStream2(). + * Older compression APIs such as compressCCtx(), which predate the introduction of + * "advanced parameters", will ignore any external sequence producer setting. + * + * The sequence producer can be "cleared" by registering a NULL function pointer. This + * removes all limitations described above in the "LIMITATIONS" section of the API docs. + * + * The user is strongly encouraged to read the full API documentation (above) before + * calling this function. */ +ZSTDLIB_STATIC_API void +ZSTD_registerSequenceProducer( + ZSTD_CCtx* cctx, + void* sequenceProducerState, + ZSTD_sequenceProducer_F sequenceProducer +); + +/*! ZSTD_CCtxParams_registerSequenceProducer() : + * Same as ZSTD_registerSequenceProducer(), but operates on ZSTD_CCtx_params. + * This is used for accurate size estimation with ZSTD_estimateCCtxSize_usingCCtxParams(), + * which is needed when creating a ZSTD_CCtx with ZSTD_initStaticCCtx(). + * + * If you are using the external sequence producer API in a scenario where ZSTD_initStaticCCtx() + * is required, then this function is for you. Otherwise, you probably don't need it. + * + * See tests/zstreamtest.c for example usage. */ +ZSTDLIB_STATIC_API void +ZSTD_CCtxParams_registerSequenceProducer( + ZSTD_CCtx_params* params, + void* sequenceProducerState, + ZSTD_sequenceProducer_F sequenceProducer +); + + +/********************************************************************* +* Buffer-less and synchronous inner streaming functions (DEPRECATED) +* +* This API is deprecated, and will be removed in a future version. +* It allows streaming (de)compression with user allocated buffers. +* However, it is hard to use, and not as well tested as the rest of +* our API. +* +* Please use the normal streaming API instead: ZSTD_compressStream2, +* and ZSTD_decompressStream. +* If there is functionality that you need, but it doesn't provide, +* please open an issue on our GitHub. +********************************************************************* */ + +/** + Buffer-less streaming compression (synchronous mode) + + A ZSTD_CCtx object is required to track streaming operations. + Use ZSTD_createCCtx() / ZSTD_freeCCtx() to manage resource. + ZSTD_CCtx object can be reused multiple times within successive compression operations. + + Start by initializing a context. + Use ZSTD_compressBegin(), or ZSTD_compressBegin_usingDict() for dictionary compression. + + Then, consume your input using ZSTD_compressContinue(). + There are some important considerations to keep in mind when using this advanced function : + - ZSTD_compressContinue() has no internal buffer. It uses externally provided buffers only. + - Interface is synchronous : input is consumed entirely and produces 1+ compressed blocks. + - Caller must ensure there is enough space in `dst` to store compressed data under worst case scenario. + Worst case evaluation is provided by ZSTD_compressBound(). + ZSTD_compressContinue() doesn't guarantee recover after a failed compression. + - ZSTD_compressContinue() presumes prior input ***is still accessible and unmodified*** (up to maximum distance size, see WindowLog). + It remembers all previous contiguous blocks, plus one separated memory segment (which can itself consists of multiple contiguous blocks) + - ZSTD_compressContinue() detects that prior input has been overwritten when `src` buffer overlaps. + In which case, it will "discard" the relevant memory section from its history. + + Finish a frame with ZSTD_compressEnd(), which will write the last block(s) and optional checksum. + It's possible to use srcSize==0, in which case, it will write a final empty block to end the frame. + Without last block mark, frames are considered unfinished (hence corrupted) by compliant decoders. + + `ZSTD_CCtx` object can be reused (ZSTD_compressBegin()) to compress again. +*/ + +/*===== Buffer-less streaming compression functions =====*/ +ZSTD_DEPRECATED("The buffer-less API is deprecated in favor of the normal streaming API. See docs.") +ZSTDLIB_STATIC_API size_t ZSTD_compressBegin(ZSTD_CCtx* cctx, int compressionLevel); +ZSTD_DEPRECATED("The buffer-less API is deprecated in favor of the normal streaming API. See docs.") +ZSTDLIB_STATIC_API size_t ZSTD_compressBegin_usingDict(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel); +ZSTD_DEPRECATED("The buffer-less API is deprecated in favor of the normal streaming API. See docs.") +ZSTDLIB_STATIC_API size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict); /**< note: fails if cdict==NULL */ + +ZSTD_DEPRECATED("This function will likely be removed in a future release. It is misleading and has very limited utility.") +ZSTDLIB_STATIC_API +size_t ZSTD_copyCCtx(ZSTD_CCtx* cctx, const ZSTD_CCtx* preparedCCtx, unsigned long long pledgedSrcSize); /**< note: if pledgedSrcSize is not known, use ZSTD_CONTENTSIZE_UNKNOWN */ + +ZSTD_DEPRECATED("The buffer-less API is deprecated in favor of the normal streaming API. See docs.") +ZSTDLIB_STATIC_API size_t ZSTD_compressContinue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); +ZSTD_DEPRECATED("The buffer-less API is deprecated in favor of the normal streaming API. See docs.") +ZSTDLIB_STATIC_API size_t ZSTD_compressEnd(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); + +/* The ZSTD_compressBegin_advanced() and ZSTD_compressBegin_usingCDict_advanced() are now DEPRECATED and will generate a compiler warning */ +ZSTD_DEPRECATED("use advanced API to access custom parameters") +ZSTDLIB_STATIC_API +size_t ZSTD_compressBegin_advanced(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, ZSTD_parameters params, unsigned long long pledgedSrcSize); /**< pledgedSrcSize : If srcSize is not known at init time, use ZSTD_CONTENTSIZE_UNKNOWN */ +ZSTD_DEPRECATED("use advanced API to access custom parameters") +ZSTDLIB_STATIC_API +size_t ZSTD_compressBegin_usingCDict_advanced(ZSTD_CCtx* const cctx, const ZSTD_CDict* const cdict, ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize); /* compression parameters are already set within cdict. pledgedSrcSize must be correct. If srcSize is not known, use macro ZSTD_CONTENTSIZE_UNKNOWN */ +/** + Buffer-less streaming decompression (synchronous mode) + + A ZSTD_DCtx object is required to track streaming operations. + Use ZSTD_createDCtx() / ZSTD_freeDCtx() to manage it. + A ZSTD_DCtx object can be reused multiple times. + + First typical operation is to retrieve frame parameters, using ZSTD_getFrameHeader(). + Frame header is extracted from the beginning of compressed frame, so providing only the frame's beginning is enough. + Data fragment must be large enough to ensure successful decoding. + `ZSTD_frameHeaderSize_max` bytes is guaranteed to always be large enough. + result : 0 : successful decoding, the `ZSTD_frameHeader` structure is correctly filled. + >0 : `srcSize` is too small, please provide at least result bytes on next attempt. + errorCode, which can be tested using ZSTD_isError(). + + It fills a ZSTD_FrameHeader structure with important information to correctly decode the frame, + such as the dictionary ID, content size, or maximum back-reference distance (`windowSize`). + Note that these values could be wrong, either because of data corruption, or because a 3rd party deliberately spoofs false information. + As a consequence, check that values remain within valid application range. + For example, do not allocate memory blindly, check that `windowSize` is within expectation. + Each application can set its own limits, depending on local restrictions. + For extended interoperability, it is recommended to support `windowSize` of at least 8 MB. + + ZSTD_decompressContinue() needs previous data blocks during decompression, up to `windowSize` bytes. + ZSTD_decompressContinue() is very sensitive to contiguity, + if 2 blocks don't follow each other, make sure that either the compressor breaks contiguity at the same place, + or that previous contiguous segment is large enough to properly handle maximum back-reference distance. + There are multiple ways to guarantee this condition. + + The most memory efficient way is to use a round buffer of sufficient size. + Sufficient size is determined by invoking ZSTD_decodingBufferSize_min(), + which can return an error code if required value is too large for current system (in 32-bits mode). + In a round buffer methodology, ZSTD_decompressContinue() decompresses each block next to previous one, + up to the moment there is not enough room left in the buffer to guarantee decoding another full block, + which maximum size is provided in `ZSTD_frameHeader` structure, field `blockSizeMax`. + At which point, decoding can resume from the beginning of the buffer. + Note that already decoded data stored in the buffer should be flushed before being overwritten. + + There are alternatives possible, for example using two or more buffers of size `windowSize` each, though they consume more memory. + + Finally, if you control the compression process, you can also ignore all buffer size rules, + as long as the encoder and decoder progress in "lock-step", + aka use exactly the same buffer sizes, break contiguity at the same place, etc. + + Once buffers are setup, start decompression, with ZSTD_decompressBegin(). + If decompression requires a dictionary, use ZSTD_decompressBegin_usingDict() or ZSTD_decompressBegin_usingDDict(). + + Then use ZSTD_nextSrcSizeToDecompress() and ZSTD_decompressContinue() alternatively. + ZSTD_nextSrcSizeToDecompress() tells how many bytes to provide as 'srcSize' to ZSTD_decompressContinue(). + ZSTD_decompressContinue() requires this _exact_ amount of bytes, or it will fail. + + result of ZSTD_decompressContinue() is the number of bytes regenerated within 'dst' (necessarily <= dstCapacity). + It can be zero : it just means ZSTD_decompressContinue() has decoded some metadata item. + It can also be an error code, which can be tested with ZSTD_isError(). + + A frame is fully decoded when ZSTD_nextSrcSizeToDecompress() returns zero. + Context can then be reset to start a new decompression. + + Note : it's possible to know if next input to present is a header or a block, using ZSTD_nextInputType(). + This information is not required to properly decode a frame. + + == Special case : skippable frames == + + Skippable frames allow integration of user-defined data into a flow of concatenated frames. + Skippable frames will be ignored (skipped) by decompressor. + The format of skippable frames is as follows : + a) Skippable frame ID - 4 Bytes, Little endian format, any value from 0x184D2A50 to 0x184D2A5F + b) Frame Size - 4 Bytes, Little endian format, unsigned 32-bits + c) Frame Content - any content (User Data) of length equal to Frame Size + For skippable frames ZSTD_getFrameHeader() returns zfhPtr->frameType==ZSTD_skippableFrame. + For skippable frames ZSTD_decompressContinue() always returns 0 : it only skips the content. +*/ + +/*===== Buffer-less streaming decompression functions =====*/ + +ZSTDLIB_STATIC_API size_t ZSTD_decodingBufferSize_min(unsigned long long windowSize, unsigned long long frameContentSize); /**< when frame content size is not known, pass in frameContentSize == ZSTD_CONTENTSIZE_UNKNOWN */ + +ZSTDLIB_STATIC_API size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx); +ZSTDLIB_STATIC_API size_t ZSTD_decompressBegin_usingDict(ZSTD_DCtx* dctx, const void* dict, size_t dictSize); +ZSTDLIB_STATIC_API size_t ZSTD_decompressBegin_usingDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict); + +ZSTDLIB_STATIC_API size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx); +ZSTDLIB_STATIC_API size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); + +/* misc */ +ZSTD_DEPRECATED("This function will likely be removed in the next minor release. It is misleading and has very limited utility.") +ZSTDLIB_STATIC_API void ZSTD_copyDCtx(ZSTD_DCtx* dctx, const ZSTD_DCtx* preparedDCtx); +typedef enum { ZSTDnit_frameHeader, ZSTDnit_blockHeader, ZSTDnit_block, ZSTDnit_lastBlock, ZSTDnit_checksum, ZSTDnit_skippableFrame } ZSTD_nextInputType_e; +ZSTDLIB_STATIC_API ZSTD_nextInputType_e ZSTD_nextInputType(ZSTD_DCtx* dctx); + + + + +/* ========================================= */ +/** Block level API (DEPRECATED) */ +/* ========================================= */ + +/*! + + This API is deprecated in favor of the regular compression API. + You can get the frame header down to 2 bytes by setting: + - ZSTD_c_format = ZSTD_f_zstd1_magicless + - ZSTD_c_contentSizeFlag = 0 + - ZSTD_c_checksumFlag = 0 + - ZSTD_c_dictIDFlag = 0 + + This API is not as well tested as our normal API, so we recommend not using it. + We will be removing it in a future version. If the normal API doesn't provide + the functionality you need, please open a GitHub issue. + + Block functions produce and decode raw zstd blocks, without frame metadata. + Frame metadata cost is typically ~12 bytes, which can be non-negligible for very small blocks (< 100 bytes). + But users will have to take in charge needed metadata to regenerate data, such as compressed and content sizes. + + A few rules to respect : + - Compressing and decompressing require a context structure + + Use ZSTD_createCCtx() and ZSTD_createDCtx() + - It is necessary to init context before starting + + compression : any ZSTD_compressBegin*() variant, including with dictionary + + decompression : any ZSTD_decompressBegin*() variant, including with dictionary + - Block size is limited, it must be <= ZSTD_getBlockSize() <= ZSTD_BLOCKSIZE_MAX == 128 KB + + If input is larger than a block size, it's necessary to split input data into multiple blocks + + For inputs larger than a single block, consider using regular ZSTD_compress() instead. + Frame metadata is not that costly, and quickly becomes negligible as source size grows larger than a block. + - When a block is considered not compressible enough, ZSTD_compressBlock() result will be 0 (zero) ! + ===> In which case, nothing is produced into `dst` ! + + User __must__ test for such outcome and deal directly with uncompressed data + + A block cannot be declared incompressible if ZSTD_compressBlock() return value was != 0. + Doing so would mess up with statistics history, leading to potential data corruption. + + ZSTD_decompressBlock() _doesn't accept uncompressed data as input_ !! + + In case of multiple successive blocks, should some of them be uncompressed, + decoder must be informed of their existence in order to follow proper history. + Use ZSTD_insertBlock() for such a case. +*/ + +/*===== Raw zstd block functions =====*/ +ZSTD_DEPRECATED("The block API is deprecated in favor of the normal compression API. See docs.") +ZSTDLIB_STATIC_API size_t ZSTD_getBlockSize (const ZSTD_CCtx* cctx); +ZSTD_DEPRECATED("The block API is deprecated in favor of the normal compression API. See docs.") +ZSTDLIB_STATIC_API size_t ZSTD_compressBlock (ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); +ZSTD_DEPRECATED("The block API is deprecated in favor of the normal compression API. See docs.") +ZSTDLIB_STATIC_API size_t ZSTD_decompressBlock(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); +ZSTD_DEPRECATED("The block API is deprecated in favor of the normal compression API. See docs.") +ZSTDLIB_STATIC_API size_t ZSTD_insertBlock (ZSTD_DCtx* dctx, const void* blockStart, size_t blockSize); /**< insert uncompressed block into `dctx` history. Useful for multi-blocks decompression. */ + +#if defined (__cplusplus) +} +#endif + +#endif /* ZSTD_H_ZSTD_STATIC_LINKING_ONLY */ diff --git a/libretrodroid/src/main/cpp/libchdr/deps/zstd-1.5.7/zstd_errors.h b/libretrodroid/src/main/cpp/libchdr/deps/zstd-1.5.7/zstd_errors.h new file mode 100644 index 000000000..c548a2c10 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/deps/zstd-1.5.7/zstd_errors.h @@ -0,0 +1,107 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTD_ERRORS_H_398273423 +#define ZSTD_ERRORS_H_398273423 + +#if defined (__cplusplus) +extern "C" { +#endif + +/* ===== ZSTDERRORLIB_API : control library symbols visibility ===== */ +#ifndef ZSTDERRORLIB_VISIBLE + /* Backwards compatibility with old macro name */ +# ifdef ZSTDERRORLIB_VISIBILITY +# define ZSTDERRORLIB_VISIBLE ZSTDERRORLIB_VISIBILITY +# elif defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__MINGW32__) +# define ZSTDERRORLIB_VISIBLE __attribute__ ((visibility ("default"))) +# else +# define ZSTDERRORLIB_VISIBLE +# endif +#endif + +#ifndef ZSTDERRORLIB_HIDDEN +# if defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__MINGW32__) +# define ZSTDERRORLIB_HIDDEN __attribute__ ((visibility ("hidden"))) +# else +# define ZSTDERRORLIB_HIDDEN +# endif +#endif + +#if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1) +# define ZSTDERRORLIB_API __declspec(dllexport) ZSTDERRORLIB_VISIBLE +#elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1) +# define ZSTDERRORLIB_API __declspec(dllimport) ZSTDERRORLIB_VISIBLE /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/ +#else +# define ZSTDERRORLIB_API ZSTDERRORLIB_VISIBLE +#endif + +/*-********************************************* + * Error codes list + *-********************************************* + * Error codes _values_ are pinned down since v1.3.1 only. + * Therefore, don't rely on values if you may link to any version < v1.3.1. + * + * Only values < 100 are considered stable. + * + * note 1 : this API shall be used with static linking only. + * dynamic linking is not yet officially supported. + * note 2 : Prefer relying on the enum than on its value whenever possible + * This is the only supported way to use the error list < v1.3.1 + * note 3 : ZSTD_isError() is always correct, whatever the library version. + **********************************************/ +typedef enum { + ZSTD_error_no_error = 0, + ZSTD_error_GENERIC = 1, + ZSTD_error_prefix_unknown = 10, + ZSTD_error_version_unsupported = 12, + ZSTD_error_frameParameter_unsupported = 14, + ZSTD_error_frameParameter_windowTooLarge = 16, + ZSTD_error_corruption_detected = 20, + ZSTD_error_checksum_wrong = 22, + ZSTD_error_literals_headerWrong = 24, + ZSTD_error_dictionary_corrupted = 30, + ZSTD_error_dictionary_wrong = 32, + ZSTD_error_dictionaryCreation_failed = 34, + ZSTD_error_parameter_unsupported = 40, + ZSTD_error_parameter_combination_unsupported = 41, + ZSTD_error_parameter_outOfBound = 42, + ZSTD_error_tableLog_tooLarge = 44, + ZSTD_error_maxSymbolValue_tooLarge = 46, + ZSTD_error_maxSymbolValue_tooSmall = 48, + ZSTD_error_cannotProduce_uncompressedBlock = 49, + ZSTD_error_stabilityCondition_notRespected = 50, + ZSTD_error_stage_wrong = 60, + ZSTD_error_init_missing = 62, + ZSTD_error_memory_allocation = 64, + ZSTD_error_workSpace_tooSmall= 66, + ZSTD_error_dstSize_tooSmall = 70, + ZSTD_error_srcSize_wrong = 72, + ZSTD_error_dstBuffer_null = 74, + ZSTD_error_noForwardProgress_destFull = 80, + ZSTD_error_noForwardProgress_inputEmpty = 82, + /* following error codes are __NOT STABLE__, they can be removed or changed in future versions */ + ZSTD_error_frameIndex_tooLarge = 100, + ZSTD_error_seekableIO = 102, + ZSTD_error_dstBuffer_wrong = 104, + ZSTD_error_srcBuffer_wrong = 105, + ZSTD_error_sequenceProducer_failed = 106, + ZSTD_error_externalSequences_invalid = 107, + ZSTD_error_maxCode = 120 /* never EVER use this value directly, it can change in future versions! Use ZSTD_isError() instead */ +} ZSTD_ErrorCode; + +ZSTDERRORLIB_API const char* ZSTD_getErrorString(ZSTD_ErrorCode code); /**< Same as ZSTD_getErrorName, but using a `ZSTD_ErrorCode` enum argument */ + + +#if defined (__cplusplus) +} +#endif + +#endif /* ZSTD_ERRORS_H_398273423 */ diff --git a/libretrodroid/src/main/cpp/libchdr/deps/zstd-1.5.7/zstddeclib.c b/libretrodroid/src/main/cpp/libchdr/deps/zstd-1.5.7/zstddeclib.c new file mode 100644 index 000000000..d0755de51 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/deps/zstd-1.5.7/zstddeclib.c @@ -0,0 +1,23644 @@ +/** + * \file zstddeclib.c + * Single-file Zstandard decompressor. + * + * Generate using: + * \code + * python combine.py -r ../../lib -x legacy/zstd_legacy.h -o zstddeclib.c zstddeclib-in.c + * \endcode + */ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ +/* + * Settings to bake for the standalone decompressor. + * + * Note: It's important that none of these affects 'zstd.h' (only the + * implementation files we're amalgamating). + * + * Note: MEM_MODULE stops xxhash redefining BYTE, U16, etc., which are also + * defined in mem.h (breaking C99 compatibility). + * + * Note: the undefs for xxHash allow Zstd's implementation to coincide with + * standalone xxHash usage (with global defines). + * + * Note: if you enable ZSTD_LEGACY_SUPPORT the combine.py script will need + * re-running without the "-x legacy/zstd_legacy.h" option (it excludes the + * legacy support at the source level). + */ +#define DEBUGLEVEL 0 +#define MEM_MODULE +#undef XXH_NAMESPACE +#define XXH_NAMESPACE ZSTD_ +#undef XXH_PRIVATE_API +#define XXH_PRIVATE_API +#undef XXH_INLINE_ALL +#define XXH_INLINE_ALL +#define ZSTD_LEGACY_SUPPORT 0 +#define ZSTD_STRIP_ERROR_STRINGS +#define ZSTD_TRACE 0 +/* TODO: Can't amalgamate ASM function */ +#define ZSTD_DISABLE_ASM 1 + +/* Include zstd_deps.h first with all the options we need enabled. */ +#define ZSTD_DEPS_NEED_MALLOC +/**** start inlining common/zstd_deps.h ****/ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +/* This file provides common libc dependencies that zstd requires. + * The purpose is to allow replacing this file with a custom implementation + * to compile zstd without libc support. + */ + +/* Need: + * NULL + * INT_MAX + * UINT_MAX + * ZSTD_memcpy() + * ZSTD_memset() + * ZSTD_memmove() + */ +#ifndef ZSTD_DEPS_COMMON +#define ZSTD_DEPS_COMMON + +/* Even though we use qsort_r only for the dictionary builder, the macro + * _GNU_SOURCE has to be declared *before* the inclusion of any standard + * header and the script 'combine.sh' combines the whole zstd source code + * in a single file. + */ +#if defined(__linux) || defined(__linux__) || defined(linux) || defined(__gnu_linux__) || \ + defined(__CYGWIN__) || defined(__MSYS__) +#if !defined(_GNU_SOURCE) && !defined(__ANDROID__) /* NDK doesn't ship qsort_r(). */ +#define _GNU_SOURCE +#endif +#endif + +#include +#include +#include + +#if defined(__GNUC__) && __GNUC__ >= 4 +# define ZSTD_memcpy(d,s,l) __builtin_memcpy((d),(s),(l)) +# define ZSTD_memmove(d,s,l) __builtin_memmove((d),(s),(l)) +# define ZSTD_memset(p,v,l) __builtin_memset((p),(v),(l)) +#else +# define ZSTD_memcpy(d,s,l) memcpy((d),(s),(l)) +# define ZSTD_memmove(d,s,l) memmove((d),(s),(l)) +# define ZSTD_memset(p,v,l) memset((p),(v),(l)) +#endif + +#endif /* ZSTD_DEPS_COMMON */ + +/* Need: + * ZSTD_malloc() + * ZSTD_free() + * ZSTD_calloc() + */ +#ifdef ZSTD_DEPS_NEED_MALLOC +#ifndef ZSTD_DEPS_MALLOC +#define ZSTD_DEPS_MALLOC + +#include + +#define ZSTD_malloc(s) malloc(s) +#define ZSTD_calloc(n,s) calloc((n), (s)) +#define ZSTD_free(p) free((p)) + +#endif /* ZSTD_DEPS_MALLOC */ +#endif /* ZSTD_DEPS_NEED_MALLOC */ + +/* + * Provides 64-bit math support. + * Need: + * U64 ZSTD_div64(U64 dividend, U32 divisor) + */ +#ifdef ZSTD_DEPS_NEED_MATH64 +#ifndef ZSTD_DEPS_MATH64 +#define ZSTD_DEPS_MATH64 + +#define ZSTD_div64(dividend, divisor) ((dividend) / (divisor)) + +#endif /* ZSTD_DEPS_MATH64 */ +#endif /* ZSTD_DEPS_NEED_MATH64 */ + +/* Need: + * assert() + */ +#ifdef ZSTD_DEPS_NEED_ASSERT +#ifndef ZSTD_DEPS_ASSERT +#define ZSTD_DEPS_ASSERT + +#include + +#endif /* ZSTD_DEPS_ASSERT */ +#endif /* ZSTD_DEPS_NEED_ASSERT */ + +/* Need: + * ZSTD_DEBUG_PRINT() + */ +#ifdef ZSTD_DEPS_NEED_IO +#ifndef ZSTD_DEPS_IO +#define ZSTD_DEPS_IO + +#include +#define ZSTD_DEBUG_PRINT(...) fprintf(stderr, __VA_ARGS__) + +#endif /* ZSTD_DEPS_IO */ +#endif /* ZSTD_DEPS_NEED_IO */ + +/* Only requested when is known to be present. + * Need: + * intptr_t + */ +#ifdef ZSTD_DEPS_NEED_STDINT +#ifndef ZSTD_DEPS_STDINT +#define ZSTD_DEPS_STDINT + +#include + +#endif /* ZSTD_DEPS_STDINT */ +#endif /* ZSTD_DEPS_NEED_STDINT */ +/**** ended inlining common/zstd_deps.h ****/ + +/**** start inlining common/debug.c ****/ +/* ****************************************************************** + * debug + * Part of FSE library + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * You can contact the author at : + * - Source repository : https://github.com/Cyan4973/FiniteStateEntropy + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. +****************************************************************** */ + + +/* + * This module only hosts one global variable + * which can be used to dynamically influence the verbosity of traces, + * such as DEBUGLOG and RAWLOG + */ + +/**** start inlining debug.h ****/ +/* ****************************************************************** + * debug + * Part of FSE library + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * You can contact the author at : + * - Source repository : https://github.com/Cyan4973/FiniteStateEntropy + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. +****************************************************************** */ + + +/* + * The purpose of this header is to enable debug functions. + * They regroup assert(), DEBUGLOG() and RAWLOG() for run-time, + * and DEBUG_STATIC_ASSERT() for compile-time. + * + * By default, DEBUGLEVEL==0, which means run-time debug is disabled. + * + * Level 1 enables assert() only. + * Starting level 2, traces can be generated and pushed to stderr. + * The higher the level, the more verbose the traces. + * + * It's possible to dynamically adjust level using variable g_debug_level, + * which is only declared if DEBUGLEVEL>=2, + * and is a global variable, not multi-thread protected (use with care) + */ + +#ifndef DEBUG_H_12987983217 +#define DEBUG_H_12987983217 + + +/* static assert is triggered at compile time, leaving no runtime artefact. + * static assert only works with compile-time constants. + * Also, this variant can only be used inside a function. */ +#define DEBUG_STATIC_ASSERT(c) (void)sizeof(char[(c) ? 1 : -1]) + + +/* DEBUGLEVEL is expected to be defined externally, + * typically through compiler command line. + * Value must be a number. */ +#ifndef DEBUGLEVEL +# define DEBUGLEVEL 0 +#endif + + +/* recommended values for DEBUGLEVEL : + * 0 : release mode, no debug, all run-time checks disabled + * 1 : enables assert() only, no display + * 2 : reserved, for currently active debug path + * 3 : events once per object lifetime (CCtx, CDict, etc.) + * 4 : events once per frame + * 5 : events once per block + * 6 : events once per sequence (verbose) + * 7+: events at every position (*very* verbose) + * + * It's generally inconvenient to output traces > 5. + * In which case, it's possible to selectively trigger high verbosity levels + * by modifying g_debug_level. + */ + +#if (DEBUGLEVEL>=1) +# define ZSTD_DEPS_NEED_ASSERT +/**** skipping file: zstd_deps.h ****/ +#else +# ifndef assert /* assert may be already defined, due to prior #include */ +# define assert(condition) ((void)0) /* disable assert (default) */ +# endif +#endif + +#if (DEBUGLEVEL>=2) +# define ZSTD_DEPS_NEED_IO +/**** skipping file: zstd_deps.h ****/ +extern int g_debuglevel; /* the variable is only declared, + it actually lives in debug.c, + and is shared by the whole process. + It's not thread-safe. + It's useful when enabling very verbose levels + on selective conditions (such as position in src) */ + +# define RAWLOG(l, ...) \ + do { \ + if (l<=g_debuglevel) { \ + ZSTD_DEBUG_PRINT(__VA_ARGS__); \ + } \ + } while (0) + +#define STRINGIFY(x) #x +#define TOSTRING(x) STRINGIFY(x) +#define LINE_AS_STRING TOSTRING(__LINE__) + +# define DEBUGLOG(l, ...) \ + do { \ + if (l<=g_debuglevel) { \ + ZSTD_DEBUG_PRINT(__FILE__ ":" LINE_AS_STRING ": " __VA_ARGS__); \ + ZSTD_DEBUG_PRINT(" \n"); \ + } \ + } while (0) +#else +# define RAWLOG(l, ...) do { } while (0) /* disabled */ +# define DEBUGLOG(l, ...) do { } while (0) /* disabled */ +#endif + +#endif /* DEBUG_H_12987983217 */ +/**** ended inlining debug.h ****/ + +#if !defined(ZSTD_LINUX_KERNEL) || (DEBUGLEVEL>=2) +/* We only use this when DEBUGLEVEL>=2, but we get -Werror=pedantic errors if a + * translation unit is empty. So remove this from Linux kernel builds, but + * otherwise just leave it in. + */ +int g_debuglevel = DEBUGLEVEL; +#endif +/**** ended inlining common/debug.c ****/ +/**** start inlining common/entropy_common.c ****/ +/* ****************************************************************** + * Common functions of New Generation Entropy library + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * You can contact the author at : + * - FSE+HUF source repository : https://github.com/Cyan4973/FiniteStateEntropy + * - Public forum : https://groups.google.com/forum/#!forum/lz4c + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. +****************************************************************** */ + +/* ************************************* +* Dependencies +***************************************/ +/**** start inlining mem.h ****/ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef MEM_H_MODULE +#define MEM_H_MODULE + +/*-**************************************** +* Dependencies +******************************************/ +#include /* size_t, ptrdiff_t */ +/**** start inlining compiler.h ****/ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTD_COMPILER_H +#define ZSTD_COMPILER_H + +#include + +/**** start inlining portability_macros.h ****/ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTD_PORTABILITY_MACROS_H +#define ZSTD_PORTABILITY_MACROS_H + +/** + * This header file contains macro definitions to support portability. + * This header is shared between C and ASM code, so it MUST only + * contain macro definitions. It MUST not contain any C code. + * + * This header ONLY defines macros to detect platforms/feature support. + * + */ + + +/* compat. with non-clang compilers */ +#ifndef __has_attribute + #define __has_attribute(x) 0 +#endif + +/* compat. with non-clang compilers */ +#ifndef __has_builtin +# define __has_builtin(x) 0 +#endif + +/* compat. with non-clang compilers */ +#ifndef __has_feature +# define __has_feature(x) 0 +#endif + +/* detects whether we are being compiled under msan */ +#ifndef ZSTD_MEMORY_SANITIZER +# if __has_feature(memory_sanitizer) +# define ZSTD_MEMORY_SANITIZER 1 +# else +# define ZSTD_MEMORY_SANITIZER 0 +# endif +#endif + +/* detects whether we are being compiled under asan */ +#ifndef ZSTD_ADDRESS_SANITIZER +# if __has_feature(address_sanitizer) +# define ZSTD_ADDRESS_SANITIZER 1 +# elif defined(__SANITIZE_ADDRESS__) +# define ZSTD_ADDRESS_SANITIZER 1 +# else +# define ZSTD_ADDRESS_SANITIZER 0 +# endif +#endif + +/* detects whether we are being compiled under dfsan */ +#ifndef ZSTD_DATAFLOW_SANITIZER +# if __has_feature(dataflow_sanitizer) +# define ZSTD_DATAFLOW_SANITIZER 1 +# else +# define ZSTD_DATAFLOW_SANITIZER 0 +# endif +#endif + +/* Mark the internal assembly functions as hidden */ +#ifdef __ELF__ +# define ZSTD_HIDE_ASM_FUNCTION(func) .hidden func +#elif defined(__APPLE__) +# define ZSTD_HIDE_ASM_FUNCTION(func) .private_extern func +#else +# define ZSTD_HIDE_ASM_FUNCTION(func) +#endif + +/* Compile time determination of BMI2 support */ +#ifndef STATIC_BMI2 +# if defined(__BMI2__) +# define STATIC_BMI2 1 +# elif defined(_MSC_VER) && defined(__AVX2__) +# define STATIC_BMI2 1 /* MSVC does not have a BMI2 specific flag, but every CPU that supports AVX2 also supports BMI2 */ +# endif +#endif + +#ifndef STATIC_BMI2 +# define STATIC_BMI2 0 +#endif + +/* Enable runtime BMI2 dispatch based on the CPU. + * Enabled for clang & gcc >=4.8 on x86 when BMI2 isn't enabled by default. + */ +#ifndef DYNAMIC_BMI2 +# if ((defined(__clang__) && __has_attribute(__target__)) \ + || (defined(__GNUC__) \ + && (__GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)))) \ + && (defined(__i386__) || defined(__x86_64__) || defined(_M_IX86) || defined(_M_X64)) \ + && !defined(__BMI2__) +# define DYNAMIC_BMI2 1 +# else +# define DYNAMIC_BMI2 0 +# endif +#endif + +/** + * Only enable assembly for GNU C compatible compilers, + * because other platforms may not support GAS assembly syntax. + * + * Only enable assembly for Linux / MacOS / Win32, other platforms may + * work, but they haven't been tested. This could likely be + * extended to BSD systems. + * + * Disable assembly when MSAN is enabled, because MSAN requires + * 100% of code to be instrumented to work. + */ +#if defined(__GNUC__) +# if defined(__linux__) || defined(__linux) || defined(__APPLE__) || defined(_WIN32) +# if ZSTD_MEMORY_SANITIZER +# define ZSTD_ASM_SUPPORTED 0 +# elif ZSTD_DATAFLOW_SANITIZER +# define ZSTD_ASM_SUPPORTED 0 +# else +# define ZSTD_ASM_SUPPORTED 1 +# endif +# else +# define ZSTD_ASM_SUPPORTED 0 +# endif +#else +# define ZSTD_ASM_SUPPORTED 0 +#endif + +/** + * Determines whether we should enable assembly for x86-64 + * with BMI2. + * + * Enable if all of the following conditions hold: + * - ASM hasn't been explicitly disabled by defining ZSTD_DISABLE_ASM + * - Assembly is supported + * - We are compiling for x86-64 and either: + * - DYNAMIC_BMI2 is enabled + * - BMI2 is supported at compile time + */ +#if !defined(ZSTD_DISABLE_ASM) && \ + ZSTD_ASM_SUPPORTED && \ + defined(__x86_64__) && \ + (DYNAMIC_BMI2 || defined(__BMI2__)) +# define ZSTD_ENABLE_ASM_X86_64_BMI2 1 +#else +# define ZSTD_ENABLE_ASM_X86_64_BMI2 0 +#endif + +/* + * For x86 ELF targets, add .note.gnu.property section for Intel CET in + * assembly sources when CET is enabled. + * + * Additionally, any function that may be called indirectly must begin + * with ZSTD_CET_ENDBRANCH. + */ +#if defined(__ELF__) && (defined(__x86_64__) || defined(__i386__)) \ + && defined(__has_include) +# if __has_include() +# include +# define ZSTD_CET_ENDBRANCH _CET_ENDBR +# endif +#endif + +#ifndef ZSTD_CET_ENDBRANCH +# define ZSTD_CET_ENDBRANCH +#endif + +#endif /* ZSTD_PORTABILITY_MACROS_H */ +/**** ended inlining portability_macros.h ****/ + +/*-******************************************************* +* Compiler specifics +*********************************************************/ +/* force inlining */ + +#if !defined(ZSTD_NO_INLINE) +#if (defined(__GNUC__) && !defined(__STRICT_ANSI__)) || defined(__cplusplus) || defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */ +# define INLINE_KEYWORD inline +#else +# define INLINE_KEYWORD +#endif + +#if defined(__GNUC__) || defined(__IAR_SYSTEMS_ICC__) +# define FORCE_INLINE_ATTR __attribute__((always_inline)) +#elif defined(_MSC_VER) +# define FORCE_INLINE_ATTR __forceinline +#else +# define FORCE_INLINE_ATTR +#endif + +#else + +#define INLINE_KEYWORD +#define FORCE_INLINE_ATTR + +#endif + +/** + On MSVC qsort requires that functions passed into it use the __cdecl calling conversion(CC). + This explicitly marks such functions as __cdecl so that the code will still compile + if a CC other than __cdecl has been made the default. +*/ +#if defined(_MSC_VER) +# define WIN_CDECL __cdecl +#else +# define WIN_CDECL +#endif + +/* UNUSED_ATTR tells the compiler it is okay if the function is unused. */ +#if defined(__GNUC__) || defined(__IAR_SYSTEMS_ICC__) +# define UNUSED_ATTR __attribute__((unused)) +#else +# define UNUSED_ATTR +#endif + +/** + * FORCE_INLINE_TEMPLATE is used to define C "templates", which take constant + * parameters. They must be inlined for the compiler to eliminate the constant + * branches. + */ +#define FORCE_INLINE_TEMPLATE static INLINE_KEYWORD FORCE_INLINE_ATTR UNUSED_ATTR +/** + * HINT_INLINE is used to help the compiler generate better code. It is *not* + * used for "templates", so it can be tweaked based on the compilers + * performance. + * + * gcc-4.8 and gcc-4.9 have been shown to benefit from leaving off the + * always_inline attribute. + * + * clang up to 5.0.0 (trunk) benefit tremendously from the always_inline + * attribute. + */ +#if !defined(__clang__) && defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 8 && __GNUC__ < 5 +# define HINT_INLINE static INLINE_KEYWORD +#else +# define HINT_INLINE FORCE_INLINE_TEMPLATE +#endif + +/* "soft" inline : + * The compiler is free to select if it's a good idea to inline or not. + * The main objective is to silence compiler warnings + * when a defined function in included but not used. + * + * Note : this macro is prefixed `MEM_` because it used to be provided by `mem.h` unit. + * Updating the prefix is probably preferable, but requires a fairly large codemod, + * since this name is used everywhere. + */ +#ifndef MEM_STATIC /* already defined in Linux Kernel mem.h */ +#if defined(__GNUC__) +# define MEM_STATIC static __inline UNUSED_ATTR +#elif defined(__IAR_SYSTEMS_ICC__) +# define MEM_STATIC static inline UNUSED_ATTR +#elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) +# define MEM_STATIC static inline +#elif defined(_MSC_VER) +# define MEM_STATIC static __inline +#else +# define MEM_STATIC static /* this version may generate warnings for unused static functions; disable the relevant warning */ +#endif +#endif + +/* force no inlining */ +#ifdef _MSC_VER +# define FORCE_NOINLINE static __declspec(noinline) +#else +# if defined(__GNUC__) || defined(__IAR_SYSTEMS_ICC__) +# define FORCE_NOINLINE static __attribute__((__noinline__)) +# else +# define FORCE_NOINLINE static +# endif +#endif + + +/* target attribute */ +#if defined(__GNUC__) || defined(__IAR_SYSTEMS_ICC__) +# define TARGET_ATTRIBUTE(target) __attribute__((__target__(target))) +#else +# define TARGET_ATTRIBUTE(target) +#endif + +/* Target attribute for BMI2 dynamic dispatch. + * Enable lzcnt, bmi, and bmi2. + * We test for bmi1 & bmi2. lzcnt is included in bmi1. + */ +#define BMI2_TARGET_ATTRIBUTE TARGET_ATTRIBUTE("lzcnt,bmi,bmi2") + +/* prefetch + * can be disabled, by declaring NO_PREFETCH build macro */ +#if defined(NO_PREFETCH) +# define PREFETCH_L1(ptr) do { (void)(ptr); } while (0) /* disabled */ +# define PREFETCH_L2(ptr) do { (void)(ptr); } while (0) /* disabled */ +#else +# if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_I86)) && !defined(_M_ARM64EC) /* _mm_prefetch() is not defined outside of x86/x64 */ +# include /* https://msdn.microsoft.com/fr-fr/library/84szxsww(v=vs.90).aspx */ +# define PREFETCH_L1(ptr) _mm_prefetch((const char*)(ptr), _MM_HINT_T0) +# define PREFETCH_L2(ptr) _mm_prefetch((const char*)(ptr), _MM_HINT_T1) +# elif defined(__GNUC__) && ( (__GNUC__ >= 4) || ( (__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) ) ) +# define PREFETCH_L1(ptr) __builtin_prefetch((ptr), 0 /* rw==read */, 3 /* locality */) +# define PREFETCH_L2(ptr) __builtin_prefetch((ptr), 0 /* rw==read */, 2 /* locality */) +# elif defined(__aarch64__) +# define PREFETCH_L1(ptr) do { __asm__ __volatile__("prfm pldl1keep, %0" ::"Q"(*(ptr))); } while (0) +# define PREFETCH_L2(ptr) do { __asm__ __volatile__("prfm pldl2keep, %0" ::"Q"(*(ptr))); } while (0) +# else +# define PREFETCH_L1(ptr) do { (void)(ptr); } while (0) /* disabled */ +# define PREFETCH_L2(ptr) do { (void)(ptr); } while (0) /* disabled */ +# endif +#endif /* NO_PREFETCH */ + +#define CACHELINE_SIZE 64 + +#define PREFETCH_AREA(p, s) \ + do { \ + const char* const _ptr = (const char*)(p); \ + size_t const _size = (size_t)(s); \ + size_t _pos; \ + for (_pos=0; _pos<_size; _pos+=CACHELINE_SIZE) { \ + PREFETCH_L2(_ptr + _pos); \ + } \ + } while (0) + +/* vectorization + * older GCC (pre gcc-4.3 picked as the cutoff) uses a different syntax, + * and some compilers, like Intel ICC and MCST LCC, do not support it at all. */ +#if !defined(__INTEL_COMPILER) && !defined(__clang__) && defined(__GNUC__) && !defined(__LCC__) +# if (__GNUC__ == 4 && __GNUC_MINOR__ > 3) || (__GNUC__ >= 5) +# define DONT_VECTORIZE __attribute__((optimize("no-tree-vectorize"))) +# else +# define DONT_VECTORIZE _Pragma("GCC optimize(\"no-tree-vectorize\")") +# endif +#else +# define DONT_VECTORIZE +#endif + +/* Tell the compiler that a branch is likely or unlikely. + * Only use these macros if it causes the compiler to generate better code. + * If you can remove a LIKELY/UNLIKELY annotation without speed changes in gcc + * and clang, please do. + */ +#if defined(__GNUC__) +#define LIKELY(x) (__builtin_expect((x), 1)) +#define UNLIKELY(x) (__builtin_expect((x), 0)) +#else +#define LIKELY(x) (x) +#define UNLIKELY(x) (x) +#endif + +#if __has_builtin(__builtin_unreachable) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))) +# define ZSTD_UNREACHABLE do { assert(0), __builtin_unreachable(); } while (0) +#else +# define ZSTD_UNREACHABLE do { assert(0); } while (0) +#endif + +/* disable warnings */ +#ifdef _MSC_VER /* Visual Studio */ +# include /* For Visual 2005 */ +# pragma warning(disable : 4100) /* disable: C4100: unreferenced formal parameter */ +# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ +# pragma warning(disable : 4204) /* disable: C4204: non-constant aggregate initializer */ +# pragma warning(disable : 4214) /* disable: C4214: non-int bitfields */ +# pragma warning(disable : 4324) /* disable: C4324: padded structure */ +#endif + +/* compile time determination of SIMD support */ +#if !defined(ZSTD_NO_INTRINSICS) +# if defined(__AVX2__) +# define ZSTD_ARCH_X86_AVX2 +# endif +# if defined(__SSE2__) || defined(_M_X64) || (defined (_M_IX86) && defined(_M_IX86_FP) && (_M_IX86_FP >= 2)) +# define ZSTD_ARCH_X86_SSE2 +# endif +# if defined(__ARM_NEON) || defined(_M_ARM64) +# define ZSTD_ARCH_ARM_NEON +# endif +# +# if defined(ZSTD_ARCH_X86_AVX2) +# include +# endif +# if defined(ZSTD_ARCH_X86_SSE2) +# include +# elif defined(ZSTD_ARCH_ARM_NEON) +# include +# endif +#endif + +/* C-language Attributes are added in C23. */ +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ > 201710L) && defined(__has_c_attribute) +# define ZSTD_HAS_C_ATTRIBUTE(x) __has_c_attribute(x) +#else +# define ZSTD_HAS_C_ATTRIBUTE(x) 0 +#endif + +/* Only use C++ attributes in C++. Some compilers report support for C++ + * attributes when compiling with C. + */ +#if defined(__cplusplus) && defined(__has_cpp_attribute) +# define ZSTD_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x) +#else +# define ZSTD_HAS_CPP_ATTRIBUTE(x) 0 +#endif + +/* Define ZSTD_FALLTHROUGH macro for annotating switch case with the 'fallthrough' attribute. + * - C23: https://en.cppreference.com/w/c/language/attributes/fallthrough + * - CPP17: https://en.cppreference.com/w/cpp/language/attributes/fallthrough + * - Else: __attribute__((__fallthrough__)) + */ +#ifndef ZSTD_FALLTHROUGH +# if ZSTD_HAS_C_ATTRIBUTE(fallthrough) +# define ZSTD_FALLTHROUGH [[fallthrough]] +# elif ZSTD_HAS_CPP_ATTRIBUTE(fallthrough) +# define ZSTD_FALLTHROUGH [[fallthrough]] +# elif __has_attribute(__fallthrough__) +/* Leading semicolon is to satisfy gcc-11 with -pedantic. Without the semicolon + * gcc complains about: a label can only be part of a statement and a declaration is not a statement. + */ +# define ZSTD_FALLTHROUGH ; __attribute__((__fallthrough__)) +# else +# define ZSTD_FALLTHROUGH +# endif +#endif + +/*-************************************************************** +* Alignment +*****************************************************************/ + +/* @return 1 if @u is a 2^n value, 0 otherwise + * useful to check a value is valid for alignment restrictions */ +MEM_STATIC int ZSTD_isPower2(size_t u) { + return (u & (u-1)) == 0; +} + +/* this test was initially positioned in mem.h, + * but this file is removed (or replaced) for linux kernel + * so it's now hosted in compiler.h, + * which remains valid for both user & kernel spaces. + */ + +#ifndef ZSTD_ALIGNOF +# if defined(__GNUC__) || defined(_MSC_VER) +/* covers gcc, clang & MSVC */ +/* note : this section must come first, before C11, + * due to a limitation in the kernel source generator */ +# define ZSTD_ALIGNOF(T) __alignof(T) + +# elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) +/* C11 support */ +# include +# define ZSTD_ALIGNOF(T) alignof(T) + +# else +/* No known support for alignof() - imperfect backup */ +# define ZSTD_ALIGNOF(T) (sizeof(void*) < sizeof(T) ? sizeof(void*) : sizeof(T)) + +# endif +#endif /* ZSTD_ALIGNOF */ + +#ifndef ZSTD_ALIGNED +/* C90-compatible alignment macro (GCC/Clang). Adjust for other compilers if needed. */ +# if defined(__GNUC__) || defined(__clang__) +# define ZSTD_ALIGNED(a) __attribute__((aligned(a))) +# elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) /* C11 */ +# define ZSTD_ALIGNED(a) _Alignas(a) +#elif defined(_MSC_VER) +# define ZSTD_ALIGNED(n) __declspec(align(n)) +# else + /* this compiler will require its own alignment instruction */ +# define ZSTD_ALIGNED(...) +# endif +#endif /* ZSTD_ALIGNED */ + + +/*-************************************************************** +* Sanitizer +*****************************************************************/ + +/** + * Zstd relies on pointer overflow in its decompressor. + * We add this attribute to functions that rely on pointer overflow. + */ +#ifndef ZSTD_ALLOW_POINTER_OVERFLOW_ATTR +# if __has_attribute(no_sanitize) +# if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 8 + /* gcc < 8 only has signed-integer-overlow which triggers on pointer overflow */ +# define ZSTD_ALLOW_POINTER_OVERFLOW_ATTR __attribute__((no_sanitize("signed-integer-overflow"))) +# else + /* older versions of clang [3.7, 5.0) will warn that pointer-overflow is ignored. */ +# define ZSTD_ALLOW_POINTER_OVERFLOW_ATTR __attribute__((no_sanitize("pointer-overflow"))) +# endif +# else +# define ZSTD_ALLOW_POINTER_OVERFLOW_ATTR +# endif +#endif + +/** + * Helper function to perform a wrapped pointer difference without triggering + * UBSAN. + * + * @returns lhs - rhs with wrapping + */ +MEM_STATIC +ZSTD_ALLOW_POINTER_OVERFLOW_ATTR +ptrdiff_t ZSTD_wrappedPtrDiff(unsigned char const* lhs, unsigned char const* rhs) +{ + return lhs - rhs; +} + +/** + * Helper function to perform a wrapped pointer add without triggering UBSAN. + * + * @return ptr + add with wrapping + */ +MEM_STATIC +ZSTD_ALLOW_POINTER_OVERFLOW_ATTR +unsigned char const* ZSTD_wrappedPtrAdd(unsigned char const* ptr, ptrdiff_t add) +{ + return ptr + add; +} + +/** + * Helper function to perform a wrapped pointer subtraction without triggering + * UBSAN. + * + * @return ptr - sub with wrapping + */ +MEM_STATIC +ZSTD_ALLOW_POINTER_OVERFLOW_ATTR +unsigned char const* ZSTD_wrappedPtrSub(unsigned char const* ptr, ptrdiff_t sub) +{ + return ptr - sub; +} + +/** + * Helper function to add to a pointer that works around C's undefined behavior + * of adding 0 to NULL. + * + * @returns `ptr + add` except it defines `NULL + 0 == NULL`. + */ +MEM_STATIC +unsigned char* ZSTD_maybeNullPtrAdd(unsigned char* ptr, ptrdiff_t add) +{ + return add > 0 ? ptr + add : ptr; +} + +/* Issue #3240 reports an ASAN failure on an llvm-mingw build. Out of an + * abundance of caution, disable our custom poisoning on mingw. */ +#ifdef __MINGW32__ +#ifndef ZSTD_ASAN_DONT_POISON_WORKSPACE +#define ZSTD_ASAN_DONT_POISON_WORKSPACE 1 +#endif +#ifndef ZSTD_MSAN_DONT_POISON_WORKSPACE +#define ZSTD_MSAN_DONT_POISON_WORKSPACE 1 +#endif +#endif + +#if ZSTD_MEMORY_SANITIZER && !defined(ZSTD_MSAN_DONT_POISON_WORKSPACE) +/* Not all platforms that support msan provide sanitizers/msan_interface.h. + * We therefore declare the functions we need ourselves, rather than trying to + * include the header file... */ +#include /* size_t */ +#define ZSTD_DEPS_NEED_STDINT +/**** skipping file: zstd_deps.h ****/ + +/* Make memory region fully initialized (without changing its contents). */ +void __msan_unpoison(const volatile void *a, size_t size); + +/* Make memory region fully uninitialized (without changing its contents). + This is a legacy interface that does not update origin information. Use + __msan_allocated_memory() instead. */ +void __msan_poison(const volatile void *a, size_t size); + +/* Returns the offset of the first (at least partially) poisoned byte in the + memory range, or -1 if the whole range is good. */ +intptr_t __msan_test_shadow(const volatile void *x, size_t size); + +/* Print shadow and origin for the memory range to stderr in a human-readable + format. */ +void __msan_print_shadow(const volatile void *x, size_t size); +#endif + +#if ZSTD_ADDRESS_SANITIZER && !defined(ZSTD_ASAN_DONT_POISON_WORKSPACE) +/* Not all platforms that support asan provide sanitizers/asan_interface.h. + * We therefore declare the functions we need ourselves, rather than trying to + * include the header file... */ +#include /* size_t */ + +/** + * Marks a memory region ([addr, addr+size)) as unaddressable. + * + * This memory must be previously allocated by your program. Instrumented + * code is forbidden from accessing addresses in this region until it is + * unpoisoned. This function is not guaranteed to poison the entire region - + * it could poison only a subregion of [addr, addr+size) due to ASan + * alignment restrictions. + * + * \note This function is not thread-safe because no two threads can poison or + * unpoison memory in the same memory region simultaneously. + * + * \param addr Start of memory region. + * \param size Size of memory region. */ +void __asan_poison_memory_region(void const volatile *addr, size_t size); + +/** + * Marks a memory region ([addr, addr+size)) as addressable. + * + * This memory must be previously allocated by your program. Accessing + * addresses in this region is allowed until this region is poisoned again. + * This function could unpoison a super-region of [addr, addr+size) due + * to ASan alignment restrictions. + * + * \note This function is not thread-safe because no two threads can + * poison or unpoison memory in the same memory region simultaneously. + * + * \param addr Start of memory region. + * \param size Size of memory region. */ +void __asan_unpoison_memory_region(void const volatile *addr, size_t size); +#endif + +#endif /* ZSTD_COMPILER_H */ +/**** ended inlining compiler.h ****/ +/**** skipping file: debug.h ****/ +/**** skipping file: zstd_deps.h ****/ + + +/*-**************************************** +* Compiler specifics +******************************************/ +#if defined(_MSC_VER) /* Visual Studio */ +# include /* _byteswap_ulong */ +# include /* _byteswap_* */ +#elif defined(__ICCARM__) +# include +#endif + +/*-************************************************************** +* Basic Types +*****************************************************************/ +#if !defined (__VMS) && (defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) ) +# if defined(_AIX) +# include +# else +# include /* intptr_t */ +# endif + typedef uint8_t BYTE; + typedef uint8_t U8; + typedef int8_t S8; + typedef uint16_t U16; + typedef int16_t S16; + typedef uint32_t U32; + typedef int32_t S32; + typedef uint64_t U64; + typedef int64_t S64; +#else +# include +#if CHAR_BIT != 8 +# error "this implementation requires char to be exactly 8-bit type" +#endif + typedef unsigned char BYTE; + typedef unsigned char U8; + typedef signed char S8; +#if USHRT_MAX != 65535 +# error "this implementation requires short to be exactly 16-bit type" +#endif + typedef unsigned short U16; + typedef signed short S16; +#if UINT_MAX != 4294967295 +# error "this implementation requires int to be exactly 32-bit type" +#endif + typedef unsigned int U32; + typedef signed int S32; +/* note : there are no limits defined for long long type in C90. + * limits exist in C99, however, in such case, is preferred */ + typedef unsigned long long U64; + typedef signed long long S64; +#endif + +/*-************************************************************** +* Memory I/O API +*****************************************************************/ +/*=== Static platform detection ===*/ +MEM_STATIC unsigned MEM_32bits(void); +MEM_STATIC unsigned MEM_64bits(void); +MEM_STATIC unsigned MEM_isLittleEndian(void); + +/*=== Native unaligned read/write ===*/ +MEM_STATIC U16 MEM_read16(const void* memPtr); +MEM_STATIC U32 MEM_read32(const void* memPtr); +MEM_STATIC U64 MEM_read64(const void* memPtr); +MEM_STATIC size_t MEM_readST(const void* memPtr); + +MEM_STATIC void MEM_write16(void* memPtr, U16 value); +MEM_STATIC void MEM_write32(void* memPtr, U32 value); +MEM_STATIC void MEM_write64(void* memPtr, U64 value); + +/*=== Little endian unaligned read/write ===*/ +MEM_STATIC U16 MEM_readLE16(const void* memPtr); +MEM_STATIC U32 MEM_readLE24(const void* memPtr); +MEM_STATIC U32 MEM_readLE32(const void* memPtr); +MEM_STATIC U64 MEM_readLE64(const void* memPtr); +MEM_STATIC size_t MEM_readLEST(const void* memPtr); + +MEM_STATIC void MEM_writeLE16(void* memPtr, U16 val); +MEM_STATIC void MEM_writeLE24(void* memPtr, U32 val); +MEM_STATIC void MEM_writeLE32(void* memPtr, U32 val32); +MEM_STATIC void MEM_writeLE64(void* memPtr, U64 val64); +MEM_STATIC void MEM_writeLEST(void* memPtr, size_t val); + +/*=== Big endian unaligned read/write ===*/ +MEM_STATIC U32 MEM_readBE32(const void* memPtr); +MEM_STATIC U64 MEM_readBE64(const void* memPtr); +MEM_STATIC size_t MEM_readBEST(const void* memPtr); + +MEM_STATIC void MEM_writeBE32(void* memPtr, U32 val32); +MEM_STATIC void MEM_writeBE64(void* memPtr, U64 val64); +MEM_STATIC void MEM_writeBEST(void* memPtr, size_t val); + +/*=== Byteswap ===*/ +MEM_STATIC U32 MEM_swap32(U32 in); +MEM_STATIC U64 MEM_swap64(U64 in); +MEM_STATIC size_t MEM_swapST(size_t in); + + +/*-************************************************************** +* Memory I/O Implementation +*****************************************************************/ +/* MEM_FORCE_MEMORY_ACCESS : For accessing unaligned memory: + * Method 0 : always use `memcpy()`. Safe and portable. + * Method 1 : Use compiler extension to set unaligned access. + * Method 2 : direct access. This method is portable but violate C standard. + * It can generate buggy code on targets depending on alignment. + * Default : method 1 if supported, else method 0 + */ +#ifndef MEM_FORCE_MEMORY_ACCESS /* can be defined externally, on command line for example */ +# ifdef __GNUC__ +# define MEM_FORCE_MEMORY_ACCESS 1 +# endif +#endif + +MEM_STATIC unsigned MEM_32bits(void) { return sizeof(size_t)==4; } +MEM_STATIC unsigned MEM_64bits(void) { return sizeof(size_t)==8; } + +MEM_STATIC unsigned MEM_isLittleEndian(void) +{ +#if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) + return 1; +#elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) + return 0; +#elif defined(__clang__) && __LITTLE_ENDIAN__ + return 1; +#elif defined(__clang__) && __BIG_ENDIAN__ + return 0; +#elif defined(_MSC_VER) && (_M_X64 || _M_IX86) + return 1; +#elif defined(__DMC__) && defined(_M_IX86) + return 1; +#elif defined(__IAR_SYSTEMS_ICC__) && __LITTLE_ENDIAN__ + return 1; +#else + const union { U32 u; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */ + return one.c[0]; +#endif +} + +#if defined(MEM_FORCE_MEMORY_ACCESS) && (MEM_FORCE_MEMORY_ACCESS==2) + +/* violates C standard, by lying on structure alignment. +Only use if no other choice to achieve best performance on target platform */ +MEM_STATIC U16 MEM_read16(const void* memPtr) { return *(const U16*) memPtr; } +MEM_STATIC U32 MEM_read32(const void* memPtr) { return *(const U32*) memPtr; } +MEM_STATIC U64 MEM_read64(const void* memPtr) { return *(const U64*) memPtr; } +MEM_STATIC size_t MEM_readST(const void* memPtr) { return *(const size_t*) memPtr; } + +MEM_STATIC void MEM_write16(void* memPtr, U16 value) { *(U16*)memPtr = value; } +MEM_STATIC void MEM_write32(void* memPtr, U32 value) { *(U32*)memPtr = value; } +MEM_STATIC void MEM_write64(void* memPtr, U64 value) { *(U64*)memPtr = value; } + +#elif defined(MEM_FORCE_MEMORY_ACCESS) && (MEM_FORCE_MEMORY_ACCESS==1) + +typedef __attribute__((aligned(1))) U16 unalign16; +typedef __attribute__((aligned(1))) U32 unalign32; +typedef __attribute__((aligned(1))) U64 unalign64; +typedef __attribute__((aligned(1))) size_t unalignArch; + +MEM_STATIC U16 MEM_read16(const void* ptr) { return *(const unalign16*)ptr; } +MEM_STATIC U32 MEM_read32(const void* ptr) { return *(const unalign32*)ptr; } +MEM_STATIC U64 MEM_read64(const void* ptr) { return *(const unalign64*)ptr; } +MEM_STATIC size_t MEM_readST(const void* ptr) { return *(const unalignArch*)ptr; } + +MEM_STATIC void MEM_write16(void* memPtr, U16 value) { *(unalign16*)memPtr = value; } +MEM_STATIC void MEM_write32(void* memPtr, U32 value) { *(unalign32*)memPtr = value; } +MEM_STATIC void MEM_write64(void* memPtr, U64 value) { *(unalign64*)memPtr = value; } + +#else + +/* default method, safe and standard. + can sometimes prove slower */ + +MEM_STATIC U16 MEM_read16(const void* memPtr) +{ + U16 val; ZSTD_memcpy(&val, memPtr, sizeof(val)); return val; +} + +MEM_STATIC U32 MEM_read32(const void* memPtr) +{ + U32 val; ZSTD_memcpy(&val, memPtr, sizeof(val)); return val; +} + +MEM_STATIC U64 MEM_read64(const void* memPtr) +{ + U64 val; ZSTD_memcpy(&val, memPtr, sizeof(val)); return val; +} + +MEM_STATIC size_t MEM_readST(const void* memPtr) +{ + size_t val; ZSTD_memcpy(&val, memPtr, sizeof(val)); return val; +} + +MEM_STATIC void MEM_write16(void* memPtr, U16 value) +{ + ZSTD_memcpy(memPtr, &value, sizeof(value)); +} + +MEM_STATIC void MEM_write32(void* memPtr, U32 value) +{ + ZSTD_memcpy(memPtr, &value, sizeof(value)); +} + +MEM_STATIC void MEM_write64(void* memPtr, U64 value) +{ + ZSTD_memcpy(memPtr, &value, sizeof(value)); +} + +#endif /* MEM_FORCE_MEMORY_ACCESS */ + +MEM_STATIC U32 MEM_swap32_fallback(U32 in) +{ + return ((in << 24) & 0xff000000 ) | + ((in << 8) & 0x00ff0000 ) | + ((in >> 8) & 0x0000ff00 ) | + ((in >> 24) & 0x000000ff ); +} + +MEM_STATIC U32 MEM_swap32(U32 in) +{ +#if defined(_MSC_VER) /* Visual Studio */ + return _byteswap_ulong(in); +#elif (defined (__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 403)) \ + || (defined(__clang__) && __has_builtin(__builtin_bswap32)) + return __builtin_bswap32(in); +#elif defined(__ICCARM__) + return __REV(in); +#else + return MEM_swap32_fallback(in); +#endif +} + +MEM_STATIC U64 MEM_swap64_fallback(U64 in) +{ + return ((in << 56) & 0xff00000000000000ULL) | + ((in << 40) & 0x00ff000000000000ULL) | + ((in << 24) & 0x0000ff0000000000ULL) | + ((in << 8) & 0x000000ff00000000ULL) | + ((in >> 8) & 0x00000000ff000000ULL) | + ((in >> 24) & 0x0000000000ff0000ULL) | + ((in >> 40) & 0x000000000000ff00ULL) | + ((in >> 56) & 0x00000000000000ffULL); +} + +MEM_STATIC U64 MEM_swap64(U64 in) +{ +#if defined(_MSC_VER) /* Visual Studio */ + return _byteswap_uint64(in); +#elif (defined (__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 403)) \ + || (defined(__clang__) && __has_builtin(__builtin_bswap64)) + return __builtin_bswap64(in); +#else + return MEM_swap64_fallback(in); +#endif +} + +MEM_STATIC size_t MEM_swapST(size_t in) +{ + if (MEM_32bits()) + return (size_t)MEM_swap32((U32)in); + else + return (size_t)MEM_swap64((U64)in); +} + +/*=== Little endian r/w ===*/ + +MEM_STATIC U16 MEM_readLE16(const void* memPtr) +{ + if (MEM_isLittleEndian()) + return MEM_read16(memPtr); + else { + const BYTE* p = (const BYTE*)memPtr; + return (U16)(p[0] + (p[1]<<8)); + } +} + +MEM_STATIC void MEM_writeLE16(void* memPtr, U16 val) +{ + if (MEM_isLittleEndian()) { + MEM_write16(memPtr, val); + } else { + BYTE* p = (BYTE*)memPtr; + p[0] = (BYTE)val; + p[1] = (BYTE)(val>>8); + } +} + +MEM_STATIC U32 MEM_readLE24(const void* memPtr) +{ + return (U32)MEM_readLE16(memPtr) + ((U32)(((const BYTE*)memPtr)[2]) << 16); +} + +MEM_STATIC void MEM_writeLE24(void* memPtr, U32 val) +{ + MEM_writeLE16(memPtr, (U16)val); + ((BYTE*)memPtr)[2] = (BYTE)(val>>16); +} + +MEM_STATIC U32 MEM_readLE32(const void* memPtr) +{ + if (MEM_isLittleEndian()) + return MEM_read32(memPtr); + else + return MEM_swap32(MEM_read32(memPtr)); +} + +MEM_STATIC void MEM_writeLE32(void* memPtr, U32 val32) +{ + if (MEM_isLittleEndian()) + MEM_write32(memPtr, val32); + else + MEM_write32(memPtr, MEM_swap32(val32)); +} + +MEM_STATIC U64 MEM_readLE64(const void* memPtr) +{ + if (MEM_isLittleEndian()) + return MEM_read64(memPtr); + else + return MEM_swap64(MEM_read64(memPtr)); +} + +MEM_STATIC void MEM_writeLE64(void* memPtr, U64 val64) +{ + if (MEM_isLittleEndian()) + MEM_write64(memPtr, val64); + else + MEM_write64(memPtr, MEM_swap64(val64)); +} + +MEM_STATIC size_t MEM_readLEST(const void* memPtr) +{ + if (MEM_32bits()) + return (size_t)MEM_readLE32(memPtr); + else + return (size_t)MEM_readLE64(memPtr); +} + +MEM_STATIC void MEM_writeLEST(void* memPtr, size_t val) +{ + if (MEM_32bits()) + MEM_writeLE32(memPtr, (U32)val); + else + MEM_writeLE64(memPtr, (U64)val); +} + +/*=== Big endian r/w ===*/ + +MEM_STATIC U32 MEM_readBE32(const void* memPtr) +{ + if (MEM_isLittleEndian()) + return MEM_swap32(MEM_read32(memPtr)); + else + return MEM_read32(memPtr); +} + +MEM_STATIC void MEM_writeBE32(void* memPtr, U32 val32) +{ + if (MEM_isLittleEndian()) + MEM_write32(memPtr, MEM_swap32(val32)); + else + MEM_write32(memPtr, val32); +} + +MEM_STATIC U64 MEM_readBE64(const void* memPtr) +{ + if (MEM_isLittleEndian()) + return MEM_swap64(MEM_read64(memPtr)); + else + return MEM_read64(memPtr); +} + +MEM_STATIC void MEM_writeBE64(void* memPtr, U64 val64) +{ + if (MEM_isLittleEndian()) + MEM_write64(memPtr, MEM_swap64(val64)); + else + MEM_write64(memPtr, val64); +} + +MEM_STATIC size_t MEM_readBEST(const void* memPtr) +{ + if (MEM_32bits()) + return (size_t)MEM_readBE32(memPtr); + else + return (size_t)MEM_readBE64(memPtr); +} + +MEM_STATIC void MEM_writeBEST(void* memPtr, size_t val) +{ + if (MEM_32bits()) + MEM_writeBE32(memPtr, (U32)val); + else + MEM_writeBE64(memPtr, (U64)val); +} + +/* code only tested on 32 and 64 bits systems */ +MEM_STATIC void MEM_check(void) { DEBUG_STATIC_ASSERT((sizeof(size_t)==4) || (sizeof(size_t)==8)); } + +#endif /* MEM_H_MODULE */ +/**** ended inlining mem.h ****/ +/**** start inlining error_private.h ****/ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +/* Note : this module is expected to remain private, do not expose it */ + +#ifndef ERROR_H_MODULE +#define ERROR_H_MODULE + +/* **************************************** +* Dependencies +******************************************/ +/**** start inlining ../zstd_errors.h ****/ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTD_ERRORS_H_398273423 +#define ZSTD_ERRORS_H_398273423 + +#if defined (__cplusplus) +extern "C" { +#endif + +/* ===== ZSTDERRORLIB_API : control library symbols visibility ===== */ +#ifndef ZSTDERRORLIB_VISIBLE + /* Backwards compatibility with old macro name */ +# ifdef ZSTDERRORLIB_VISIBILITY +# define ZSTDERRORLIB_VISIBLE ZSTDERRORLIB_VISIBILITY +# elif defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__MINGW32__) +# define ZSTDERRORLIB_VISIBLE __attribute__ ((visibility ("default"))) +# else +# define ZSTDERRORLIB_VISIBLE +# endif +#endif + +#ifndef ZSTDERRORLIB_HIDDEN +# if defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__MINGW32__) +# define ZSTDERRORLIB_HIDDEN __attribute__ ((visibility ("hidden"))) +# else +# define ZSTDERRORLIB_HIDDEN +# endif +#endif + +#if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1) +# define ZSTDERRORLIB_API __declspec(dllexport) ZSTDERRORLIB_VISIBLE +#elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1) +# define ZSTDERRORLIB_API __declspec(dllimport) ZSTDERRORLIB_VISIBLE /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/ +#else +# define ZSTDERRORLIB_API ZSTDERRORLIB_VISIBLE +#endif + +/*-********************************************* + * Error codes list + *-********************************************* + * Error codes _values_ are pinned down since v1.3.1 only. + * Therefore, don't rely on values if you may link to any version < v1.3.1. + * + * Only values < 100 are considered stable. + * + * note 1 : this API shall be used with static linking only. + * dynamic linking is not yet officially supported. + * note 2 : Prefer relying on the enum than on its value whenever possible + * This is the only supported way to use the error list < v1.3.1 + * note 3 : ZSTD_isError() is always correct, whatever the library version. + **********************************************/ +typedef enum { + ZSTD_error_no_error = 0, + ZSTD_error_GENERIC = 1, + ZSTD_error_prefix_unknown = 10, + ZSTD_error_version_unsupported = 12, + ZSTD_error_frameParameter_unsupported = 14, + ZSTD_error_frameParameter_windowTooLarge = 16, + ZSTD_error_corruption_detected = 20, + ZSTD_error_checksum_wrong = 22, + ZSTD_error_literals_headerWrong = 24, + ZSTD_error_dictionary_corrupted = 30, + ZSTD_error_dictionary_wrong = 32, + ZSTD_error_dictionaryCreation_failed = 34, + ZSTD_error_parameter_unsupported = 40, + ZSTD_error_parameter_combination_unsupported = 41, + ZSTD_error_parameter_outOfBound = 42, + ZSTD_error_tableLog_tooLarge = 44, + ZSTD_error_maxSymbolValue_tooLarge = 46, + ZSTD_error_maxSymbolValue_tooSmall = 48, + ZSTD_error_cannotProduce_uncompressedBlock = 49, + ZSTD_error_stabilityCondition_notRespected = 50, + ZSTD_error_stage_wrong = 60, + ZSTD_error_init_missing = 62, + ZSTD_error_memory_allocation = 64, + ZSTD_error_workSpace_tooSmall= 66, + ZSTD_error_dstSize_tooSmall = 70, + ZSTD_error_srcSize_wrong = 72, + ZSTD_error_dstBuffer_null = 74, + ZSTD_error_noForwardProgress_destFull = 80, + ZSTD_error_noForwardProgress_inputEmpty = 82, + /* following error codes are __NOT STABLE__, they can be removed or changed in future versions */ + ZSTD_error_frameIndex_tooLarge = 100, + ZSTD_error_seekableIO = 102, + ZSTD_error_dstBuffer_wrong = 104, + ZSTD_error_srcBuffer_wrong = 105, + ZSTD_error_sequenceProducer_failed = 106, + ZSTD_error_externalSequences_invalid = 107, + ZSTD_error_maxCode = 120 /* never EVER use this value directly, it can change in future versions! Use ZSTD_isError() instead */ +} ZSTD_ErrorCode; + +ZSTDERRORLIB_API const char* ZSTD_getErrorString(ZSTD_ErrorCode code); /**< Same as ZSTD_getErrorName, but using a `ZSTD_ErrorCode` enum argument */ + + +#if defined (__cplusplus) +} +#endif + +#endif /* ZSTD_ERRORS_H_398273423 */ +/**** ended inlining ../zstd_errors.h ****/ +/**** skipping file: compiler.h ****/ +/**** skipping file: debug.h ****/ +/**** skipping file: zstd_deps.h ****/ + +/* **************************************** +* Compiler-specific +******************************************/ +#if defined(__GNUC__) +# define ERR_STATIC static __attribute__((unused)) +#elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) +# define ERR_STATIC static inline +#elif defined(_MSC_VER) +# define ERR_STATIC static __inline +#else +# define ERR_STATIC static /* this version may generate warnings for unused static functions; disable the relevant warning */ +#endif + + +/*-**************************************** +* Customization (error_public.h) +******************************************/ +typedef ZSTD_ErrorCode ERR_enum; +#define PREFIX(name) ZSTD_error_##name + + +/*-**************************************** +* Error codes handling +******************************************/ +#undef ERROR /* already defined on Visual Studio */ +#define ERROR(name) ZSTD_ERROR(name) +#define ZSTD_ERROR(name) ((size_t)-PREFIX(name)) + +ERR_STATIC unsigned ERR_isError(size_t code) { return (code > ERROR(maxCode)); } + +ERR_STATIC ERR_enum ERR_getErrorCode(size_t code) { if (!ERR_isError(code)) return (ERR_enum)0; return (ERR_enum) (0-code); } + +/* check and forward error code */ +#define CHECK_V_F(e, f) \ + size_t const e = f; \ + do { \ + if (ERR_isError(e)) \ + return e; \ + } while (0) +#define CHECK_F(f) do { CHECK_V_F(_var_err__, f); } while (0) + + +/*-**************************************** +* Error Strings +******************************************/ + +const char* ERR_getErrorString(ERR_enum code); /* error_private.c */ + +ERR_STATIC const char* ERR_getErrorName(size_t code) +{ + return ERR_getErrorString(ERR_getErrorCode(code)); +} + +/** + * Ignore: this is an internal helper. + * + * This is a helper function to help force C99-correctness during compilation. + * Under strict compilation modes, variadic macro arguments can't be empty. + * However, variadic function arguments can be. Using a function therefore lets + * us statically check that at least one (string) argument was passed, + * independent of the compilation flags. + */ +static INLINE_KEYWORD UNUSED_ATTR +void _force_has_format_string(const char *format, ...) { + (void)format; +} + +/** + * Ignore: this is an internal helper. + * + * We want to force this function invocation to be syntactically correct, but + * we don't want to force runtime evaluation of its arguments. + */ +#define _FORCE_HAS_FORMAT_STRING(...) \ + do { \ + if (0) { \ + _force_has_format_string(__VA_ARGS__); \ + } \ + } while (0) + +#define ERR_QUOTE(str) #str + +/** + * Return the specified error if the condition evaluates to true. + * + * In debug modes, prints additional information. + * In order to do that (particularly, printing the conditional that failed), + * this can't just wrap RETURN_ERROR(). + */ +#define RETURN_ERROR_IF(cond, err, ...) \ + do { \ + if (cond) { \ + RAWLOG(3, "%s:%d: ERROR!: check %s failed, returning %s", \ + __FILE__, __LINE__, ERR_QUOTE(cond), ERR_QUOTE(ERROR(err))); \ + _FORCE_HAS_FORMAT_STRING(__VA_ARGS__); \ + RAWLOG(3, ": " __VA_ARGS__); \ + RAWLOG(3, "\n"); \ + return ERROR(err); \ + } \ + } while (0) + +/** + * Unconditionally return the specified error. + * + * In debug modes, prints additional information. + */ +#define RETURN_ERROR(err, ...) \ + do { \ + RAWLOG(3, "%s:%d: ERROR!: unconditional check failed, returning %s", \ + __FILE__, __LINE__, ERR_QUOTE(ERROR(err))); \ + _FORCE_HAS_FORMAT_STRING(__VA_ARGS__); \ + RAWLOG(3, ": " __VA_ARGS__); \ + RAWLOG(3, "\n"); \ + return ERROR(err); \ + } while(0) + +/** + * If the provided expression evaluates to an error code, returns that error code. + * + * In debug modes, prints additional information. + */ +#define FORWARD_IF_ERROR(err, ...) \ + do { \ + size_t const err_code = (err); \ + if (ERR_isError(err_code)) { \ + RAWLOG(3, "%s:%d: ERROR!: forwarding error in %s: %s", \ + __FILE__, __LINE__, ERR_QUOTE(err), ERR_getErrorName(err_code)); \ + _FORCE_HAS_FORMAT_STRING(__VA_ARGS__); \ + RAWLOG(3, ": " __VA_ARGS__); \ + RAWLOG(3, "\n"); \ + return err_code; \ + } \ + } while(0) + +#endif /* ERROR_H_MODULE */ +/**** ended inlining error_private.h ****/ +#define FSE_STATIC_LINKING_ONLY /* FSE_MIN_TABLELOG */ +/**** start inlining fse.h ****/ +/* ****************************************************************** + * FSE : Finite State Entropy codec + * Public Prototypes declaration + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * You can contact the author at : + * - Source repository : https://github.com/Cyan4973/FiniteStateEntropy + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. +****************************************************************** */ +#ifndef FSE_H +#define FSE_H + + +/*-***************************************** +* Dependencies +******************************************/ +/**** skipping file: zstd_deps.h ****/ + +/*-***************************************** +* FSE_PUBLIC_API : control library symbols visibility +******************************************/ +#if defined(FSE_DLL_EXPORT) && (FSE_DLL_EXPORT==1) && defined(__GNUC__) && (__GNUC__ >= 4) +# define FSE_PUBLIC_API __attribute__ ((visibility ("default"))) +#elif defined(FSE_DLL_EXPORT) && (FSE_DLL_EXPORT==1) /* Visual expected */ +# define FSE_PUBLIC_API __declspec(dllexport) +#elif defined(FSE_DLL_IMPORT) && (FSE_DLL_IMPORT==1) +# define FSE_PUBLIC_API __declspec(dllimport) /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/ +#else +# define FSE_PUBLIC_API +#endif + +/*------ Version ------*/ +#define FSE_VERSION_MAJOR 0 +#define FSE_VERSION_MINOR 9 +#define FSE_VERSION_RELEASE 0 + +#define FSE_LIB_VERSION FSE_VERSION_MAJOR.FSE_VERSION_MINOR.FSE_VERSION_RELEASE +#define FSE_QUOTE(str) #str +#define FSE_EXPAND_AND_QUOTE(str) FSE_QUOTE(str) +#define FSE_VERSION_STRING FSE_EXPAND_AND_QUOTE(FSE_LIB_VERSION) + +#define FSE_VERSION_NUMBER (FSE_VERSION_MAJOR *100*100 + FSE_VERSION_MINOR *100 + FSE_VERSION_RELEASE) +FSE_PUBLIC_API unsigned FSE_versionNumber(void); /**< library version number; to be used when checking dll version */ + + +/*-***************************************** +* Tool functions +******************************************/ +FSE_PUBLIC_API size_t FSE_compressBound(size_t size); /* maximum compressed size */ + +/* Error Management */ +FSE_PUBLIC_API unsigned FSE_isError(size_t code); /* tells if a return value is an error code */ +FSE_PUBLIC_API const char* FSE_getErrorName(size_t code); /* provides error code string (useful for debugging) */ + + +/*-***************************************** +* FSE detailed API +******************************************/ +/*! +FSE_compress() does the following: +1. count symbol occurrence from source[] into table count[] (see hist.h) +2. normalize counters so that sum(count[]) == Power_of_2 (2^tableLog) +3. save normalized counters to memory buffer using writeNCount() +4. build encoding table 'CTable' from normalized counters +5. encode the data stream using encoding table 'CTable' + +FSE_decompress() does the following: +1. read normalized counters with readNCount() +2. build decoding table 'DTable' from normalized counters +3. decode the data stream using decoding table 'DTable' + +The following API allows targeting specific sub-functions for advanced tasks. +For example, it's possible to compress several blocks using the same 'CTable', +or to save and provide normalized distribution using external method. +*/ + +/* *** COMPRESSION *** */ + +/*! FSE_optimalTableLog(): + dynamically downsize 'tableLog' when conditions are met. + It saves CPU time, by using smaller tables, while preserving or even improving compression ratio. + @return : recommended tableLog (necessarily <= 'maxTableLog') */ +FSE_PUBLIC_API unsigned FSE_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue); + +/*! FSE_normalizeCount(): + normalize counts so that sum(count[]) == Power_of_2 (2^tableLog) + 'normalizedCounter' is a table of short, of minimum size (maxSymbolValue+1). + useLowProbCount is a boolean parameter which trades off compressed size for + faster header decoding. When it is set to 1, the compressed data will be slightly + smaller. And when it is set to 0, FSE_readNCount() and FSE_buildDTable() will be + faster. If you are compressing a small amount of data (< 2 KB) then useLowProbCount=0 + is a good default, since header deserialization makes a big speed difference. + Otherwise, useLowProbCount=1 is a good default, since the speed difference is small. + @return : tableLog, + or an errorCode, which can be tested using FSE_isError() */ +FSE_PUBLIC_API size_t FSE_normalizeCount(short* normalizedCounter, unsigned tableLog, + const unsigned* count, size_t srcSize, unsigned maxSymbolValue, unsigned useLowProbCount); + +/*! FSE_NCountWriteBound(): + Provides the maximum possible size of an FSE normalized table, given 'maxSymbolValue' and 'tableLog'. + Typically useful for allocation purpose. */ +FSE_PUBLIC_API size_t FSE_NCountWriteBound(unsigned maxSymbolValue, unsigned tableLog); + +/*! FSE_writeNCount(): + Compactly save 'normalizedCounter' into 'buffer'. + @return : size of the compressed table, + or an errorCode, which can be tested using FSE_isError(). */ +FSE_PUBLIC_API size_t FSE_writeNCount (void* buffer, size_t bufferSize, + const short* normalizedCounter, + unsigned maxSymbolValue, unsigned tableLog); + +/*! Constructor and Destructor of FSE_CTable. + Note that FSE_CTable size depends on 'tableLog' and 'maxSymbolValue' */ +typedef unsigned FSE_CTable; /* don't allocate that. It's only meant to be more restrictive than void* */ + +/*! FSE_buildCTable(): + Builds `ct`, which must be already allocated, using FSE_createCTable(). + @return : 0, or an errorCode, which can be tested using FSE_isError() */ +FSE_PUBLIC_API size_t FSE_buildCTable(FSE_CTable* ct, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog); + +/*! FSE_compress_usingCTable(): + Compress `src` using `ct` into `dst` which must be already allocated. + @return : size of compressed data (<= `dstCapacity`), + or 0 if compressed data could not fit into `dst`, + or an errorCode, which can be tested using FSE_isError() */ +FSE_PUBLIC_API size_t FSE_compress_usingCTable (void* dst, size_t dstCapacity, const void* src, size_t srcSize, const FSE_CTable* ct); + +/*! +Tutorial : +---------- +The first step is to count all symbols. FSE_count() does this job very fast. +Result will be saved into 'count', a table of unsigned int, which must be already allocated, and have 'maxSymbolValuePtr[0]+1' cells. +'src' is a table of bytes of size 'srcSize'. All values within 'src' MUST be <= maxSymbolValuePtr[0] +maxSymbolValuePtr[0] will be updated, with its real value (necessarily <= original value) +FSE_count() will return the number of occurrence of the most frequent symbol. +This can be used to know if there is a single symbol within 'src', and to quickly evaluate its compressibility. +If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError()). + +The next step is to normalize the frequencies. +FSE_normalizeCount() will ensure that sum of frequencies is == 2 ^'tableLog'. +It also guarantees a minimum of 1 to any Symbol with frequency >= 1. +You can use 'tableLog'==0 to mean "use default tableLog value". +If you are unsure of which tableLog value to use, you can ask FSE_optimalTableLog(), +which will provide the optimal valid tableLog given sourceSize, maxSymbolValue, and a user-defined maximum (0 means "default"). + +The result of FSE_normalizeCount() will be saved into a table, +called 'normalizedCounter', which is a table of signed short. +'normalizedCounter' must be already allocated, and have at least 'maxSymbolValue+1' cells. +The return value is tableLog if everything proceeded as expected. +It is 0 if there is a single symbol within distribution. +If there is an error (ex: invalid tableLog value), the function will return an ErrorCode (which can be tested using FSE_isError()). + +'normalizedCounter' can be saved in a compact manner to a memory area using FSE_writeNCount(). +'buffer' must be already allocated. +For guaranteed success, buffer size must be at least FSE_headerBound(). +The result of the function is the number of bytes written into 'buffer'. +If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError(); ex : buffer size too small). + +'normalizedCounter' can then be used to create the compression table 'CTable'. +The space required by 'CTable' must be already allocated, using FSE_createCTable(). +You can then use FSE_buildCTable() to fill 'CTable'. +If there is an error, both functions will return an ErrorCode (which can be tested using FSE_isError()). + +'CTable' can then be used to compress 'src', with FSE_compress_usingCTable(). +Similar to FSE_count(), the convention is that 'src' is assumed to be a table of char of size 'srcSize' +The function returns the size of compressed data (without header), necessarily <= `dstCapacity`. +If it returns '0', compressed data could not fit into 'dst'. +If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError()). +*/ + + +/* *** DECOMPRESSION *** */ + +/*! FSE_readNCount(): + Read compactly saved 'normalizedCounter' from 'rBuffer'. + @return : size read from 'rBuffer', + or an errorCode, which can be tested using FSE_isError(). + maxSymbolValuePtr[0] and tableLogPtr[0] will also be updated with their respective values */ +FSE_PUBLIC_API size_t FSE_readNCount (short* normalizedCounter, + unsigned* maxSymbolValuePtr, unsigned* tableLogPtr, + const void* rBuffer, size_t rBuffSize); + +/*! FSE_readNCount_bmi2(): + * Same as FSE_readNCount() but pass bmi2=1 when your CPU supports BMI2 and 0 otherwise. + */ +FSE_PUBLIC_API size_t FSE_readNCount_bmi2(short* normalizedCounter, + unsigned* maxSymbolValuePtr, unsigned* tableLogPtr, + const void* rBuffer, size_t rBuffSize, int bmi2); + +typedef unsigned FSE_DTable; /* don't allocate that. It's just a way to be more restrictive than void* */ + +/*! +Tutorial : +---------- +(Note : these functions only decompress FSE-compressed blocks. + If block is uncompressed, use memcpy() instead + If block is a single repeated byte, use memset() instead ) + +The first step is to obtain the normalized frequencies of symbols. +This can be performed by FSE_readNCount() if it was saved using FSE_writeNCount(). +'normalizedCounter' must be already allocated, and have at least 'maxSymbolValuePtr[0]+1' cells of signed short. +In practice, that means it's necessary to know 'maxSymbolValue' beforehand, +or size the table to handle worst case situations (typically 256). +FSE_readNCount() will provide 'tableLog' and 'maxSymbolValue'. +The result of FSE_readNCount() is the number of bytes read from 'rBuffer'. +Note that 'rBufferSize' must be at least 4 bytes, even if useful information is less than that. +If there is an error, the function will return an error code, which can be tested using FSE_isError(). + +The next step is to build the decompression tables 'FSE_DTable' from 'normalizedCounter'. +This is performed by the function FSE_buildDTable(). +The space required by 'FSE_DTable' must be already allocated using FSE_createDTable(). +If there is an error, the function will return an error code, which can be tested using FSE_isError(). + +`FSE_DTable` can then be used to decompress `cSrc`, with FSE_decompress_usingDTable(). +`cSrcSize` must be strictly correct, otherwise decompression will fail. +FSE_decompress_usingDTable() result will tell how many bytes were regenerated (<=`dstCapacity`). +If there is an error, the function will return an error code, which can be tested using FSE_isError(). (ex: dst buffer too small) +*/ + +#endif /* FSE_H */ + + +#if defined(FSE_STATIC_LINKING_ONLY) && !defined(FSE_H_FSE_STATIC_LINKING_ONLY) +#define FSE_H_FSE_STATIC_LINKING_ONLY +/**** start inlining bitstream.h ****/ +/* ****************************************************************** + * bitstream + * Part of FSE library + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * You can contact the author at : + * - Source repository : https://github.com/Cyan4973/FiniteStateEntropy + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. +****************************************************************** */ +#ifndef BITSTREAM_H_MODULE +#define BITSTREAM_H_MODULE + +/* +* This API consists of small unitary functions, which must be inlined for best performance. +* Since link-time-optimization is not available for all compilers, +* these functions are defined into a .h to be included. +*/ + +/*-**************************************** +* Dependencies +******************************************/ +/**** skipping file: mem.h ****/ +/**** skipping file: compiler.h ****/ +/**** skipping file: debug.h ****/ +/**** skipping file: error_private.h ****/ +/**** start inlining bits.h ****/ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTD_BITS_H +#define ZSTD_BITS_H + +/**** skipping file: mem.h ****/ + +MEM_STATIC unsigned ZSTD_countTrailingZeros32_fallback(U32 val) +{ + assert(val != 0); + { + static const U32 DeBruijnBytePos[32] = {0, 1, 28, 2, 29, 14, 24, 3, + 30, 22, 20, 15, 25, 17, 4, 8, + 31, 27, 13, 23, 21, 19, 16, 7, + 26, 12, 18, 6, 11, 5, 10, 9}; + return DeBruijnBytePos[((U32) ((val & -(S32) val) * 0x077CB531U)) >> 27]; + } +} + +MEM_STATIC unsigned ZSTD_countTrailingZeros32(U32 val) +{ + assert(val != 0); +#if defined(_MSC_VER) +# if STATIC_BMI2 + return (unsigned)_tzcnt_u32(val); +# else + if (val != 0) { + unsigned long r; + _BitScanForward(&r, val); + return (unsigned)r; + } else { + __assume(0); /* Should not reach this code path */ + } +# endif +#elif defined(__GNUC__) && (__GNUC__ >= 4) + return (unsigned)__builtin_ctz(val); +#elif defined(__ICCARM__) + return (unsigned)__builtin_ctz(val); +#else + return ZSTD_countTrailingZeros32_fallback(val); +#endif +} + +MEM_STATIC unsigned ZSTD_countLeadingZeros32_fallback(U32 val) +{ + assert(val != 0); + { + static const U32 DeBruijnClz[32] = {0, 9, 1, 10, 13, 21, 2, 29, + 11, 14, 16, 18, 22, 25, 3, 30, + 8, 12, 20, 28, 15, 17, 24, 7, + 19, 27, 23, 6, 26, 5, 4, 31}; + val |= val >> 1; + val |= val >> 2; + val |= val >> 4; + val |= val >> 8; + val |= val >> 16; + return 31 - DeBruijnClz[(val * 0x07C4ACDDU) >> 27]; + } +} + +MEM_STATIC unsigned ZSTD_countLeadingZeros32(U32 val) +{ + assert(val != 0); +#if defined(_MSC_VER) +# if STATIC_BMI2 + return (unsigned)_lzcnt_u32(val); +# else + if (val != 0) { + unsigned long r; + _BitScanReverse(&r, val); + return (unsigned)(31 - r); + } else { + __assume(0); /* Should not reach this code path */ + } +# endif +#elif defined(__GNUC__) && (__GNUC__ >= 4) + return (unsigned)__builtin_clz(val); +#elif defined(__ICCARM__) + return (unsigned)__builtin_clz(val); +#else + return ZSTD_countLeadingZeros32_fallback(val); +#endif +} + +MEM_STATIC unsigned ZSTD_countTrailingZeros64(U64 val) +{ + assert(val != 0); +#if defined(_MSC_VER) && defined(_WIN64) +# if STATIC_BMI2 + return (unsigned)_tzcnt_u64(val); +# else + if (val != 0) { + unsigned long r; + _BitScanForward64(&r, val); + return (unsigned)r; + } else { + __assume(0); /* Should not reach this code path */ + } +# endif +#elif defined(__GNUC__) && (__GNUC__ >= 4) && defined(__LP64__) + return (unsigned)__builtin_ctzll(val); +#elif defined(__ICCARM__) + return (unsigned)__builtin_ctzll(val); +#else + { + U32 mostSignificantWord = (U32)(val >> 32); + U32 leastSignificantWord = (U32)val; + if (leastSignificantWord == 0) { + return 32 + ZSTD_countTrailingZeros32(mostSignificantWord); + } else { + return ZSTD_countTrailingZeros32(leastSignificantWord); + } + } +#endif +} + +MEM_STATIC unsigned ZSTD_countLeadingZeros64(U64 val) +{ + assert(val != 0); +#if defined(_MSC_VER) && defined(_WIN64) +# if STATIC_BMI2 + return (unsigned)_lzcnt_u64(val); +# else + if (val != 0) { + unsigned long r; + _BitScanReverse64(&r, val); + return (unsigned)(63 - r); + } else { + __assume(0); /* Should not reach this code path */ + } +# endif +#elif defined(__GNUC__) && (__GNUC__ >= 4) + return (unsigned)(__builtin_clzll(val)); +#elif defined(__ICCARM__) + return (unsigned)(__builtin_clzll(val)); +#else + { + U32 mostSignificantWord = (U32)(val >> 32); + U32 leastSignificantWord = (U32)val; + if (mostSignificantWord == 0) { + return 32 + ZSTD_countLeadingZeros32(leastSignificantWord); + } else { + return ZSTD_countLeadingZeros32(mostSignificantWord); + } + } +#endif +} + +MEM_STATIC unsigned ZSTD_NbCommonBytes(size_t val) +{ + if (MEM_isLittleEndian()) { + if (MEM_64bits()) { + return ZSTD_countTrailingZeros64((U64)val) >> 3; + } else { + return ZSTD_countTrailingZeros32((U32)val) >> 3; + } + } else { /* Big Endian CPU */ + if (MEM_64bits()) { + return ZSTD_countLeadingZeros64((U64)val) >> 3; + } else { + return ZSTD_countLeadingZeros32((U32)val) >> 3; + } + } +} + +MEM_STATIC unsigned ZSTD_highbit32(U32 val) /* compress, dictBuilder, decodeCorpus */ +{ + assert(val != 0); + return 31 - ZSTD_countLeadingZeros32(val); +} + +/* ZSTD_rotateRight_*(): + * Rotates a bitfield to the right by "count" bits. + * https://en.wikipedia.org/w/index.php?title=Circular_shift&oldid=991635599#Implementing_circular_shifts + */ +MEM_STATIC +U64 ZSTD_rotateRight_U64(U64 const value, U32 count) { + assert(count < 64); + count &= 0x3F; /* for fickle pattern recognition */ + return (value >> count) | (U64)(value << ((0U - count) & 0x3F)); +} + +MEM_STATIC +U32 ZSTD_rotateRight_U32(U32 const value, U32 count) { + assert(count < 32); + count &= 0x1F; /* for fickle pattern recognition */ + return (value >> count) | (U32)(value << ((0U - count) & 0x1F)); +} + +MEM_STATIC +U16 ZSTD_rotateRight_U16(U16 const value, U32 count) { + assert(count < 16); + count &= 0x0F; /* for fickle pattern recognition */ + return (value >> count) | (U16)(value << ((0U - count) & 0x0F)); +} + +#endif /* ZSTD_BITS_H */ +/**** ended inlining bits.h ****/ + +/*========================================= +* Target specific +=========================================*/ +#ifndef ZSTD_NO_INTRINSICS +# if (defined(__BMI__) || defined(__BMI2__)) && defined(__GNUC__) +# include /* support for bextr (experimental)/bzhi */ +# elif defined(__ICCARM__) +# include +# endif +#endif + +#define STREAM_ACCUMULATOR_MIN_32 25 +#define STREAM_ACCUMULATOR_MIN_64 57 +#define STREAM_ACCUMULATOR_MIN ((U32)(MEM_32bits() ? STREAM_ACCUMULATOR_MIN_32 : STREAM_ACCUMULATOR_MIN_64)) + + +/*-****************************************** +* bitStream encoding API (write forward) +********************************************/ +typedef size_t BitContainerType; +/* bitStream can mix input from multiple sources. + * A critical property of these streams is that they encode and decode in **reverse** direction. + * So the first bit sequence you add will be the last to be read, like a LIFO stack. + */ +typedef struct { + BitContainerType bitContainer; + unsigned bitPos; + char* startPtr; + char* ptr; + char* endPtr; +} BIT_CStream_t; + +MEM_STATIC size_t BIT_initCStream(BIT_CStream_t* bitC, void* dstBuffer, size_t dstCapacity); +MEM_STATIC void BIT_addBits(BIT_CStream_t* bitC, BitContainerType value, unsigned nbBits); +MEM_STATIC void BIT_flushBits(BIT_CStream_t* bitC); +MEM_STATIC size_t BIT_closeCStream(BIT_CStream_t* bitC); + +/* Start with initCStream, providing the size of buffer to write into. +* bitStream will never write outside of this buffer. +* `dstCapacity` must be >= sizeof(bitD->bitContainer), otherwise @return will be an error code. +* +* bits are first added to a local register. +* Local register is BitContainerType, 64-bits on 64-bits systems, or 32-bits on 32-bits systems. +* Writing data into memory is an explicit operation, performed by the flushBits function. +* Hence keep track how many bits are potentially stored into local register to avoid register overflow. +* After a flushBits, a maximum of 7 bits might still be stored into local register. +* +* Avoid storing elements of more than 24 bits if you want compatibility with 32-bits bitstream readers. +* +* Last operation is to close the bitStream. +* The function returns the final size of CStream in bytes. +* If data couldn't fit into `dstBuffer`, it will return a 0 ( == not storable) +*/ + + +/*-******************************************** +* bitStream decoding API (read backward) +**********************************************/ +typedef struct { + BitContainerType bitContainer; + unsigned bitsConsumed; + const char* ptr; + const char* start; + const char* limitPtr; +} BIT_DStream_t; + +typedef enum { BIT_DStream_unfinished = 0, /* fully refilled */ + BIT_DStream_endOfBuffer = 1, /* still some bits left in bitstream */ + BIT_DStream_completed = 2, /* bitstream entirely consumed, bit-exact */ + BIT_DStream_overflow = 3 /* user requested more bits than present in bitstream */ + } BIT_DStream_status; /* result of BIT_reloadDStream() */ + +MEM_STATIC size_t BIT_initDStream(BIT_DStream_t* bitD, const void* srcBuffer, size_t srcSize); +MEM_STATIC BitContainerType BIT_readBits(BIT_DStream_t* bitD, unsigned nbBits); +MEM_STATIC BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD); +MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* bitD); + + +/* Start by invoking BIT_initDStream(). +* A chunk of the bitStream is then stored into a local register. +* Local register size is 64-bits on 64-bits systems, 32-bits on 32-bits systems (BitContainerType). +* You can then retrieve bitFields stored into the local register, **in reverse order**. +* Local register is explicitly reloaded from memory by the BIT_reloadDStream() method. +* A reload guarantee a minimum of ((8*sizeof(bitD->bitContainer))-7) bits when its result is BIT_DStream_unfinished. +* Otherwise, it can be less than that, so proceed accordingly. +* Checking if DStream has reached its end can be performed with BIT_endOfDStream(). +*/ + + +/*-**************************************** +* unsafe API +******************************************/ +MEM_STATIC void BIT_addBitsFast(BIT_CStream_t* bitC, BitContainerType value, unsigned nbBits); +/* faster, but works only if value is "clean", meaning all high bits above nbBits are 0 */ + +MEM_STATIC void BIT_flushBitsFast(BIT_CStream_t* bitC); +/* unsafe version; does not check buffer overflow */ + +MEM_STATIC size_t BIT_readBitsFast(BIT_DStream_t* bitD, unsigned nbBits); +/* faster, but works only if nbBits >= 1 */ + +/*===== Local Constants =====*/ +static const unsigned BIT_mask[] = { + 0, 1, 3, 7, 0xF, 0x1F, + 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, + 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF, 0x1FFFF, + 0x3FFFF, 0x7FFFF, 0xFFFFF, 0x1FFFFF, 0x3FFFFF, 0x7FFFFF, + 0xFFFFFF, 0x1FFFFFF, 0x3FFFFFF, 0x7FFFFFF, 0xFFFFFFF, 0x1FFFFFFF, + 0x3FFFFFFF, 0x7FFFFFFF}; /* up to 31 bits */ +#define BIT_MASK_SIZE (sizeof(BIT_mask) / sizeof(BIT_mask[0])) + +/*-************************************************************** +* bitStream encoding +****************************************************************/ +/*! BIT_initCStream() : + * `dstCapacity` must be > sizeof(size_t) + * @return : 0 if success, + * otherwise an error code (can be tested using ERR_isError()) */ +MEM_STATIC size_t BIT_initCStream(BIT_CStream_t* bitC, + void* startPtr, size_t dstCapacity) +{ + bitC->bitContainer = 0; + bitC->bitPos = 0; + bitC->startPtr = (char*)startPtr; + bitC->ptr = bitC->startPtr; + bitC->endPtr = bitC->startPtr + dstCapacity - sizeof(bitC->bitContainer); + if (dstCapacity <= sizeof(bitC->bitContainer)) return ERROR(dstSize_tooSmall); + return 0; +} + +FORCE_INLINE_TEMPLATE BitContainerType BIT_getLowerBits(BitContainerType bitContainer, U32 const nbBits) +{ +#if STATIC_BMI2 && !defined(ZSTD_NO_INTRINSICS) +# if (defined(__x86_64__) || defined(_M_X64)) && !defined(__ILP32__) + return _bzhi_u64(bitContainer, nbBits); +# else + DEBUG_STATIC_ASSERT(sizeof(bitContainer) == sizeof(U32)); + return _bzhi_u32(bitContainer, nbBits); +# endif +#else + assert(nbBits < BIT_MASK_SIZE); + return bitContainer & BIT_mask[nbBits]; +#endif +} + +/*! BIT_addBits() : + * can add up to 31 bits into `bitC`. + * Note : does not check for register overflow ! */ +MEM_STATIC void BIT_addBits(BIT_CStream_t* bitC, + BitContainerType value, unsigned nbBits) +{ + DEBUG_STATIC_ASSERT(BIT_MASK_SIZE == 32); + assert(nbBits < BIT_MASK_SIZE); + assert(nbBits + bitC->bitPos < sizeof(bitC->bitContainer) * 8); + bitC->bitContainer |= BIT_getLowerBits(value, nbBits) << bitC->bitPos; + bitC->bitPos += nbBits; +} + +/*! BIT_addBitsFast() : + * works only if `value` is _clean_, + * meaning all high bits above nbBits are 0 */ +MEM_STATIC void BIT_addBitsFast(BIT_CStream_t* bitC, + BitContainerType value, unsigned nbBits) +{ + assert((value>>nbBits) == 0); + assert(nbBits + bitC->bitPos < sizeof(bitC->bitContainer) * 8); + bitC->bitContainer |= value << bitC->bitPos; + bitC->bitPos += nbBits; +} + +/*! BIT_flushBitsFast() : + * assumption : bitContainer has not overflowed + * unsafe version; does not check buffer overflow */ +MEM_STATIC void BIT_flushBitsFast(BIT_CStream_t* bitC) +{ + size_t const nbBytes = bitC->bitPos >> 3; + assert(bitC->bitPos < sizeof(bitC->bitContainer) * 8); + assert(bitC->ptr <= bitC->endPtr); + MEM_writeLEST(bitC->ptr, bitC->bitContainer); + bitC->ptr += nbBytes; + bitC->bitPos &= 7; + bitC->bitContainer >>= nbBytes*8; +} + +/*! BIT_flushBits() : + * assumption : bitContainer has not overflowed + * safe version; check for buffer overflow, and prevents it. + * note : does not signal buffer overflow. + * overflow will be revealed later on using BIT_closeCStream() */ +MEM_STATIC void BIT_flushBits(BIT_CStream_t* bitC) +{ + size_t const nbBytes = bitC->bitPos >> 3; + assert(bitC->bitPos < sizeof(bitC->bitContainer) * 8); + assert(bitC->ptr <= bitC->endPtr); + MEM_writeLEST(bitC->ptr, bitC->bitContainer); + bitC->ptr += nbBytes; + if (bitC->ptr > bitC->endPtr) bitC->ptr = bitC->endPtr; + bitC->bitPos &= 7; + bitC->bitContainer >>= nbBytes*8; +} + +/*! BIT_closeCStream() : + * @return : size of CStream, in bytes, + * or 0 if it could not fit into dstBuffer */ +MEM_STATIC size_t BIT_closeCStream(BIT_CStream_t* bitC) +{ + BIT_addBitsFast(bitC, 1, 1); /* endMark */ + BIT_flushBits(bitC); + if (bitC->ptr >= bitC->endPtr) return 0; /* overflow detected */ + return (size_t)(bitC->ptr - bitC->startPtr) + (bitC->bitPos > 0); +} + + +/*-******************************************************** +* bitStream decoding +**********************************************************/ +/*! BIT_initDStream() : + * Initialize a BIT_DStream_t. + * `bitD` : a pointer to an already allocated BIT_DStream_t structure. + * `srcSize` must be the *exact* size of the bitStream, in bytes. + * @return : size of stream (== srcSize), or an errorCode if a problem is detected + */ +MEM_STATIC size_t BIT_initDStream(BIT_DStream_t* bitD, const void* srcBuffer, size_t srcSize) +{ + if (srcSize < 1) { ZSTD_memset(bitD, 0, sizeof(*bitD)); return ERROR(srcSize_wrong); } + + bitD->start = (const char*)srcBuffer; + bitD->limitPtr = bitD->start + sizeof(bitD->bitContainer); + + if (srcSize >= sizeof(bitD->bitContainer)) { /* normal case */ + bitD->ptr = (const char*)srcBuffer + srcSize - sizeof(bitD->bitContainer); + bitD->bitContainer = MEM_readLEST(bitD->ptr); + { BYTE const lastByte = ((const BYTE*)srcBuffer)[srcSize-1]; + bitD->bitsConsumed = lastByte ? 8 - ZSTD_highbit32(lastByte) : 0; /* ensures bitsConsumed is always set */ + if (lastByte == 0) return ERROR(GENERIC); /* endMark not present */ } + } else { + bitD->ptr = bitD->start; + bitD->bitContainer = *(const BYTE*)(bitD->start); + switch(srcSize) + { + case 7: bitD->bitContainer += (BitContainerType)(((const BYTE*)(srcBuffer))[6]) << (sizeof(bitD->bitContainer)*8 - 16); + ZSTD_FALLTHROUGH; + + case 6: bitD->bitContainer += (BitContainerType)(((const BYTE*)(srcBuffer))[5]) << (sizeof(bitD->bitContainer)*8 - 24); + ZSTD_FALLTHROUGH; + + case 5: bitD->bitContainer += (BitContainerType)(((const BYTE*)(srcBuffer))[4]) << (sizeof(bitD->bitContainer)*8 - 32); + ZSTD_FALLTHROUGH; + + case 4: bitD->bitContainer += (BitContainerType)(((const BYTE*)(srcBuffer))[3]) << 24; + ZSTD_FALLTHROUGH; + + case 3: bitD->bitContainer += (BitContainerType)(((const BYTE*)(srcBuffer))[2]) << 16; + ZSTD_FALLTHROUGH; + + case 2: bitD->bitContainer += (BitContainerType)(((const BYTE*)(srcBuffer))[1]) << 8; + ZSTD_FALLTHROUGH; + + default: break; + } + { BYTE const lastByte = ((const BYTE*)srcBuffer)[srcSize-1]; + bitD->bitsConsumed = lastByte ? 8 - ZSTD_highbit32(lastByte) : 0; + if (lastByte == 0) return ERROR(corruption_detected); /* endMark not present */ + } + bitD->bitsConsumed += (U32)(sizeof(bitD->bitContainer) - srcSize)*8; + } + + return srcSize; +} + +FORCE_INLINE_TEMPLATE BitContainerType BIT_getUpperBits(BitContainerType bitContainer, U32 const start) +{ + return bitContainer >> start; +} + +FORCE_INLINE_TEMPLATE BitContainerType BIT_getMiddleBits(BitContainerType bitContainer, U32 const start, U32 const nbBits) +{ + U32 const regMask = sizeof(bitContainer)*8 - 1; + /* if start > regMask, bitstream is corrupted, and result is undefined */ + assert(nbBits < BIT_MASK_SIZE); + /* x86 transform & ((1 << nbBits) - 1) to bzhi instruction, it is better + * than accessing memory. When bmi2 instruction is not present, we consider + * such cpus old (pre-Haswell, 2013) and their performance is not of that + * importance. + */ +#if defined(__x86_64__) || defined(_M_X64) + return (bitContainer >> (start & regMask)) & ((((U64)1) << nbBits) - 1); +#else + return (bitContainer >> (start & regMask)) & BIT_mask[nbBits]; +#endif +} + +/*! BIT_lookBits() : + * Provides next n bits from local register. + * local register is not modified. + * On 32-bits, maxNbBits==24. + * On 64-bits, maxNbBits==56. + * @return : value extracted */ +FORCE_INLINE_TEMPLATE BitContainerType BIT_lookBits(const BIT_DStream_t* bitD, U32 nbBits) +{ + /* arbitrate between double-shift and shift+mask */ +#if 1 + /* if bitD->bitsConsumed + nbBits > sizeof(bitD->bitContainer)*8, + * bitstream is likely corrupted, and result is undefined */ + return BIT_getMiddleBits(bitD->bitContainer, (sizeof(bitD->bitContainer)*8) - bitD->bitsConsumed - nbBits, nbBits); +#else + /* this code path is slower on my os-x laptop */ + U32 const regMask = sizeof(bitD->bitContainer)*8 - 1; + return ((bitD->bitContainer << (bitD->bitsConsumed & regMask)) >> 1) >> ((regMask-nbBits) & regMask); +#endif +} + +/*! BIT_lookBitsFast() : + * unsafe version; only works if nbBits >= 1 */ +MEM_STATIC BitContainerType BIT_lookBitsFast(const BIT_DStream_t* bitD, U32 nbBits) +{ + U32 const regMask = sizeof(bitD->bitContainer)*8 - 1; + assert(nbBits >= 1); + return (bitD->bitContainer << (bitD->bitsConsumed & regMask)) >> (((regMask+1)-nbBits) & regMask); +} + +FORCE_INLINE_TEMPLATE void BIT_skipBits(BIT_DStream_t* bitD, U32 nbBits) +{ + bitD->bitsConsumed += nbBits; +} + +/*! BIT_readBits() : + * Read (consume) next n bits from local register and update. + * Pay attention to not read more than nbBits contained into local register. + * @return : extracted value. */ +FORCE_INLINE_TEMPLATE BitContainerType BIT_readBits(BIT_DStream_t* bitD, unsigned nbBits) +{ + BitContainerType const value = BIT_lookBits(bitD, nbBits); + BIT_skipBits(bitD, nbBits); + return value; +} + +/*! BIT_readBitsFast() : + * unsafe version; only works if nbBits >= 1 */ +MEM_STATIC BitContainerType BIT_readBitsFast(BIT_DStream_t* bitD, unsigned nbBits) +{ + BitContainerType const value = BIT_lookBitsFast(bitD, nbBits); + assert(nbBits >= 1); + BIT_skipBits(bitD, nbBits); + return value; +} + +/*! BIT_reloadDStream_internal() : + * Simple variant of BIT_reloadDStream(), with two conditions: + * 1. bitstream is valid : bitsConsumed <= sizeof(bitD->bitContainer)*8 + * 2. look window is valid after shifted down : bitD->ptr >= bitD->start + */ +MEM_STATIC BIT_DStream_status BIT_reloadDStream_internal(BIT_DStream_t* bitD) +{ + assert(bitD->bitsConsumed <= sizeof(bitD->bitContainer)*8); + bitD->ptr -= bitD->bitsConsumed >> 3; + assert(bitD->ptr >= bitD->start); + bitD->bitsConsumed &= 7; + bitD->bitContainer = MEM_readLEST(bitD->ptr); + return BIT_DStream_unfinished; +} + +/*! BIT_reloadDStreamFast() : + * Similar to BIT_reloadDStream(), but with two differences: + * 1. bitsConsumed <= sizeof(bitD->bitContainer)*8 must hold! + * 2. Returns BIT_DStream_overflow when bitD->ptr < bitD->limitPtr, at this + * point you must use BIT_reloadDStream() to reload. + */ +MEM_STATIC BIT_DStream_status BIT_reloadDStreamFast(BIT_DStream_t* bitD) +{ + if (UNLIKELY(bitD->ptr < bitD->limitPtr)) + return BIT_DStream_overflow; + return BIT_reloadDStream_internal(bitD); +} + +/*! BIT_reloadDStream() : + * Refill `bitD` from buffer previously set in BIT_initDStream() . + * This function is safe, it guarantees it will not never beyond src buffer. + * @return : status of `BIT_DStream_t` internal register. + * when status == BIT_DStream_unfinished, internal register is filled with at least 25 or 57 bits */ +FORCE_INLINE_TEMPLATE BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD) +{ + /* note : once in overflow mode, a bitstream remains in this mode until it's reset */ + if (UNLIKELY(bitD->bitsConsumed > (sizeof(bitD->bitContainer)*8))) { + static const BitContainerType zeroFilled = 0; + bitD->ptr = (const char*)&zeroFilled; /* aliasing is allowed for char */ + /* overflow detected, erroneous scenario or end of stream: no update */ + return BIT_DStream_overflow; + } + + assert(bitD->ptr >= bitD->start); + + if (bitD->ptr >= bitD->limitPtr) { + return BIT_reloadDStream_internal(bitD); + } + if (bitD->ptr == bitD->start) { + /* reached end of bitStream => no update */ + if (bitD->bitsConsumed < sizeof(bitD->bitContainer)*8) return BIT_DStream_endOfBuffer; + return BIT_DStream_completed; + } + /* start < ptr < limitPtr => cautious update */ + { U32 nbBytes = bitD->bitsConsumed >> 3; + BIT_DStream_status result = BIT_DStream_unfinished; + if (bitD->ptr - nbBytes < bitD->start) { + nbBytes = (U32)(bitD->ptr - bitD->start); /* ptr > start */ + result = BIT_DStream_endOfBuffer; + } + bitD->ptr -= nbBytes; + bitD->bitsConsumed -= nbBytes*8; + bitD->bitContainer = MEM_readLEST(bitD->ptr); /* reminder : srcSize > sizeof(bitD->bitContainer), otherwise bitD->ptr == bitD->start */ + return result; + } +} + +/*! BIT_endOfDStream() : + * @return : 1 if DStream has _exactly_ reached its end (all bits consumed). + */ +MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* DStream) +{ + return ((DStream->ptr == DStream->start) && (DStream->bitsConsumed == sizeof(DStream->bitContainer)*8)); +} + +#endif /* BITSTREAM_H_MODULE */ +/**** ended inlining bitstream.h ****/ + +/* ***************************************** +* Static allocation +*******************************************/ +/* FSE buffer bounds */ +#define FSE_NCOUNTBOUND 512 +#define FSE_BLOCKBOUND(size) ((size) + ((size)>>7) + 4 /* fse states */ + sizeof(size_t) /* bitContainer */) +#define FSE_COMPRESSBOUND(size) (FSE_NCOUNTBOUND + FSE_BLOCKBOUND(size)) /* Macro version, useful for static allocation */ + +/* It is possible to statically allocate FSE CTable/DTable as a table of FSE_CTable/FSE_DTable using below macros */ +#define FSE_CTABLE_SIZE_U32(maxTableLog, maxSymbolValue) (1 + (1<<((maxTableLog)-1)) + (((maxSymbolValue)+1)*2)) +#define FSE_DTABLE_SIZE_U32(maxTableLog) (1 + (1<<(maxTableLog))) + +/* or use the size to malloc() space directly. Pay attention to alignment restrictions though */ +#define FSE_CTABLE_SIZE(maxTableLog, maxSymbolValue) (FSE_CTABLE_SIZE_U32(maxTableLog, maxSymbolValue) * sizeof(FSE_CTable)) +#define FSE_DTABLE_SIZE(maxTableLog) (FSE_DTABLE_SIZE_U32(maxTableLog) * sizeof(FSE_DTable)) + + +/* ***************************************** + * FSE advanced API + ***************************************** */ + +unsigned FSE_optimalTableLog_internal(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue, unsigned minus); +/**< same as FSE_optimalTableLog(), which used `minus==2` */ + +size_t FSE_buildCTable_rle (FSE_CTable* ct, unsigned char symbolValue); +/**< build a fake FSE_CTable, designed to compress always the same symbolValue */ + +/* FSE_buildCTable_wksp() : + * Same as FSE_buildCTable(), but using an externally allocated scratch buffer (`workSpace`). + * `wkspSize` must be >= `FSE_BUILD_CTABLE_WORKSPACE_SIZE_U32(maxSymbolValue, tableLog)` of `unsigned`. + * See FSE_buildCTable_wksp() for breakdown of workspace usage. + */ +#define FSE_BUILD_CTABLE_WORKSPACE_SIZE_U32(maxSymbolValue, tableLog) (((maxSymbolValue + 2) + (1ull << (tableLog)))/2 + sizeof(U64)/sizeof(U32) /* additional 8 bytes for potential table overwrite */) +#define FSE_BUILD_CTABLE_WORKSPACE_SIZE(maxSymbolValue, tableLog) (sizeof(unsigned) * FSE_BUILD_CTABLE_WORKSPACE_SIZE_U32(maxSymbolValue, tableLog)) +size_t FSE_buildCTable_wksp(FSE_CTable* ct, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog, void* workSpace, size_t wkspSize); + +#define FSE_BUILD_DTABLE_WKSP_SIZE(maxTableLog, maxSymbolValue) (sizeof(short) * (maxSymbolValue + 1) + (1ULL << maxTableLog) + 8) +#define FSE_BUILD_DTABLE_WKSP_SIZE_U32(maxTableLog, maxSymbolValue) ((FSE_BUILD_DTABLE_WKSP_SIZE(maxTableLog, maxSymbolValue) + sizeof(unsigned) - 1) / sizeof(unsigned)) +FSE_PUBLIC_API size_t FSE_buildDTable_wksp(FSE_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog, void* workSpace, size_t wkspSize); +/**< Same as FSE_buildDTable(), using an externally allocated `workspace` produced with `FSE_BUILD_DTABLE_WKSP_SIZE_U32(maxSymbolValue)` */ + +#define FSE_DECOMPRESS_WKSP_SIZE_U32(maxTableLog, maxSymbolValue) (FSE_DTABLE_SIZE_U32(maxTableLog) + 1 + FSE_BUILD_DTABLE_WKSP_SIZE_U32(maxTableLog, maxSymbolValue) + (FSE_MAX_SYMBOL_VALUE + 1) / 2 + 1) +#define FSE_DECOMPRESS_WKSP_SIZE(maxTableLog, maxSymbolValue) (FSE_DECOMPRESS_WKSP_SIZE_U32(maxTableLog, maxSymbolValue) * sizeof(unsigned)) +size_t FSE_decompress_wksp_bmi2(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize, unsigned maxLog, void* workSpace, size_t wkspSize, int bmi2); +/**< same as FSE_decompress(), using an externally allocated `workSpace` produced with `FSE_DECOMPRESS_WKSP_SIZE_U32(maxLog, maxSymbolValue)`. + * Set bmi2 to 1 if your CPU supports BMI2 or 0 if it doesn't */ + +typedef enum { + FSE_repeat_none, /**< Cannot use the previous table */ + FSE_repeat_check, /**< Can use the previous table but it must be checked */ + FSE_repeat_valid /**< Can use the previous table and it is assumed to be valid */ + } FSE_repeat; + +/* ***************************************** +* FSE symbol compression API +*******************************************/ +/*! + This API consists of small unitary functions, which highly benefit from being inlined. + Hence their body are included in next section. +*/ +typedef struct { + ptrdiff_t value; + const void* stateTable; + const void* symbolTT; + unsigned stateLog; +} FSE_CState_t; + +static void FSE_initCState(FSE_CState_t* CStatePtr, const FSE_CTable* ct); + +static void FSE_encodeSymbol(BIT_CStream_t* bitC, FSE_CState_t* CStatePtr, unsigned symbol); + +static void FSE_flushCState(BIT_CStream_t* bitC, const FSE_CState_t* CStatePtr); + +/**< +These functions are inner components of FSE_compress_usingCTable(). +They allow the creation of custom streams, mixing multiple tables and bit sources. + +A key property to keep in mind is that encoding and decoding are done **in reverse direction**. +So the first symbol you will encode is the last you will decode, like a LIFO stack. + +You will need a few variables to track your CStream. They are : + +FSE_CTable ct; // Provided by FSE_buildCTable() +BIT_CStream_t bitStream; // bitStream tracking structure +FSE_CState_t state; // State tracking structure (can have several) + + +The first thing to do is to init bitStream and state. + size_t errorCode = BIT_initCStream(&bitStream, dstBuffer, maxDstSize); + FSE_initCState(&state, ct); + +Note that BIT_initCStream() can produce an error code, so its result should be tested, using FSE_isError(); +You can then encode your input data, byte after byte. +FSE_encodeSymbol() outputs a maximum of 'tableLog' bits at a time. +Remember decoding will be done in reverse direction. + FSE_encodeByte(&bitStream, &state, symbol); + +At any time, you can also add any bit sequence. +Note : maximum allowed nbBits is 25, for compatibility with 32-bits decoders + BIT_addBits(&bitStream, bitField, nbBits); + +The above methods don't commit data to memory, they just store it into local register, for speed. +Local register size is 64-bits on 64-bits systems, 32-bits on 32-bits systems (size_t). +Writing data to memory is a manual operation, performed by the flushBits function. + BIT_flushBits(&bitStream); + +Your last FSE encoding operation shall be to flush your last state value(s). + FSE_flushState(&bitStream, &state); + +Finally, you must close the bitStream. +The function returns the size of CStream in bytes. +If data couldn't fit into dstBuffer, it will return a 0 ( == not compressible) +If there is an error, it returns an errorCode (which can be tested using FSE_isError()). + size_t size = BIT_closeCStream(&bitStream); +*/ + + +/* ***************************************** +* FSE symbol decompression API +*******************************************/ +typedef struct { + size_t state; + const void* table; /* precise table may vary, depending on U16 */ +} FSE_DState_t; + + +static void FSE_initDState(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD, const FSE_DTable* dt); + +static unsigned char FSE_decodeSymbol(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD); + +static unsigned FSE_endOfDState(const FSE_DState_t* DStatePtr); + +/**< +Let's now decompose FSE_decompress_usingDTable() into its unitary components. +You will decode FSE-encoded symbols from the bitStream, +and also any other bitFields you put in, **in reverse order**. + +You will need a few variables to track your bitStream. They are : + +BIT_DStream_t DStream; // Stream context +FSE_DState_t DState; // State context. Multiple ones are possible +FSE_DTable* DTablePtr; // Decoding table, provided by FSE_buildDTable() + +The first thing to do is to init the bitStream. + errorCode = BIT_initDStream(&DStream, srcBuffer, srcSize); + +You should then retrieve your initial state(s) +(in reverse flushing order if you have several ones) : + errorCode = FSE_initDState(&DState, &DStream, DTablePtr); + +You can then decode your data, symbol after symbol. +For information the maximum number of bits read by FSE_decodeSymbol() is 'tableLog'. +Keep in mind that symbols are decoded in reverse order, like a LIFO stack (last in, first out). + unsigned char symbol = FSE_decodeSymbol(&DState, &DStream); + +You can retrieve any bitfield you eventually stored into the bitStream (in reverse order) +Note : maximum allowed nbBits is 25, for 32-bits compatibility + size_t bitField = BIT_readBits(&DStream, nbBits); + +All above operations only read from local register (which size depends on size_t). +Refueling the register from memory is manually performed by the reload method. + endSignal = FSE_reloadDStream(&DStream); + +BIT_reloadDStream() result tells if there is still some more data to read from DStream. +BIT_DStream_unfinished : there is still some data left into the DStream. +BIT_DStream_endOfBuffer : Dstream reached end of buffer. Its container may no longer be completely filled. +BIT_DStream_completed : Dstream reached its exact end, corresponding in general to decompression completed. +BIT_DStream_tooFar : Dstream went too far. Decompression result is corrupted. + +When reaching end of buffer (BIT_DStream_endOfBuffer), progress slowly, notably if you decode multiple symbols per loop, +to properly detect the exact end of stream. +After each decoded symbol, check if DStream is fully consumed using this simple test : + BIT_reloadDStream(&DStream) >= BIT_DStream_completed + +When it's done, verify decompression is fully completed, by checking both DStream and the relevant states. +Checking if DStream has reached its end is performed by : + BIT_endOfDStream(&DStream); +Check also the states. There might be some symbols left there, if some high probability ones (>50%) are possible. + FSE_endOfDState(&DState); +*/ + + +/* ***************************************** +* FSE unsafe API +*******************************************/ +static unsigned char FSE_decodeSymbolFast(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD); +/* faster, but works only if nbBits is always >= 1 (otherwise, result will be corrupted) */ + + +/* ***************************************** +* Implementation of inlined functions +*******************************************/ +typedef struct { + int deltaFindState; + U32 deltaNbBits; +} FSE_symbolCompressionTransform; /* total 8 bytes */ + +MEM_STATIC void FSE_initCState(FSE_CState_t* statePtr, const FSE_CTable* ct) +{ + const void* ptr = ct; + const U16* u16ptr = (const U16*) ptr; + const U32 tableLog = MEM_read16(ptr); + statePtr->value = (ptrdiff_t)1<stateTable = u16ptr+2; + statePtr->symbolTT = ct + 1 + (tableLog ? (1<<(tableLog-1)) : 1); + statePtr->stateLog = tableLog; +} + + +/*! FSE_initCState2() : +* Same as FSE_initCState(), but the first symbol to include (which will be the last to be read) +* uses the smallest state value possible, saving the cost of this symbol */ +MEM_STATIC void FSE_initCState2(FSE_CState_t* statePtr, const FSE_CTable* ct, U32 symbol) +{ + FSE_initCState(statePtr, ct); + { const FSE_symbolCompressionTransform symbolTT = ((const FSE_symbolCompressionTransform*)(statePtr->symbolTT))[symbol]; + const U16* stateTable = (const U16*)(statePtr->stateTable); + U32 nbBitsOut = (U32)((symbolTT.deltaNbBits + (1<<15)) >> 16); + statePtr->value = (nbBitsOut << 16) - symbolTT.deltaNbBits; + statePtr->value = stateTable[(statePtr->value >> nbBitsOut) + symbolTT.deltaFindState]; + } +} + +MEM_STATIC void FSE_encodeSymbol(BIT_CStream_t* bitC, FSE_CState_t* statePtr, unsigned symbol) +{ + FSE_symbolCompressionTransform const symbolTT = ((const FSE_symbolCompressionTransform*)(statePtr->symbolTT))[symbol]; + const U16* const stateTable = (const U16*)(statePtr->stateTable); + U32 const nbBitsOut = (U32)((statePtr->value + symbolTT.deltaNbBits) >> 16); + BIT_addBits(bitC, (BitContainerType)statePtr->value, nbBitsOut); + statePtr->value = stateTable[ (statePtr->value >> nbBitsOut) + symbolTT.deltaFindState]; +} + +MEM_STATIC void FSE_flushCState(BIT_CStream_t* bitC, const FSE_CState_t* statePtr) +{ + BIT_addBits(bitC, (BitContainerType)statePtr->value, statePtr->stateLog); + BIT_flushBits(bitC); +} + + +/* FSE_getMaxNbBits() : + * Approximate maximum cost of a symbol, in bits. + * Fractional get rounded up (i.e. a symbol with a normalized frequency of 3 gives the same result as a frequency of 2) + * note 1 : assume symbolValue is valid (<= maxSymbolValue) + * note 2 : if freq[symbolValue]==0, @return a fake cost of tableLog+1 bits */ +MEM_STATIC U32 FSE_getMaxNbBits(const void* symbolTTPtr, U32 symbolValue) +{ + const FSE_symbolCompressionTransform* symbolTT = (const FSE_symbolCompressionTransform*) symbolTTPtr; + return (symbolTT[symbolValue].deltaNbBits + ((1<<16)-1)) >> 16; +} + +/* FSE_bitCost() : + * Approximate symbol cost, as fractional value, using fixed-point format (accuracyLog fractional bits) + * note 1 : assume symbolValue is valid (<= maxSymbolValue) + * note 2 : if freq[symbolValue]==0, @return a fake cost of tableLog+1 bits */ +MEM_STATIC U32 FSE_bitCost(const void* symbolTTPtr, U32 tableLog, U32 symbolValue, U32 accuracyLog) +{ + const FSE_symbolCompressionTransform* symbolTT = (const FSE_symbolCompressionTransform*) symbolTTPtr; + U32 const minNbBits = symbolTT[symbolValue].deltaNbBits >> 16; + U32 const threshold = (minNbBits+1) << 16; + assert(tableLog < 16); + assert(accuracyLog < 31-tableLog); /* ensure enough room for renormalization double shift */ + { U32 const tableSize = 1 << tableLog; + U32 const deltaFromThreshold = threshold - (symbolTT[symbolValue].deltaNbBits + tableSize); + U32 const normalizedDeltaFromThreshold = (deltaFromThreshold << accuracyLog) >> tableLog; /* linear interpolation (very approximate) */ + U32 const bitMultiplier = 1 << accuracyLog; + assert(symbolTT[symbolValue].deltaNbBits + tableSize <= threshold); + assert(normalizedDeltaFromThreshold <= bitMultiplier); + return (minNbBits+1)*bitMultiplier - normalizedDeltaFromThreshold; + } +} + + +/* ====== Decompression ====== */ + +typedef struct { + U16 tableLog; + U16 fastMode; +} FSE_DTableHeader; /* sizeof U32 */ + +typedef struct +{ + unsigned short newState; + unsigned char symbol; + unsigned char nbBits; +} FSE_decode_t; /* size == U32 */ + +MEM_STATIC void FSE_initDState(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD, const FSE_DTable* dt) +{ + const void* ptr = dt; + const FSE_DTableHeader* const DTableH = (const FSE_DTableHeader*)ptr; + DStatePtr->state = BIT_readBits(bitD, DTableH->tableLog); + BIT_reloadDStream(bitD); + DStatePtr->table = dt + 1; +} + +MEM_STATIC BYTE FSE_peekSymbol(const FSE_DState_t* DStatePtr) +{ + FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state]; + return DInfo.symbol; +} + +MEM_STATIC void FSE_updateState(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD) +{ + FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state]; + U32 const nbBits = DInfo.nbBits; + size_t const lowBits = BIT_readBits(bitD, nbBits); + DStatePtr->state = DInfo.newState + lowBits; +} + +MEM_STATIC BYTE FSE_decodeSymbol(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD) +{ + FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state]; + U32 const nbBits = DInfo.nbBits; + BYTE const symbol = DInfo.symbol; + size_t const lowBits = BIT_readBits(bitD, nbBits); + + DStatePtr->state = DInfo.newState + lowBits; + return symbol; +} + +/*! FSE_decodeSymbolFast() : + unsafe, only works if no symbol has a probability > 50% */ +MEM_STATIC BYTE FSE_decodeSymbolFast(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD) +{ + FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state]; + U32 const nbBits = DInfo.nbBits; + BYTE const symbol = DInfo.symbol; + size_t const lowBits = BIT_readBitsFast(bitD, nbBits); + + DStatePtr->state = DInfo.newState + lowBits; + return symbol; +} + +MEM_STATIC unsigned FSE_endOfDState(const FSE_DState_t* DStatePtr) +{ + return DStatePtr->state == 0; +} + + + +#ifndef FSE_COMMONDEFS_ONLY + +/* ************************************************************** +* Tuning parameters +****************************************************************/ +/*!MEMORY_USAGE : +* Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.) +* Increasing memory usage improves compression ratio +* Reduced memory usage can improve speed, due to cache effect +* Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */ +#ifndef FSE_MAX_MEMORY_USAGE +# define FSE_MAX_MEMORY_USAGE 14 +#endif +#ifndef FSE_DEFAULT_MEMORY_USAGE +# define FSE_DEFAULT_MEMORY_USAGE 13 +#endif +#if (FSE_DEFAULT_MEMORY_USAGE > FSE_MAX_MEMORY_USAGE) +# error "FSE_DEFAULT_MEMORY_USAGE must be <= FSE_MAX_MEMORY_USAGE" +#endif + +/*!FSE_MAX_SYMBOL_VALUE : +* Maximum symbol value authorized. +* Required for proper stack allocation */ +#ifndef FSE_MAX_SYMBOL_VALUE +# define FSE_MAX_SYMBOL_VALUE 255 +#endif + +/* ************************************************************** +* template functions type & suffix +****************************************************************/ +#define FSE_FUNCTION_TYPE BYTE +#define FSE_FUNCTION_EXTENSION +#define FSE_DECODE_TYPE FSE_decode_t + + +#endif /* !FSE_COMMONDEFS_ONLY */ + + +/* *************************************************************** +* Constants +*****************************************************************/ +#define FSE_MAX_TABLELOG (FSE_MAX_MEMORY_USAGE-2) +#define FSE_MAX_TABLESIZE (1U< FSE_TABLELOG_ABSOLUTE_MAX +# error "FSE_MAX_TABLELOG > FSE_TABLELOG_ABSOLUTE_MAX is not supported" +#endif + +#define FSE_TABLESTEP(tableSize) (((tableSize)>>1) + ((tableSize)>>3) + 3) + +#endif /* FSE_STATIC_LINKING_ONLY */ +/**** ended inlining fse.h ****/ +/**** start inlining huf.h ****/ +/* ****************************************************************** + * huff0 huffman codec, + * part of Finite State Entropy library + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * You can contact the author at : + * - Source repository : https://github.com/Cyan4973/FiniteStateEntropy + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. +****************************************************************** */ + +#ifndef HUF_H_298734234 +#define HUF_H_298734234 + +/* *** Dependencies *** */ +/**** skipping file: zstd_deps.h ****/ +/**** skipping file: mem.h ****/ +#define FSE_STATIC_LINKING_ONLY +/**** skipping file: fse.h ****/ + +/* *** Tool functions *** */ +#define HUF_BLOCKSIZE_MAX (128 * 1024) /**< maximum input size for a single block compressed with HUF_compress */ +size_t HUF_compressBound(size_t size); /**< maximum compressed size (worst case) */ + +/* Error Management */ +unsigned HUF_isError(size_t code); /**< tells if a return value is an error code */ +const char* HUF_getErrorName(size_t code); /**< provides error code string (useful for debugging) */ + + +#define HUF_WORKSPACE_SIZE ((8 << 10) + 512 /* sorting scratch space */) +#define HUF_WORKSPACE_SIZE_U64 (HUF_WORKSPACE_SIZE / sizeof(U64)) + +/* *** Constants *** */ +#define HUF_TABLELOG_MAX 12 /* max runtime value of tableLog (due to static allocation); can be modified up to HUF_TABLELOG_ABSOLUTEMAX */ +#define HUF_TABLELOG_DEFAULT 11 /* default tableLog value when none specified */ +#define HUF_SYMBOLVALUE_MAX 255 + +#define HUF_TABLELOG_ABSOLUTEMAX 12 /* absolute limit of HUF_MAX_TABLELOG. Beyond that value, code does not work */ +#if (HUF_TABLELOG_MAX > HUF_TABLELOG_ABSOLUTEMAX) +# error "HUF_TABLELOG_MAX is too large !" +#endif + + +/* **************************************** +* Static allocation +******************************************/ +/* HUF buffer bounds */ +#define HUF_CTABLEBOUND 129 +#define HUF_BLOCKBOUND(size) (size + (size>>8) + 8) /* only true when incompressible is pre-filtered with fast heuristic */ +#define HUF_COMPRESSBOUND(size) (HUF_CTABLEBOUND + HUF_BLOCKBOUND(size)) /* Macro version, useful for static allocation */ + +/* static allocation of HUF's Compression Table */ +/* this is a private definition, just exposed for allocation and strict aliasing purpose. never EVER access its members directly */ +typedef size_t HUF_CElt; /* consider it an incomplete type */ +#define HUF_CTABLE_SIZE_ST(maxSymbolValue) ((maxSymbolValue)+2) /* Use tables of size_t, for proper alignment */ +#define HUF_CTABLE_SIZE(maxSymbolValue) (HUF_CTABLE_SIZE_ST(maxSymbolValue) * sizeof(size_t)) +#define HUF_CREATE_STATIC_CTABLE(name, maxSymbolValue) \ + HUF_CElt name[HUF_CTABLE_SIZE_ST(maxSymbolValue)] /* no final ; */ + +/* static allocation of HUF's DTable */ +typedef U32 HUF_DTable; +#define HUF_DTABLE_SIZE(maxTableLog) (1 + (1<<(maxTableLog))) +#define HUF_CREATE_STATIC_DTABLEX1(DTable, maxTableLog) \ + HUF_DTable DTable[HUF_DTABLE_SIZE((maxTableLog)-1)] = { ((U32)((maxTableLog)-1) * 0x01000001) } +#define HUF_CREATE_STATIC_DTABLEX2(DTable, maxTableLog) \ + HUF_DTable DTable[HUF_DTABLE_SIZE(maxTableLog)] = { ((U32)(maxTableLog) * 0x01000001) } + + +/* **************************************** +* Advanced decompression functions +******************************************/ + +/** + * Huffman flags bitset. + * For all flags, 0 is the default value. + */ +typedef enum { + /** + * If compiled with DYNAMIC_BMI2: Set flag only if the CPU supports BMI2 at runtime. + * Otherwise: Ignored. + */ + HUF_flags_bmi2 = (1 << 0), + /** + * If set: Test possible table depths to find the one that produces the smallest header + encoded size. + * If unset: Use heuristic to find the table depth. + */ + HUF_flags_optimalDepth = (1 << 1), + /** + * If set: If the previous table can encode the input, always reuse the previous table. + * If unset: If the previous table can encode the input, reuse the previous table if it results in a smaller output. + */ + HUF_flags_preferRepeat = (1 << 2), + /** + * If set: Sample the input and check if the sample is uncompressible, if it is then don't attempt to compress. + * If unset: Always histogram the entire input. + */ + HUF_flags_suspectUncompressible = (1 << 3), + /** + * If set: Don't use assembly implementations + * If unset: Allow using assembly implementations + */ + HUF_flags_disableAsm = (1 << 4), + /** + * If set: Don't use the fast decoding loop, always use the fallback decoding loop. + * If unset: Use the fast decoding loop when possible. + */ + HUF_flags_disableFast = (1 << 5) +} HUF_flags_e; + + +/* **************************************** + * HUF detailed API + * ****************************************/ +#define HUF_OPTIMAL_DEPTH_THRESHOLD ZSTD_btultra + +/*! HUF_compress() does the following: + * 1. count symbol occurrence from source[] into table count[] using FSE_count() (exposed within "fse.h") + * 2. (optional) refine tableLog using HUF_optimalTableLog() + * 3. build Huffman table from count using HUF_buildCTable() + * 4. save Huffman table to memory buffer using HUF_writeCTable() + * 5. encode the data stream using HUF_compress4X_usingCTable() + * + * The following API allows targeting specific sub-functions for advanced tasks. + * For example, it's possible to compress several blocks using the same 'CTable', + * or to save and regenerate 'CTable' using external methods. + */ +unsigned HUF_minTableLog(unsigned symbolCardinality); +unsigned HUF_cardinality(const unsigned* count, unsigned maxSymbolValue); +unsigned HUF_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue, void* workSpace, + size_t wkspSize, HUF_CElt* table, const unsigned* count, int flags); /* table is used as scratch space for building and testing tables, not a return value */ +size_t HUF_writeCTable_wksp(void* dst, size_t maxDstSize, const HUF_CElt* CTable, unsigned maxSymbolValue, unsigned huffLog, void* workspace, size_t workspaceSize); +size_t HUF_compress4X_usingCTable(void* dst, size_t dstSize, const void* src, size_t srcSize, const HUF_CElt* CTable, int flags); +size_t HUF_estimateCompressedSize(const HUF_CElt* CTable, const unsigned* count, unsigned maxSymbolValue); +int HUF_validateCTable(const HUF_CElt* CTable, const unsigned* count, unsigned maxSymbolValue); + +typedef enum { + HUF_repeat_none, /**< Cannot use the previous table */ + HUF_repeat_check, /**< Can use the previous table but it must be checked. Note : The previous table must have been constructed by HUF_compress{1, 4}X_repeat */ + HUF_repeat_valid /**< Can use the previous table and it is assumed to be valid */ + } HUF_repeat; + +/** HUF_compress4X_repeat() : + * Same as HUF_compress4X_wksp(), but considers using hufTable if *repeat != HUF_repeat_none. + * If it uses hufTable it does not modify hufTable or repeat. + * If it doesn't, it sets *repeat = HUF_repeat_none, and it sets hufTable to the table used. + * If preferRepeat then the old table will always be used if valid. + * If suspectUncompressible then some sampling checks will be run to potentially skip huffman coding */ +size_t HUF_compress4X_repeat(void* dst, size_t dstSize, + const void* src, size_t srcSize, + unsigned maxSymbolValue, unsigned tableLog, + void* workSpace, size_t wkspSize, /**< `workSpace` must be aligned on 4-bytes boundaries, `wkspSize` must be >= HUF_WORKSPACE_SIZE */ + HUF_CElt* hufTable, HUF_repeat* repeat, int flags); + +/** HUF_buildCTable_wksp() : + * Same as HUF_buildCTable(), but using externally allocated scratch buffer. + * `workSpace` must be aligned on 4-bytes boundaries, and its size must be >= HUF_CTABLE_WORKSPACE_SIZE. + */ +#define HUF_CTABLE_WORKSPACE_SIZE_U32 ((4 * (HUF_SYMBOLVALUE_MAX + 1)) + 192) +#define HUF_CTABLE_WORKSPACE_SIZE (HUF_CTABLE_WORKSPACE_SIZE_U32 * sizeof(unsigned)) +size_t HUF_buildCTable_wksp (HUF_CElt* tree, + const unsigned* count, U32 maxSymbolValue, U32 maxNbBits, + void* workSpace, size_t wkspSize); + +/*! HUF_readStats() : + * Read compact Huffman tree, saved by HUF_writeCTable(). + * `huffWeight` is destination buffer. + * @return : size read from `src` , or an error Code . + * Note : Needed by HUF_readCTable() and HUF_readDTableXn() . */ +size_t HUF_readStats(BYTE* huffWeight, size_t hwSize, + U32* rankStats, U32* nbSymbolsPtr, U32* tableLogPtr, + const void* src, size_t srcSize); + +/*! HUF_readStats_wksp() : + * Same as HUF_readStats() but takes an external workspace which must be + * 4-byte aligned and its size must be >= HUF_READ_STATS_WORKSPACE_SIZE. + * If the CPU has BMI2 support, pass bmi2=1, otherwise pass bmi2=0. + */ +#define HUF_READ_STATS_WORKSPACE_SIZE_U32 FSE_DECOMPRESS_WKSP_SIZE_U32(6, HUF_TABLELOG_MAX-1) +#define HUF_READ_STATS_WORKSPACE_SIZE (HUF_READ_STATS_WORKSPACE_SIZE_U32 * sizeof(unsigned)) +size_t HUF_readStats_wksp(BYTE* huffWeight, size_t hwSize, + U32* rankStats, U32* nbSymbolsPtr, U32* tableLogPtr, + const void* src, size_t srcSize, + void* workspace, size_t wkspSize, + int flags); + +/** HUF_readCTable() : + * Loading a CTable saved with HUF_writeCTable() */ +size_t HUF_readCTable (HUF_CElt* CTable, unsigned* maxSymbolValuePtr, const void* src, size_t srcSize, unsigned *hasZeroWeights); + +/** HUF_getNbBitsFromCTable() : + * Read nbBits from CTable symbolTable, for symbol `symbolValue` presumed <= HUF_SYMBOLVALUE_MAX + * Note 1 : If symbolValue > HUF_readCTableHeader(symbolTable).maxSymbolValue, returns 0 + * Note 2 : is not inlined, as HUF_CElt definition is private + */ +U32 HUF_getNbBitsFromCTable(const HUF_CElt* symbolTable, U32 symbolValue); + +typedef struct { + BYTE tableLog; + BYTE maxSymbolValue; + BYTE unused[sizeof(size_t) - 2]; +} HUF_CTableHeader; + +/** HUF_readCTableHeader() : + * @returns The header from the CTable specifying the tableLog and the maxSymbolValue. + */ +HUF_CTableHeader HUF_readCTableHeader(HUF_CElt const* ctable); + +/* + * HUF_decompress() does the following: + * 1. select the decompression algorithm (X1, X2) based on pre-computed heuristics + * 2. build Huffman table from save, using HUF_readDTableX?() + * 3. decode 1 or 4 segments in parallel using HUF_decompress?X?_usingDTable() + */ + +/** HUF_selectDecoder() : + * Tells which decoder is likely to decode faster, + * based on a set of pre-computed metrics. + * @return : 0==HUF_decompress4X1, 1==HUF_decompress4X2 . + * Assumption : 0 < dstSize <= 128 KB */ +U32 HUF_selectDecoder (size_t dstSize, size_t cSrcSize); + +/** + * The minimum workspace size for the `workSpace` used in + * HUF_readDTableX1_wksp() and HUF_readDTableX2_wksp(). + * + * The space used depends on HUF_TABLELOG_MAX, ranging from ~1500 bytes when + * HUF_TABLE_LOG_MAX=12 to ~1850 bytes when HUF_TABLE_LOG_MAX=15. + * Buffer overflow errors may potentially occur if code modifications result in + * a required workspace size greater than that specified in the following + * macro. + */ +#define HUF_DECOMPRESS_WORKSPACE_SIZE ((2 << 10) + (1 << 9)) +#define HUF_DECOMPRESS_WORKSPACE_SIZE_U32 (HUF_DECOMPRESS_WORKSPACE_SIZE / sizeof(U32)) + + +/* ====================== */ +/* single stream variants */ +/* ====================== */ + +size_t HUF_compress1X_usingCTable(void* dst, size_t dstSize, const void* src, size_t srcSize, const HUF_CElt* CTable, int flags); +/** HUF_compress1X_repeat() : + * Same as HUF_compress1X_wksp(), but considers using hufTable if *repeat != HUF_repeat_none. + * If it uses hufTable it does not modify hufTable or repeat. + * If it doesn't, it sets *repeat = HUF_repeat_none, and it sets hufTable to the table used. + * If preferRepeat then the old table will always be used if valid. + * If suspectUncompressible then some sampling checks will be run to potentially skip huffman coding */ +size_t HUF_compress1X_repeat(void* dst, size_t dstSize, + const void* src, size_t srcSize, + unsigned maxSymbolValue, unsigned tableLog, + void* workSpace, size_t wkspSize, /**< `workSpace` must be aligned on 4-bytes boundaries, `wkspSize` must be >= HUF_WORKSPACE_SIZE */ + HUF_CElt* hufTable, HUF_repeat* repeat, int flags); + +size_t HUF_decompress1X_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int flags); +#ifndef HUF_FORCE_DECOMPRESS_X1 +size_t HUF_decompress1X2_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int flags); /**< double-symbols decoder */ +#endif + +/* BMI2 variants. + * If the CPU has BMI2 support, pass bmi2=1, otherwise pass bmi2=0. + */ +size_t HUF_decompress1X_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable, int flags); +#ifndef HUF_FORCE_DECOMPRESS_X2 +size_t HUF_decompress1X1_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int flags); +#endif +size_t HUF_decompress4X_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable, int flags); +size_t HUF_decompress4X_hufOnly_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int flags); +#ifndef HUF_FORCE_DECOMPRESS_X2 +size_t HUF_readDTableX1_wksp(HUF_DTable* DTable, const void* src, size_t srcSize, void* workSpace, size_t wkspSize, int flags); +#endif +#ifndef HUF_FORCE_DECOMPRESS_X1 +size_t HUF_readDTableX2_wksp(HUF_DTable* DTable, const void* src, size_t srcSize, void* workSpace, size_t wkspSize, int flags); +#endif + +#endif /* HUF_H_298734234 */ +/**** ended inlining huf.h ****/ +/**** skipping file: bits.h ****/ + + +/*=== Version ===*/ +unsigned FSE_versionNumber(void) { return FSE_VERSION_NUMBER; } + + +/*=== Error Management ===*/ +unsigned FSE_isError(size_t code) { return ERR_isError(code); } +const char* FSE_getErrorName(size_t code) { return ERR_getErrorName(code); } + +unsigned HUF_isError(size_t code) { return ERR_isError(code); } +const char* HUF_getErrorName(size_t code) { return ERR_getErrorName(code); } + + +/*-************************************************************** +* FSE NCount encoding-decoding +****************************************************************/ +FORCE_INLINE_TEMPLATE +size_t FSE_readNCount_body(short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr, + const void* headerBuffer, size_t hbSize) +{ + const BYTE* const istart = (const BYTE*) headerBuffer; + const BYTE* const iend = istart + hbSize; + const BYTE* ip = istart; + int nbBits; + int remaining; + int threshold; + U32 bitStream; + int bitCount; + unsigned charnum = 0; + unsigned const maxSV1 = *maxSVPtr + 1; + int previous0 = 0; + + if (hbSize < 8) { + /* This function only works when hbSize >= 8 */ + char buffer[8] = {0}; + ZSTD_memcpy(buffer, headerBuffer, hbSize); + { size_t const countSize = FSE_readNCount(normalizedCounter, maxSVPtr, tableLogPtr, + buffer, sizeof(buffer)); + if (FSE_isError(countSize)) return countSize; + if (countSize > hbSize) return ERROR(corruption_detected); + return countSize; + } } + assert(hbSize >= 8); + + /* init */ + ZSTD_memset(normalizedCounter, 0, (*maxSVPtr+1) * sizeof(normalizedCounter[0])); /* all symbols not present in NCount have a frequency of 0 */ + bitStream = MEM_readLE32(ip); + nbBits = (bitStream & 0xF) + FSE_MIN_TABLELOG; /* extract tableLog */ + if (nbBits > FSE_TABLELOG_ABSOLUTE_MAX) return ERROR(tableLog_tooLarge); + bitStream >>= 4; + bitCount = 4; + *tableLogPtr = nbBits; + remaining = (1<> 1; + while (repeats >= 12) { + charnum += 3 * 12; + if (LIKELY(ip <= iend-7)) { + ip += 3; + } else { + bitCount -= (int)(8 * (iend - 7 - ip)); + bitCount &= 31; + ip = iend - 4; + } + bitStream = MEM_readLE32(ip) >> bitCount; + repeats = ZSTD_countTrailingZeros32(~bitStream | 0x80000000) >> 1; + } + charnum += 3 * repeats; + bitStream >>= 2 * repeats; + bitCount += 2 * repeats; + + /* Add the final repeat which isn't 0b11. */ + assert((bitStream & 3) < 3); + charnum += bitStream & 3; + bitCount += 2; + + /* This is an error, but break and return an error + * at the end, because returning out of a loop makes + * it harder for the compiler to optimize. + */ + if (charnum >= maxSV1) break; + + /* We don't need to set the normalized count to 0 + * because we already memset the whole buffer to 0. + */ + + if (LIKELY(ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) { + assert((bitCount >> 3) <= 3); /* For first condition to work */ + ip += bitCount>>3; + bitCount &= 7; + } else { + bitCount -= (int)(8 * (iend - 4 - ip)); + bitCount &= 31; + ip = iend - 4; + } + bitStream = MEM_readLE32(ip) >> bitCount; + } + { + int const max = (2*threshold-1) - remaining; + int count; + + if ((bitStream & (threshold-1)) < (U32)max) { + count = bitStream & (threshold-1); + bitCount += nbBits-1; + } else { + count = bitStream & (2*threshold-1); + if (count >= threshold) count -= max; + bitCount += nbBits; + } + + count--; /* extra accuracy */ + /* When it matters (small blocks), this is a + * predictable branch, because we don't use -1. + */ + if (count >= 0) { + remaining -= count; + } else { + assert(count == -1); + remaining += count; + } + normalizedCounter[charnum++] = (short)count; + previous0 = !count; + + assert(threshold > 1); + if (remaining < threshold) { + /* This branch can be folded into the + * threshold update condition because we + * know that threshold > 1. + */ + if (remaining <= 1) break; + nbBits = ZSTD_highbit32(remaining) + 1; + threshold = 1 << (nbBits - 1); + } + if (charnum >= maxSV1) break; + + if (LIKELY(ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) { + ip += bitCount>>3; + bitCount &= 7; + } else { + bitCount -= (int)(8 * (iend - 4 - ip)); + bitCount &= 31; + ip = iend - 4; + } + bitStream = MEM_readLE32(ip) >> bitCount; + } } + if (remaining != 1) return ERROR(corruption_detected); + /* Only possible when there are too many zeros. */ + if (charnum > maxSV1) return ERROR(maxSymbolValue_tooSmall); + if (bitCount > 32) return ERROR(corruption_detected); + *maxSVPtr = charnum-1; + + ip += (bitCount+7)>>3; + return ip-istart; +} + +/* Avoids the FORCE_INLINE of the _body() function. */ +static size_t FSE_readNCount_body_default( + short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr, + const void* headerBuffer, size_t hbSize) +{ + return FSE_readNCount_body(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize); +} + +#if DYNAMIC_BMI2 +BMI2_TARGET_ATTRIBUTE static size_t FSE_readNCount_body_bmi2( + short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr, + const void* headerBuffer, size_t hbSize) +{ + return FSE_readNCount_body(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize); +} +#endif + +size_t FSE_readNCount_bmi2( + short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr, + const void* headerBuffer, size_t hbSize, int bmi2) +{ +#if DYNAMIC_BMI2 + if (bmi2) { + return FSE_readNCount_body_bmi2(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize); + } +#endif + (void)bmi2; + return FSE_readNCount_body_default(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize); +} + +size_t FSE_readNCount( + short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr, + const void* headerBuffer, size_t hbSize) +{ + return FSE_readNCount_bmi2(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize, /* bmi2 */ 0); +} + + +/*! HUF_readStats() : + Read compact Huffman tree, saved by HUF_writeCTable(). + `huffWeight` is destination buffer. + `rankStats` is assumed to be a table of at least HUF_TABLELOG_MAX U32. + @return : size read from `src` , or an error Code . + Note : Needed by HUF_readCTable() and HUF_readDTableX?() . +*/ +size_t HUF_readStats(BYTE* huffWeight, size_t hwSize, U32* rankStats, + U32* nbSymbolsPtr, U32* tableLogPtr, + const void* src, size_t srcSize) +{ + U32 wksp[HUF_READ_STATS_WORKSPACE_SIZE_U32]; + return HUF_readStats_wksp(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, wksp, sizeof(wksp), /* flags */ 0); +} + +FORCE_INLINE_TEMPLATE size_t +HUF_readStats_body(BYTE* huffWeight, size_t hwSize, U32* rankStats, + U32* nbSymbolsPtr, U32* tableLogPtr, + const void* src, size_t srcSize, + void* workSpace, size_t wkspSize, + int bmi2) +{ + U32 weightTotal; + const BYTE* ip = (const BYTE*) src; + size_t iSize; + size_t oSize; + + if (!srcSize) return ERROR(srcSize_wrong); + iSize = ip[0]; + /* ZSTD_memset(huffWeight, 0, hwSize); *//* is not necessary, even though some analyzer complain ... */ + + if (iSize >= 128) { /* special header */ + oSize = iSize - 127; + iSize = ((oSize+1)/2); + if (iSize+1 > srcSize) return ERROR(srcSize_wrong); + if (oSize >= hwSize) return ERROR(corruption_detected); + ip += 1; + { U32 n; + for (n=0; n> 4; + huffWeight[n+1] = ip[n/2] & 15; + } } } + else { /* header compressed with FSE (normal case) */ + if (iSize+1 > srcSize) return ERROR(srcSize_wrong); + /* max (hwSize-1) values decoded, as last one is implied */ + oSize = FSE_decompress_wksp_bmi2(huffWeight, hwSize-1, ip+1, iSize, 6, workSpace, wkspSize, bmi2); + if (FSE_isError(oSize)) return oSize; + } + + /* collect weight stats */ + ZSTD_memset(rankStats, 0, (HUF_TABLELOG_MAX + 1) * sizeof(U32)); + weightTotal = 0; + { U32 n; for (n=0; n HUF_TABLELOG_MAX) return ERROR(corruption_detected); + rankStats[huffWeight[n]]++; + weightTotal += (1 << huffWeight[n]) >> 1; + } } + if (weightTotal == 0) return ERROR(corruption_detected); + + /* get last non-null symbol weight (implied, total must be 2^n) */ + { U32 const tableLog = ZSTD_highbit32(weightTotal) + 1; + if (tableLog > HUF_TABLELOG_MAX) return ERROR(corruption_detected); + *tableLogPtr = tableLog; + /* determine last weight */ + { U32 const total = 1 << tableLog; + U32 const rest = total - weightTotal; + U32 const verif = 1 << ZSTD_highbit32(rest); + U32 const lastWeight = ZSTD_highbit32(rest) + 1; + if (verif != rest) return ERROR(corruption_detected); /* last value must be a clean power of 2 */ + huffWeight[oSize] = (BYTE)lastWeight; + rankStats[lastWeight]++; + } } + + /* check tree construction validity */ + if ((rankStats[1] < 2) || (rankStats[1] & 1)) return ERROR(corruption_detected); /* by construction : at least 2 elts of rank 1, must be even */ + + /* results */ + *nbSymbolsPtr = (U32)(oSize+1); + return iSize+1; +} + +/* Avoids the FORCE_INLINE of the _body() function. */ +static size_t HUF_readStats_body_default(BYTE* huffWeight, size_t hwSize, U32* rankStats, + U32* nbSymbolsPtr, U32* tableLogPtr, + const void* src, size_t srcSize, + void* workSpace, size_t wkspSize) +{ + return HUF_readStats_body(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize, 0); +} + +#if DYNAMIC_BMI2 +static BMI2_TARGET_ATTRIBUTE size_t HUF_readStats_body_bmi2(BYTE* huffWeight, size_t hwSize, U32* rankStats, + U32* nbSymbolsPtr, U32* tableLogPtr, + const void* src, size_t srcSize, + void* workSpace, size_t wkspSize) +{ + return HUF_readStats_body(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize, 1); +} +#endif + +size_t HUF_readStats_wksp(BYTE* huffWeight, size_t hwSize, U32* rankStats, + U32* nbSymbolsPtr, U32* tableLogPtr, + const void* src, size_t srcSize, + void* workSpace, size_t wkspSize, + int flags) +{ +#if DYNAMIC_BMI2 + if (flags & HUF_flags_bmi2) { + return HUF_readStats_body_bmi2(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize); + } +#endif + (void)flags; + return HUF_readStats_body_default(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize); +} +/**** ended inlining common/entropy_common.c ****/ +/**** start inlining common/error_private.c ****/ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +/* The purpose of this file is to have a single list of error strings embedded in binary */ + +/**** skipping file: error_private.h ****/ + +const char* ERR_getErrorString(ERR_enum code) +{ +#ifdef ZSTD_STRIP_ERROR_STRINGS + (void)code; + return "Error strings stripped"; +#else + static const char* const notErrorCode = "Unspecified error code"; + switch( code ) + { + case PREFIX(no_error): return "No error detected"; + case PREFIX(GENERIC): return "Error (generic)"; + case PREFIX(prefix_unknown): return "Unknown frame descriptor"; + case PREFIX(version_unsupported): return "Version not supported"; + case PREFIX(frameParameter_unsupported): return "Unsupported frame parameter"; + case PREFIX(frameParameter_windowTooLarge): return "Frame requires too much memory for decoding"; + case PREFIX(corruption_detected): return "Data corruption detected"; + case PREFIX(checksum_wrong): return "Restored data doesn't match checksum"; + case PREFIX(literals_headerWrong): return "Header of Literals' block doesn't respect format specification"; + case PREFIX(parameter_unsupported): return "Unsupported parameter"; + case PREFIX(parameter_combination_unsupported): return "Unsupported combination of parameters"; + case PREFIX(parameter_outOfBound): return "Parameter is out of bound"; + case PREFIX(init_missing): return "Context should be init first"; + case PREFIX(memory_allocation): return "Allocation error : not enough memory"; + case PREFIX(workSpace_tooSmall): return "workSpace buffer is not large enough"; + case PREFIX(stage_wrong): return "Operation not authorized at current processing stage"; + case PREFIX(tableLog_tooLarge): return "tableLog requires too much memory : unsupported"; + case PREFIX(maxSymbolValue_tooLarge): return "Unsupported max Symbol Value : too large"; + case PREFIX(maxSymbolValue_tooSmall): return "Specified maxSymbolValue is too small"; + case PREFIX(cannotProduce_uncompressedBlock): return "This mode cannot generate an uncompressed block"; + case PREFIX(stabilityCondition_notRespected): return "pledged buffer stability condition is not respected"; + case PREFIX(dictionary_corrupted): return "Dictionary is corrupted"; + case PREFIX(dictionary_wrong): return "Dictionary mismatch"; + case PREFIX(dictionaryCreation_failed): return "Cannot create Dictionary from provided samples"; + case PREFIX(dstSize_tooSmall): return "Destination buffer is too small"; + case PREFIX(srcSize_wrong): return "Src size is incorrect"; + case PREFIX(dstBuffer_null): return "Operation on NULL destination buffer"; + case PREFIX(noForwardProgress_destFull): return "Operation made no progress over multiple calls, due to output buffer being full"; + case PREFIX(noForwardProgress_inputEmpty): return "Operation made no progress over multiple calls, due to input being empty"; + /* following error codes are not stable and may be removed or changed in a future version */ + case PREFIX(frameIndex_tooLarge): return "Frame index is too large"; + case PREFIX(seekableIO): return "An I/O error occurred when reading/seeking"; + case PREFIX(dstBuffer_wrong): return "Destination buffer is wrong"; + case PREFIX(srcBuffer_wrong): return "Source buffer is wrong"; + case PREFIX(sequenceProducer_failed): return "Block-level external sequence producer returned an error code"; + case PREFIX(externalSequences_invalid): return "External sequences are not valid"; + case PREFIX(maxCode): + default: return notErrorCode; + } +#endif +} +/**** ended inlining common/error_private.c ****/ +/**** start inlining common/fse_decompress.c ****/ +/* ****************************************************************** + * FSE : Finite State Entropy decoder + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * You can contact the author at : + * - FSE source repository : https://github.com/Cyan4973/FiniteStateEntropy + * - Public forum : https://groups.google.com/forum/#!forum/lz4c + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. +****************************************************************** */ + + +/* ************************************************************** +* Includes +****************************************************************/ +/**** skipping file: debug.h ****/ +/**** skipping file: bitstream.h ****/ +/**** skipping file: compiler.h ****/ +#define FSE_STATIC_LINKING_ONLY +/**** skipping file: fse.h ****/ +/**** skipping file: error_private.h ****/ +/**** skipping file: zstd_deps.h ****/ +/**** skipping file: bits.h ****/ + + +/* ************************************************************** +* Error Management +****************************************************************/ +#define FSE_isError ERR_isError +#define FSE_STATIC_ASSERT(c) DEBUG_STATIC_ASSERT(c) /* use only *after* variable declarations */ + + +/* ************************************************************** +* Templates +****************************************************************/ +/* + designed to be included + for type-specific functions (template emulation in C) + Objective is to write these functions only once, for improved maintenance +*/ + +/* safety checks */ +#ifndef FSE_FUNCTION_EXTENSION +# error "FSE_FUNCTION_EXTENSION must be defined" +#endif +#ifndef FSE_FUNCTION_TYPE +# error "FSE_FUNCTION_TYPE must be defined" +#endif + +/* Function names */ +#define FSE_CAT(X,Y) X##Y +#define FSE_FUNCTION_NAME(X,Y) FSE_CAT(X,Y) +#define FSE_TYPE_NAME(X,Y) FSE_CAT(X,Y) + +static size_t FSE_buildDTable_internal(FSE_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog, void* workSpace, size_t wkspSize) +{ + void* const tdPtr = dt+1; /* because *dt is unsigned, 32-bits aligned on 32-bits */ + FSE_DECODE_TYPE* const tableDecode = (FSE_DECODE_TYPE*) (tdPtr); + U16* symbolNext = (U16*)workSpace; + BYTE* spread = (BYTE*)(symbolNext + maxSymbolValue + 1); + + U32 const maxSV1 = maxSymbolValue + 1; + U32 const tableSize = 1 << tableLog; + U32 highThreshold = tableSize-1; + + /* Sanity Checks */ + if (FSE_BUILD_DTABLE_WKSP_SIZE(tableLog, maxSymbolValue) > wkspSize) return ERROR(maxSymbolValue_tooLarge); + if (maxSymbolValue > FSE_MAX_SYMBOL_VALUE) return ERROR(maxSymbolValue_tooLarge); + if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge); + + /* Init, lay down lowprob symbols */ + { FSE_DTableHeader DTableH; + DTableH.tableLog = (U16)tableLog; + DTableH.fastMode = 1; + { S16 const largeLimit= (S16)(1 << (tableLog-1)); + U32 s; + for (s=0; s= largeLimit) DTableH.fastMode=0; + symbolNext[s] = (U16)normalizedCounter[s]; + } } } + ZSTD_memcpy(dt, &DTableH, sizeof(DTableH)); + } + + /* Spread symbols */ + if (highThreshold == tableSize - 1) { + size_t const tableMask = tableSize-1; + size_t const step = FSE_TABLESTEP(tableSize); + /* First lay down the symbols in order. + * We use a uint64_t to lay down 8 bytes at a time. This reduces branch + * misses since small blocks generally have small table logs, so nearly + * all symbols have counts <= 8. We ensure we have 8 bytes at the end of + * our buffer to handle the over-write. + */ + { U64 const add = 0x0101010101010101ull; + size_t pos = 0; + U64 sv = 0; + U32 s; + for (s=0; s highThreshold) position = (position + step) & tableMask; /* lowprob area */ + } } + if (position!=0) return ERROR(GENERIC); /* position must reach all cells once, otherwise normalizedCounter is incorrect */ + } + + /* Build Decoding table */ + { U32 u; + for (u=0; u sizeof(bitD.bitContainer)*8) /* This test must be static */ + BIT_reloadDStream(&bitD); + + op[1] = FSE_GETSYMBOL(&state2); + + if (FSE_MAX_TABLELOG*4+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */ + { if (BIT_reloadDStream(&bitD) > BIT_DStream_unfinished) { op+=2; break; } } + + op[2] = FSE_GETSYMBOL(&state1); + + if (FSE_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */ + BIT_reloadDStream(&bitD); + + op[3] = FSE_GETSYMBOL(&state2); + } + + /* tail */ + /* note : BIT_reloadDStream(&bitD) >= FSE_DStream_partiallyFilled; Ends at exactly BIT_DStream_completed */ + while (1) { + if (op>(omax-2)) return ERROR(dstSize_tooSmall); + *op++ = FSE_GETSYMBOL(&state1); + if (BIT_reloadDStream(&bitD)==BIT_DStream_overflow) { + *op++ = FSE_GETSYMBOL(&state2); + break; + } + + if (op>(omax-2)) return ERROR(dstSize_tooSmall); + *op++ = FSE_GETSYMBOL(&state2); + if (BIT_reloadDStream(&bitD)==BIT_DStream_overflow) { + *op++ = FSE_GETSYMBOL(&state1); + break; + } } + + assert(op >= ostart); + return (size_t)(op-ostart); +} + +typedef struct { + short ncount[FSE_MAX_SYMBOL_VALUE + 1]; +} FSE_DecompressWksp; + + +FORCE_INLINE_TEMPLATE size_t FSE_decompress_wksp_body( + void* dst, size_t dstCapacity, + const void* cSrc, size_t cSrcSize, + unsigned maxLog, void* workSpace, size_t wkspSize, + int bmi2) +{ + const BYTE* const istart = (const BYTE*)cSrc; + const BYTE* ip = istart; + unsigned tableLog; + unsigned maxSymbolValue = FSE_MAX_SYMBOL_VALUE; + FSE_DecompressWksp* const wksp = (FSE_DecompressWksp*)workSpace; + size_t const dtablePos = sizeof(FSE_DecompressWksp) / sizeof(FSE_DTable); + FSE_DTable* const dtable = (FSE_DTable*)workSpace + dtablePos; + + FSE_STATIC_ASSERT((FSE_MAX_SYMBOL_VALUE + 1) % 2 == 0); + if (wkspSize < sizeof(*wksp)) return ERROR(GENERIC); + + /* correct offset to dtable depends on this property */ + FSE_STATIC_ASSERT(sizeof(FSE_DecompressWksp) % sizeof(FSE_DTable) == 0); + + /* normal FSE decoding mode */ + { size_t const NCountLength = + FSE_readNCount_bmi2(wksp->ncount, &maxSymbolValue, &tableLog, istart, cSrcSize, bmi2); + if (FSE_isError(NCountLength)) return NCountLength; + if (tableLog > maxLog) return ERROR(tableLog_tooLarge); + assert(NCountLength <= cSrcSize); + ip += NCountLength; + cSrcSize -= NCountLength; + } + + if (FSE_DECOMPRESS_WKSP_SIZE(tableLog, maxSymbolValue) > wkspSize) return ERROR(tableLog_tooLarge); + assert(sizeof(*wksp) + FSE_DTABLE_SIZE(tableLog) <= wkspSize); + workSpace = (BYTE*)workSpace + sizeof(*wksp) + FSE_DTABLE_SIZE(tableLog); + wkspSize -= sizeof(*wksp) + FSE_DTABLE_SIZE(tableLog); + + CHECK_F( FSE_buildDTable_internal(dtable, wksp->ncount, maxSymbolValue, tableLog, workSpace, wkspSize) ); + + { + const void* ptr = dtable; + const FSE_DTableHeader* DTableH = (const FSE_DTableHeader*)ptr; + const U32 fastMode = DTableH->fastMode; + + /* select fast mode (static) */ + if (fastMode) return FSE_decompress_usingDTable_generic(dst, dstCapacity, ip, cSrcSize, dtable, 1); + return FSE_decompress_usingDTable_generic(dst, dstCapacity, ip, cSrcSize, dtable, 0); + } +} + +/* Avoids the FORCE_INLINE of the _body() function. */ +static size_t FSE_decompress_wksp_body_default(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize, unsigned maxLog, void* workSpace, size_t wkspSize) +{ + return FSE_decompress_wksp_body(dst, dstCapacity, cSrc, cSrcSize, maxLog, workSpace, wkspSize, 0); +} + +#if DYNAMIC_BMI2 +BMI2_TARGET_ATTRIBUTE static size_t FSE_decompress_wksp_body_bmi2(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize, unsigned maxLog, void* workSpace, size_t wkspSize) +{ + return FSE_decompress_wksp_body(dst, dstCapacity, cSrc, cSrcSize, maxLog, workSpace, wkspSize, 1); +} +#endif + +size_t FSE_decompress_wksp_bmi2(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize, unsigned maxLog, void* workSpace, size_t wkspSize, int bmi2) +{ +#if DYNAMIC_BMI2 + if (bmi2) { + return FSE_decompress_wksp_body_bmi2(dst, dstCapacity, cSrc, cSrcSize, maxLog, workSpace, wkspSize); + } +#endif + (void)bmi2; + return FSE_decompress_wksp_body_default(dst, dstCapacity, cSrc, cSrcSize, maxLog, workSpace, wkspSize); +} + +#endif /* FSE_COMMONDEFS_ONLY */ +/**** ended inlining common/fse_decompress.c ****/ +/**** start inlining common/zstd_common.c ****/ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + + + +/*-************************************* +* Dependencies +***************************************/ +#define ZSTD_DEPS_NEED_MALLOC +/**** skipping file: error_private.h ****/ +/**** start inlining zstd_internal.h ****/ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTD_CCOMMON_H_MODULE +#define ZSTD_CCOMMON_H_MODULE + +/* this module contains definitions which must be identical + * across compression, decompression and dictBuilder. + * It also contains a few functions useful to at least 2 of them + * and which benefit from being inlined */ + +/*-************************************* +* Dependencies +***************************************/ +/**** skipping file: compiler.h ****/ +/**** start inlining cpu.h ****/ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTD_COMMON_CPU_H +#define ZSTD_COMMON_CPU_H + +/** + * Implementation taken from folly/CpuId.h + * https://github.com/facebook/folly/blob/master/folly/CpuId.h + */ + +/**** skipping file: mem.h ****/ + +#ifdef _MSC_VER +#include +#endif + +typedef struct { + U32 f1c; + U32 f1d; + U32 f7b; + U32 f7c; +} ZSTD_cpuid_t; + +MEM_STATIC ZSTD_cpuid_t ZSTD_cpuid(void) { + U32 f1c = 0; + U32 f1d = 0; + U32 f7b = 0; + U32 f7c = 0; +#if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86)) +#if !defined(_M_X64) || !defined(__clang__) || __clang_major__ >= 16 + int reg[4]; + __cpuid((int*)reg, 0); + { + int const n = reg[0]; + if (n >= 1) { + __cpuid((int*)reg, 1); + f1c = (U32)reg[2]; + f1d = (U32)reg[3]; + } + if (n >= 7) { + __cpuidex((int*)reg, 7, 0); + f7b = (U32)reg[1]; + f7c = (U32)reg[2]; + } + } +#else + /* Clang compiler has a bug (fixed in https://reviews.llvm.org/D101338) in + * which the `__cpuid` intrinsic does not save and restore `rbx` as it needs + * to due to being a reserved register. So in that case, do the `cpuid` + * ourselves. Clang supports inline assembly anyway. + */ + U32 n; + __asm__( + "pushq %%rbx\n\t" + "cpuid\n\t" + "popq %%rbx\n\t" + : "=a"(n) + : "a"(0) + : "rcx", "rdx"); + if (n >= 1) { + U32 f1a; + __asm__( + "pushq %%rbx\n\t" + "cpuid\n\t" + "popq %%rbx\n\t" + : "=a"(f1a), "=c"(f1c), "=d"(f1d) + : "a"(1) + :); + } + if (n >= 7) { + __asm__( + "pushq %%rbx\n\t" + "cpuid\n\t" + "movq %%rbx, %%rax\n\t" + "popq %%rbx" + : "=a"(f7b), "=c"(f7c) + : "a"(7), "c"(0) + : "rdx"); + } +#endif +#elif defined(__i386__) && defined(__PIC__) && !defined(__clang__) && defined(__GNUC__) + /* The following block like the normal cpuid branch below, but gcc + * reserves ebx for use of its pic register so we must specially + * handle the save and restore to avoid clobbering the register + */ + U32 n; + __asm__( + "pushl %%ebx\n\t" + "cpuid\n\t" + "popl %%ebx\n\t" + : "=a"(n) + : "a"(0) + : "ecx", "edx"); + if (n >= 1) { + U32 f1a; + __asm__( + "pushl %%ebx\n\t" + "cpuid\n\t" + "popl %%ebx\n\t" + : "=a"(f1a), "=c"(f1c), "=d"(f1d) + : "a"(1)); + } + if (n >= 7) { + __asm__( + "pushl %%ebx\n\t" + "cpuid\n\t" + "movl %%ebx, %%eax\n\t" + "popl %%ebx" + : "=a"(f7b), "=c"(f7c) + : "a"(7), "c"(0) + : "edx"); + } +#elif defined(__x86_64__) || defined(_M_X64) || defined(__i386__) + U32 n; + __asm__("cpuid" : "=a"(n) : "a"(0) : "ebx", "ecx", "edx"); + if (n >= 1) { + U32 f1a; + __asm__("cpuid" : "=a"(f1a), "=c"(f1c), "=d"(f1d) : "a"(1) : "ebx"); + } + if (n >= 7) { + U32 f7a; + __asm__("cpuid" + : "=a"(f7a), "=b"(f7b), "=c"(f7c) + : "a"(7), "c"(0) + : "edx"); + } +#endif + { + ZSTD_cpuid_t cpuid; + cpuid.f1c = f1c; + cpuid.f1d = f1d; + cpuid.f7b = f7b; + cpuid.f7c = f7c; + return cpuid; + } +} + +#define X(name, r, bit) \ + MEM_STATIC int ZSTD_cpuid_##name(ZSTD_cpuid_t const cpuid) { \ + return ((cpuid.r) & (1U << bit)) != 0; \ + } + +/* cpuid(1): Processor Info and Feature Bits. */ +#define C(name, bit) X(name, f1c, bit) + C(sse3, 0) + C(pclmuldq, 1) + C(dtes64, 2) + C(monitor, 3) + C(dscpl, 4) + C(vmx, 5) + C(smx, 6) + C(eist, 7) + C(tm2, 8) + C(ssse3, 9) + C(cnxtid, 10) + C(fma, 12) + C(cx16, 13) + C(xtpr, 14) + C(pdcm, 15) + C(pcid, 17) + C(dca, 18) + C(sse41, 19) + C(sse42, 20) + C(x2apic, 21) + C(movbe, 22) + C(popcnt, 23) + C(tscdeadline, 24) + C(aes, 25) + C(xsave, 26) + C(osxsave, 27) + C(avx, 28) + C(f16c, 29) + C(rdrand, 30) +#undef C +#define D(name, bit) X(name, f1d, bit) + D(fpu, 0) + D(vme, 1) + D(de, 2) + D(pse, 3) + D(tsc, 4) + D(msr, 5) + D(pae, 6) + D(mce, 7) + D(cx8, 8) + D(apic, 9) + D(sep, 11) + D(mtrr, 12) + D(pge, 13) + D(mca, 14) + D(cmov, 15) + D(pat, 16) + D(pse36, 17) + D(psn, 18) + D(clfsh, 19) + D(ds, 21) + D(acpi, 22) + D(mmx, 23) + D(fxsr, 24) + D(sse, 25) + D(sse2, 26) + D(ss, 27) + D(htt, 28) + D(tm, 29) + D(pbe, 31) +#undef D + +/* cpuid(7): Extended Features. */ +#define B(name, bit) X(name, f7b, bit) + B(bmi1, 3) + B(hle, 4) + B(avx2, 5) + B(smep, 7) + B(bmi2, 8) + B(erms, 9) + B(invpcid, 10) + B(rtm, 11) + B(mpx, 14) + B(avx512f, 16) + B(avx512dq, 17) + B(rdseed, 18) + B(adx, 19) + B(smap, 20) + B(avx512ifma, 21) + B(pcommit, 22) + B(clflushopt, 23) + B(clwb, 24) + B(avx512pf, 26) + B(avx512er, 27) + B(avx512cd, 28) + B(sha, 29) + B(avx512bw, 30) + B(avx512vl, 31) +#undef B +#define C(name, bit) X(name, f7c, bit) + C(prefetchwt1, 0) + C(avx512vbmi, 1) +#undef C + +#undef X + +#endif /* ZSTD_COMMON_CPU_H */ +/**** ended inlining cpu.h ****/ +/**** skipping file: mem.h ****/ +/**** skipping file: debug.h ****/ +/**** skipping file: error_private.h ****/ +#define ZSTD_STATIC_LINKING_ONLY +/**** start inlining ../zstd.h ****/ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTD_H_235446 +#define ZSTD_H_235446 + + +/* ====== Dependencies ======*/ +#include /* size_t */ + +/**** skipping file: zstd_errors.h ****/ +#if defined(ZSTD_STATIC_LINKING_ONLY) && !defined(ZSTD_H_ZSTD_STATIC_LINKING_ONLY) +#include /* INT_MAX */ +#endif /* ZSTD_STATIC_LINKING_ONLY */ + +#if defined (__cplusplus) +extern "C" { +#endif + +/* ===== ZSTDLIB_API : control library symbols visibility ===== */ +#ifndef ZSTDLIB_VISIBLE + /* Backwards compatibility with old macro name */ +# ifdef ZSTDLIB_VISIBILITY +# define ZSTDLIB_VISIBLE ZSTDLIB_VISIBILITY +# elif defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__MINGW32__) +# define ZSTDLIB_VISIBLE __attribute__ ((visibility ("default"))) +# else +# define ZSTDLIB_VISIBLE +# endif +#endif + +#ifndef ZSTDLIB_HIDDEN +# if defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__MINGW32__) +# define ZSTDLIB_HIDDEN __attribute__ ((visibility ("hidden"))) +# else +# define ZSTDLIB_HIDDEN +# endif +#endif + +#if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1) +# define ZSTDLIB_API __declspec(dllexport) ZSTDLIB_VISIBLE +#elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1) +# define ZSTDLIB_API __declspec(dllimport) ZSTDLIB_VISIBLE /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/ +#else +# define ZSTDLIB_API ZSTDLIB_VISIBLE +#endif + +/* Deprecation warnings : + * Should these warnings be a problem, it is generally possible to disable them, + * typically with -Wno-deprecated-declarations for gcc or _CRT_SECURE_NO_WARNINGS in Visual. + * Otherwise, it's also possible to define ZSTD_DISABLE_DEPRECATE_WARNINGS. + */ +#ifdef ZSTD_DISABLE_DEPRECATE_WARNINGS +# define ZSTD_DEPRECATED(message) /* disable deprecation warnings */ +#else +# if defined (__cplusplus) && (__cplusplus >= 201402) /* C++14 or greater */ +# define ZSTD_DEPRECATED(message) [[deprecated(message)]] +# elif (defined(GNUC) && (GNUC > 4 || (GNUC == 4 && GNUC_MINOR >= 5))) || defined(__clang__) || defined(__IAR_SYSTEMS_ICC__) +# define ZSTD_DEPRECATED(message) __attribute__((deprecated(message))) +# elif defined(__GNUC__) && (__GNUC__ >= 3) +# define ZSTD_DEPRECATED(message) __attribute__((deprecated)) +# elif defined(_MSC_VER) +# define ZSTD_DEPRECATED(message) __declspec(deprecated(message)) +# else +# pragma message("WARNING: You need to implement ZSTD_DEPRECATED for this compiler") +# define ZSTD_DEPRECATED(message) +# endif +#endif /* ZSTD_DISABLE_DEPRECATE_WARNINGS */ + + +/******************************************************************************* + Introduction + + zstd, short for Zstandard, is a fast lossless compression algorithm, targeting + real-time compression scenarios at zlib-level and better compression ratios. + The zstd compression library provides in-memory compression and decompression + functions. + + The library supports regular compression levels from 1 up to ZSTD_maxCLevel(), + which is currently 22. Levels >= 20, labeled `--ultra`, should be used with + caution, as they require more memory. The library also offers negative + compression levels, which extend the range of speed vs. ratio preferences. + The lower the level, the faster the speed (at the cost of compression). + + Compression can be done in: + - a single step (described as Simple API) + - a single step, reusing a context (described as Explicit context) + - unbounded multiple steps (described as Streaming compression) + + The compression ratio achievable on small data can be highly improved using + a dictionary. Dictionary compression can be performed in: + - a single step (described as Simple dictionary API) + - a single step, reusing a dictionary (described as Bulk-processing + dictionary API) + + Advanced experimental functions can be accessed using + `#define ZSTD_STATIC_LINKING_ONLY` before including zstd.h. + + Advanced experimental APIs should never be used with a dynamically-linked + library. They are not "stable"; their definitions or signatures may change in + the future. Only static linking is allowed. +*******************************************************************************/ + +/*------ Version ------*/ +#define ZSTD_VERSION_MAJOR 1 +#define ZSTD_VERSION_MINOR 5 +#define ZSTD_VERSION_RELEASE 7 +#define ZSTD_VERSION_NUMBER (ZSTD_VERSION_MAJOR *100*100 + ZSTD_VERSION_MINOR *100 + ZSTD_VERSION_RELEASE) + +/*! ZSTD_versionNumber() : + * Return runtime library version, the value is (MAJOR*100*100 + MINOR*100 + RELEASE). */ +ZSTDLIB_API unsigned ZSTD_versionNumber(void); + +#define ZSTD_LIB_VERSION ZSTD_VERSION_MAJOR.ZSTD_VERSION_MINOR.ZSTD_VERSION_RELEASE +#define ZSTD_QUOTE(str) #str +#define ZSTD_EXPAND_AND_QUOTE(str) ZSTD_QUOTE(str) +#define ZSTD_VERSION_STRING ZSTD_EXPAND_AND_QUOTE(ZSTD_LIB_VERSION) + +/*! ZSTD_versionString() : + * Return runtime library version, like "1.4.5". Requires v1.3.0+. */ +ZSTDLIB_API const char* ZSTD_versionString(void); + +/* ************************************* + * Default constant + ***************************************/ +#ifndef ZSTD_CLEVEL_DEFAULT +# define ZSTD_CLEVEL_DEFAULT 3 +#endif + +/* ************************************* + * Constants + ***************************************/ + +/* All magic numbers are supposed read/written to/from files/memory using little-endian convention */ +#define ZSTD_MAGICNUMBER 0xFD2FB528 /* valid since v0.8.0 */ +#define ZSTD_MAGIC_DICTIONARY 0xEC30A437 /* valid since v0.7.0 */ +#define ZSTD_MAGIC_SKIPPABLE_START 0x184D2A50 /* all 16 values, from 0x184D2A50 to 0x184D2A5F, signal the beginning of a skippable frame */ +#define ZSTD_MAGIC_SKIPPABLE_MASK 0xFFFFFFF0 + +#define ZSTD_BLOCKSIZELOG_MAX 17 +#define ZSTD_BLOCKSIZE_MAX (1<= ZSTD_compressBound(srcSize)` guarantees that zstd will have + * enough space to successfully compress the data. + * @return : compressed size written into `dst` (<= `dstCapacity), + * or an error code if it fails (which can be tested using ZSTD_isError()). */ +ZSTDLIB_API size_t ZSTD_compress( void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + int compressionLevel); + +/*! ZSTD_decompress() : + * `compressedSize` : must be the _exact_ size of some number of compressed and/or skippable frames. + * Multiple compressed frames can be decompressed at once with this method. + * The result will be the concatenation of all decompressed frames, back to back. + * `dstCapacity` is an upper bound of originalSize to regenerate. + * First frame's decompressed size can be extracted using ZSTD_getFrameContentSize(). + * If maximum upper bound isn't known, prefer using streaming mode to decompress data. + * @return : the number of bytes decompressed into `dst` (<= `dstCapacity`), + * or an errorCode if it fails (which can be tested using ZSTD_isError()). */ +ZSTDLIB_API size_t ZSTD_decompress( void* dst, size_t dstCapacity, + const void* src, size_t compressedSize); + + +/*====== Decompression helper functions ======*/ + +/*! ZSTD_getFrameContentSize() : requires v1.3.0+ + * `src` should point to the start of a ZSTD encoded frame. + * `srcSize` must be at least as large as the frame header. + * hint : any size >= `ZSTD_frameHeaderSize_max` is large enough. + * @return : - decompressed size of `src` frame content, if known + * - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined + * - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small) + * note 1 : a 0 return value means the frame is valid but "empty". + * When invoking this method on a skippable frame, it will return 0. + * note 2 : decompressed size is an optional field, it may not be present (typically in streaming mode). + * When `return==ZSTD_CONTENTSIZE_UNKNOWN`, data to decompress could be any size. + * In which case, it's necessary to use streaming mode to decompress data. + * Optionally, application can rely on some implicit limit, + * as ZSTD_decompress() only needs an upper bound of decompressed size. + * (For example, data could be necessarily cut into blocks <= 16 KB). + * note 3 : decompressed size is always present when compression is completed using single-pass functions, + * such as ZSTD_compress(), ZSTD_compressCCtx() ZSTD_compress_usingDict() or ZSTD_compress_usingCDict(). + * note 4 : decompressed size can be very large (64-bits value), + * potentially larger than what local system can handle as a single memory segment. + * In which case, it's necessary to use streaming mode to decompress data. + * note 5 : If source is untrusted, decompressed size could be wrong or intentionally modified. + * Always ensure return value fits within application's authorized limits. + * Each application can set its own limits. + * note 6 : This function replaces ZSTD_getDecompressedSize() */ +#define ZSTD_CONTENTSIZE_UNKNOWN (0ULL - 1) +#define ZSTD_CONTENTSIZE_ERROR (0ULL - 2) +ZSTDLIB_API unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize); + +/*! ZSTD_getDecompressedSize() (obsolete): + * This function is now obsolete, in favor of ZSTD_getFrameContentSize(). + * Both functions work the same way, but ZSTD_getDecompressedSize() blends + * "empty", "unknown" and "error" results to the same return value (0), + * while ZSTD_getFrameContentSize() gives them separate return values. + * @return : decompressed size of `src` frame content _if known and not empty_, 0 otherwise. */ +ZSTD_DEPRECATED("Replaced by ZSTD_getFrameContentSize") +ZSTDLIB_API unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize); + +/*! ZSTD_findFrameCompressedSize() : Requires v1.4.0+ + * `src` should point to the start of a ZSTD frame or skippable frame. + * `srcSize` must be >= first frame size + * @return : the compressed size of the first frame starting at `src`, + * suitable to pass as `srcSize` to `ZSTD_decompress` or similar, + * or an error code if input is invalid + * Note 1: this method is called _find*() because it's not enough to read the header, + * it may have to scan through the frame's content, to reach its end. + * Note 2: this method also works with Skippable Frames. In which case, + * it returns the size of the complete skippable frame, + * which is always equal to its content size + 8 bytes for headers. */ +ZSTDLIB_API size_t ZSTD_findFrameCompressedSize(const void* src, size_t srcSize); + + +/*====== Compression helper functions ======*/ + +/*! ZSTD_compressBound() : + * maximum compressed size in worst case single-pass scenario. + * When invoking `ZSTD_compress()`, or any other one-pass compression function, + * it's recommended to provide @dstCapacity >= ZSTD_compressBound(srcSize) + * as it eliminates one potential failure scenario, + * aka not enough room in dst buffer to write the compressed frame. + * Note : ZSTD_compressBound() itself can fail, if @srcSize >= ZSTD_MAX_INPUT_SIZE . + * In which case, ZSTD_compressBound() will return an error code + * which can be tested using ZSTD_isError(). + * + * ZSTD_COMPRESSBOUND() : + * same as ZSTD_compressBound(), but as a macro. + * It can be used to produce constants, which can be useful for static allocation, + * for example to size a static array on stack. + * Will produce constant value 0 if srcSize is too large. + */ +#define ZSTD_MAX_INPUT_SIZE ((sizeof(size_t)==8) ? 0xFF00FF00FF00FF00ULL : 0xFF00FF00U) +#define ZSTD_COMPRESSBOUND(srcSize) (((size_t)(srcSize) >= ZSTD_MAX_INPUT_SIZE) ? 0 : (srcSize) + ((srcSize)>>8) + (((srcSize) < (128<<10)) ? (((128<<10) - (srcSize)) >> 11) /* margin, from 64 to 0 */ : 0)) /* this formula ensures that bound(A) + bound(B) <= bound(A+B) as long as A and B >= 128 KB */ +ZSTDLIB_API size_t ZSTD_compressBound(size_t srcSize); /*!< maximum compressed size in worst case single-pass scenario */ + + +/*====== Error helper functions ======*/ +/* ZSTD_isError() : + * Most ZSTD_* functions returning a size_t value can be tested for error, + * using ZSTD_isError(). + * @return 1 if error, 0 otherwise + */ +ZSTDLIB_API unsigned ZSTD_isError(size_t result); /*!< tells if a `size_t` function result is an error code */ +ZSTDLIB_API ZSTD_ErrorCode ZSTD_getErrorCode(size_t functionResult); /* convert a result into an error code, which can be compared to error enum list */ +ZSTDLIB_API const char* ZSTD_getErrorName(size_t result); /*!< provides readable string from a function result */ +ZSTDLIB_API int ZSTD_minCLevel(void); /*!< minimum negative compression level allowed, requires v1.4.0+ */ +ZSTDLIB_API int ZSTD_maxCLevel(void); /*!< maximum compression level available */ +ZSTDLIB_API int ZSTD_defaultCLevel(void); /*!< default compression level, specified by ZSTD_CLEVEL_DEFAULT, requires v1.5.0+ */ + + +/*************************************** +* Explicit context +***************************************/ +/*= Compression context + * When compressing many times, + * it is recommended to allocate a compression context just once, + * and reuse it for each successive compression operation. + * This will make the workload easier for system's memory. + * Note : re-using context is just a speed / resource optimization. + * It doesn't change the compression ratio, which remains identical. + * Note 2: For parallel execution in multi-threaded environments, + * use one different context per thread . + */ +typedef struct ZSTD_CCtx_s ZSTD_CCtx; +ZSTDLIB_API ZSTD_CCtx* ZSTD_createCCtx(void); +ZSTDLIB_API size_t ZSTD_freeCCtx(ZSTD_CCtx* cctx); /* compatible with NULL pointer */ + +/*! ZSTD_compressCCtx() : + * Same as ZSTD_compress(), using an explicit ZSTD_CCtx. + * Important : in order to mirror `ZSTD_compress()` behavior, + * this function compresses at the requested compression level, + * __ignoring any other advanced parameter__ . + * If any advanced parameter was set using the advanced API, + * they will all be reset. Only @compressionLevel remains. + */ +ZSTDLIB_API size_t ZSTD_compressCCtx(ZSTD_CCtx* cctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + int compressionLevel); + +/*= Decompression context + * When decompressing many times, + * it is recommended to allocate a context only once, + * and reuse it for each successive compression operation. + * This will make workload friendlier for system's memory. + * Use one context per thread for parallel execution. */ +typedef struct ZSTD_DCtx_s ZSTD_DCtx; +ZSTDLIB_API ZSTD_DCtx* ZSTD_createDCtx(void); +ZSTDLIB_API size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx); /* accept NULL pointer */ + +/*! ZSTD_decompressDCtx() : + * Same as ZSTD_decompress(), + * requires an allocated ZSTD_DCtx. + * Compatible with sticky parameters (see below). + */ +ZSTDLIB_API size_t ZSTD_decompressDCtx(ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize); + + +/********************************************* +* Advanced compression API (Requires v1.4.0+) +**********************************************/ + +/* API design : + * Parameters are pushed one by one into an existing context, + * using ZSTD_CCtx_set*() functions. + * Pushed parameters are sticky : they are valid for next compressed frame, and any subsequent frame. + * "sticky" parameters are applicable to `ZSTD_compress2()` and `ZSTD_compressStream*()` ! + * __They do not apply to one-shot variants such as ZSTD_compressCCtx()__ . + * + * It's possible to reset all parameters to "default" using ZSTD_CCtx_reset(). + * + * This API supersedes all other "advanced" API entry points in the experimental section. + * In the future, we expect to remove API entry points from experimental which are redundant with this API. + */ + + +/* Compression strategies, listed from fastest to strongest */ +typedef enum { ZSTD_fast=1, + ZSTD_dfast=2, + ZSTD_greedy=3, + ZSTD_lazy=4, + ZSTD_lazy2=5, + ZSTD_btlazy2=6, + ZSTD_btopt=7, + ZSTD_btultra=8, + ZSTD_btultra2=9 + /* note : new strategies _might_ be added in the future. + Only the order (from fast to strong) is guaranteed */ +} ZSTD_strategy; + +typedef enum { + + /* compression parameters + * Note: When compressing with a ZSTD_CDict these parameters are superseded + * by the parameters used to construct the ZSTD_CDict. + * See ZSTD_CCtx_refCDict() for more info (superseded-by-cdict). */ + ZSTD_c_compressionLevel=100, /* Set compression parameters according to pre-defined cLevel table. + * Note that exact compression parameters are dynamically determined, + * depending on both compression level and srcSize (when known). + * Default level is ZSTD_CLEVEL_DEFAULT==3. + * Special: value 0 means default, which is controlled by ZSTD_CLEVEL_DEFAULT. + * Note 1 : it's possible to pass a negative compression level. + * Note 2 : setting a level does not automatically set all other compression parameters + * to default. Setting this will however eventually dynamically impact the compression + * parameters which have not been manually set. The manually set + * ones will 'stick'. */ + /* Advanced compression parameters : + * It's possible to pin down compression parameters to some specific values. + * In which case, these values are no longer dynamically selected by the compressor */ + ZSTD_c_windowLog=101, /* Maximum allowed back-reference distance, expressed as power of 2. + * This will set a memory budget for streaming decompression, + * with larger values requiring more memory + * and typically compressing more. + * Must be clamped between ZSTD_WINDOWLOG_MIN and ZSTD_WINDOWLOG_MAX. + * Special: value 0 means "use default windowLog". + * Note: Using a windowLog greater than ZSTD_WINDOWLOG_LIMIT_DEFAULT + * requires explicitly allowing such size at streaming decompression stage. */ + ZSTD_c_hashLog=102, /* Size of the initial probe table, as a power of 2. + * Resulting memory usage is (1 << (hashLog+2)). + * Must be clamped between ZSTD_HASHLOG_MIN and ZSTD_HASHLOG_MAX. + * Larger tables improve compression ratio of strategies <= dFast, + * and improve speed of strategies > dFast. + * Special: value 0 means "use default hashLog". */ + ZSTD_c_chainLog=103, /* Size of the multi-probe search table, as a power of 2. + * Resulting memory usage is (1 << (chainLog+2)). + * Must be clamped between ZSTD_CHAINLOG_MIN and ZSTD_CHAINLOG_MAX. + * Larger tables result in better and slower compression. + * This parameter is useless for "fast" strategy. + * It's still useful when using "dfast" strategy, + * in which case it defines a secondary probe table. + * Special: value 0 means "use default chainLog". */ + ZSTD_c_searchLog=104, /* Number of search attempts, as a power of 2. + * More attempts result in better and slower compression. + * This parameter is useless for "fast" and "dFast" strategies. + * Special: value 0 means "use default searchLog". */ + ZSTD_c_minMatch=105, /* Minimum size of searched matches. + * Note that Zstandard can still find matches of smaller size, + * it just tweaks its search algorithm to look for this size and larger. + * Larger values increase compression and decompression speed, but decrease ratio. + * Must be clamped between ZSTD_MINMATCH_MIN and ZSTD_MINMATCH_MAX. + * Note that currently, for all strategies < btopt, effective minimum is 4. + * , for all strategies > fast, effective maximum is 6. + * Special: value 0 means "use default minMatchLength". */ + ZSTD_c_targetLength=106, /* Impact of this field depends on strategy. + * For strategies btopt, btultra & btultra2: + * Length of Match considered "good enough" to stop search. + * Larger values make compression stronger, and slower. + * For strategy fast: + * Distance between match sampling. + * Larger values make compression faster, and weaker. + * Special: value 0 means "use default targetLength". */ + ZSTD_c_strategy=107, /* See ZSTD_strategy enum definition. + * The higher the value of selected strategy, the more complex it is, + * resulting in stronger and slower compression. + * Special: value 0 means "use default strategy". */ + + ZSTD_c_targetCBlockSize=130, /* v1.5.6+ + * Attempts to fit compressed block size into approximately targetCBlockSize. + * Bound by ZSTD_TARGETCBLOCKSIZE_MIN and ZSTD_TARGETCBLOCKSIZE_MAX. + * Note that it's not a guarantee, just a convergence target (default:0). + * No target when targetCBlockSize == 0. + * This is helpful in low bandwidth streaming environments to improve end-to-end latency, + * when a client can make use of partial documents (a prominent example being Chrome). + * Note: this parameter is stable since v1.5.6. + * It was present as an experimental parameter in earlier versions, + * but it's not recommended using it with earlier library versions + * due to massive performance regressions. + */ + /* LDM mode parameters */ + ZSTD_c_enableLongDistanceMatching=160, /* Enable long distance matching. + * This parameter is designed to improve compression ratio + * for large inputs, by finding large matches at long distance. + * It increases memory usage and window size. + * Note: enabling this parameter increases default ZSTD_c_windowLog to 128 MB + * except when expressly set to a different value. + * Note: will be enabled by default if ZSTD_c_windowLog >= 128 MB and + * compression strategy >= ZSTD_btopt (== compression level 16+) */ + ZSTD_c_ldmHashLog=161, /* Size of the table for long distance matching, as a power of 2. + * Larger values increase memory usage and compression ratio, + * but decrease compression speed. + * Must be clamped between ZSTD_HASHLOG_MIN and ZSTD_HASHLOG_MAX + * default: windowlog - 7. + * Special: value 0 means "automatically determine hashlog". */ + ZSTD_c_ldmMinMatch=162, /* Minimum match size for long distance matcher. + * Larger/too small values usually decrease compression ratio. + * Must be clamped between ZSTD_LDM_MINMATCH_MIN and ZSTD_LDM_MINMATCH_MAX. + * Special: value 0 means "use default value" (default: 64). */ + ZSTD_c_ldmBucketSizeLog=163, /* Log size of each bucket in the LDM hash table for collision resolution. + * Larger values improve collision resolution but decrease compression speed. + * The maximum value is ZSTD_LDM_BUCKETSIZELOG_MAX. + * Special: value 0 means "use default value" (default: 3). */ + ZSTD_c_ldmHashRateLog=164, /* Frequency of inserting/looking up entries into the LDM hash table. + * Must be clamped between 0 and (ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN). + * Default is MAX(0, (windowLog - ldmHashLog)), optimizing hash table usage. + * Larger values improve compression speed. + * Deviating far from default value will likely result in a compression ratio decrease. + * Special: value 0 means "automatically determine hashRateLog". */ + + /* frame parameters */ + ZSTD_c_contentSizeFlag=200, /* Content size will be written into frame header _whenever known_ (default:1) + * Content size must be known at the beginning of compression. + * This is automatically the case when using ZSTD_compress2(), + * For streaming scenarios, content size must be provided with ZSTD_CCtx_setPledgedSrcSize() */ + ZSTD_c_checksumFlag=201, /* A 32-bits checksum of content is written at end of frame (default:0) */ + ZSTD_c_dictIDFlag=202, /* When applicable, dictionary's ID is written into frame header (default:1) */ + + /* multi-threading parameters */ + /* These parameters are only active if multi-threading is enabled (compiled with build macro ZSTD_MULTITHREAD). + * Otherwise, trying to set any other value than default (0) will be a no-op and return an error. + * In a situation where it's unknown if the linked library supports multi-threading or not, + * setting ZSTD_c_nbWorkers to any value >= 1 and consulting the return value provides a quick way to check this property. + */ + ZSTD_c_nbWorkers=400, /* Select how many threads will be spawned to compress in parallel. + * When nbWorkers >= 1, triggers asynchronous mode when invoking ZSTD_compressStream*() : + * ZSTD_compressStream*() consumes input and flush output if possible, but immediately gives back control to caller, + * while compression is performed in parallel, within worker thread(s). + * (note : a strong exception to this rule is when first invocation of ZSTD_compressStream2() sets ZSTD_e_end : + * in which case, ZSTD_compressStream2() delegates to ZSTD_compress2(), which is always a blocking call). + * More workers improve speed, but also increase memory usage. + * Default value is `0`, aka "single-threaded mode" : no worker is spawned, + * compression is performed inside Caller's thread, and all invocations are blocking */ + ZSTD_c_jobSize=401, /* Size of a compression job. This value is enforced only when nbWorkers >= 1. + * Each compression job is completed in parallel, so this value can indirectly impact the nb of active threads. + * 0 means default, which is dynamically determined based on compression parameters. + * Job size must be a minimum of overlap size, or ZSTDMT_JOBSIZE_MIN (= 512 KB), whichever is largest. + * The minimum size is automatically and transparently enforced. */ + ZSTD_c_overlapLog=402, /* Control the overlap size, as a fraction of window size. + * The overlap size is an amount of data reloaded from previous job at the beginning of a new job. + * It helps preserve compression ratio, while each job is compressed in parallel. + * This value is enforced only when nbWorkers >= 1. + * Larger values increase compression ratio, but decrease speed. + * Possible values range from 0 to 9 : + * - 0 means "default" : value will be determined by the library, depending on strategy + * - 1 means "no overlap" + * - 9 means "full overlap", using a full window size. + * Each intermediate rank increases/decreases load size by a factor 2 : + * 9: full window; 8: w/2; 7: w/4; 6: w/8; 5:w/16; 4: w/32; 3:w/64; 2:w/128; 1:no overlap; 0:default + * default value varies between 6 and 9, depending on strategy */ + + /* note : additional experimental parameters are also available + * within the experimental section of the API. + * At the time of this writing, they include : + * ZSTD_c_rsyncable + * ZSTD_c_format + * ZSTD_c_forceMaxWindow + * ZSTD_c_forceAttachDict + * ZSTD_c_literalCompressionMode + * ZSTD_c_srcSizeHint + * ZSTD_c_enableDedicatedDictSearch + * ZSTD_c_stableInBuffer + * ZSTD_c_stableOutBuffer + * ZSTD_c_blockDelimiters + * ZSTD_c_validateSequences + * ZSTD_c_blockSplitterLevel + * ZSTD_c_splitAfterSequences + * ZSTD_c_useRowMatchFinder + * ZSTD_c_prefetchCDictTables + * ZSTD_c_enableSeqProducerFallback + * ZSTD_c_maxBlockSize + * Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them. + * note : never ever use experimentalParam? names directly; + * also, the enums values themselves are unstable and can still change. + */ + ZSTD_c_experimentalParam1=500, + ZSTD_c_experimentalParam2=10, + ZSTD_c_experimentalParam3=1000, + ZSTD_c_experimentalParam4=1001, + ZSTD_c_experimentalParam5=1002, + /* was ZSTD_c_experimentalParam6=1003; is now ZSTD_c_targetCBlockSize */ + ZSTD_c_experimentalParam7=1004, + ZSTD_c_experimentalParam8=1005, + ZSTD_c_experimentalParam9=1006, + ZSTD_c_experimentalParam10=1007, + ZSTD_c_experimentalParam11=1008, + ZSTD_c_experimentalParam12=1009, + ZSTD_c_experimentalParam13=1010, + ZSTD_c_experimentalParam14=1011, + ZSTD_c_experimentalParam15=1012, + ZSTD_c_experimentalParam16=1013, + ZSTD_c_experimentalParam17=1014, + ZSTD_c_experimentalParam18=1015, + ZSTD_c_experimentalParam19=1016, + ZSTD_c_experimentalParam20=1017 +} ZSTD_cParameter; + +typedef struct { + size_t error; + int lowerBound; + int upperBound; +} ZSTD_bounds; + +/*! ZSTD_cParam_getBounds() : + * All parameters must belong to an interval with lower and upper bounds, + * otherwise they will either trigger an error or be automatically clamped. + * @return : a structure, ZSTD_bounds, which contains + * - an error status field, which must be tested using ZSTD_isError() + * - lower and upper bounds, both inclusive + */ +ZSTDLIB_API ZSTD_bounds ZSTD_cParam_getBounds(ZSTD_cParameter cParam); + +/*! ZSTD_CCtx_setParameter() : + * Set one compression parameter, selected by enum ZSTD_cParameter. + * All parameters have valid bounds. Bounds can be queried using ZSTD_cParam_getBounds(). + * Providing a value beyond bound will either clamp it, or trigger an error (depending on parameter). + * Setting a parameter is generally only possible during frame initialization (before starting compression). + * Exception : when using multi-threading mode (nbWorkers >= 1), + * the following parameters can be updated _during_ compression (within same frame): + * => compressionLevel, hashLog, chainLog, searchLog, minMatch, targetLength and strategy. + * new parameters will be active for next job only (after a flush()). + * @return : an error code (which can be tested using ZSTD_isError()). + */ +ZSTDLIB_API size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int value); + +/*! ZSTD_CCtx_setPledgedSrcSize() : + * Total input data size to be compressed as a single frame. + * Value will be written in frame header, unless if explicitly forbidden using ZSTD_c_contentSizeFlag. + * This value will also be controlled at end of frame, and trigger an error if not respected. + * @result : 0, or an error code (which can be tested with ZSTD_isError()). + * Note 1 : pledgedSrcSize==0 actually means zero, aka an empty frame. + * In order to mean "unknown content size", pass constant ZSTD_CONTENTSIZE_UNKNOWN. + * ZSTD_CONTENTSIZE_UNKNOWN is default value for any new frame. + * Note 2 : pledgedSrcSize is only valid once, for the next frame. + * It's discarded at the end of the frame, and replaced by ZSTD_CONTENTSIZE_UNKNOWN. + * Note 3 : Whenever all input data is provided and consumed in a single round, + * for example with ZSTD_compress2(), + * or invoking immediately ZSTD_compressStream2(,,,ZSTD_e_end), + * this value is automatically overridden by srcSize instead. + */ +ZSTDLIB_API size_t ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx* cctx, unsigned long long pledgedSrcSize); + +typedef enum { + ZSTD_reset_session_only = 1, + ZSTD_reset_parameters = 2, + ZSTD_reset_session_and_parameters = 3 +} ZSTD_ResetDirective; + +/*! ZSTD_CCtx_reset() : + * There are 2 different things that can be reset, independently or jointly : + * - The session : will stop compressing current frame, and make CCtx ready to start a new one. + * Useful after an error, or to interrupt any ongoing compression. + * Any internal data not yet flushed is cancelled. + * Compression parameters and dictionary remain unchanged. + * They will be used to compress next frame. + * Resetting session never fails. + * - The parameters : changes all parameters back to "default". + * This also removes any reference to any dictionary or external sequence producer. + * Parameters can only be changed between 2 sessions (i.e. no compression is currently ongoing) + * otherwise the reset fails, and function returns an error value (which can be tested using ZSTD_isError()) + * - Both : similar to resetting the session, followed by resetting parameters. + */ +ZSTDLIB_API size_t ZSTD_CCtx_reset(ZSTD_CCtx* cctx, ZSTD_ResetDirective reset); + +/*! ZSTD_compress2() : + * Behave the same as ZSTD_compressCCtx(), but compression parameters are set using the advanced API. + * (note that this entry point doesn't even expose a compression level parameter). + * ZSTD_compress2() always starts a new frame. + * Should cctx hold data from a previously unfinished frame, everything about it is forgotten. + * - Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_set*() + * - The function is always blocking, returns when compression is completed. + * NOTE: Providing `dstCapacity >= ZSTD_compressBound(srcSize)` guarantees that zstd will have + * enough space to successfully compress the data, though it is possible it fails for other reasons. + * @return : compressed size written into `dst` (<= `dstCapacity), + * or an error code if it fails (which can be tested using ZSTD_isError()). + */ +ZSTDLIB_API size_t ZSTD_compress2( ZSTD_CCtx* cctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize); + + +/*********************************************** +* Advanced decompression API (Requires v1.4.0+) +************************************************/ + +/* The advanced API pushes parameters one by one into an existing DCtx context. + * Parameters are sticky, and remain valid for all following frames + * using the same DCtx context. + * It's possible to reset parameters to default values using ZSTD_DCtx_reset(). + * Note : This API is compatible with existing ZSTD_decompressDCtx() and ZSTD_decompressStream(). + * Therefore, no new decompression function is necessary. + */ + +typedef enum { + + ZSTD_d_windowLogMax=100, /* Select a size limit (in power of 2) beyond which + * the streaming API will refuse to allocate memory buffer + * in order to protect the host from unreasonable memory requirements. + * This parameter is only useful in streaming mode, since no internal buffer is allocated in single-pass mode. + * By default, a decompression context accepts window sizes <= (1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT). + * Special: value 0 means "use default maximum windowLog". */ + + /* note : additional experimental parameters are also available + * within the experimental section of the API. + * At the time of this writing, they include : + * ZSTD_d_format + * ZSTD_d_stableOutBuffer + * ZSTD_d_forceIgnoreChecksum + * ZSTD_d_refMultipleDDicts + * ZSTD_d_disableHuffmanAssembly + * ZSTD_d_maxBlockSize + * Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them. + * note : never ever use experimentalParam? names directly + */ + ZSTD_d_experimentalParam1=1000, + ZSTD_d_experimentalParam2=1001, + ZSTD_d_experimentalParam3=1002, + ZSTD_d_experimentalParam4=1003, + ZSTD_d_experimentalParam5=1004, + ZSTD_d_experimentalParam6=1005 + +} ZSTD_dParameter; + +/*! ZSTD_dParam_getBounds() : + * All parameters must belong to an interval with lower and upper bounds, + * otherwise they will either trigger an error or be automatically clamped. + * @return : a structure, ZSTD_bounds, which contains + * - an error status field, which must be tested using ZSTD_isError() + * - both lower and upper bounds, inclusive + */ +ZSTDLIB_API ZSTD_bounds ZSTD_dParam_getBounds(ZSTD_dParameter dParam); + +/*! ZSTD_DCtx_setParameter() : + * Set one compression parameter, selected by enum ZSTD_dParameter. + * All parameters have valid bounds. Bounds can be queried using ZSTD_dParam_getBounds(). + * Providing a value beyond bound will either clamp it, or trigger an error (depending on parameter). + * Setting a parameter is only possible during frame initialization (before starting decompression). + * @return : 0, or an error code (which can be tested using ZSTD_isError()). + */ +ZSTDLIB_API size_t ZSTD_DCtx_setParameter(ZSTD_DCtx* dctx, ZSTD_dParameter param, int value); + +/*! ZSTD_DCtx_reset() : + * Return a DCtx to clean state. + * Session and parameters can be reset jointly or separately. + * Parameters can only be reset when no active frame is being decompressed. + * @return : 0, or an error code, which can be tested with ZSTD_isError() + */ +ZSTDLIB_API size_t ZSTD_DCtx_reset(ZSTD_DCtx* dctx, ZSTD_ResetDirective reset); + + +/**************************** +* Streaming +****************************/ + +typedef struct ZSTD_inBuffer_s { + const void* src; /**< start of input buffer */ + size_t size; /**< size of input buffer */ + size_t pos; /**< position where reading stopped. Will be updated. Necessarily 0 <= pos <= size */ +} ZSTD_inBuffer; + +typedef struct ZSTD_outBuffer_s { + void* dst; /**< start of output buffer */ + size_t size; /**< size of output buffer */ + size_t pos; /**< position where writing stopped. Will be updated. Necessarily 0 <= pos <= size */ +} ZSTD_outBuffer; + + + +/*-*********************************************************************** +* Streaming compression - HowTo +* +* A ZSTD_CStream object is required to track streaming operation. +* Use ZSTD_createCStream() and ZSTD_freeCStream() to create/release resources. +* ZSTD_CStream objects can be reused multiple times on consecutive compression operations. +* It is recommended to reuse ZSTD_CStream since it will play nicer with system's memory, by re-using already allocated memory. +* +* For parallel execution, use one separate ZSTD_CStream per thread. +* +* note : since v1.3.0, ZSTD_CStream and ZSTD_CCtx are the same thing. +* +* Parameters are sticky : when starting a new compression on the same context, +* it will reuse the same sticky parameters as previous compression session. +* When in doubt, it's recommended to fully initialize the context before usage. +* Use ZSTD_CCtx_reset() to reset the context and ZSTD_CCtx_setParameter(), +* ZSTD_CCtx_setPledgedSrcSize(), or ZSTD_CCtx_loadDictionary() and friends to +* set more specific parameters, the pledged source size, or load a dictionary. +* +* Use ZSTD_compressStream2() with ZSTD_e_continue as many times as necessary to +* consume input stream. The function will automatically update both `pos` +* fields within `input` and `output`. +* Note that the function may not consume the entire input, for example, because +* the output buffer is already full, in which case `input.pos < input.size`. +* The caller must check if input has been entirely consumed. +* If not, the caller must make some room to receive more compressed data, +* and then present again remaining input data. +* note: ZSTD_e_continue is guaranteed to make some forward progress when called, +* but doesn't guarantee maximal forward progress. This is especially relevant +* when compressing with multiple threads. The call won't block if it can +* consume some input, but if it can't it will wait for some, but not all, +* output to be flushed. +* @return : provides a minimum amount of data remaining to be flushed from internal buffers +* or an error code, which can be tested using ZSTD_isError(). +* +* At any moment, it's possible to flush whatever data might remain stuck within internal buffer, +* using ZSTD_compressStream2() with ZSTD_e_flush. `output->pos` will be updated. +* Note that, if `output->size` is too small, a single invocation with ZSTD_e_flush might not be enough (return code > 0). +* In which case, make some room to receive more compressed data, and call again ZSTD_compressStream2() with ZSTD_e_flush. +* You must continue calling ZSTD_compressStream2() with ZSTD_e_flush until it returns 0, at which point you can change the +* operation. +* note: ZSTD_e_flush will flush as much output as possible, meaning when compressing with multiple threads, it will +* block until the flush is complete or the output buffer is full. +* @return : 0 if internal buffers are entirely flushed, +* >0 if some data still present within internal buffer (the value is minimal estimation of remaining size), +* or an error code, which can be tested using ZSTD_isError(). +* +* Calling ZSTD_compressStream2() with ZSTD_e_end instructs to finish a frame. +* It will perform a flush and write frame epilogue. +* The epilogue is required for decoders to consider a frame completed. +* flush operation is the same, and follows same rules as calling ZSTD_compressStream2() with ZSTD_e_flush. +* You must continue calling ZSTD_compressStream2() with ZSTD_e_end until it returns 0, at which point you are free to +* start a new frame. +* note: ZSTD_e_end will flush as much output as possible, meaning when compressing with multiple threads, it will +* block until the flush is complete or the output buffer is full. +* @return : 0 if frame fully completed and fully flushed, +* >0 if some data still present within internal buffer (the value is minimal estimation of remaining size), +* or an error code, which can be tested using ZSTD_isError(). +* +* *******************************************************************/ + +typedef ZSTD_CCtx ZSTD_CStream; /**< CCtx and CStream are now effectively same object (>= v1.3.0) */ + /* Continue to distinguish them for compatibility with older versions <= v1.2.0 */ +/*===== ZSTD_CStream management functions =====*/ +ZSTDLIB_API ZSTD_CStream* ZSTD_createCStream(void); +ZSTDLIB_API size_t ZSTD_freeCStream(ZSTD_CStream* zcs); /* accept NULL pointer */ + +/*===== Streaming compression functions =====*/ +typedef enum { + ZSTD_e_continue=0, /* collect more data, encoder decides when to output compressed result, for optimal compression ratio */ + ZSTD_e_flush=1, /* flush any data provided so far, + * it creates (at least) one new block, that can be decoded immediately on reception; + * frame will continue: any future data can still reference previously compressed data, improving compression. + * note : multithreaded compression will block to flush as much output as possible. */ + ZSTD_e_end=2 /* flush any remaining data _and_ close current frame. + * note that frame is only closed after compressed data is fully flushed (return value == 0). + * After that point, any additional data starts a new frame. + * note : each frame is independent (does not reference any content from previous frame). + : note : multithreaded compression will block to flush as much output as possible. */ +} ZSTD_EndDirective; + +/*! ZSTD_compressStream2() : Requires v1.4.0+ + * Behaves about the same as ZSTD_compressStream, with additional control on end directive. + * - Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_set*() + * - Compression parameters cannot be changed once compression is started (save a list of exceptions in multi-threading mode) + * - output->pos must be <= dstCapacity, input->pos must be <= srcSize + * - output->pos and input->pos will be updated. They are guaranteed to remain below their respective limit. + * - endOp must be a valid directive + * - When nbWorkers==0 (default), function is blocking : it completes its job before returning to caller. + * - When nbWorkers>=1, function is non-blocking : it copies a portion of input, distributes jobs to internal worker threads, flush to output whatever is available, + * and then immediately returns, just indicating that there is some data remaining to be flushed. + * The function nonetheless guarantees forward progress : it will return only after it reads or write at least 1+ byte. + * - Exception : if the first call requests a ZSTD_e_end directive and provides enough dstCapacity, the function delegates to ZSTD_compress2() which is always blocking. + * - @return provides a minimum amount of data remaining to be flushed from internal buffers + * or an error code, which can be tested using ZSTD_isError(). + * if @return != 0, flush is not fully completed, there is still some data left within internal buffers. + * This is useful for ZSTD_e_flush, since in this case more flushes are necessary to empty all buffers. + * For ZSTD_e_end, @return == 0 when internal buffers are fully flushed and frame is completed. + * - after a ZSTD_e_end directive, if internal buffer is not fully flushed (@return != 0), + * only ZSTD_e_end or ZSTD_e_flush operations are allowed. + * Before starting a new compression job, or changing compression parameters, + * it is required to fully flush internal buffers. + * - note: if an operation ends with an error, it may leave @cctx in an undefined state. + * Therefore, it's UB to invoke ZSTD_compressStream2() of ZSTD_compressStream() on such a state. + * In order to be re-employed after an error, a state must be reset, + * which can be done explicitly (ZSTD_CCtx_reset()), + * or is sometimes implied by methods starting a new compression job (ZSTD_initCStream(), ZSTD_compressCCtx()) + */ +ZSTDLIB_API size_t ZSTD_compressStream2( ZSTD_CCtx* cctx, + ZSTD_outBuffer* output, + ZSTD_inBuffer* input, + ZSTD_EndDirective endOp); + + +/* These buffer sizes are softly recommended. + * They are not required : ZSTD_compressStream*() happily accepts any buffer size, for both input and output. + * Respecting the recommended size just makes it a bit easier for ZSTD_compressStream*(), + * reducing the amount of memory shuffling and buffering, resulting in minor performance savings. + * + * However, note that these recommendations are from the perspective of a C caller program. + * If the streaming interface is invoked from some other language, + * especially managed ones such as Java or Go, through a foreign function interface such as jni or cgo, + * a major performance rule is to reduce crossing such interface to an absolute minimum. + * It's not rare that performance ends being spent more into the interface, rather than compression itself. + * In which cases, prefer using large buffers, as large as practical, + * for both input and output, to reduce the nb of roundtrips. + */ +ZSTDLIB_API size_t ZSTD_CStreamInSize(void); /**< recommended size for input buffer */ +ZSTDLIB_API size_t ZSTD_CStreamOutSize(void); /**< recommended size for output buffer. Guarantee to successfully flush at least one complete compressed block. */ + + +/* ***************************************************************************** + * This following is a legacy streaming API, available since v1.0+ . + * It can be replaced by ZSTD_CCtx_reset() and ZSTD_compressStream2(). + * It is redundant, but remains fully supported. + ******************************************************************************/ + +/*! + * Equivalent to: + * + * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); + * ZSTD_CCtx_refCDict(zcs, NULL); // clear the dictionary (if any) + * ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel); + * + * Note that ZSTD_initCStream() clears any previously set dictionary. Use the new API + * to compress with a dictionary. + */ +ZSTDLIB_API size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel); +/*! + * Alternative for ZSTD_compressStream2(zcs, output, input, ZSTD_e_continue). + * NOTE: The return value is different. ZSTD_compressStream() returns a hint for + * the next read size (if non-zero and not an error). ZSTD_compressStream2() + * returns the minimum nb of bytes left to flush (if non-zero and not an error). + */ +ZSTDLIB_API size_t ZSTD_compressStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output, ZSTD_inBuffer* input); +/*! Equivalent to ZSTD_compressStream2(zcs, output, &emptyInput, ZSTD_e_flush). */ +ZSTDLIB_API size_t ZSTD_flushStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output); +/*! Equivalent to ZSTD_compressStream2(zcs, output, &emptyInput, ZSTD_e_end). */ +ZSTDLIB_API size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output); + + +/*-*************************************************************************** +* Streaming decompression - HowTo +* +* A ZSTD_DStream object is required to track streaming operations. +* Use ZSTD_createDStream() and ZSTD_freeDStream() to create/release resources. +* ZSTD_DStream objects can be re-employed multiple times. +* +* Use ZSTD_initDStream() to start a new decompression operation. +* @return : recommended first input size +* Alternatively, use advanced API to set specific properties. +* +* Use ZSTD_decompressStream() repetitively to consume your input. +* The function will update both `pos` fields. +* If `input.pos < input.size`, some input has not been consumed. +* It's up to the caller to present again remaining data. +* +* The function tries to flush all data decoded immediately, respecting output buffer size. +* If `output.pos < output.size`, decoder has flushed everything it could. +* +* However, when `output.pos == output.size`, it's more difficult to know. +* If @return > 0, the frame is not complete, meaning +* either there is still some data left to flush within internal buffers, +* or there is more input to read to complete the frame (or both). +* In which case, call ZSTD_decompressStream() again to flush whatever remains in the buffer. +* Note : with no additional input provided, amount of data flushed is necessarily <= ZSTD_BLOCKSIZE_MAX. +* @return : 0 when a frame is completely decoded and fully flushed, +* or an error code, which can be tested using ZSTD_isError(), +* or any other value > 0, which means there is still some decoding or flushing to do to complete current frame : +* the return value is a suggested next input size (just a hint for better latency) +* that will never request more than the remaining content of the compressed frame. +* *******************************************************************************/ + +typedef ZSTD_DCtx ZSTD_DStream; /**< DCtx and DStream are now effectively same object (>= v1.3.0) */ + /* For compatibility with versions <= v1.2.0, prefer differentiating them. */ +/*===== ZSTD_DStream management functions =====*/ +ZSTDLIB_API ZSTD_DStream* ZSTD_createDStream(void); +ZSTDLIB_API size_t ZSTD_freeDStream(ZSTD_DStream* zds); /* accept NULL pointer */ + +/*===== Streaming decompression functions =====*/ + +/*! ZSTD_initDStream() : + * Initialize/reset DStream state for new decompression operation. + * Call before new decompression operation using same DStream. + * + * Note : This function is redundant with the advanced API and equivalent to: + * ZSTD_DCtx_reset(zds, ZSTD_reset_session_only); + * ZSTD_DCtx_refDDict(zds, NULL); + */ +ZSTDLIB_API size_t ZSTD_initDStream(ZSTD_DStream* zds); + +/*! ZSTD_decompressStream() : + * Streaming decompression function. + * Call repetitively to consume full input updating it as necessary. + * Function will update both input and output `pos` fields exposing current state via these fields: + * - `input.pos < input.size`, some input remaining and caller should provide remaining input + * on the next call. + * - `output.pos < output.size`, decoder flushed internal output buffer. + * - `output.pos == output.size`, unflushed data potentially present in the internal buffers, + * check ZSTD_decompressStream() @return value, + * if > 0, invoke it again to flush remaining data to output. + * Note : with no additional input, amount of data flushed <= ZSTD_BLOCKSIZE_MAX. + * + * @return : 0 when a frame is completely decoded and fully flushed, + * or an error code, which can be tested using ZSTD_isError(), + * or any other value > 0, which means there is some decoding or flushing to do to complete current frame. + * + * Note: when an operation returns with an error code, the @zds state may be left in undefined state. + * It's UB to invoke `ZSTD_decompressStream()` on such a state. + * In order to re-use such a state, it must be first reset, + * which can be done explicitly (`ZSTD_DCtx_reset()`), + * or is implied for operations starting some new decompression job (`ZSTD_initDStream`, `ZSTD_decompressDCtx()`, `ZSTD_decompress_usingDict()`) + */ +ZSTDLIB_API size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input); + +ZSTDLIB_API size_t ZSTD_DStreamInSize(void); /*!< recommended size for input buffer */ +ZSTDLIB_API size_t ZSTD_DStreamOutSize(void); /*!< recommended size for output buffer. Guarantee to successfully flush at least one complete block in all circumstances. */ + + +/************************** +* Simple dictionary API +***************************/ +/*! ZSTD_compress_usingDict() : + * Compression at an explicit compression level using a Dictionary. + * A dictionary can be any arbitrary data segment (also called a prefix), + * or a buffer with specified information (see zdict.h). + * Note : This function loads the dictionary, resulting in significant startup delay. + * It's intended for a dictionary used only once. + * Note 2 : When `dict == NULL || dictSize < 8` no dictionary is used. */ +ZSTDLIB_API size_t ZSTD_compress_usingDict(ZSTD_CCtx* ctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const void* dict,size_t dictSize, + int compressionLevel); + +/*! ZSTD_decompress_usingDict() : + * Decompression using a known Dictionary. + * Dictionary must be identical to the one used during compression. + * Note : This function loads the dictionary, resulting in significant startup delay. + * It's intended for a dictionary used only once. + * Note : When `dict == NULL || dictSize < 8` no dictionary is used. */ +ZSTDLIB_API size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const void* dict,size_t dictSize); + + +/*********************************** + * Bulk processing dictionary API + **********************************/ +typedef struct ZSTD_CDict_s ZSTD_CDict; + +/*! ZSTD_createCDict() : + * When compressing multiple messages or blocks using the same dictionary, + * it's recommended to digest the dictionary only once, since it's a costly operation. + * ZSTD_createCDict() will create a state from digesting a dictionary. + * The resulting state can be used for future compression operations with very limited startup cost. + * ZSTD_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only. + * @dictBuffer can be released after ZSTD_CDict creation, because its content is copied within CDict. + * Note 1 : Consider experimental function `ZSTD_createCDict_byReference()` if you prefer to not duplicate @dictBuffer content. + * Note 2 : A ZSTD_CDict can be created from an empty @dictBuffer, + * in which case the only thing that it transports is the @compressionLevel. + * This can be useful in a pipeline featuring ZSTD_compress_usingCDict() exclusively, + * expecting a ZSTD_CDict parameter with any data, including those without a known dictionary. */ +ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict(const void* dictBuffer, size_t dictSize, + int compressionLevel); + +/*! ZSTD_freeCDict() : + * Function frees memory allocated by ZSTD_createCDict(). + * If a NULL pointer is passed, no operation is performed. */ +ZSTDLIB_API size_t ZSTD_freeCDict(ZSTD_CDict* CDict); + +/*! ZSTD_compress_usingCDict() : + * Compression using a digested Dictionary. + * Recommended when same dictionary is used multiple times. + * Note : compression level is _decided at dictionary creation time_, + * and frame parameters are hardcoded (dictID=yes, contentSize=yes, checksum=no) */ +ZSTDLIB_API size_t ZSTD_compress_usingCDict(ZSTD_CCtx* cctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const ZSTD_CDict* cdict); + + +typedef struct ZSTD_DDict_s ZSTD_DDict; + +/*! ZSTD_createDDict() : + * Create a digested dictionary, ready to start decompression operation without startup delay. + * dictBuffer can be released after DDict creation, as its content is copied inside DDict. */ +ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict(const void* dictBuffer, size_t dictSize); + +/*! ZSTD_freeDDict() : + * Function frees memory allocated with ZSTD_createDDict() + * If a NULL pointer is passed, no operation is performed. */ +ZSTDLIB_API size_t ZSTD_freeDDict(ZSTD_DDict* ddict); + +/*! ZSTD_decompress_usingDDict() : + * Decompression using a digested Dictionary. + * Recommended when same dictionary is used multiple times. */ +ZSTDLIB_API size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const ZSTD_DDict* ddict); + + +/******************************** + * Dictionary helper functions + *******************************/ + +/*! ZSTD_getDictID_fromDict() : Requires v1.4.0+ + * Provides the dictID stored within dictionary. + * if @return == 0, the dictionary is not conformant with Zstandard specification. + * It can still be loaded, but as a content-only dictionary. */ +ZSTDLIB_API unsigned ZSTD_getDictID_fromDict(const void* dict, size_t dictSize); + +/*! ZSTD_getDictID_fromCDict() : Requires v1.5.0+ + * Provides the dictID of the dictionary loaded into `cdict`. + * If @return == 0, the dictionary is not conformant to Zstandard specification, or empty. + * Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */ +ZSTDLIB_API unsigned ZSTD_getDictID_fromCDict(const ZSTD_CDict* cdict); + +/*! ZSTD_getDictID_fromDDict() : Requires v1.4.0+ + * Provides the dictID of the dictionary loaded into `ddict`. + * If @return == 0, the dictionary is not conformant to Zstandard specification, or empty. + * Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */ +ZSTDLIB_API unsigned ZSTD_getDictID_fromDDict(const ZSTD_DDict* ddict); + +/*! ZSTD_getDictID_fromFrame() : Requires v1.4.0+ + * Provides the dictID required to decompressed the frame stored within `src`. + * If @return == 0, the dictID could not be decoded. + * This could for one of the following reasons : + * - The frame does not require a dictionary to be decoded (most common case). + * - The frame was built with dictID intentionally removed. Whatever dictionary is necessary is a hidden piece of information. + * Note : this use case also happens when using a non-conformant dictionary. + * - `srcSize` is too small, and as a result, the frame header could not be decoded (only possible if `srcSize < ZSTD_FRAMEHEADERSIZE_MAX`). + * - This is not a Zstandard frame. + * When identifying the exact failure cause, it's possible to use ZSTD_getFrameHeader(), which will provide a more precise error code. */ +ZSTDLIB_API unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize); + + +/******************************************************************************* + * Advanced dictionary and prefix API (Requires v1.4.0+) + * + * This API allows dictionaries to be used with ZSTD_compress2(), + * ZSTD_compressStream2(), and ZSTD_decompressDCtx(). + * Dictionaries are sticky, they remain valid when same context is reused, + * they only reset when the context is reset + * with ZSTD_reset_parameters or ZSTD_reset_session_and_parameters. + * In contrast, Prefixes are single-use. + ******************************************************************************/ + + +/*! ZSTD_CCtx_loadDictionary() : Requires v1.4.0+ + * Create an internal CDict from `dict` buffer. + * Decompression will have to use same dictionary. + * @result : 0, or an error code (which can be tested with ZSTD_isError()). + * Special: Loading a NULL (or 0-size) dictionary invalidates previous dictionary, + * meaning "return to no-dictionary mode". + * Note 1 : Dictionary is sticky, it will be used for all future compressed frames, + * until parameters are reset, a new dictionary is loaded, or the dictionary + * is explicitly invalidated by loading a NULL dictionary. + * Note 2 : Loading a dictionary involves building tables. + * It's also a CPU consuming operation, with non-negligible impact on latency. + * Tables are dependent on compression parameters, and for this reason, + * compression parameters can no longer be changed after loading a dictionary. + * Note 3 :`dict` content will be copied internally. + * Use experimental ZSTD_CCtx_loadDictionary_byReference() to reference content instead. + * In such a case, dictionary buffer must outlive its users. + * Note 4 : Use ZSTD_CCtx_loadDictionary_advanced() + * to precisely select how dictionary content must be interpreted. + * Note 5 : This method does not benefit from LDM (long distance mode). + * If you want to employ LDM on some large dictionary content, + * prefer employing ZSTD_CCtx_refPrefix() described below. + */ +ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary(ZSTD_CCtx* cctx, const void* dict, size_t dictSize); + +/*! ZSTD_CCtx_refCDict() : Requires v1.4.0+ + * Reference a prepared dictionary, to be used for all future compressed frames. + * Note that compression parameters are enforced from within CDict, + * and supersede any compression parameter previously set within CCtx. + * The parameters ignored are labelled as "superseded-by-cdict" in the ZSTD_cParameter enum docs. + * The ignored parameters will be used again if the CCtx is returned to no-dictionary mode. + * The dictionary will remain valid for future compressed frames using same CCtx. + * @result : 0, or an error code (which can be tested with ZSTD_isError()). + * Special : Referencing a NULL CDict means "return to no-dictionary mode". + * Note 1 : Currently, only one dictionary can be managed. + * Referencing a new dictionary effectively "discards" any previous one. + * Note 2 : CDict is just referenced, its lifetime must outlive its usage within CCtx. */ +ZSTDLIB_API size_t ZSTD_CCtx_refCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict); + +/*! ZSTD_CCtx_refPrefix() : Requires v1.4.0+ + * Reference a prefix (single-usage dictionary) for next compressed frame. + * A prefix is **only used once**. Tables are discarded at end of frame (ZSTD_e_end). + * Decompression will need same prefix to properly regenerate data. + * Compressing with a prefix is similar in outcome as performing a diff and compressing it, + * but performs much faster, especially during decompression (compression speed is tunable with compression level). + * This method is compatible with LDM (long distance mode). + * @result : 0, or an error code (which can be tested with ZSTD_isError()). + * Special: Adding any prefix (including NULL) invalidates any previous prefix or dictionary + * Note 1 : Prefix buffer is referenced. It **must** outlive compression. + * Its content must remain unmodified during compression. + * Note 2 : If the intention is to diff some large src data blob with some prior version of itself, + * ensure that the window size is large enough to contain the entire source. + * See ZSTD_c_windowLog. + * Note 3 : Referencing a prefix involves building tables, which are dependent on compression parameters. + * It's a CPU consuming operation, with non-negligible impact on latency. + * If there is a need to use the same prefix multiple times, consider loadDictionary instead. + * Note 4 : By default, the prefix is interpreted as raw content (ZSTD_dct_rawContent). + * Use experimental ZSTD_CCtx_refPrefix_advanced() to alter dictionary interpretation. */ +ZSTDLIB_API size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx, + const void* prefix, size_t prefixSize); + +/*! ZSTD_DCtx_loadDictionary() : Requires v1.4.0+ + * Create an internal DDict from dict buffer, to be used to decompress all future frames. + * The dictionary remains valid for all future frames, until explicitly invalidated, or + * a new dictionary is loaded. + * @result : 0, or an error code (which can be tested with ZSTD_isError()). + * Special : Adding a NULL (or 0-size) dictionary invalidates any previous dictionary, + * meaning "return to no-dictionary mode". + * Note 1 : Loading a dictionary involves building tables, + * which has a non-negligible impact on CPU usage and latency. + * It's recommended to "load once, use many times", to amortize the cost + * Note 2 :`dict` content will be copied internally, so `dict` can be released after loading. + * Use ZSTD_DCtx_loadDictionary_byReference() to reference dictionary content instead. + * Note 3 : Use ZSTD_DCtx_loadDictionary_advanced() to take control of + * how dictionary content is loaded and interpreted. + */ +ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize); + +/*! ZSTD_DCtx_refDDict() : Requires v1.4.0+ + * Reference a prepared dictionary, to be used to decompress next frames. + * The dictionary remains active for decompression of future frames using same DCtx. + * + * If called with ZSTD_d_refMultipleDDicts enabled, repeated calls of this function + * will store the DDict references in a table, and the DDict used for decompression + * will be determined at decompression time, as per the dict ID in the frame. + * The memory for the table is allocated on the first call to refDDict, and can be + * freed with ZSTD_freeDCtx(). + * + * If called with ZSTD_d_refMultipleDDicts disabled (the default), only one dictionary + * will be managed, and referencing a dictionary effectively "discards" any previous one. + * + * @result : 0, or an error code (which can be tested with ZSTD_isError()). + * Special: referencing a NULL DDict means "return to no-dictionary mode". + * Note 2 : DDict is just referenced, its lifetime must outlive its usage from DCtx. + */ +ZSTDLIB_API size_t ZSTD_DCtx_refDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict); + +/*! ZSTD_DCtx_refPrefix() : Requires v1.4.0+ + * Reference a prefix (single-usage dictionary) to decompress next frame. + * This is the reverse operation of ZSTD_CCtx_refPrefix(), + * and must use the same prefix as the one used during compression. + * Prefix is **only used once**. Reference is discarded at end of frame. + * End of frame is reached when ZSTD_decompressStream() returns 0. + * @result : 0, or an error code (which can be tested with ZSTD_isError()). + * Note 1 : Adding any prefix (including NULL) invalidates any previously set prefix or dictionary + * Note 2 : Prefix buffer is referenced. It **must** outlive decompression. + * Prefix buffer must remain unmodified up to the end of frame, + * reached when ZSTD_decompressStream() returns 0. + * Note 3 : By default, the prefix is treated as raw content (ZSTD_dct_rawContent). + * Use ZSTD_CCtx_refPrefix_advanced() to alter dictMode (Experimental section) + * Note 4 : Referencing a raw content prefix has almost no cpu nor memory cost. + * A full dictionary is more costly, as it requires building tables. + */ +ZSTDLIB_API size_t ZSTD_DCtx_refPrefix(ZSTD_DCtx* dctx, + const void* prefix, size_t prefixSize); + +/* === Memory management === */ + +/*! ZSTD_sizeof_*() : Requires v1.4.0+ + * These functions give the _current_ memory usage of selected object. + * Note that object memory usage can evolve (increase or decrease) over time. */ +ZSTDLIB_API size_t ZSTD_sizeof_CCtx(const ZSTD_CCtx* cctx); +ZSTDLIB_API size_t ZSTD_sizeof_DCtx(const ZSTD_DCtx* dctx); +ZSTDLIB_API size_t ZSTD_sizeof_CStream(const ZSTD_CStream* zcs); +ZSTDLIB_API size_t ZSTD_sizeof_DStream(const ZSTD_DStream* zds); +ZSTDLIB_API size_t ZSTD_sizeof_CDict(const ZSTD_CDict* cdict); +ZSTDLIB_API size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict); + +#if defined (__cplusplus) +} +#endif + +#endif /* ZSTD_H_235446 */ + + +/* ************************************************************************************** + * ADVANCED AND EXPERIMENTAL FUNCTIONS + **************************************************************************************** + * The definitions in the following section are considered experimental. + * They are provided for advanced scenarios. + * They should never be used with a dynamic library, as prototypes may change in the future. + * Use them only in association with static linking. + * ***************************************************************************************/ + +#if defined(ZSTD_STATIC_LINKING_ONLY) && !defined(ZSTD_H_ZSTD_STATIC_LINKING_ONLY) +#define ZSTD_H_ZSTD_STATIC_LINKING_ONLY + +#if defined (__cplusplus) +extern "C" { +#endif + +/* This can be overridden externally to hide static symbols. */ +#ifndef ZSTDLIB_STATIC_API +# if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1) +# define ZSTDLIB_STATIC_API __declspec(dllexport) ZSTDLIB_VISIBLE +# elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1) +# define ZSTDLIB_STATIC_API __declspec(dllimport) ZSTDLIB_VISIBLE +# else +# define ZSTDLIB_STATIC_API ZSTDLIB_VISIBLE +# endif +#endif + +/**************************************************************************************** + * experimental API (static linking only) + **************************************************************************************** + * The following symbols and constants + * are not planned to join "stable API" status in the near future. + * They can still change in future versions. + * Some of them are planned to remain in the static_only section indefinitely. + * Some of them might be removed in the future (especially when redundant with existing stable functions) + * ***************************************************************************************/ + +#define ZSTD_FRAMEHEADERSIZE_PREFIX(format) ((format) == ZSTD_f_zstd1 ? 5 : 1) /* minimum input size required to query frame header size */ +#define ZSTD_FRAMEHEADERSIZE_MIN(format) ((format) == ZSTD_f_zstd1 ? 6 : 2) +#define ZSTD_FRAMEHEADERSIZE_MAX 18 /* can be useful for static allocation */ +#define ZSTD_SKIPPABLEHEADERSIZE 8 + +/* compression parameter bounds */ +#define ZSTD_WINDOWLOG_MAX_32 30 +#define ZSTD_WINDOWLOG_MAX_64 31 +#define ZSTD_WINDOWLOG_MAX ((int)(sizeof(size_t) == 4 ? ZSTD_WINDOWLOG_MAX_32 : ZSTD_WINDOWLOG_MAX_64)) +#define ZSTD_WINDOWLOG_MIN 10 +#define ZSTD_HASHLOG_MAX ((ZSTD_WINDOWLOG_MAX < 30) ? ZSTD_WINDOWLOG_MAX : 30) +#define ZSTD_HASHLOG_MIN 6 +#define ZSTD_CHAINLOG_MAX_32 29 +#define ZSTD_CHAINLOG_MAX_64 30 +#define ZSTD_CHAINLOG_MAX ((int)(sizeof(size_t) == 4 ? ZSTD_CHAINLOG_MAX_32 : ZSTD_CHAINLOG_MAX_64)) +#define ZSTD_CHAINLOG_MIN ZSTD_HASHLOG_MIN +#define ZSTD_SEARCHLOG_MAX (ZSTD_WINDOWLOG_MAX-1) +#define ZSTD_SEARCHLOG_MIN 1 +#define ZSTD_MINMATCH_MAX 7 /* only for ZSTD_fast, other strategies are limited to 6 */ +#define ZSTD_MINMATCH_MIN 3 /* only for ZSTD_btopt+, faster strategies are limited to 4 */ +#define ZSTD_TARGETLENGTH_MAX ZSTD_BLOCKSIZE_MAX +#define ZSTD_TARGETLENGTH_MIN 0 /* note : comparing this constant to an unsigned results in a tautological test */ +#define ZSTD_STRATEGY_MIN ZSTD_fast +#define ZSTD_STRATEGY_MAX ZSTD_btultra2 +#define ZSTD_BLOCKSIZE_MAX_MIN (1 << 10) /* The minimum valid max blocksize. Maximum blocksizes smaller than this make compressBound() inaccurate. */ + + +#define ZSTD_OVERLAPLOG_MIN 0 +#define ZSTD_OVERLAPLOG_MAX 9 + +#define ZSTD_WINDOWLOG_LIMIT_DEFAULT 27 /* by default, the streaming decoder will refuse any frame + * requiring larger than (1< 0: + * If litLength != 0: + * rep == 1 --> offset == repeat_offset_1 + * rep == 2 --> offset == repeat_offset_2 + * rep == 3 --> offset == repeat_offset_3 + * If litLength == 0: + * rep == 1 --> offset == repeat_offset_2 + * rep == 2 --> offset == repeat_offset_3 + * rep == 3 --> offset == repeat_offset_1 - 1 + * + * Note: This field is optional. ZSTD_generateSequences() will calculate the value of + * 'rep', but repeat offsets do not necessarily need to be calculated from an external + * sequence provider perspective. For example, ZSTD_compressSequences() does not + * use this 'rep' field at all (as of now). + */ +} ZSTD_Sequence; + +typedef struct { + unsigned windowLog; /**< largest match distance : larger == more compression, more memory needed during decompression */ + unsigned chainLog; /**< fully searched segment : larger == more compression, slower, more memory (useless for fast) */ + unsigned hashLog; /**< dispatch table : larger == faster, more memory */ + unsigned searchLog; /**< nb of searches : larger == more compression, slower */ + unsigned minMatch; /**< match length searched : larger == faster decompression, sometimes less compression */ + unsigned targetLength; /**< acceptable match size for optimal parser (only) : larger == more compression, slower */ + ZSTD_strategy strategy; /**< see ZSTD_strategy definition above */ +} ZSTD_compressionParameters; + +typedef struct { + int contentSizeFlag; /**< 1: content size will be in frame header (when known) */ + int checksumFlag; /**< 1: generate a 32-bits checksum using XXH64 algorithm at end of frame, for error detection */ + int noDictIDFlag; /**< 1: no dictID will be saved into frame header (dictID is only useful for dictionary compression) */ +} ZSTD_frameParameters; + +typedef struct { + ZSTD_compressionParameters cParams; + ZSTD_frameParameters fParams; +} ZSTD_parameters; + +typedef enum { + ZSTD_dct_auto = 0, /* dictionary is "full" when starting with ZSTD_MAGIC_DICTIONARY, otherwise it is "rawContent" */ + ZSTD_dct_rawContent = 1, /* ensures dictionary is always loaded as rawContent, even if it starts with ZSTD_MAGIC_DICTIONARY */ + ZSTD_dct_fullDict = 2 /* refuses to load a dictionary if it does not respect Zstandard's specification, starting with ZSTD_MAGIC_DICTIONARY */ +} ZSTD_dictContentType_e; + +typedef enum { + ZSTD_dlm_byCopy = 0, /**< Copy dictionary content internally */ + ZSTD_dlm_byRef = 1 /**< Reference dictionary content -- the dictionary buffer must outlive its users. */ +} ZSTD_dictLoadMethod_e; + +typedef enum { + ZSTD_f_zstd1 = 0, /* zstd frame format, specified in zstd_compression_format.md (default) */ + ZSTD_f_zstd1_magicless = 1 /* Variant of zstd frame format, without initial 4-bytes magic number. + * Useful to save 4 bytes per generated frame. + * Decoder cannot recognise automatically this format, requiring this instruction. */ +} ZSTD_format_e; + +typedef enum { + /* Note: this enum controls ZSTD_d_forceIgnoreChecksum */ + ZSTD_d_validateChecksum = 0, + ZSTD_d_ignoreChecksum = 1 +} ZSTD_forceIgnoreChecksum_e; + +typedef enum { + /* Note: this enum controls ZSTD_d_refMultipleDDicts */ + ZSTD_rmd_refSingleDDict = 0, + ZSTD_rmd_refMultipleDDicts = 1 +} ZSTD_refMultipleDDicts_e; + +typedef enum { + /* Note: this enum and the behavior it controls are effectively internal + * implementation details of the compressor. They are expected to continue + * to evolve and should be considered only in the context of extremely + * advanced performance tuning. + * + * Zstd currently supports the use of a CDict in three ways: + * + * - The contents of the CDict can be copied into the working context. This + * means that the compression can search both the dictionary and input + * while operating on a single set of internal tables. This makes + * the compression faster per-byte of input. However, the initial copy of + * the CDict's tables incurs a fixed cost at the beginning of the + * compression. For small compressions (< 8 KB), that copy can dominate + * the cost of the compression. + * + * - The CDict's tables can be used in-place. In this model, compression is + * slower per input byte, because the compressor has to search two sets of + * tables. However, this model incurs no start-up cost (as long as the + * working context's tables can be reused). For small inputs, this can be + * faster than copying the CDict's tables. + * + * - The CDict's tables are not used at all, and instead we use the working + * context alone to reload the dictionary and use params based on the source + * size. See ZSTD_compress_insertDictionary() and ZSTD_compress_usingDict(). + * This method is effective when the dictionary sizes are very small relative + * to the input size, and the input size is fairly large to begin with. + * + * Zstd has a simple internal heuristic that selects which strategy to use + * at the beginning of a compression. However, if experimentation shows that + * Zstd is making poor choices, it is possible to override that choice with + * this enum. + */ + ZSTD_dictDefaultAttach = 0, /* Use the default heuristic. */ + ZSTD_dictForceAttach = 1, /* Never copy the dictionary. */ + ZSTD_dictForceCopy = 2, /* Always copy the dictionary. */ + ZSTD_dictForceLoad = 3 /* Always reload the dictionary */ +} ZSTD_dictAttachPref_e; + +typedef enum { + ZSTD_lcm_auto = 0, /**< Automatically determine the compression mode based on the compression level. + * Negative compression levels will be uncompressed, and positive compression + * levels will be compressed. */ + ZSTD_lcm_huffman = 1, /**< Always attempt Huffman compression. Uncompressed literals will still be + * emitted if Huffman compression is not profitable. */ + ZSTD_lcm_uncompressed = 2 /**< Always emit uncompressed literals. */ +} ZSTD_literalCompressionMode_e; + +typedef enum { + /* Note: This enum controls features which are conditionally beneficial. + * Zstd can take a decision on whether or not to enable the feature (ZSTD_ps_auto), + * but setting the switch to ZSTD_ps_enable or ZSTD_ps_disable force enable/disable the feature. + */ + ZSTD_ps_auto = 0, /* Let the library automatically determine whether the feature shall be enabled */ + ZSTD_ps_enable = 1, /* Force-enable the feature */ + ZSTD_ps_disable = 2 /* Do not use the feature */ +} ZSTD_ParamSwitch_e; +#define ZSTD_paramSwitch_e ZSTD_ParamSwitch_e /* old name */ + +/*************************************** +* Frame header and size functions +***************************************/ + +/*! ZSTD_findDecompressedSize() : + * `src` should point to the start of a series of ZSTD encoded and/or skippable frames + * `srcSize` must be the _exact_ size of this series + * (i.e. there should be a frame boundary at `src + srcSize`) + * @return : - decompressed size of all data in all successive frames + * - if the decompressed size cannot be determined: ZSTD_CONTENTSIZE_UNKNOWN + * - if an error occurred: ZSTD_CONTENTSIZE_ERROR + * + * note 1 : decompressed size is an optional field, that may not be present, especially in streaming mode. + * When `return==ZSTD_CONTENTSIZE_UNKNOWN`, data to decompress could be any size. + * In which case, it's necessary to use streaming mode to decompress data. + * note 2 : decompressed size is always present when compression is done with ZSTD_compress() + * note 3 : decompressed size can be very large (64-bits value), + * potentially larger than what local system can handle as a single memory segment. + * In which case, it's necessary to use streaming mode to decompress data. + * note 4 : If source is untrusted, decompressed size could be wrong or intentionally modified. + * Always ensure result fits within application's authorized limits. + * Each application can set its own limits. + * note 5 : ZSTD_findDecompressedSize handles multiple frames, and so it must traverse the input to + * read each contained frame header. This is fast as most of the data is skipped, + * however it does mean that all frame data must be present and valid. */ +ZSTDLIB_STATIC_API unsigned long long ZSTD_findDecompressedSize(const void* src, size_t srcSize); + +/*! ZSTD_decompressBound() : + * `src` should point to the start of a series of ZSTD encoded and/or skippable frames + * `srcSize` must be the _exact_ size of this series + * (i.e. there should be a frame boundary at `src + srcSize`) + * @return : - upper-bound for the decompressed size of all data in all successive frames + * - if an error occurred: ZSTD_CONTENTSIZE_ERROR + * + * note 1 : an error can occur if `src` contains an invalid or incorrectly formatted frame. + * note 2 : the upper-bound is exact when the decompressed size field is available in every ZSTD encoded frame of `src`. + * in this case, `ZSTD_findDecompressedSize` and `ZSTD_decompressBound` return the same value. + * note 3 : when the decompressed size field isn't available, the upper-bound for that frame is calculated by: + * upper-bound = # blocks * min(128 KB, Window_Size) + */ +ZSTDLIB_STATIC_API unsigned long long ZSTD_decompressBound(const void* src, size_t srcSize); + +/*! ZSTD_frameHeaderSize() : + * srcSize must be large enough, aka >= ZSTD_FRAMEHEADERSIZE_PREFIX. + * @return : size of the Frame Header, + * or an error code (if srcSize is too small) */ +ZSTDLIB_STATIC_API size_t ZSTD_frameHeaderSize(const void* src, size_t srcSize); + +typedef enum { ZSTD_frame, ZSTD_skippableFrame } ZSTD_FrameType_e; +#define ZSTD_frameType_e ZSTD_FrameType_e /* old name */ +typedef struct { + unsigned long long frameContentSize; /* if == ZSTD_CONTENTSIZE_UNKNOWN, it means this field is not available. 0 means "empty" */ + unsigned long long windowSize; /* can be very large, up to <= frameContentSize */ + unsigned blockSizeMax; + ZSTD_FrameType_e frameType; /* if == ZSTD_skippableFrame, frameContentSize is the size of skippable content */ + unsigned headerSize; + unsigned dictID; /* for ZSTD_skippableFrame, contains the skippable magic variant [0-15] */ + unsigned checksumFlag; + unsigned _reserved1; + unsigned _reserved2; +} ZSTD_FrameHeader; +#define ZSTD_frameHeader ZSTD_FrameHeader /* old name */ + +/*! ZSTD_getFrameHeader() : + * decode Frame Header into `zfhPtr`, or requires larger `srcSize`. + * @return : 0 => header is complete, `zfhPtr` is correctly filled, + * >0 => `srcSize` is too small, @return value is the wanted `srcSize` amount, `zfhPtr` is not filled, + * or an error code, which can be tested using ZSTD_isError() */ +ZSTDLIB_STATIC_API size_t ZSTD_getFrameHeader(ZSTD_FrameHeader* zfhPtr, const void* src, size_t srcSize); +/*! ZSTD_getFrameHeader_advanced() : + * same as ZSTD_getFrameHeader(), + * with added capability to select a format (like ZSTD_f_zstd1_magicless) */ +ZSTDLIB_STATIC_API size_t ZSTD_getFrameHeader_advanced(ZSTD_FrameHeader* zfhPtr, const void* src, size_t srcSize, ZSTD_format_e format); + +/*! ZSTD_decompressionMargin() : + * Zstd supports in-place decompression, where the input and output buffers overlap. + * In this case, the output buffer must be at least (Margin + Output_Size) bytes large, + * and the input buffer must be at the end of the output buffer. + * + * _______________________ Output Buffer ________________________ + * | | + * | ____ Input Buffer ____| + * | | | + * v v v + * |---------------------------------------|-----------|----------| + * ^ ^ ^ + * |___________________ Output_Size ___________________|_ Margin _| + * + * NOTE: See also ZSTD_DECOMPRESSION_MARGIN(). + * NOTE: This applies only to single-pass decompression through ZSTD_decompress() or + * ZSTD_decompressDCtx(). + * NOTE: This function supports multi-frame input. + * + * @param src The compressed frame(s) + * @param srcSize The size of the compressed frame(s) + * @returns The decompression margin or an error that can be checked with ZSTD_isError(). + */ +ZSTDLIB_STATIC_API size_t ZSTD_decompressionMargin(const void* src, size_t srcSize); + +/*! ZSTD_DECOMPRESS_MARGIN() : + * Similar to ZSTD_decompressionMargin(), but instead of computing the margin from + * the compressed frame, compute it from the original size and the blockSizeLog. + * See ZSTD_decompressionMargin() for details. + * + * WARNING: This macro does not support multi-frame input, the input must be a single + * zstd frame. If you need that support use the function, or implement it yourself. + * + * @param originalSize The original uncompressed size of the data. + * @param blockSize The block size == MIN(windowSize, ZSTD_BLOCKSIZE_MAX). + * Unless you explicitly set the windowLog smaller than + * ZSTD_BLOCKSIZELOG_MAX you can just use ZSTD_BLOCKSIZE_MAX. + */ +#define ZSTD_DECOMPRESSION_MARGIN(originalSize, blockSize) ((size_t)( \ + ZSTD_FRAMEHEADERSIZE_MAX /* Frame header */ + \ + 4 /* checksum */ + \ + ((originalSize) == 0 ? 0 : 3 * (((originalSize) + (blockSize) - 1) / blockSize)) /* 3 bytes per block */ + \ + (blockSize) /* One block of margin */ \ + )) + +typedef enum { + ZSTD_sf_noBlockDelimiters = 0, /* ZSTD_Sequence[] has no block delimiters, just sequences */ + ZSTD_sf_explicitBlockDelimiters = 1 /* ZSTD_Sequence[] contains explicit block delimiters */ +} ZSTD_SequenceFormat_e; +#define ZSTD_sequenceFormat_e ZSTD_SequenceFormat_e /* old name */ + +/*! ZSTD_sequenceBound() : + * `srcSize` : size of the input buffer + * @return : upper-bound for the number of sequences that can be generated + * from a buffer of srcSize bytes + * + * note : returns number of sequences - to get bytes, multiply by sizeof(ZSTD_Sequence). + */ +ZSTDLIB_STATIC_API size_t ZSTD_sequenceBound(size_t srcSize); + +/*! ZSTD_generateSequences() : + * WARNING: This function is meant for debugging and informational purposes ONLY! + * Its implementation is flawed, and it will be deleted in a future version. + * It is not guaranteed to succeed, as there are several cases where it will give + * up and fail. You should NOT use this function in production code. + * + * This function is deprecated, and will be removed in a future version. + * + * Generate sequences using ZSTD_compress2(), given a source buffer. + * + * @param zc The compression context to be used for ZSTD_compress2(). Set any + * compression parameters you need on this context. + * @param outSeqs The output sequences buffer of size @p outSeqsSize + * @param outSeqsCapacity The size of the output sequences buffer. + * ZSTD_sequenceBound(srcSize) is an upper bound on the number + * of sequences that can be generated. + * @param src The source buffer to generate sequences from of size @p srcSize. + * @param srcSize The size of the source buffer. + * + * Each block will end with a dummy sequence + * with offset == 0, matchLength == 0, and litLength == length of last literals. + * litLength may be == 0, and if so, then the sequence of (of: 0 ml: 0 ll: 0) + * simply acts as a block delimiter. + * + * @returns The number of sequences generated, necessarily less than + * ZSTD_sequenceBound(srcSize), or an error code that can be checked + * with ZSTD_isError(). + */ +ZSTD_DEPRECATED("For debugging only, will be replaced by ZSTD_extractSequences()") +ZSTDLIB_STATIC_API size_t +ZSTD_generateSequences(ZSTD_CCtx* zc, + ZSTD_Sequence* outSeqs, size_t outSeqsCapacity, + const void* src, size_t srcSize); + +/*! ZSTD_mergeBlockDelimiters() : + * Given an array of ZSTD_Sequence, remove all sequences that represent block delimiters/last literals + * by merging them into the literals of the next sequence. + * + * As such, the final generated result has no explicit representation of block boundaries, + * and the final last literals segment is not represented in the sequences. + * + * The output of this function can be fed into ZSTD_compressSequences() with CCtx + * setting of ZSTD_c_blockDelimiters as ZSTD_sf_noBlockDelimiters + * @return : number of sequences left after merging + */ +ZSTDLIB_STATIC_API size_t ZSTD_mergeBlockDelimiters(ZSTD_Sequence* sequences, size_t seqsSize); + +/*! ZSTD_compressSequences() : + * Compress an array of ZSTD_Sequence, associated with @src buffer, into dst. + * @src contains the entire input (not just the literals). + * If @srcSize > sum(sequence.length), the remaining bytes are considered all literals + * If a dictionary is included, then the cctx should reference the dict (see: ZSTD_CCtx_refCDict(), ZSTD_CCtx_loadDictionary(), etc.). + * The entire source is compressed into a single frame. + * + * The compression behavior changes based on cctx params. In particular: + * If ZSTD_c_blockDelimiters == ZSTD_sf_noBlockDelimiters, the array of ZSTD_Sequence is expected to contain + * no block delimiters (defined in ZSTD_Sequence). Block boundaries are roughly determined based on + * the block size derived from the cctx, and sequences may be split. This is the default setting. + * + * If ZSTD_c_blockDelimiters == ZSTD_sf_explicitBlockDelimiters, the array of ZSTD_Sequence is expected to contain + * valid block delimiters (defined in ZSTD_Sequence). Behavior is undefined if no block delimiters are provided. + * + * When ZSTD_c_blockDelimiters == ZSTD_sf_explicitBlockDelimiters, it's possible to decide generating repcodes + * using the advanced parameter ZSTD_c_repcodeResolution. Repcodes will improve compression ratio, though the benefit + * can vary greatly depending on Sequences. On the other hand, repcode resolution is an expensive operation. + * By default, it's disabled at low (<10) compression levels, and enabled above the threshold (>=10). + * ZSTD_c_repcodeResolution makes it possible to directly manage this processing in either direction. + * + * If ZSTD_c_validateSequences == 0, this function blindly accepts the Sequences provided. Invalid Sequences cause undefined + * behavior. If ZSTD_c_validateSequences == 1, then the function will detect invalid Sequences (see doc/zstd_compression_format.md for + * specifics regarding offset/matchlength requirements) and then bail out and return an error. + * + * In addition to the two adjustable experimental params, there are other important cctx params. + * - ZSTD_c_minMatch MUST be set as less than or equal to the smallest match generated by the match finder. It has a minimum value of ZSTD_MINMATCH_MIN. + * - ZSTD_c_compressionLevel accordingly adjusts the strength of the entropy coder, as it would in typical compression. + * - ZSTD_c_windowLog affects offset validation: this function will return an error at higher debug levels if a provided offset + * is larger than what the spec allows for a given window log and dictionary (if present). See: doc/zstd_compression_format.md + * + * Note: Repcodes are, as of now, always re-calculated within this function, ZSTD_Sequence.rep is effectively unused. + * Dev Note: Once ability to ingest repcodes become available, the explicit block delims mode must respect those repcodes exactly, + * and cannot emit an RLE block that disagrees with the repcode history. + * @return : final compressed size, or a ZSTD error code. + */ +ZSTDLIB_STATIC_API size_t +ZSTD_compressSequences(ZSTD_CCtx* cctx, + void* dst, size_t dstCapacity, + const ZSTD_Sequence* inSeqs, size_t inSeqsSize, + const void* src, size_t srcSize); + + +/*! ZSTD_compressSequencesAndLiterals() : + * This is a variant of ZSTD_compressSequences() which, + * instead of receiving (src,srcSize) as input parameter, receives (literals,litSize), + * aka all the literals, already extracted and laid out into a single continuous buffer. + * This can be useful if the process generating the sequences also happens to generate the buffer of literals, + * thus skipping an extraction + caching stage. + * It's a speed optimization, useful when the right conditions are met, + * but it also features the following limitations: + * - Only supports explicit delimiter mode + * - Currently does not support Sequences validation (so input Sequences are trusted) + * - Not compatible with frame checksum, which must be disabled + * - If any block is incompressible, will fail and return an error + * - @litSize must be == sum of all @.litLength fields in @inSeqs. Any discrepancy will generate an error. + * - @litBufCapacity is the size of the underlying buffer into which literals are written, starting at address @literals. + * @litBufCapacity must be at least 8 bytes larger than @litSize. + * - @decompressedSize must be correct, and correspond to the sum of all Sequences. Any discrepancy will generate an error. + * @return : final compressed size, or a ZSTD error code. + */ +ZSTDLIB_STATIC_API size_t +ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, + void* dst, size_t dstCapacity, + const ZSTD_Sequence* inSeqs, size_t nbSequences, + const void* literals, size_t litSize, size_t litBufCapacity, + size_t decompressedSize); + + +/*! ZSTD_writeSkippableFrame() : + * Generates a zstd skippable frame containing data given by src, and writes it to dst buffer. + * + * Skippable frames begin with a 4-byte magic number. There are 16 possible choices of magic number, + * ranging from ZSTD_MAGIC_SKIPPABLE_START to ZSTD_MAGIC_SKIPPABLE_START+15. + * As such, the parameter magicVariant controls the exact skippable frame magic number variant used, + * so the magic number used will be ZSTD_MAGIC_SKIPPABLE_START + magicVariant. + * + * Returns an error if destination buffer is not large enough, if the source size is not representable + * with a 4-byte unsigned int, or if the parameter magicVariant is greater than 15 (and therefore invalid). + * + * @return : number of bytes written or a ZSTD error. + */ +ZSTDLIB_STATIC_API size_t ZSTD_writeSkippableFrame(void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + unsigned magicVariant); + +/*! ZSTD_readSkippableFrame() : + * Retrieves the content of a zstd skippable frame starting at @src, and writes it to @dst buffer. + * + * The parameter @magicVariant will receive the magicVariant that was supplied when the frame was written, + * i.e. magicNumber - ZSTD_MAGIC_SKIPPABLE_START. + * This can be NULL if the caller is not interested in the magicVariant. + * + * Returns an error if destination buffer is not large enough, or if the frame is not skippable. + * + * @return : number of bytes written or a ZSTD error. + */ +ZSTDLIB_STATIC_API size_t ZSTD_readSkippableFrame(void* dst, size_t dstCapacity, + unsigned* magicVariant, + const void* src, size_t srcSize); + +/*! ZSTD_isSkippableFrame() : + * Tells if the content of `buffer` starts with a valid Frame Identifier for a skippable frame. + */ +ZSTDLIB_STATIC_API unsigned ZSTD_isSkippableFrame(const void* buffer, size_t size); + + + +/*************************************** +* Memory management +***************************************/ + +/*! ZSTD_estimate*() : + * These functions make it possible to estimate memory usage + * of a future {D,C}Ctx, before its creation. + * This is useful in combination with ZSTD_initStatic(), + * which makes it possible to employ a static buffer for ZSTD_CCtx* state. + * + * ZSTD_estimateCCtxSize() will provide a memory budget large enough + * to compress data of any size using one-shot compression ZSTD_compressCCtx() or ZSTD_compress2() + * associated with any compression level up to max specified one. + * The estimate will assume the input may be arbitrarily large, + * which is the worst case. + * + * Note that the size estimation is specific for one-shot compression, + * it is not valid for streaming (see ZSTD_estimateCStreamSize*()) + * nor other potential ways of using a ZSTD_CCtx* state. + * + * When srcSize can be bound by a known and rather "small" value, + * this knowledge can be used to provide a tighter budget estimation + * because the ZSTD_CCtx* state will need less memory for small inputs. + * This tighter estimation can be provided by employing more advanced functions + * ZSTD_estimateCCtxSize_usingCParams(), which can be used in tandem with ZSTD_getCParams(), + * and ZSTD_estimateCCtxSize_usingCCtxParams(), which can be used in tandem with ZSTD_CCtxParams_setParameter(). + * Both can be used to estimate memory using custom compression parameters and arbitrary srcSize limits. + * + * Note : only single-threaded compression is supported. + * ZSTD_estimateCCtxSize_usingCCtxParams() will return an error code if ZSTD_c_nbWorkers is >= 1. + */ +ZSTDLIB_STATIC_API size_t ZSTD_estimateCCtxSize(int maxCompressionLevel); +ZSTDLIB_STATIC_API size_t ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams); +ZSTDLIB_STATIC_API size_t ZSTD_estimateCCtxSize_usingCCtxParams(const ZSTD_CCtx_params* params); +ZSTDLIB_STATIC_API size_t ZSTD_estimateDCtxSize(void); + +/*! ZSTD_estimateCStreamSize() : + * ZSTD_estimateCStreamSize() will provide a memory budget large enough for streaming compression + * using any compression level up to the max specified one. + * It will also consider src size to be arbitrarily "large", which is a worst case scenario. + * If srcSize is known to always be small, ZSTD_estimateCStreamSize_usingCParams() can provide a tighter estimation. + * ZSTD_estimateCStreamSize_usingCParams() can be used in tandem with ZSTD_getCParams() to create cParams from compressionLevel. + * ZSTD_estimateCStreamSize_usingCCtxParams() can be used in tandem with ZSTD_CCtxParams_setParameter(). Only single-threaded compression is supported. This function will return an error code if ZSTD_c_nbWorkers is >= 1. + * Note : CStream size estimation is only correct for single-threaded compression. + * ZSTD_estimateCStreamSize_usingCCtxParams() will return an error code if ZSTD_c_nbWorkers is >= 1. + * Note 2 : ZSTD_estimateCStreamSize* functions are not compatible with the Block-Level Sequence Producer API at this time. + * Size estimates assume that no external sequence producer is registered. + * + * ZSTD_DStream memory budget depends on frame's window Size. + * This information can be passed manually, using ZSTD_estimateDStreamSize, + * or deducted from a valid frame Header, using ZSTD_estimateDStreamSize_fromFrame(); + * Any frame requesting a window size larger than max specified one will be rejected. + * Note : if streaming is init with function ZSTD_init?Stream_usingDict(), + * an internal ?Dict will be created, which additional size is not estimated here. + * In this case, get total size by adding ZSTD_estimate?DictSize + */ +ZSTDLIB_STATIC_API size_t ZSTD_estimateCStreamSize(int maxCompressionLevel); +ZSTDLIB_STATIC_API size_t ZSTD_estimateCStreamSize_usingCParams(ZSTD_compressionParameters cParams); +ZSTDLIB_STATIC_API size_t ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params* params); +ZSTDLIB_STATIC_API size_t ZSTD_estimateDStreamSize(size_t maxWindowSize); +ZSTDLIB_STATIC_API size_t ZSTD_estimateDStreamSize_fromFrame(const void* src, size_t srcSize); + +/*! ZSTD_estimate?DictSize() : + * ZSTD_estimateCDictSize() will bet that src size is relatively "small", and content is copied, like ZSTD_createCDict(). + * ZSTD_estimateCDictSize_advanced() makes it possible to control compression parameters precisely, like ZSTD_createCDict_advanced(). + * Note : dictionaries created by reference (`ZSTD_dlm_byRef`) are logically smaller. + */ +ZSTDLIB_STATIC_API size_t ZSTD_estimateCDictSize(size_t dictSize, int compressionLevel); +ZSTDLIB_STATIC_API size_t ZSTD_estimateCDictSize_advanced(size_t dictSize, ZSTD_compressionParameters cParams, ZSTD_dictLoadMethod_e dictLoadMethod); +ZSTDLIB_STATIC_API size_t ZSTD_estimateDDictSize(size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod); + +/*! ZSTD_initStatic*() : + * Initialize an object using a pre-allocated fixed-size buffer. + * workspace: The memory area to emplace the object into. + * Provided pointer *must be 8-bytes aligned*. + * Buffer must outlive object. + * workspaceSize: Use ZSTD_estimate*Size() to determine + * how large workspace must be to support target scenario. + * @return : pointer to object (same address as workspace, just different type), + * or NULL if error (size too small, incorrect alignment, etc.) + * Note : zstd will never resize nor malloc() when using a static buffer. + * If the object requires more memory than available, + * zstd will just error out (typically ZSTD_error_memory_allocation). + * Note 2 : there is no corresponding "free" function. + * Since workspace is allocated externally, it must be freed externally too. + * Note 3 : cParams : use ZSTD_getCParams() to convert a compression level + * into its associated cParams. + * Limitation 1 : currently not compatible with internal dictionary creation, triggered by + * ZSTD_CCtx_loadDictionary(), ZSTD_initCStream_usingDict() or ZSTD_initDStream_usingDict(). + * Limitation 2 : static cctx currently not compatible with multi-threading. + * Limitation 3 : static dctx is incompatible with legacy support. + */ +ZSTDLIB_STATIC_API ZSTD_CCtx* ZSTD_initStaticCCtx(void* workspace, size_t workspaceSize); +ZSTDLIB_STATIC_API ZSTD_CStream* ZSTD_initStaticCStream(void* workspace, size_t workspaceSize); /**< same as ZSTD_initStaticCCtx() */ + +ZSTDLIB_STATIC_API ZSTD_DCtx* ZSTD_initStaticDCtx(void* workspace, size_t workspaceSize); +ZSTDLIB_STATIC_API ZSTD_DStream* ZSTD_initStaticDStream(void* workspace, size_t workspaceSize); /**< same as ZSTD_initStaticDCtx() */ + +ZSTDLIB_STATIC_API const ZSTD_CDict* ZSTD_initStaticCDict( + void* workspace, size_t workspaceSize, + const void* dict, size_t dictSize, + ZSTD_dictLoadMethod_e dictLoadMethod, + ZSTD_dictContentType_e dictContentType, + ZSTD_compressionParameters cParams); + +ZSTDLIB_STATIC_API const ZSTD_DDict* ZSTD_initStaticDDict( + void* workspace, size_t workspaceSize, + const void* dict, size_t dictSize, + ZSTD_dictLoadMethod_e dictLoadMethod, + ZSTD_dictContentType_e dictContentType); + + +/*! Custom memory allocation : + * These prototypes make it possible to pass your own allocation/free functions. + * ZSTD_customMem is provided at creation time, using ZSTD_create*_advanced() variants listed below. + * All allocation/free operations will be completed using these custom variants instead of regular ones. + */ +typedef void* (*ZSTD_allocFunction) (void* opaque, size_t size); +typedef void (*ZSTD_freeFunction) (void* opaque, void* address); +typedef struct { ZSTD_allocFunction customAlloc; ZSTD_freeFunction customFree; void* opaque; } ZSTD_customMem; +static +#ifdef __GNUC__ +__attribute__((__unused__)) +#endif + +#if defined(__clang__) && __clang_major__ >= 5 +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" +#endif +ZSTD_customMem const ZSTD_defaultCMem = { NULL, NULL, NULL }; /**< this constant defers to stdlib's functions */ +#if defined(__clang__) && __clang_major__ >= 5 +#pragma clang diagnostic pop +#endif + +ZSTDLIB_STATIC_API ZSTD_CCtx* ZSTD_createCCtx_advanced(ZSTD_customMem customMem); +ZSTDLIB_STATIC_API ZSTD_CStream* ZSTD_createCStream_advanced(ZSTD_customMem customMem); +ZSTDLIB_STATIC_API ZSTD_DCtx* ZSTD_createDCtx_advanced(ZSTD_customMem customMem); +ZSTDLIB_STATIC_API ZSTD_DStream* ZSTD_createDStream_advanced(ZSTD_customMem customMem); + +ZSTDLIB_STATIC_API ZSTD_CDict* ZSTD_createCDict_advanced(const void* dict, size_t dictSize, + ZSTD_dictLoadMethod_e dictLoadMethod, + ZSTD_dictContentType_e dictContentType, + ZSTD_compressionParameters cParams, + ZSTD_customMem customMem); + +/*! Thread pool : + * These prototypes make it possible to share a thread pool among multiple compression contexts. + * This can limit resources for applications with multiple threads where each one uses + * a threaded compression mode (via ZSTD_c_nbWorkers parameter). + * ZSTD_createThreadPool creates a new thread pool with a given number of threads. + * Note that the lifetime of such pool must exist while being used. + * ZSTD_CCtx_refThreadPool assigns a thread pool to a context (use NULL argument value + * to use an internal thread pool). + * ZSTD_freeThreadPool frees a thread pool, accepts NULL pointer. + */ +typedef struct POOL_ctx_s ZSTD_threadPool; +ZSTDLIB_STATIC_API ZSTD_threadPool* ZSTD_createThreadPool(size_t numThreads); +ZSTDLIB_STATIC_API void ZSTD_freeThreadPool (ZSTD_threadPool* pool); /* accept NULL pointer */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtx_refThreadPool(ZSTD_CCtx* cctx, ZSTD_threadPool* pool); + + +/* + * This API is temporary and is expected to change or disappear in the future! + */ +ZSTDLIB_STATIC_API ZSTD_CDict* ZSTD_createCDict_advanced2( + const void* dict, size_t dictSize, + ZSTD_dictLoadMethod_e dictLoadMethod, + ZSTD_dictContentType_e dictContentType, + const ZSTD_CCtx_params* cctxParams, + ZSTD_customMem customMem); + +ZSTDLIB_STATIC_API ZSTD_DDict* ZSTD_createDDict_advanced( + const void* dict, size_t dictSize, + ZSTD_dictLoadMethod_e dictLoadMethod, + ZSTD_dictContentType_e dictContentType, + ZSTD_customMem customMem); + + +/*************************************** +* Advanced compression functions +***************************************/ + +/*! ZSTD_createCDict_byReference() : + * Create a digested dictionary for compression + * Dictionary content is just referenced, not duplicated. + * As a consequence, `dictBuffer` **must** outlive CDict, + * and its content must remain unmodified throughout the lifetime of CDict. + * note: equivalent to ZSTD_createCDict_advanced(), with dictLoadMethod==ZSTD_dlm_byRef */ +ZSTDLIB_STATIC_API ZSTD_CDict* ZSTD_createCDict_byReference(const void* dictBuffer, size_t dictSize, int compressionLevel); + +/*! ZSTD_getCParams() : + * @return ZSTD_compressionParameters structure for a selected compression level and estimated srcSize. + * `estimatedSrcSize` value is optional, select 0 if not known */ +ZSTDLIB_STATIC_API ZSTD_compressionParameters ZSTD_getCParams(int compressionLevel, unsigned long long estimatedSrcSize, size_t dictSize); + +/*! ZSTD_getParams() : + * same as ZSTD_getCParams(), but @return a full `ZSTD_parameters` object instead of sub-component `ZSTD_compressionParameters`. + * All fields of `ZSTD_frameParameters` are set to default : contentSize=1, checksum=0, noDictID=0 */ +ZSTDLIB_STATIC_API ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long estimatedSrcSize, size_t dictSize); + +/*! ZSTD_checkCParams() : + * Ensure param values remain within authorized range. + * @return 0 on success, or an error code (can be checked with ZSTD_isError()) */ +ZSTDLIB_STATIC_API size_t ZSTD_checkCParams(ZSTD_compressionParameters params); + +/*! ZSTD_adjustCParams() : + * optimize params for a given `srcSize` and `dictSize`. + * `srcSize` can be unknown, in which case use ZSTD_CONTENTSIZE_UNKNOWN. + * `dictSize` must be `0` when there is no dictionary. + * cPar can be invalid : all parameters will be clamped within valid range in the @return struct. + * This function never fails (wide contract) */ +ZSTDLIB_STATIC_API ZSTD_compressionParameters ZSTD_adjustCParams(ZSTD_compressionParameters cPar, unsigned long long srcSize, size_t dictSize); + +/*! ZSTD_CCtx_setCParams() : + * Set all parameters provided within @p cparams into the working @p cctx. + * Note : if modifying parameters during compression (MT mode only), + * note that changes to the .windowLog parameter will be ignored. + * @return 0 on success, or an error code (can be checked with ZSTD_isError()). + * On failure, no parameters are updated. + */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtx_setCParams(ZSTD_CCtx* cctx, ZSTD_compressionParameters cparams); + +/*! ZSTD_CCtx_setFParams() : + * Set all parameters provided within @p fparams into the working @p cctx. + * @return 0 on success, or an error code (can be checked with ZSTD_isError()). + */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtx_setFParams(ZSTD_CCtx* cctx, ZSTD_frameParameters fparams); + +/*! ZSTD_CCtx_setParams() : + * Set all parameters provided within @p params into the working @p cctx. + * @return 0 on success, or an error code (can be checked with ZSTD_isError()). + */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtx_setParams(ZSTD_CCtx* cctx, ZSTD_parameters params); + +/*! ZSTD_compress_advanced() : + * Note : this function is now DEPRECATED. + * It can be replaced by ZSTD_compress2(), in combination with ZSTD_CCtx_setParameter() and other parameter setters. + * This prototype will generate compilation warnings. */ +ZSTD_DEPRECATED("use ZSTD_compress2") +ZSTDLIB_STATIC_API +size_t ZSTD_compress_advanced(ZSTD_CCtx* cctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const void* dict,size_t dictSize, + ZSTD_parameters params); + +/*! ZSTD_compress_usingCDict_advanced() : + * Note : this function is now DEPRECATED. + * It can be replaced by ZSTD_compress2(), in combination with ZSTD_CCtx_loadDictionary() and other parameter setters. + * This prototype will generate compilation warnings. */ +ZSTD_DEPRECATED("use ZSTD_compress2 with ZSTD_CCtx_loadDictionary") +ZSTDLIB_STATIC_API +size_t ZSTD_compress_usingCDict_advanced(ZSTD_CCtx* cctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const ZSTD_CDict* cdict, + ZSTD_frameParameters fParams); + + +/*! ZSTD_CCtx_loadDictionary_byReference() : + * Same as ZSTD_CCtx_loadDictionary(), but dictionary content is referenced, instead of being copied into CCtx. + * It saves some memory, but also requires that `dict` outlives its usage within `cctx` */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtx_loadDictionary_byReference(ZSTD_CCtx* cctx, const void* dict, size_t dictSize); + +/*! ZSTD_CCtx_loadDictionary_advanced() : + * Same as ZSTD_CCtx_loadDictionary(), but gives finer control over + * how to load the dictionary (by copy ? by reference ?) + * and how to interpret it (automatic ? force raw mode ? full mode only ?) */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtx_loadDictionary_advanced(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType); + +/*! ZSTD_CCtx_refPrefix_advanced() : + * Same as ZSTD_CCtx_refPrefix(), but gives finer control over + * how to interpret prefix content (automatic ? force raw mode (default) ? full mode only ?) */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtx_refPrefix_advanced(ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType); + +/* === experimental parameters === */ +/* these parameters can be used with ZSTD_setParameter() + * they are not guaranteed to remain supported in the future */ + + /* Enables rsyncable mode, + * which makes compressed files more rsync friendly + * by adding periodic synchronization points to the compressed data. + * The target average block size is ZSTD_c_jobSize / 2. + * It's possible to modify the job size to increase or decrease + * the granularity of the synchronization point. + * Once the jobSize is smaller than the window size, + * it will result in compression ratio degradation. + * NOTE 1: rsyncable mode only works when multithreading is enabled. + * NOTE 2: rsyncable performs poorly in combination with long range mode, + * since it will decrease the effectiveness of synchronization points, + * though mileage may vary. + * NOTE 3: Rsyncable mode limits maximum compression speed to ~400 MB/s. + * If the selected compression level is already running significantly slower, + * the overall speed won't be significantly impacted. + */ + #define ZSTD_c_rsyncable ZSTD_c_experimentalParam1 + +/* Select a compression format. + * The value must be of type ZSTD_format_e. + * See ZSTD_format_e enum definition for details */ +#define ZSTD_c_format ZSTD_c_experimentalParam2 + +/* Force back-reference distances to remain < windowSize, + * even when referencing into Dictionary content (default:0) */ +#define ZSTD_c_forceMaxWindow ZSTD_c_experimentalParam3 + +/* Controls whether the contents of a CDict + * are used in place, or copied into the working context. + * Accepts values from the ZSTD_dictAttachPref_e enum. + * See the comments on that enum for an explanation of the feature. */ +#define ZSTD_c_forceAttachDict ZSTD_c_experimentalParam4 + +/* Controlled with ZSTD_ParamSwitch_e enum. + * Default is ZSTD_ps_auto. + * Set to ZSTD_ps_disable to never compress literals. + * Set to ZSTD_ps_enable to always compress literals. (Note: uncompressed literals + * may still be emitted if huffman is not beneficial to use.) + * + * By default, in ZSTD_ps_auto, the library will decide at runtime whether to use + * literals compression based on the compression parameters - specifically, + * negative compression levels do not use literal compression. + */ +#define ZSTD_c_literalCompressionMode ZSTD_c_experimentalParam5 + +/* User's best guess of source size. + * Hint is not valid when srcSizeHint == 0. + * There is no guarantee that hint is close to actual source size, + * but compression ratio may regress significantly if guess considerably underestimates */ +#define ZSTD_c_srcSizeHint ZSTD_c_experimentalParam7 + +/* Controls whether the new and experimental "dedicated dictionary search + * structure" can be used. This feature is still rough around the edges, be + * prepared for surprising behavior! + * + * How to use it: + * + * When using a CDict, whether to use this feature or not is controlled at + * CDict creation, and it must be set in a CCtxParams set passed into that + * construction (via ZSTD_createCDict_advanced2()). A compression will then + * use the feature or not based on how the CDict was constructed; the value of + * this param, set in the CCtx, will have no effect. + * + * However, when a dictionary buffer is passed into a CCtx, such as via + * ZSTD_CCtx_loadDictionary(), this param can be set on the CCtx to control + * whether the CDict that is created internally can use the feature or not. + * + * What it does: + * + * Normally, the internal data structures of the CDict are analogous to what + * would be stored in a CCtx after compressing the contents of a dictionary. + * To an approximation, a compression using a dictionary can then use those + * data structures to simply continue what is effectively a streaming + * compression where the simulated compression of the dictionary left off. + * Which is to say, the search structures in the CDict are normally the same + * format as in the CCtx. + * + * It is possible to do better, since the CDict is not like a CCtx: the search + * structures are written once during CDict creation, and then are only read + * after that, while the search structures in the CCtx are both read and + * written as the compression goes along. This means we can choose a search + * structure for the dictionary that is read-optimized. + * + * This feature enables the use of that different structure. + * + * Note that some of the members of the ZSTD_compressionParameters struct have + * different semantics and constraints in the dedicated search structure. It is + * highly recommended that you simply set a compression level in the CCtxParams + * you pass into the CDict creation call, and avoid messing with the cParams + * directly. + * + * Effects: + * + * This will only have any effect when the selected ZSTD_strategy + * implementation supports this feature. Currently, that's limited to + * ZSTD_greedy, ZSTD_lazy, and ZSTD_lazy2. + * + * Note that this means that the CDict tables can no longer be copied into the + * CCtx, so the dict attachment mode ZSTD_dictForceCopy will no longer be + * usable. The dictionary can only be attached or reloaded. + * + * In general, you should expect compression to be faster--sometimes very much + * so--and CDict creation to be slightly slower. Eventually, we will probably + * make this mode the default. + */ +#define ZSTD_c_enableDedicatedDictSearch ZSTD_c_experimentalParam8 + +/* ZSTD_c_stableInBuffer + * Experimental parameter. + * Default is 0 == disabled. Set to 1 to enable. + * + * Tells the compressor that input data presented with ZSTD_inBuffer + * will ALWAYS be the same between calls. + * Technically, the @src pointer must never be changed, + * and the @pos field can only be updated by zstd. + * However, it's possible to increase the @size field, + * allowing scenarios where more data can be appended after compressions starts. + * These conditions are checked by the compressor, + * and compression will fail if they are not respected. + * Also, data in the ZSTD_inBuffer within the range [src, src + pos) + * MUST not be modified during compression or it will result in data corruption. + * + * When this flag is enabled zstd won't allocate an input window buffer, + * because the user guarantees it can reference the ZSTD_inBuffer until + * the frame is complete. But, it will still allocate an output buffer + * large enough to fit a block (see ZSTD_c_stableOutBuffer). This will also + * avoid the memcpy() from the input buffer to the input window buffer. + * + * NOTE: So long as the ZSTD_inBuffer always points to valid memory, using + * this flag is ALWAYS memory safe, and will never access out-of-bounds + * memory. However, compression WILL fail if conditions are not respected. + * + * WARNING: The data in the ZSTD_inBuffer in the range [src, src + pos) MUST + * not be modified during compression or it will result in data corruption. + * This is because zstd needs to reference data in the ZSTD_inBuffer to find + * matches. Normally zstd maintains its own window buffer for this purpose, + * but passing this flag tells zstd to rely on user provided buffer instead. + */ +#define ZSTD_c_stableInBuffer ZSTD_c_experimentalParam9 + +/* ZSTD_c_stableOutBuffer + * Experimental parameter. + * Default is 0 == disabled. Set to 1 to enable. + * + * Tells he compressor that the ZSTD_outBuffer will not be resized between + * calls. Specifically: (out.size - out.pos) will never grow. This gives the + * compressor the freedom to say: If the compressed data doesn't fit in the + * output buffer then return ZSTD_error_dstSizeTooSmall. This allows us to + * always decompress directly into the output buffer, instead of decompressing + * into an internal buffer and copying to the output buffer. + * + * When this flag is enabled zstd won't allocate an output buffer, because + * it can write directly to the ZSTD_outBuffer. It will still allocate the + * input window buffer (see ZSTD_c_stableInBuffer). + * + * Zstd will check that (out.size - out.pos) never grows and return an error + * if it does. While not strictly necessary, this should prevent surprises. + */ +#define ZSTD_c_stableOutBuffer ZSTD_c_experimentalParam10 + +/* ZSTD_c_blockDelimiters + * Default is 0 == ZSTD_sf_noBlockDelimiters. + * + * For use with sequence compression API: ZSTD_compressSequences(). + * + * Designates whether or not the given array of ZSTD_Sequence contains block delimiters + * and last literals, which are defined as sequences with offset == 0 and matchLength == 0. + * See the definition of ZSTD_Sequence for more specifics. + */ +#define ZSTD_c_blockDelimiters ZSTD_c_experimentalParam11 + +/* ZSTD_c_validateSequences + * Default is 0 == disabled. Set to 1 to enable sequence validation. + * + * For use with sequence compression API: ZSTD_compressSequences*(). + * Designates whether or not provided sequences are validated within ZSTD_compressSequences*() + * during function execution. + * + * When Sequence validation is disabled (default), Sequences are compressed as-is, + * so they must correct, otherwise it would result in a corruption error. + * + * Sequence validation adds some protection, by ensuring that all values respect boundary conditions. + * If a Sequence is detected invalid (see doc/zstd_compression_format.md for + * specifics regarding offset/matchlength requirements) then the function will bail out and + * return an error. + */ +#define ZSTD_c_validateSequences ZSTD_c_experimentalParam12 + +/* ZSTD_c_blockSplitterLevel + * note: this parameter only influences the first splitter stage, + * which is active before producing the sequences. + * ZSTD_c_splitAfterSequences controls the next splitter stage, + * which is active after sequence production. + * Note that both can be combined. + * Allowed values are between 0 and ZSTD_BLOCKSPLITTER_LEVEL_MAX included. + * 0 means "auto", which will select a value depending on current ZSTD_c_strategy. + * 1 means no splitting. + * Then, values from 2 to 6 are sorted in increasing cpu load order. + * + * Note that currently the first block is never split, + * to ensure expansion guarantees in presence of incompressible data. + */ +#define ZSTD_BLOCKSPLITTER_LEVEL_MAX 6 +#define ZSTD_c_blockSplitterLevel ZSTD_c_experimentalParam20 + +/* ZSTD_c_splitAfterSequences + * This is a stronger splitter algorithm, + * based on actual sequences previously produced by the selected parser. + * It's also slower, and as a consequence, mostly used for high compression levels. + * While the post-splitter does overlap with the pre-splitter, + * both can nonetheless be combined, + * notably with ZSTD_c_blockSplitterLevel at ZSTD_BLOCKSPLITTER_LEVEL_MAX, + * resulting in higher compression ratio than just one of them. + * + * Default is ZSTD_ps_auto. + * Set to ZSTD_ps_disable to never use block splitter. + * Set to ZSTD_ps_enable to always use block splitter. + * + * By default, in ZSTD_ps_auto, the library will decide at runtime whether to use + * block splitting based on the compression parameters. + */ +#define ZSTD_c_splitAfterSequences ZSTD_c_experimentalParam13 + +/* ZSTD_c_useRowMatchFinder + * Controlled with ZSTD_ParamSwitch_e enum. + * Default is ZSTD_ps_auto. + * Set to ZSTD_ps_disable to never use row-based matchfinder. + * Set to ZSTD_ps_enable to force usage of row-based matchfinder. + * + * By default, in ZSTD_ps_auto, the library will decide at runtime whether to use + * the row-based matchfinder based on support for SIMD instructions and the window log. + * Note that this only pertains to compression strategies: greedy, lazy, and lazy2 + */ +#define ZSTD_c_useRowMatchFinder ZSTD_c_experimentalParam14 + +/* ZSTD_c_deterministicRefPrefix + * Default is 0 == disabled. Set to 1 to enable. + * + * Zstd produces different results for prefix compression when the prefix is + * directly adjacent to the data about to be compressed vs. when it isn't. + * This is because zstd detects that the two buffers are contiguous and it can + * use a more efficient match finding algorithm. However, this produces different + * results than when the two buffers are non-contiguous. This flag forces zstd + * to always load the prefix in non-contiguous mode, even if it happens to be + * adjacent to the data, to guarantee determinism. + * + * If you really care about determinism when using a dictionary or prefix, + * like when doing delta compression, you should select this option. It comes + * at a speed penalty of about ~2.5% if the dictionary and data happened to be + * contiguous, and is free if they weren't contiguous. We don't expect that + * intentionally making the dictionary and data contiguous will be worth the + * cost to memcpy() the data. + */ +#define ZSTD_c_deterministicRefPrefix ZSTD_c_experimentalParam15 + +/* ZSTD_c_prefetchCDictTables + * Controlled with ZSTD_ParamSwitch_e enum. Default is ZSTD_ps_auto. + * + * In some situations, zstd uses CDict tables in-place rather than copying them + * into the working context. (See docs on ZSTD_dictAttachPref_e above for details). + * In such situations, compression speed is seriously impacted when CDict tables are + * "cold" (outside CPU cache). This parameter instructs zstd to prefetch CDict tables + * when they are used in-place. + * + * For sufficiently small inputs, the cost of the prefetch will outweigh the benefit. + * For sufficiently large inputs, zstd will by default memcpy() CDict tables + * into the working context, so there is no need to prefetch. This parameter is + * targeted at a middle range of input sizes, where a prefetch is cheap enough to be + * useful but memcpy() is too expensive. The exact range of input sizes where this + * makes sense is best determined by careful experimentation. + * + * Note: for this parameter, ZSTD_ps_auto is currently equivalent to ZSTD_ps_disable, + * but in the future zstd may conditionally enable this feature via an auto-detection + * heuristic for cold CDicts. + * Use ZSTD_ps_disable to opt out of prefetching under any circumstances. + */ +#define ZSTD_c_prefetchCDictTables ZSTD_c_experimentalParam16 + +/* ZSTD_c_enableSeqProducerFallback + * Allowed values are 0 (disable) and 1 (enable). The default setting is 0. + * + * Controls whether zstd will fall back to an internal sequence producer if an + * external sequence producer is registered and returns an error code. This fallback + * is block-by-block: the internal sequence producer will only be called for blocks + * where the external sequence producer returns an error code. Fallback parsing will + * follow any other cParam settings, such as compression level, the same as in a + * normal (fully-internal) compression operation. + * + * The user is strongly encouraged to read the full Block-Level Sequence Producer API + * documentation (below) before setting this parameter. */ +#define ZSTD_c_enableSeqProducerFallback ZSTD_c_experimentalParam17 + +/* ZSTD_c_maxBlockSize + * Allowed values are between 1KB and ZSTD_BLOCKSIZE_MAX (128KB). + * The default is ZSTD_BLOCKSIZE_MAX, and setting to 0 will set to the default. + * + * This parameter can be used to set an upper bound on the blocksize + * that overrides the default ZSTD_BLOCKSIZE_MAX. It cannot be used to set upper + * bounds greater than ZSTD_BLOCKSIZE_MAX or bounds lower than 1KB (will make + * compressBound() inaccurate). Only currently meant to be used for testing. + */ +#define ZSTD_c_maxBlockSize ZSTD_c_experimentalParam18 + +/* ZSTD_c_repcodeResolution + * This parameter only has an effect if ZSTD_c_blockDelimiters is + * set to ZSTD_sf_explicitBlockDelimiters (may change in the future). + * + * This parameter affects how zstd parses external sequences, + * provided via the ZSTD_compressSequences*() API + * or from an external block-level sequence producer. + * + * If set to ZSTD_ps_enable, the library will check for repeated offsets within + * external sequences, even if those repcodes are not explicitly indicated in + * the "rep" field. Note that this is the only way to exploit repcode matches + * while using compressSequences*() or an external sequence producer, since zstd + * currently ignores the "rep" field of external sequences. + * + * If set to ZSTD_ps_disable, the library will not exploit repeated offsets in + * external sequences, regardless of whether the "rep" field has been set. This + * reduces sequence compression overhead by about 25% while sacrificing some + * compression ratio. + * + * The default value is ZSTD_ps_auto, for which the library will enable/disable + * based on compression level (currently: level<10 disables, level>=10 enables). + */ +#define ZSTD_c_repcodeResolution ZSTD_c_experimentalParam19 +#define ZSTD_c_searchForExternalRepcodes ZSTD_c_experimentalParam19 /* older name */ + + +/*! ZSTD_CCtx_getParameter() : + * Get the requested compression parameter value, selected by enum ZSTD_cParameter, + * and store it into int* value. + * @return : 0, or an error code (which can be tested with ZSTD_isError()). + */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtx_getParameter(const ZSTD_CCtx* cctx, ZSTD_cParameter param, int* value); + + +/*! ZSTD_CCtx_params : + * Quick howto : + * - ZSTD_createCCtxParams() : Create a ZSTD_CCtx_params structure + * - ZSTD_CCtxParams_setParameter() : Push parameters one by one into + * an existing ZSTD_CCtx_params structure. + * This is similar to + * ZSTD_CCtx_setParameter(). + * - ZSTD_CCtx_setParametersUsingCCtxParams() : Apply parameters to + * an existing CCtx. + * These parameters will be applied to + * all subsequent frames. + * - ZSTD_compressStream2() : Do compression using the CCtx. + * - ZSTD_freeCCtxParams() : Free the memory, accept NULL pointer. + * + * This can be used with ZSTD_estimateCCtxSize_advanced_usingCCtxParams() + * for static allocation of CCtx for single-threaded compression. + */ +ZSTDLIB_STATIC_API ZSTD_CCtx_params* ZSTD_createCCtxParams(void); +ZSTDLIB_STATIC_API size_t ZSTD_freeCCtxParams(ZSTD_CCtx_params* params); /* accept NULL pointer */ + +/*! ZSTD_CCtxParams_reset() : + * Reset params to default values. + */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtxParams_reset(ZSTD_CCtx_params* params); + +/*! ZSTD_CCtxParams_init() : + * Initializes the compression parameters of cctxParams according to + * compression level. All other parameters are reset to their default values. + */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtxParams_init(ZSTD_CCtx_params* cctxParams, int compressionLevel); + +/*! ZSTD_CCtxParams_init_advanced() : + * Initializes the compression and frame parameters of cctxParams according to + * params. All other parameters are reset to their default values. + */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtxParams_init_advanced(ZSTD_CCtx_params* cctxParams, ZSTD_parameters params); + +/*! ZSTD_CCtxParams_setParameter() : Requires v1.4.0+ + * Similar to ZSTD_CCtx_setParameter. + * Set one compression parameter, selected by enum ZSTD_cParameter. + * Parameters must be applied to a ZSTD_CCtx using + * ZSTD_CCtx_setParametersUsingCCtxParams(). + * @result : a code representing success or failure (which can be tested with + * ZSTD_isError()). + */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* params, ZSTD_cParameter param, int value); + +/*! ZSTD_CCtxParams_getParameter() : + * Similar to ZSTD_CCtx_getParameter. + * Get the requested value of one compression parameter, selected by enum ZSTD_cParameter. + * @result : 0, or an error code (which can be tested with ZSTD_isError()). + */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtxParams_getParameter(const ZSTD_CCtx_params* params, ZSTD_cParameter param, int* value); + +/*! ZSTD_CCtx_setParametersUsingCCtxParams() : + * Apply a set of ZSTD_CCtx_params to the compression context. + * This can be done even after compression is started, + * if nbWorkers==0, this will have no impact until a new compression is started. + * if nbWorkers>=1, new parameters will be picked up at next job, + * with a few restrictions (windowLog, pledgedSrcSize, nbWorkers, jobSize, and overlapLog are not updated). + */ +ZSTDLIB_STATIC_API size_t ZSTD_CCtx_setParametersUsingCCtxParams( + ZSTD_CCtx* cctx, const ZSTD_CCtx_params* params); + +/*! ZSTD_compressStream2_simpleArgs() : + * Same as ZSTD_compressStream2(), + * but using only integral types as arguments. + * This variant might be helpful for binders from dynamic languages + * which have troubles handling structures containing memory pointers. + */ +ZSTDLIB_STATIC_API size_t ZSTD_compressStream2_simpleArgs ( + ZSTD_CCtx* cctx, + void* dst, size_t dstCapacity, size_t* dstPos, + const void* src, size_t srcSize, size_t* srcPos, + ZSTD_EndDirective endOp); + + +/*************************************** +* Advanced decompression functions +***************************************/ + +/*! ZSTD_isFrame() : + * Tells if the content of `buffer` starts with a valid Frame Identifier. + * Note : Frame Identifier is 4 bytes. If `size < 4`, @return will always be 0. + * Note 2 : Legacy Frame Identifiers are considered valid only if Legacy Support is enabled. + * Note 3 : Skippable Frame Identifiers are considered valid. */ +ZSTDLIB_STATIC_API unsigned ZSTD_isFrame(const void* buffer, size_t size); + +/*! ZSTD_createDDict_byReference() : + * Create a digested dictionary, ready to start decompression operation without startup delay. + * Dictionary content is referenced, and therefore stays in dictBuffer. + * It is important that dictBuffer outlives DDict, + * it must remain read accessible throughout the lifetime of DDict */ +ZSTDLIB_STATIC_API ZSTD_DDict* ZSTD_createDDict_byReference(const void* dictBuffer, size_t dictSize); + +/*! ZSTD_DCtx_loadDictionary_byReference() : + * Same as ZSTD_DCtx_loadDictionary(), + * but references `dict` content instead of copying it into `dctx`. + * This saves memory if `dict` remains around., + * However, it's imperative that `dict` remains accessible (and unmodified) while being used, so it must outlive decompression. */ +ZSTDLIB_STATIC_API size_t ZSTD_DCtx_loadDictionary_byReference(ZSTD_DCtx* dctx, const void* dict, size_t dictSize); + +/*! ZSTD_DCtx_loadDictionary_advanced() : + * Same as ZSTD_DCtx_loadDictionary(), + * but gives direct control over + * how to load the dictionary (by copy ? by reference ?) + * and how to interpret it (automatic ? force raw mode ? full mode only ?). */ +ZSTDLIB_STATIC_API size_t ZSTD_DCtx_loadDictionary_advanced(ZSTD_DCtx* dctx, const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType); + +/*! ZSTD_DCtx_refPrefix_advanced() : + * Same as ZSTD_DCtx_refPrefix(), but gives finer control over + * how to interpret prefix content (automatic ? force raw mode (default) ? full mode only ?) */ +ZSTDLIB_STATIC_API size_t ZSTD_DCtx_refPrefix_advanced(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType); + +/*! ZSTD_DCtx_setMaxWindowSize() : + * Refuses allocating internal buffers for frames requiring a window size larger than provided limit. + * This protects a decoder context from reserving too much memory for itself (potential attack scenario). + * This parameter is only useful in streaming mode, since no internal buffer is allocated in single-pass mode. + * By default, a decompression context accepts all window sizes <= (1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT) + * @return : 0, or an error code (which can be tested using ZSTD_isError()). + */ +ZSTDLIB_STATIC_API size_t ZSTD_DCtx_setMaxWindowSize(ZSTD_DCtx* dctx, size_t maxWindowSize); + +/*! ZSTD_DCtx_getParameter() : + * Get the requested decompression parameter value, selected by enum ZSTD_dParameter, + * and store it into int* value. + * @return : 0, or an error code (which can be tested with ZSTD_isError()). + */ +ZSTDLIB_STATIC_API size_t ZSTD_DCtx_getParameter(ZSTD_DCtx* dctx, ZSTD_dParameter param, int* value); + +/* ZSTD_d_format + * experimental parameter, + * allowing selection between ZSTD_format_e input compression formats + */ +#define ZSTD_d_format ZSTD_d_experimentalParam1 +/* ZSTD_d_stableOutBuffer + * Experimental parameter. + * Default is 0 == disabled. Set to 1 to enable. + * + * Tells the decompressor that the ZSTD_outBuffer will ALWAYS be the same + * between calls, except for the modifications that zstd makes to pos (the + * caller must not modify pos). This is checked by the decompressor, and + * decompression will fail if it ever changes. Therefore the ZSTD_outBuffer + * MUST be large enough to fit the entire decompressed frame. This will be + * checked when the frame content size is known. The data in the ZSTD_outBuffer + * in the range [dst, dst + pos) MUST not be modified during decompression + * or you will get data corruption. + * + * When this flag is enabled zstd won't allocate an output buffer, because + * it can write directly to the ZSTD_outBuffer, but it will still allocate + * an input buffer large enough to fit any compressed block. This will also + * avoid the memcpy() from the internal output buffer to the ZSTD_outBuffer. + * If you need to avoid the input buffer allocation use the buffer-less + * streaming API. + * + * NOTE: So long as the ZSTD_outBuffer always points to valid memory, using + * this flag is ALWAYS memory safe, and will never access out-of-bounds + * memory. However, decompression WILL fail if you violate the preconditions. + * + * WARNING: The data in the ZSTD_outBuffer in the range [dst, dst + pos) MUST + * not be modified during decompression or you will get data corruption. This + * is because zstd needs to reference data in the ZSTD_outBuffer to regenerate + * matches. Normally zstd maintains its own buffer for this purpose, but passing + * this flag tells zstd to use the user provided buffer. + */ +#define ZSTD_d_stableOutBuffer ZSTD_d_experimentalParam2 + +/* ZSTD_d_forceIgnoreChecksum + * Experimental parameter. + * Default is 0 == disabled. Set to 1 to enable + * + * Tells the decompressor to skip checksum validation during decompression, regardless + * of whether checksumming was specified during compression. This offers some + * slight performance benefits, and may be useful for debugging. + * Param has values of type ZSTD_forceIgnoreChecksum_e + */ +#define ZSTD_d_forceIgnoreChecksum ZSTD_d_experimentalParam3 + +/* ZSTD_d_refMultipleDDicts + * Experimental parameter. + * Default is 0 == disabled. Set to 1 to enable + * + * If enabled and dctx is allocated on the heap, then additional memory will be allocated + * to store references to multiple ZSTD_DDict. That is, multiple calls of ZSTD_refDDict() + * using a given ZSTD_DCtx, rather than overwriting the previous DDict reference, will instead + * store all references. At decompression time, the appropriate dictID is selected + * from the set of DDicts based on the dictID in the frame. + * + * Usage is simply calling ZSTD_refDDict() on multiple dict buffers. + * + * Param has values of byte ZSTD_refMultipleDDicts_e + * + * WARNING: Enabling this parameter and calling ZSTD_DCtx_refDDict(), will trigger memory + * allocation for the hash table. ZSTD_freeDCtx() also frees this memory. + * Memory is allocated as per ZSTD_DCtx::customMem. + * + * Although this function allocates memory for the table, the user is still responsible for + * memory management of the underlying ZSTD_DDict* themselves. + */ +#define ZSTD_d_refMultipleDDicts ZSTD_d_experimentalParam4 + +/* ZSTD_d_disableHuffmanAssembly + * Set to 1 to disable the Huffman assembly implementation. + * The default value is 0, which allows zstd to use the Huffman assembly + * implementation if available. + * + * This parameter can be used to disable Huffman assembly at runtime. + * If you want to disable it at compile time you can define the macro + * ZSTD_DISABLE_ASM. + */ +#define ZSTD_d_disableHuffmanAssembly ZSTD_d_experimentalParam5 + +/* ZSTD_d_maxBlockSize + * Allowed values are between 1KB and ZSTD_BLOCKSIZE_MAX (128KB). + * The default is ZSTD_BLOCKSIZE_MAX, and setting to 0 will set to the default. + * + * Forces the decompressor to reject blocks whose content size is + * larger than the configured maxBlockSize. When maxBlockSize is + * larger than the windowSize, the windowSize is used instead. + * This saves memory on the decoder when you know all blocks are small. + * + * This option is typically used in conjunction with ZSTD_c_maxBlockSize. + * + * WARNING: This causes the decoder to reject otherwise valid frames + * that have block sizes larger than the configured maxBlockSize. + */ +#define ZSTD_d_maxBlockSize ZSTD_d_experimentalParam6 + + +/*! ZSTD_DCtx_setFormat() : + * This function is REDUNDANT. Prefer ZSTD_DCtx_setParameter(). + * Instruct the decoder context about what kind of data to decode next. + * This instruction is mandatory to decode data without a fully-formed header, + * such ZSTD_f_zstd1_magicless for example. + * @return : 0, or an error code (which can be tested using ZSTD_isError()). */ +ZSTD_DEPRECATED("use ZSTD_DCtx_setParameter() instead") +ZSTDLIB_STATIC_API +size_t ZSTD_DCtx_setFormat(ZSTD_DCtx* dctx, ZSTD_format_e format); + +/*! ZSTD_decompressStream_simpleArgs() : + * Same as ZSTD_decompressStream(), + * but using only integral types as arguments. + * This can be helpful for binders from dynamic languages + * which have troubles handling structures containing memory pointers. + */ +ZSTDLIB_STATIC_API size_t ZSTD_decompressStream_simpleArgs ( + ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, size_t* dstPos, + const void* src, size_t srcSize, size_t* srcPos); + + +/******************************************************************** +* Advanced streaming functions +* Warning : most of these functions are now redundant with the Advanced API. +* Once Advanced API reaches "stable" status, +* redundant functions will be deprecated, and then at some point removed. +********************************************************************/ + +/*===== Advanced Streaming compression functions =====*/ + +/*! ZSTD_initCStream_srcSize() : + * This function is DEPRECATED, and equivalent to: + * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); + * ZSTD_CCtx_refCDict(zcs, NULL); // clear the dictionary (if any) + * ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel); + * ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize); + * + * pledgedSrcSize must be correct. If it is not known at init time, use + * ZSTD_CONTENTSIZE_UNKNOWN. Note that, for compatibility with older programs, + * "0" also disables frame content size field. It may be enabled in the future. + * This prototype will generate compilation warnings. + */ +ZSTD_DEPRECATED("use ZSTD_CCtx_reset, see zstd.h for detailed instructions") +ZSTDLIB_STATIC_API +size_t ZSTD_initCStream_srcSize(ZSTD_CStream* zcs, + int compressionLevel, + unsigned long long pledgedSrcSize); + +/*! ZSTD_initCStream_usingDict() : + * This function is DEPRECATED, and is equivalent to: + * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); + * ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel); + * ZSTD_CCtx_loadDictionary(zcs, dict, dictSize); + * + * Creates of an internal CDict (incompatible with static CCtx), except if + * dict == NULL or dictSize < 8, in which case no dict is used. + * Note: dict is loaded with ZSTD_dct_auto (treated as a full zstd dictionary if + * it begins with ZSTD_MAGIC_DICTIONARY, else as raw content) and ZSTD_dlm_byCopy. + * This prototype will generate compilation warnings. + */ +ZSTD_DEPRECATED("use ZSTD_CCtx_reset, see zstd.h for detailed instructions") +ZSTDLIB_STATIC_API +size_t ZSTD_initCStream_usingDict(ZSTD_CStream* zcs, + const void* dict, size_t dictSize, + int compressionLevel); + +/*! ZSTD_initCStream_advanced() : + * This function is DEPRECATED, and is equivalent to: + * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); + * ZSTD_CCtx_setParams(zcs, params); + * ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize); + * ZSTD_CCtx_loadDictionary(zcs, dict, dictSize); + * + * dict is loaded with ZSTD_dct_auto and ZSTD_dlm_byCopy. + * pledgedSrcSize must be correct. + * If srcSize is not known at init time, use value ZSTD_CONTENTSIZE_UNKNOWN. + * This prototype will generate compilation warnings. + */ +ZSTD_DEPRECATED("use ZSTD_CCtx_reset, see zstd.h for detailed instructions") +ZSTDLIB_STATIC_API +size_t ZSTD_initCStream_advanced(ZSTD_CStream* zcs, + const void* dict, size_t dictSize, + ZSTD_parameters params, + unsigned long long pledgedSrcSize); + +/*! ZSTD_initCStream_usingCDict() : + * This function is DEPRECATED, and equivalent to: + * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); + * ZSTD_CCtx_refCDict(zcs, cdict); + * + * note : cdict will just be referenced, and must outlive compression session + * This prototype will generate compilation warnings. + */ +ZSTD_DEPRECATED("use ZSTD_CCtx_reset and ZSTD_CCtx_refCDict, see zstd.h for detailed instructions") +ZSTDLIB_STATIC_API +size_t ZSTD_initCStream_usingCDict(ZSTD_CStream* zcs, const ZSTD_CDict* cdict); + +/*! ZSTD_initCStream_usingCDict_advanced() : + * This function is DEPRECATED, and is equivalent to: + * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); + * ZSTD_CCtx_setFParams(zcs, fParams); + * ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize); + * ZSTD_CCtx_refCDict(zcs, cdict); + * + * same as ZSTD_initCStream_usingCDict(), with control over frame parameters. + * pledgedSrcSize must be correct. If srcSize is not known at init time, use + * value ZSTD_CONTENTSIZE_UNKNOWN. + * This prototype will generate compilation warnings. + */ +ZSTD_DEPRECATED("use ZSTD_CCtx_reset and ZSTD_CCtx_refCDict, see zstd.h for detailed instructions") +ZSTDLIB_STATIC_API +size_t ZSTD_initCStream_usingCDict_advanced(ZSTD_CStream* zcs, + const ZSTD_CDict* cdict, + ZSTD_frameParameters fParams, + unsigned long long pledgedSrcSize); + +/*! ZSTD_resetCStream() : + * This function is DEPRECATED, and is equivalent to: + * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); + * ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize); + * Note: ZSTD_resetCStream() interprets pledgedSrcSize == 0 as ZSTD_CONTENTSIZE_UNKNOWN, but + * ZSTD_CCtx_setPledgedSrcSize() does not do the same, so ZSTD_CONTENTSIZE_UNKNOWN must be + * explicitly specified. + * + * start a new frame, using same parameters from previous frame. + * This is typically useful to skip dictionary loading stage, since it will reuse it in-place. + * Note that zcs must be init at least once before using ZSTD_resetCStream(). + * If pledgedSrcSize is not known at reset time, use macro ZSTD_CONTENTSIZE_UNKNOWN. + * If pledgedSrcSize > 0, its value must be correct, as it will be written in header, and controlled at the end. + * For the time being, pledgedSrcSize==0 is interpreted as "srcSize unknown" for compatibility with older programs, + * but it will change to mean "empty" in future version, so use macro ZSTD_CONTENTSIZE_UNKNOWN instead. + * @return : 0, or an error code (which can be tested using ZSTD_isError()) + * This prototype will generate compilation warnings. + */ +ZSTD_DEPRECATED("use ZSTD_CCtx_reset, see zstd.h for detailed instructions") +ZSTDLIB_STATIC_API +size_t ZSTD_resetCStream(ZSTD_CStream* zcs, unsigned long long pledgedSrcSize); + + +typedef struct { + unsigned long long ingested; /* nb input bytes read and buffered */ + unsigned long long consumed; /* nb input bytes actually compressed */ + unsigned long long produced; /* nb of compressed bytes generated and buffered */ + unsigned long long flushed; /* nb of compressed bytes flushed : not provided; can be tracked from caller side */ + unsigned currentJobID; /* MT only : latest started job nb */ + unsigned nbActiveWorkers; /* MT only : nb of workers actively compressing at probe time */ +} ZSTD_frameProgression; + +/* ZSTD_getFrameProgression() : + * tells how much data has been ingested (read from input) + * consumed (input actually compressed) and produced (output) for current frame. + * Note : (ingested - consumed) is amount of input data buffered internally, not yet compressed. + * Aggregates progression inside active worker threads. + */ +ZSTDLIB_STATIC_API ZSTD_frameProgression ZSTD_getFrameProgression(const ZSTD_CCtx* cctx); + +/*! ZSTD_toFlushNow() : + * Tell how many bytes are ready to be flushed immediately. + * Useful for multithreading scenarios (nbWorkers >= 1). + * Probe the oldest active job, defined as oldest job not yet entirely flushed, + * and check its output buffer. + * @return : amount of data stored in oldest job and ready to be flushed immediately. + * if @return == 0, it means either : + * + there is no active job (could be checked with ZSTD_frameProgression()), or + * + oldest job is still actively compressing data, + * but everything it has produced has also been flushed so far, + * therefore flush speed is limited by production speed of oldest job + * irrespective of the speed of concurrent (and newer) jobs. + */ +ZSTDLIB_STATIC_API size_t ZSTD_toFlushNow(ZSTD_CCtx* cctx); + + +/*===== Advanced Streaming decompression functions =====*/ + +/*! + * This function is deprecated, and is equivalent to: + * + * ZSTD_DCtx_reset(zds, ZSTD_reset_session_only); + * ZSTD_DCtx_loadDictionary(zds, dict, dictSize); + * + * note: no dictionary will be used if dict == NULL or dictSize < 8 + */ +ZSTD_DEPRECATED("use ZSTD_DCtx_reset + ZSTD_DCtx_loadDictionary, see zstd.h for detailed instructions") +ZSTDLIB_STATIC_API size_t ZSTD_initDStream_usingDict(ZSTD_DStream* zds, const void* dict, size_t dictSize); + +/*! + * This function is deprecated, and is equivalent to: + * + * ZSTD_DCtx_reset(zds, ZSTD_reset_session_only); + * ZSTD_DCtx_refDDict(zds, ddict); + * + * note : ddict is referenced, it must outlive decompression session + */ +ZSTD_DEPRECATED("use ZSTD_DCtx_reset + ZSTD_DCtx_refDDict, see zstd.h for detailed instructions") +ZSTDLIB_STATIC_API size_t ZSTD_initDStream_usingDDict(ZSTD_DStream* zds, const ZSTD_DDict* ddict); + +/*! + * This function is deprecated, and is equivalent to: + * + * ZSTD_DCtx_reset(zds, ZSTD_reset_session_only); + * + * reuse decompression parameters from previous init; saves dictionary loading + */ +ZSTD_DEPRECATED("use ZSTD_DCtx_reset, see zstd.h for detailed instructions") +ZSTDLIB_STATIC_API size_t ZSTD_resetDStream(ZSTD_DStream* zds); + + +/* ********************* BLOCK-LEVEL SEQUENCE PRODUCER API ********************* + * + * *** OVERVIEW *** + * The Block-Level Sequence Producer API allows users to provide their own custom + * sequence producer which libzstd invokes to process each block. The produced list + * of sequences (literals and matches) is then post-processed by libzstd to produce + * valid compressed blocks. + * + * This block-level offload API is a more granular complement of the existing + * frame-level offload API compressSequences() (introduced in v1.5.1). It offers + * an easier migration story for applications already integrated with libzstd: the + * user application continues to invoke the same compression functions + * ZSTD_compress2() or ZSTD_compressStream2() as usual, and transparently benefits + * from the specific advantages of the external sequence producer. For example, + * the sequence producer could be tuned to take advantage of known characteristics + * of the input, to offer better speed / ratio, or could leverage hardware + * acceleration not available within libzstd itself. + * + * See contrib/externalSequenceProducer for an example program employing the + * Block-Level Sequence Producer API. + * + * *** USAGE *** + * The user is responsible for implementing a function of type + * ZSTD_sequenceProducer_F. For each block, zstd will pass the following + * arguments to the user-provided function: + * + * - sequenceProducerState: a pointer to a user-managed state for the sequence + * producer. + * + * - outSeqs, outSeqsCapacity: an output buffer for the sequence producer. + * outSeqsCapacity is guaranteed >= ZSTD_sequenceBound(srcSize). The memory + * backing outSeqs is managed by the CCtx. + * + * - src, srcSize: an input buffer for the sequence producer to parse. + * srcSize is guaranteed to be <= ZSTD_BLOCKSIZE_MAX. + * + * - dict, dictSize: a history buffer, which may be empty, which the sequence + * producer may reference as it parses the src buffer. Currently, zstd will + * always pass dictSize == 0 into external sequence producers, but this will + * change in the future. + * + * - compressionLevel: a signed integer representing the zstd compression level + * set by the user for the current operation. The sequence producer may choose + * to use this information to change its compression strategy and speed/ratio + * tradeoff. Note: the compression level does not reflect zstd parameters set + * through the advanced API. + * + * - windowSize: a size_t representing the maximum allowed offset for external + * sequences. Note that sequence offsets are sometimes allowed to exceed the + * windowSize if a dictionary is present, see doc/zstd_compression_format.md + * for details. + * + * The user-provided function shall return a size_t representing the number of + * sequences written to outSeqs. This return value will be treated as an error + * code if it is greater than outSeqsCapacity. The return value must be non-zero + * if srcSize is non-zero. The ZSTD_SEQUENCE_PRODUCER_ERROR macro is provided + * for convenience, but any value greater than outSeqsCapacity will be treated as + * an error code. + * + * If the user-provided function does not return an error code, the sequences + * written to outSeqs must be a valid parse of the src buffer. Data corruption may + * occur if the parse is not valid. A parse is defined to be valid if the + * following conditions hold: + * - The sum of matchLengths and literalLengths must equal srcSize. + * - All sequences in the parse, except for the final sequence, must have + * matchLength >= ZSTD_MINMATCH_MIN. The final sequence must have + * matchLength >= ZSTD_MINMATCH_MIN or matchLength == 0. + * - All offsets must respect the windowSize parameter as specified in + * doc/zstd_compression_format.md. + * - If the final sequence has matchLength == 0, it must also have offset == 0. + * + * zstd will only validate these conditions (and fail compression if they do not + * hold) if the ZSTD_c_validateSequences cParam is enabled. Note that sequence + * validation has a performance cost. + * + * If the user-provided function returns an error, zstd will either fall back + * to an internal sequence producer or fail the compression operation. The user can + * choose between the two behaviors by setting the ZSTD_c_enableSeqProducerFallback + * cParam. Fallback compression will follow any other cParam settings, such as + * compression level, the same as in a normal compression operation. + * + * The user shall instruct zstd to use a particular ZSTD_sequenceProducer_F + * function by calling + * ZSTD_registerSequenceProducer(cctx, + * sequenceProducerState, + * sequenceProducer) + * This setting will persist until the next parameter reset of the CCtx. + * + * The sequenceProducerState must be initialized by the user before calling + * ZSTD_registerSequenceProducer(). The user is responsible for destroying the + * sequenceProducerState. + * + * *** LIMITATIONS *** + * This API is compatible with all zstd compression APIs which respect advanced parameters. + * However, there are three limitations: + * + * First, the ZSTD_c_enableLongDistanceMatching cParam is not currently supported. + * COMPRESSION WILL FAIL if it is enabled and the user tries to compress with a block-level + * external sequence producer. + * - Note that ZSTD_c_enableLongDistanceMatching is auto-enabled by default in some + * cases (see its documentation for details). Users must explicitly set + * ZSTD_c_enableLongDistanceMatching to ZSTD_ps_disable in such cases if an external + * sequence producer is registered. + * - As of this writing, ZSTD_c_enableLongDistanceMatching is disabled by default + * whenever ZSTD_c_windowLog < 128MB, but that's subject to change. Users should + * check the docs on ZSTD_c_enableLongDistanceMatching whenever the Block-Level Sequence + * Producer API is used in conjunction with advanced settings (like ZSTD_c_windowLog). + * + * Second, history buffers are not currently supported. Concretely, zstd will always pass + * dictSize == 0 to the external sequence producer (for now). This has two implications: + * - Dictionaries are not currently supported. Compression will *not* fail if the user + * references a dictionary, but the dictionary won't have any effect. + * - Stream history is not currently supported. All advanced compression APIs, including + * streaming APIs, work with external sequence producers, but each block is treated as + * an independent chunk without history from previous blocks. + * + * Third, multi-threading within a single compression is not currently supported. In other words, + * COMPRESSION WILL FAIL if ZSTD_c_nbWorkers > 0 and an external sequence producer is registered. + * Multi-threading across compressions is fine: simply create one CCtx per thread. + * + * Long-term, we plan to overcome all three limitations. There is no technical blocker to + * overcoming them. It is purely a question of engineering effort. + */ + +#define ZSTD_SEQUENCE_PRODUCER_ERROR ((size_t)(-1)) + +typedef size_t (*ZSTD_sequenceProducer_F) ( + void* sequenceProducerState, + ZSTD_Sequence* outSeqs, size_t outSeqsCapacity, + const void* src, size_t srcSize, + const void* dict, size_t dictSize, + int compressionLevel, + size_t windowSize +); + +/*! ZSTD_registerSequenceProducer() : + * Instruct zstd to use a block-level external sequence producer function. + * + * The sequenceProducerState must be initialized by the caller, and the caller is + * responsible for managing its lifetime. This parameter is sticky across + * compressions. It will remain set until the user explicitly resets compression + * parameters. + * + * Sequence producer registration is considered to be an "advanced parameter", + * part of the "advanced API". This means it will only have an effect on compression + * APIs which respect advanced parameters, such as compress2() and compressStream2(). + * Older compression APIs such as compressCCtx(), which predate the introduction of + * "advanced parameters", will ignore any external sequence producer setting. + * + * The sequence producer can be "cleared" by registering a NULL function pointer. This + * removes all limitations described above in the "LIMITATIONS" section of the API docs. + * + * The user is strongly encouraged to read the full API documentation (above) before + * calling this function. */ +ZSTDLIB_STATIC_API void +ZSTD_registerSequenceProducer( + ZSTD_CCtx* cctx, + void* sequenceProducerState, + ZSTD_sequenceProducer_F sequenceProducer +); + +/*! ZSTD_CCtxParams_registerSequenceProducer() : + * Same as ZSTD_registerSequenceProducer(), but operates on ZSTD_CCtx_params. + * This is used for accurate size estimation with ZSTD_estimateCCtxSize_usingCCtxParams(), + * which is needed when creating a ZSTD_CCtx with ZSTD_initStaticCCtx(). + * + * If you are using the external sequence producer API in a scenario where ZSTD_initStaticCCtx() + * is required, then this function is for you. Otherwise, you probably don't need it. + * + * See tests/zstreamtest.c for example usage. */ +ZSTDLIB_STATIC_API void +ZSTD_CCtxParams_registerSequenceProducer( + ZSTD_CCtx_params* params, + void* sequenceProducerState, + ZSTD_sequenceProducer_F sequenceProducer +); + + +/********************************************************************* +* Buffer-less and synchronous inner streaming functions (DEPRECATED) +* +* This API is deprecated, and will be removed in a future version. +* It allows streaming (de)compression with user allocated buffers. +* However, it is hard to use, and not as well tested as the rest of +* our API. +* +* Please use the normal streaming API instead: ZSTD_compressStream2, +* and ZSTD_decompressStream. +* If there is functionality that you need, but it doesn't provide, +* please open an issue on our GitHub. +********************************************************************* */ + +/** + Buffer-less streaming compression (synchronous mode) + + A ZSTD_CCtx object is required to track streaming operations. + Use ZSTD_createCCtx() / ZSTD_freeCCtx() to manage resource. + ZSTD_CCtx object can be reused multiple times within successive compression operations. + + Start by initializing a context. + Use ZSTD_compressBegin(), or ZSTD_compressBegin_usingDict() for dictionary compression. + + Then, consume your input using ZSTD_compressContinue(). + There are some important considerations to keep in mind when using this advanced function : + - ZSTD_compressContinue() has no internal buffer. It uses externally provided buffers only. + - Interface is synchronous : input is consumed entirely and produces 1+ compressed blocks. + - Caller must ensure there is enough space in `dst` to store compressed data under worst case scenario. + Worst case evaluation is provided by ZSTD_compressBound(). + ZSTD_compressContinue() doesn't guarantee recover after a failed compression. + - ZSTD_compressContinue() presumes prior input ***is still accessible and unmodified*** (up to maximum distance size, see WindowLog). + It remembers all previous contiguous blocks, plus one separated memory segment (which can itself consists of multiple contiguous blocks) + - ZSTD_compressContinue() detects that prior input has been overwritten when `src` buffer overlaps. + In which case, it will "discard" the relevant memory section from its history. + + Finish a frame with ZSTD_compressEnd(), which will write the last block(s) and optional checksum. + It's possible to use srcSize==0, in which case, it will write a final empty block to end the frame. + Without last block mark, frames are considered unfinished (hence corrupted) by compliant decoders. + + `ZSTD_CCtx` object can be reused (ZSTD_compressBegin()) to compress again. +*/ + +/*===== Buffer-less streaming compression functions =====*/ +ZSTD_DEPRECATED("The buffer-less API is deprecated in favor of the normal streaming API. See docs.") +ZSTDLIB_STATIC_API size_t ZSTD_compressBegin(ZSTD_CCtx* cctx, int compressionLevel); +ZSTD_DEPRECATED("The buffer-less API is deprecated in favor of the normal streaming API. See docs.") +ZSTDLIB_STATIC_API size_t ZSTD_compressBegin_usingDict(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel); +ZSTD_DEPRECATED("The buffer-less API is deprecated in favor of the normal streaming API. See docs.") +ZSTDLIB_STATIC_API size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict); /**< note: fails if cdict==NULL */ + +ZSTD_DEPRECATED("This function will likely be removed in a future release. It is misleading and has very limited utility.") +ZSTDLIB_STATIC_API +size_t ZSTD_copyCCtx(ZSTD_CCtx* cctx, const ZSTD_CCtx* preparedCCtx, unsigned long long pledgedSrcSize); /**< note: if pledgedSrcSize is not known, use ZSTD_CONTENTSIZE_UNKNOWN */ + +ZSTD_DEPRECATED("The buffer-less API is deprecated in favor of the normal streaming API. See docs.") +ZSTDLIB_STATIC_API size_t ZSTD_compressContinue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); +ZSTD_DEPRECATED("The buffer-less API is deprecated in favor of the normal streaming API. See docs.") +ZSTDLIB_STATIC_API size_t ZSTD_compressEnd(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); + +/* The ZSTD_compressBegin_advanced() and ZSTD_compressBegin_usingCDict_advanced() are now DEPRECATED and will generate a compiler warning */ +ZSTD_DEPRECATED("use advanced API to access custom parameters") +ZSTDLIB_STATIC_API +size_t ZSTD_compressBegin_advanced(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, ZSTD_parameters params, unsigned long long pledgedSrcSize); /**< pledgedSrcSize : If srcSize is not known at init time, use ZSTD_CONTENTSIZE_UNKNOWN */ +ZSTD_DEPRECATED("use advanced API to access custom parameters") +ZSTDLIB_STATIC_API +size_t ZSTD_compressBegin_usingCDict_advanced(ZSTD_CCtx* const cctx, const ZSTD_CDict* const cdict, ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize); /* compression parameters are already set within cdict. pledgedSrcSize must be correct. If srcSize is not known, use macro ZSTD_CONTENTSIZE_UNKNOWN */ +/** + Buffer-less streaming decompression (synchronous mode) + + A ZSTD_DCtx object is required to track streaming operations. + Use ZSTD_createDCtx() / ZSTD_freeDCtx() to manage it. + A ZSTD_DCtx object can be reused multiple times. + + First typical operation is to retrieve frame parameters, using ZSTD_getFrameHeader(). + Frame header is extracted from the beginning of compressed frame, so providing only the frame's beginning is enough. + Data fragment must be large enough to ensure successful decoding. + `ZSTD_frameHeaderSize_max` bytes is guaranteed to always be large enough. + result : 0 : successful decoding, the `ZSTD_frameHeader` structure is correctly filled. + >0 : `srcSize` is too small, please provide at least result bytes on next attempt. + errorCode, which can be tested using ZSTD_isError(). + + It fills a ZSTD_FrameHeader structure with important information to correctly decode the frame, + such as the dictionary ID, content size, or maximum back-reference distance (`windowSize`). + Note that these values could be wrong, either because of data corruption, or because a 3rd party deliberately spoofs false information. + As a consequence, check that values remain within valid application range. + For example, do not allocate memory blindly, check that `windowSize` is within expectation. + Each application can set its own limits, depending on local restrictions. + For extended interoperability, it is recommended to support `windowSize` of at least 8 MB. + + ZSTD_decompressContinue() needs previous data blocks during decompression, up to `windowSize` bytes. + ZSTD_decompressContinue() is very sensitive to contiguity, + if 2 blocks don't follow each other, make sure that either the compressor breaks contiguity at the same place, + or that previous contiguous segment is large enough to properly handle maximum back-reference distance. + There are multiple ways to guarantee this condition. + + The most memory efficient way is to use a round buffer of sufficient size. + Sufficient size is determined by invoking ZSTD_decodingBufferSize_min(), + which can return an error code if required value is too large for current system (in 32-bits mode). + In a round buffer methodology, ZSTD_decompressContinue() decompresses each block next to previous one, + up to the moment there is not enough room left in the buffer to guarantee decoding another full block, + which maximum size is provided in `ZSTD_frameHeader` structure, field `blockSizeMax`. + At which point, decoding can resume from the beginning of the buffer. + Note that already decoded data stored in the buffer should be flushed before being overwritten. + + There are alternatives possible, for example using two or more buffers of size `windowSize` each, though they consume more memory. + + Finally, if you control the compression process, you can also ignore all buffer size rules, + as long as the encoder and decoder progress in "lock-step", + aka use exactly the same buffer sizes, break contiguity at the same place, etc. + + Once buffers are setup, start decompression, with ZSTD_decompressBegin(). + If decompression requires a dictionary, use ZSTD_decompressBegin_usingDict() or ZSTD_decompressBegin_usingDDict(). + + Then use ZSTD_nextSrcSizeToDecompress() and ZSTD_decompressContinue() alternatively. + ZSTD_nextSrcSizeToDecompress() tells how many bytes to provide as 'srcSize' to ZSTD_decompressContinue(). + ZSTD_decompressContinue() requires this _exact_ amount of bytes, or it will fail. + + result of ZSTD_decompressContinue() is the number of bytes regenerated within 'dst' (necessarily <= dstCapacity). + It can be zero : it just means ZSTD_decompressContinue() has decoded some metadata item. + It can also be an error code, which can be tested with ZSTD_isError(). + + A frame is fully decoded when ZSTD_nextSrcSizeToDecompress() returns zero. + Context can then be reset to start a new decompression. + + Note : it's possible to know if next input to present is a header or a block, using ZSTD_nextInputType(). + This information is not required to properly decode a frame. + + == Special case : skippable frames == + + Skippable frames allow integration of user-defined data into a flow of concatenated frames. + Skippable frames will be ignored (skipped) by decompressor. + The format of skippable frames is as follows : + a) Skippable frame ID - 4 Bytes, Little endian format, any value from 0x184D2A50 to 0x184D2A5F + b) Frame Size - 4 Bytes, Little endian format, unsigned 32-bits + c) Frame Content - any content (User Data) of length equal to Frame Size + For skippable frames ZSTD_getFrameHeader() returns zfhPtr->frameType==ZSTD_skippableFrame. + For skippable frames ZSTD_decompressContinue() always returns 0 : it only skips the content. +*/ + +/*===== Buffer-less streaming decompression functions =====*/ + +ZSTDLIB_STATIC_API size_t ZSTD_decodingBufferSize_min(unsigned long long windowSize, unsigned long long frameContentSize); /**< when frame content size is not known, pass in frameContentSize == ZSTD_CONTENTSIZE_UNKNOWN */ + +ZSTDLIB_STATIC_API size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx); +ZSTDLIB_STATIC_API size_t ZSTD_decompressBegin_usingDict(ZSTD_DCtx* dctx, const void* dict, size_t dictSize); +ZSTDLIB_STATIC_API size_t ZSTD_decompressBegin_usingDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict); + +ZSTDLIB_STATIC_API size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx); +ZSTDLIB_STATIC_API size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); + +/* misc */ +ZSTD_DEPRECATED("This function will likely be removed in the next minor release. It is misleading and has very limited utility.") +ZSTDLIB_STATIC_API void ZSTD_copyDCtx(ZSTD_DCtx* dctx, const ZSTD_DCtx* preparedDCtx); +typedef enum { ZSTDnit_frameHeader, ZSTDnit_blockHeader, ZSTDnit_block, ZSTDnit_lastBlock, ZSTDnit_checksum, ZSTDnit_skippableFrame } ZSTD_nextInputType_e; +ZSTDLIB_STATIC_API ZSTD_nextInputType_e ZSTD_nextInputType(ZSTD_DCtx* dctx); + + + + +/* ========================================= */ +/** Block level API (DEPRECATED) */ +/* ========================================= */ + +/*! + + This API is deprecated in favor of the regular compression API. + You can get the frame header down to 2 bytes by setting: + - ZSTD_c_format = ZSTD_f_zstd1_magicless + - ZSTD_c_contentSizeFlag = 0 + - ZSTD_c_checksumFlag = 0 + - ZSTD_c_dictIDFlag = 0 + + This API is not as well tested as our normal API, so we recommend not using it. + We will be removing it in a future version. If the normal API doesn't provide + the functionality you need, please open a GitHub issue. + + Block functions produce and decode raw zstd blocks, without frame metadata. + Frame metadata cost is typically ~12 bytes, which can be non-negligible for very small blocks (< 100 bytes). + But users will have to take in charge needed metadata to regenerate data, such as compressed and content sizes. + + A few rules to respect : + - Compressing and decompressing require a context structure + + Use ZSTD_createCCtx() and ZSTD_createDCtx() + - It is necessary to init context before starting + + compression : any ZSTD_compressBegin*() variant, including with dictionary + + decompression : any ZSTD_decompressBegin*() variant, including with dictionary + - Block size is limited, it must be <= ZSTD_getBlockSize() <= ZSTD_BLOCKSIZE_MAX == 128 KB + + If input is larger than a block size, it's necessary to split input data into multiple blocks + + For inputs larger than a single block, consider using regular ZSTD_compress() instead. + Frame metadata is not that costly, and quickly becomes negligible as source size grows larger than a block. + - When a block is considered not compressible enough, ZSTD_compressBlock() result will be 0 (zero) ! + ===> In which case, nothing is produced into `dst` ! + + User __must__ test for such outcome and deal directly with uncompressed data + + A block cannot be declared incompressible if ZSTD_compressBlock() return value was != 0. + Doing so would mess up with statistics history, leading to potential data corruption. + + ZSTD_decompressBlock() _doesn't accept uncompressed data as input_ !! + + In case of multiple successive blocks, should some of them be uncompressed, + decoder must be informed of their existence in order to follow proper history. + Use ZSTD_insertBlock() for such a case. +*/ + +/*===== Raw zstd block functions =====*/ +ZSTD_DEPRECATED("The block API is deprecated in favor of the normal compression API. See docs.") +ZSTDLIB_STATIC_API size_t ZSTD_getBlockSize (const ZSTD_CCtx* cctx); +ZSTD_DEPRECATED("The block API is deprecated in favor of the normal compression API. See docs.") +ZSTDLIB_STATIC_API size_t ZSTD_compressBlock (ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); +ZSTD_DEPRECATED("The block API is deprecated in favor of the normal compression API. See docs.") +ZSTDLIB_STATIC_API size_t ZSTD_decompressBlock(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); +ZSTD_DEPRECATED("The block API is deprecated in favor of the normal compression API. See docs.") +ZSTDLIB_STATIC_API size_t ZSTD_insertBlock (ZSTD_DCtx* dctx, const void* blockStart, size_t blockSize); /**< insert uncompressed block into `dctx` history. Useful for multi-blocks decompression. */ + +#if defined (__cplusplus) +} +#endif + +#endif /* ZSTD_H_ZSTD_STATIC_LINKING_ONLY */ +/**** ended inlining ../zstd.h ****/ +#define FSE_STATIC_LINKING_ONLY +/**** skipping file: fse.h ****/ +/**** skipping file: huf.h ****/ +#ifndef XXH_STATIC_LINKING_ONLY +# define XXH_STATIC_LINKING_ONLY /* XXH64_state_t */ +#endif +/**** start inlining xxhash.h ****/ +/* + * xxHash - Extremely Fast Hash algorithm + * Header File + * Copyright (c) Yann Collet - Meta Platforms, Inc + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +/* Local adaptations for Zstandard */ + +#ifndef XXH_NO_XXH3 +# define XXH_NO_XXH3 +#endif + +#ifndef XXH_NAMESPACE +# define XXH_NAMESPACE ZSTD_ +#endif + +/*! + * @mainpage xxHash + * + * xxHash is an extremely fast non-cryptographic hash algorithm, working at RAM speed + * limits. + * + * It is proposed in four flavors, in three families: + * 1. @ref XXH32_family + * - Classic 32-bit hash function. Simple, compact, and runs on almost all + * 32-bit and 64-bit systems. + * 2. @ref XXH64_family + * - Classic 64-bit adaptation of XXH32. Just as simple, and runs well on most + * 64-bit systems (but _not_ 32-bit systems). + * 3. @ref XXH3_family + * - Modern 64-bit and 128-bit hash function family which features improved + * strength and performance across the board, especially on smaller data. + * It benefits greatly from SIMD and 64-bit without requiring it. + * + * Benchmarks + * --- + * The reference system uses an Intel i7-9700K CPU, and runs Ubuntu x64 20.04. + * The open source benchmark program is compiled with clang v10.0 using -O3 flag. + * + * | Hash Name | ISA ext | Width | Large Data Speed | Small Data Velocity | + * | -------------------- | ------- | ----: | ---------------: | ------------------: | + * | XXH3_64bits() | @b AVX2 | 64 | 59.4 GB/s | 133.1 | + * | MeowHash | AES-NI | 128 | 58.2 GB/s | 52.5 | + * | XXH3_128bits() | @b AVX2 | 128 | 57.9 GB/s | 118.1 | + * | CLHash | PCLMUL | 64 | 37.1 GB/s | 58.1 | + * | XXH3_64bits() | @b SSE2 | 64 | 31.5 GB/s | 133.1 | + * | XXH3_128bits() | @b SSE2 | 128 | 29.6 GB/s | 118.1 | + * | RAM sequential read | | N/A | 28.0 GB/s | N/A | + * | ahash | AES-NI | 64 | 22.5 GB/s | 107.2 | + * | City64 | | 64 | 22.0 GB/s | 76.6 | + * | T1ha2 | | 64 | 22.0 GB/s | 99.0 | + * | City128 | | 128 | 21.7 GB/s | 57.7 | + * | FarmHash | AES-NI | 64 | 21.3 GB/s | 71.9 | + * | XXH64() | | 64 | 19.4 GB/s | 71.0 | + * | SpookyHash | | 64 | 19.3 GB/s | 53.2 | + * | Mum | | 64 | 18.0 GB/s | 67.0 | + * | CRC32C | SSE4.2 | 32 | 13.0 GB/s | 57.9 | + * | XXH32() | | 32 | 9.7 GB/s | 71.9 | + * | City32 | | 32 | 9.1 GB/s | 66.0 | + * | Blake3* | @b AVX2 | 256 | 4.4 GB/s | 8.1 | + * | Murmur3 | | 32 | 3.9 GB/s | 56.1 | + * | SipHash* | | 64 | 3.0 GB/s | 43.2 | + * | Blake3* | @b SSE2 | 256 | 2.4 GB/s | 8.1 | + * | HighwayHash | | 64 | 1.4 GB/s | 6.0 | + * | FNV64 | | 64 | 1.2 GB/s | 62.7 | + * | Blake2* | | 256 | 1.1 GB/s | 5.1 | + * | SHA1* | | 160 | 0.8 GB/s | 5.6 | + * | MD5* | | 128 | 0.6 GB/s | 7.8 | + * @note + * - Hashes which require a specific ISA extension are noted. SSE2 is also noted, + * even though it is mandatory on x64. + * - Hashes with an asterisk are cryptographic. Note that MD5 is non-cryptographic + * by modern standards. + * - Small data velocity is a rough average of algorithm's efficiency for small + * data. For more accurate information, see the wiki. + * - More benchmarks and strength tests are found on the wiki: + * https://github.com/Cyan4973/xxHash/wiki + * + * Usage + * ------ + * All xxHash variants use a similar API. Changing the algorithm is a trivial + * substitution. + * + * @pre + * For functions which take an input and length parameter, the following + * requirements are assumed: + * - The range from [`input`, `input + length`) is valid, readable memory. + * - The only exception is if the `length` is `0`, `input` may be `NULL`. + * - For C++, the objects must have the *TriviallyCopyable* property, as the + * functions access bytes directly as if it was an array of `unsigned char`. + * + * @anchor single_shot_example + * **Single Shot** + * + * These functions are stateless functions which hash a contiguous block of memory, + * immediately returning the result. They are the easiest and usually the fastest + * option. + * + * XXH32(), XXH64(), XXH3_64bits(), XXH3_128bits() + * + * @code{.c} + * #include + * #include "xxhash.h" + * + * // Example for a function which hashes a null terminated string with XXH32(). + * XXH32_hash_t hash_string(const char* string, XXH32_hash_t seed) + * { + * // NULL pointers are only valid if the length is zero + * size_t length = (string == NULL) ? 0 : strlen(string); + * return XXH32(string, length, seed); + * } + * @endcode + * + * + * @anchor streaming_example + * **Streaming** + * + * These groups of functions allow incremental hashing of unknown size, even + * more than what would fit in a size_t. + * + * XXH32_reset(), XXH64_reset(), XXH3_64bits_reset(), XXH3_128bits_reset() + * + * @code{.c} + * #include + * #include + * #include "xxhash.h" + * // Example for a function which hashes a FILE incrementally with XXH3_64bits(). + * XXH64_hash_t hashFile(FILE* f) + * { + * // Allocate a state struct. Do not just use malloc() or new. + * XXH3_state_t* state = XXH3_createState(); + * assert(state != NULL && "Out of memory!"); + * // Reset the state to start a new hashing session. + * XXH3_64bits_reset(state); + * char buffer[4096]; + * size_t count; + * // Read the file in chunks + * while ((count = fread(buffer, 1, sizeof(buffer), f)) != 0) { + * // Run update() as many times as necessary to process the data + * XXH3_64bits_update(state, buffer, count); + * } + * // Retrieve the finalized hash. This will not change the state. + * XXH64_hash_t result = XXH3_64bits_digest(state); + * // Free the state. Do not use free(). + * XXH3_freeState(state); + * return result; + * } + * @endcode + * + * Streaming functions generate the xxHash value from an incremental input. + * This method is slower than single-call functions, due to state management. + * For small inputs, prefer `XXH32()` and `XXH64()`, which are better optimized. + * + * An XXH state must first be allocated using `XXH*_createState()`. + * + * Start a new hash by initializing the state with a seed using `XXH*_reset()`. + * + * Then, feed the hash state by calling `XXH*_update()` as many times as necessary. + * + * The function returns an error code, with 0 meaning OK, and any other value + * meaning there is an error. + * + * Finally, a hash value can be produced anytime, by using `XXH*_digest()`. + * This function returns the nn-bits hash as an int or long long. + * + * It's still possible to continue inserting input into the hash state after a + * digest, and generate new hash values later on by invoking `XXH*_digest()`. + * + * When done, release the state using `XXH*_freeState()`. + * + * + * @anchor canonical_representation_example + * **Canonical Representation** + * + * The default return values from XXH functions are unsigned 32, 64 and 128 bit + * integers. + * This the simplest and fastest format for further post-processing. + * + * However, this leaves open the question of what is the order on the byte level, + * since little and big endian conventions will store the same number differently. + * + * The canonical representation settles this issue by mandating big-endian + * convention, the same convention as human-readable numbers (large digits first). + * + * When writing hash values to storage, sending them over a network, or printing + * them, it's highly recommended to use the canonical representation to ensure + * portability across a wider range of systems, present and future. + * + * The following functions allow transformation of hash values to and from + * canonical format. + * + * XXH32_canonicalFromHash(), XXH32_hashFromCanonical(), + * XXH64_canonicalFromHash(), XXH64_hashFromCanonical(), + * XXH128_canonicalFromHash(), XXH128_hashFromCanonical(), + * + * @code{.c} + * #include + * #include "xxhash.h" + * + * // Example for a function which prints XXH32_hash_t in human readable format + * void printXxh32(XXH32_hash_t hash) + * { + * XXH32_canonical_t cano; + * XXH32_canonicalFromHash(&cano, hash); + * size_t i; + * for(i = 0; i < sizeof(cano.digest); ++i) { + * printf("%02x", cano.digest[i]); + * } + * printf("\n"); + * } + * + * // Example for a function which converts XXH32_canonical_t to XXH32_hash_t + * XXH32_hash_t convertCanonicalToXxh32(XXH32_canonical_t cano) + * { + * XXH32_hash_t hash = XXH32_hashFromCanonical(&cano); + * return hash; + * } + * @endcode + * + * + * @file xxhash.h + * xxHash prototypes and implementation + */ + +/* **************************** + * INLINE mode + ******************************/ +/*! + * @defgroup public Public API + * Contains details on the public xxHash functions. + * @{ + */ +#ifdef XXH_DOXYGEN +/*! + * @brief Gives access to internal state declaration, required for static allocation. + * + * Incompatible with dynamic linking, due to risks of ABI changes. + * + * Usage: + * @code{.c} + * #define XXH_STATIC_LINKING_ONLY + * #include "xxhash.h" + * @endcode + */ +# define XXH_STATIC_LINKING_ONLY +/* Do not undef XXH_STATIC_LINKING_ONLY for Doxygen */ + +/*! + * @brief Gives access to internal definitions. + * + * Usage: + * @code{.c} + * #define XXH_STATIC_LINKING_ONLY + * #define XXH_IMPLEMENTATION + * #include "xxhash.h" + * @endcode + */ +# define XXH_IMPLEMENTATION +/* Do not undef XXH_IMPLEMENTATION for Doxygen */ + +/*! + * @brief Exposes the implementation and marks all functions as `inline`. + * + * Use these build macros to inline xxhash into the target unit. + * Inlining improves performance on small inputs, especially when the length is + * expressed as a compile-time constant: + * + * https://fastcompression.blogspot.com/2018/03/xxhash-for-small-keys-impressive-power.html + * + * It also keeps xxHash symbols private to the unit, so they are not exported. + * + * Usage: + * @code{.c} + * #define XXH_INLINE_ALL + * #include "xxhash.h" + * @endcode + * Do not compile and link xxhash.o as a separate object, as it is not useful. + */ +# define XXH_INLINE_ALL +# undef XXH_INLINE_ALL +/*! + * @brief Exposes the implementation without marking functions as inline. + */ +# define XXH_PRIVATE_API +# undef XXH_PRIVATE_API +/*! + * @brief Emulate a namespace by transparently prefixing all symbols. + * + * If you want to include _and expose_ xxHash functions from within your own + * library, but also want to avoid symbol collisions with other libraries which + * may also include xxHash, you can use @ref XXH_NAMESPACE to automatically prefix + * any public symbol from xxhash library with the value of @ref XXH_NAMESPACE + * (therefore, avoid empty or numeric values). + * + * Note that no change is required within the calling program as long as it + * includes `xxhash.h`: Regular symbol names will be automatically translated + * by this header. + */ +# define XXH_NAMESPACE /* YOUR NAME HERE */ +# undef XXH_NAMESPACE +#endif + +#if (defined(XXH_INLINE_ALL) || defined(XXH_PRIVATE_API)) \ + && !defined(XXH_INLINE_ALL_31684351384) + /* this section should be traversed only once */ +# define XXH_INLINE_ALL_31684351384 + /* give access to the advanced API, required to compile implementations */ +# undef XXH_STATIC_LINKING_ONLY /* avoid macro redef */ +# define XXH_STATIC_LINKING_ONLY + /* make all functions private */ +# undef XXH_PUBLIC_API +# if defined(__GNUC__) +# define XXH_PUBLIC_API static __inline __attribute__((unused)) +# elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) +# define XXH_PUBLIC_API static inline +# elif defined(_MSC_VER) +# define XXH_PUBLIC_API static __inline +# else + /* note: this version may generate warnings for unused static functions */ +# define XXH_PUBLIC_API static +# endif + + /* + * This part deals with the special case where a unit wants to inline xxHash, + * but "xxhash.h" has previously been included without XXH_INLINE_ALL, + * such as part of some previously included *.h header file. + * Without further action, the new include would just be ignored, + * and functions would effectively _not_ be inlined (silent failure). + * The following macros solve this situation by prefixing all inlined names, + * avoiding naming collision with previous inclusions. + */ + /* Before that, we unconditionally #undef all symbols, + * in case they were already defined with XXH_NAMESPACE. + * They will then be redefined for XXH_INLINE_ALL + */ +# undef XXH_versionNumber + /* XXH32 */ +# undef XXH32 +# undef XXH32_createState +# undef XXH32_freeState +# undef XXH32_reset +# undef XXH32_update +# undef XXH32_digest +# undef XXH32_copyState +# undef XXH32_canonicalFromHash +# undef XXH32_hashFromCanonical + /* XXH64 */ +# undef XXH64 +# undef XXH64_createState +# undef XXH64_freeState +# undef XXH64_reset +# undef XXH64_update +# undef XXH64_digest +# undef XXH64_copyState +# undef XXH64_canonicalFromHash +# undef XXH64_hashFromCanonical + /* XXH3_64bits */ +# undef XXH3_64bits +# undef XXH3_64bits_withSecret +# undef XXH3_64bits_withSeed +# undef XXH3_64bits_withSecretandSeed +# undef XXH3_createState +# undef XXH3_freeState +# undef XXH3_copyState +# undef XXH3_64bits_reset +# undef XXH3_64bits_reset_withSeed +# undef XXH3_64bits_reset_withSecret +# undef XXH3_64bits_update +# undef XXH3_64bits_digest +# undef XXH3_generateSecret + /* XXH3_128bits */ +# undef XXH128 +# undef XXH3_128bits +# undef XXH3_128bits_withSeed +# undef XXH3_128bits_withSecret +# undef XXH3_128bits_reset +# undef XXH3_128bits_reset_withSeed +# undef XXH3_128bits_reset_withSecret +# undef XXH3_128bits_reset_withSecretandSeed +# undef XXH3_128bits_update +# undef XXH3_128bits_digest +# undef XXH128_isEqual +# undef XXH128_cmp +# undef XXH128_canonicalFromHash +# undef XXH128_hashFromCanonical + /* Finally, free the namespace itself */ +# undef XXH_NAMESPACE + + /* employ the namespace for XXH_INLINE_ALL */ +# define XXH_NAMESPACE XXH_INLINE_ + /* + * Some identifiers (enums, type names) are not symbols, + * but they must nonetheless be renamed to avoid redeclaration. + * Alternative solution: do not redeclare them. + * However, this requires some #ifdefs, and has a more dispersed impact. + * Meanwhile, renaming can be achieved in a single place. + */ +# define XXH_IPREF(Id) XXH_NAMESPACE ## Id +# define XXH_OK XXH_IPREF(XXH_OK) +# define XXH_ERROR XXH_IPREF(XXH_ERROR) +# define XXH_errorcode XXH_IPREF(XXH_errorcode) +# define XXH32_canonical_t XXH_IPREF(XXH32_canonical_t) +# define XXH64_canonical_t XXH_IPREF(XXH64_canonical_t) +# define XXH128_canonical_t XXH_IPREF(XXH128_canonical_t) +# define XXH32_state_s XXH_IPREF(XXH32_state_s) +# define XXH32_state_t XXH_IPREF(XXH32_state_t) +# define XXH64_state_s XXH_IPREF(XXH64_state_s) +# define XXH64_state_t XXH_IPREF(XXH64_state_t) +# define XXH3_state_s XXH_IPREF(XXH3_state_s) +# define XXH3_state_t XXH_IPREF(XXH3_state_t) +# define XXH128_hash_t XXH_IPREF(XXH128_hash_t) + /* Ensure the header is parsed again, even if it was previously included */ +# undef XXHASH_H_5627135585666179 +# undef XXHASH_H_STATIC_13879238742 +#endif /* XXH_INLINE_ALL || XXH_PRIVATE_API */ + +/* **************************************************************** + * Stable API + *****************************************************************/ +#ifndef XXHASH_H_5627135585666179 +#define XXHASH_H_5627135585666179 1 + +/*! @brief Marks a global symbol. */ +#if !defined(XXH_INLINE_ALL) && !defined(XXH_PRIVATE_API) +# if defined(WIN32) && defined(_MSC_VER) && (defined(XXH_IMPORT) || defined(XXH_EXPORT)) +# ifdef XXH_EXPORT +# define XXH_PUBLIC_API __declspec(dllexport) +# elif XXH_IMPORT +# define XXH_PUBLIC_API __declspec(dllimport) +# endif +# else +# define XXH_PUBLIC_API /* do nothing */ +# endif +#endif + +#ifdef XXH_NAMESPACE +# define XXH_CAT(A,B) A##B +# define XXH_NAME2(A,B) XXH_CAT(A,B) +# define XXH_versionNumber XXH_NAME2(XXH_NAMESPACE, XXH_versionNumber) +/* XXH32 */ +# define XXH32 XXH_NAME2(XXH_NAMESPACE, XXH32) +# define XXH32_createState XXH_NAME2(XXH_NAMESPACE, XXH32_createState) +# define XXH32_freeState XXH_NAME2(XXH_NAMESPACE, XXH32_freeState) +# define XXH32_reset XXH_NAME2(XXH_NAMESPACE, XXH32_reset) +# define XXH32_update XXH_NAME2(XXH_NAMESPACE, XXH32_update) +# define XXH32_digest XXH_NAME2(XXH_NAMESPACE, XXH32_digest) +# define XXH32_copyState XXH_NAME2(XXH_NAMESPACE, XXH32_copyState) +# define XXH32_canonicalFromHash XXH_NAME2(XXH_NAMESPACE, XXH32_canonicalFromHash) +# define XXH32_hashFromCanonical XXH_NAME2(XXH_NAMESPACE, XXH32_hashFromCanonical) +/* XXH64 */ +# define XXH64 XXH_NAME2(XXH_NAMESPACE, XXH64) +# define XXH64_createState XXH_NAME2(XXH_NAMESPACE, XXH64_createState) +# define XXH64_freeState XXH_NAME2(XXH_NAMESPACE, XXH64_freeState) +# define XXH64_reset XXH_NAME2(XXH_NAMESPACE, XXH64_reset) +# define XXH64_update XXH_NAME2(XXH_NAMESPACE, XXH64_update) +# define XXH64_digest XXH_NAME2(XXH_NAMESPACE, XXH64_digest) +# define XXH64_copyState XXH_NAME2(XXH_NAMESPACE, XXH64_copyState) +# define XXH64_canonicalFromHash XXH_NAME2(XXH_NAMESPACE, XXH64_canonicalFromHash) +# define XXH64_hashFromCanonical XXH_NAME2(XXH_NAMESPACE, XXH64_hashFromCanonical) +/* XXH3_64bits */ +# define XXH3_64bits XXH_NAME2(XXH_NAMESPACE, XXH3_64bits) +# define XXH3_64bits_withSecret XXH_NAME2(XXH_NAMESPACE, XXH3_64bits_withSecret) +# define XXH3_64bits_withSeed XXH_NAME2(XXH_NAMESPACE, XXH3_64bits_withSeed) +# define XXH3_64bits_withSecretandSeed XXH_NAME2(XXH_NAMESPACE, XXH3_64bits_withSecretandSeed) +# define XXH3_createState XXH_NAME2(XXH_NAMESPACE, XXH3_createState) +# define XXH3_freeState XXH_NAME2(XXH_NAMESPACE, XXH3_freeState) +# define XXH3_copyState XXH_NAME2(XXH_NAMESPACE, XXH3_copyState) +# define XXH3_64bits_reset XXH_NAME2(XXH_NAMESPACE, XXH3_64bits_reset) +# define XXH3_64bits_reset_withSeed XXH_NAME2(XXH_NAMESPACE, XXH3_64bits_reset_withSeed) +# define XXH3_64bits_reset_withSecret XXH_NAME2(XXH_NAMESPACE, XXH3_64bits_reset_withSecret) +# define XXH3_64bits_reset_withSecretandSeed XXH_NAME2(XXH_NAMESPACE, XXH3_64bits_reset_withSecretandSeed) +# define XXH3_64bits_update XXH_NAME2(XXH_NAMESPACE, XXH3_64bits_update) +# define XXH3_64bits_digest XXH_NAME2(XXH_NAMESPACE, XXH3_64bits_digest) +# define XXH3_generateSecret XXH_NAME2(XXH_NAMESPACE, XXH3_generateSecret) +# define XXH3_generateSecret_fromSeed XXH_NAME2(XXH_NAMESPACE, XXH3_generateSecret_fromSeed) +/* XXH3_128bits */ +# define XXH128 XXH_NAME2(XXH_NAMESPACE, XXH128) +# define XXH3_128bits XXH_NAME2(XXH_NAMESPACE, XXH3_128bits) +# define XXH3_128bits_withSeed XXH_NAME2(XXH_NAMESPACE, XXH3_128bits_withSeed) +# define XXH3_128bits_withSecret XXH_NAME2(XXH_NAMESPACE, XXH3_128bits_withSecret) +# define XXH3_128bits_withSecretandSeed XXH_NAME2(XXH_NAMESPACE, XXH3_128bits_withSecretandSeed) +# define XXH3_128bits_reset XXH_NAME2(XXH_NAMESPACE, XXH3_128bits_reset) +# define XXH3_128bits_reset_withSeed XXH_NAME2(XXH_NAMESPACE, XXH3_128bits_reset_withSeed) +# define XXH3_128bits_reset_withSecret XXH_NAME2(XXH_NAMESPACE, XXH3_128bits_reset_withSecret) +# define XXH3_128bits_reset_withSecretandSeed XXH_NAME2(XXH_NAMESPACE, XXH3_128bits_reset_withSecretandSeed) +# define XXH3_128bits_update XXH_NAME2(XXH_NAMESPACE, XXH3_128bits_update) +# define XXH3_128bits_digest XXH_NAME2(XXH_NAMESPACE, XXH3_128bits_digest) +# define XXH128_isEqual XXH_NAME2(XXH_NAMESPACE, XXH128_isEqual) +# define XXH128_cmp XXH_NAME2(XXH_NAMESPACE, XXH128_cmp) +# define XXH128_canonicalFromHash XXH_NAME2(XXH_NAMESPACE, XXH128_canonicalFromHash) +# define XXH128_hashFromCanonical XXH_NAME2(XXH_NAMESPACE, XXH128_hashFromCanonical) +#endif + + +/* ************************************* +* Compiler specifics +***************************************/ + +/* specific declaration modes for Windows */ +#if !defined(XXH_INLINE_ALL) && !defined(XXH_PRIVATE_API) +# if defined(WIN32) && defined(_MSC_VER) && (defined(XXH_IMPORT) || defined(XXH_EXPORT)) +# ifdef XXH_EXPORT +# define XXH_PUBLIC_API __declspec(dllexport) +# elif XXH_IMPORT +# define XXH_PUBLIC_API __declspec(dllimport) +# endif +# else +# define XXH_PUBLIC_API /* do nothing */ +# endif +#endif + +#if defined (__GNUC__) +# define XXH_CONSTF __attribute__((const)) +# define XXH_PUREF __attribute__((pure)) +# define XXH_MALLOCF __attribute__((malloc)) +#else +# define XXH_CONSTF /* disable */ +# define XXH_PUREF +# define XXH_MALLOCF +#endif + +/* ************************************* +* Version +***************************************/ +#define XXH_VERSION_MAJOR 0 +#define XXH_VERSION_MINOR 8 +#define XXH_VERSION_RELEASE 2 +/*! @brief Version number, encoded as two digits each */ +#define XXH_VERSION_NUMBER (XXH_VERSION_MAJOR *100*100 + XXH_VERSION_MINOR *100 + XXH_VERSION_RELEASE) + +#if defined (__cplusplus) +extern "C" { +#endif +/*! + * @brief Obtains the xxHash version. + * + * This is mostly useful when xxHash is compiled as a shared library, + * since the returned value comes from the library, as opposed to header file. + * + * @return @ref XXH_VERSION_NUMBER of the invoked library. + */ +XXH_PUBLIC_API XXH_CONSTF unsigned XXH_versionNumber (void); + +#if defined (__cplusplus) +} +#endif + +/* **************************** +* Common basic types +******************************/ +#include /* size_t */ +/*! + * @brief Exit code for the streaming API. + */ +typedef enum { + XXH_OK = 0, /*!< OK */ + XXH_ERROR /*!< Error */ +} XXH_errorcode; + + +/*-********************************************************************** +* 32-bit hash +************************************************************************/ +#if defined(XXH_DOXYGEN) /* Don't show include */ +/*! + * @brief An unsigned 32-bit integer. + * + * Not necessarily defined to `uint32_t` but functionally equivalent. + */ +typedef uint32_t XXH32_hash_t; + +#elif !defined (__VMS) \ + && (defined (__cplusplus) \ + || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) ) +# ifdef _AIX +# include +# else +# include +# endif + typedef uint32_t XXH32_hash_t; + +#else +# include +# if UINT_MAX == 0xFFFFFFFFUL + typedef unsigned int XXH32_hash_t; +# elif ULONG_MAX == 0xFFFFFFFFUL + typedef unsigned long XXH32_hash_t; +# else +# error "unsupported platform: need a 32-bit type" +# endif +#endif + +#if defined (__cplusplus) +extern "C" { +#endif + +/*! + * @} + * + * @defgroup XXH32_family XXH32 family + * @ingroup public + * Contains functions used in the classic 32-bit xxHash algorithm. + * + * @note + * XXH32 is useful for older platforms, with no or poor 64-bit performance. + * Note that the @ref XXH3_family provides competitive speed for both 32-bit + * and 64-bit systems, and offers true 64/128 bit hash results. + * + * @see @ref XXH64_family, @ref XXH3_family : Other xxHash families + * @see @ref XXH32_impl for implementation details + * @{ + */ + +/*! + * @brief Calculates the 32-bit hash of @p input using xxHash32. + * + * @param input The block of data to be hashed, at least @p length bytes in size. + * @param length The length of @p input, in bytes. + * @param seed The 32-bit seed to alter the hash's output predictably. + * + * @pre + * The memory between @p input and @p input + @p length must be valid, + * readable, contiguous memory. However, if @p length is `0`, @p input may be + * `NULL`. In C++, this also must be *TriviallyCopyable*. + * + * @return The calculated 32-bit xxHash32 value. + * + * @see @ref single_shot_example "Single Shot Example" for an example. + */ +XXH_PUBLIC_API XXH_PUREF XXH32_hash_t XXH32 (const void* input, size_t length, XXH32_hash_t seed); + +#ifndef XXH_NO_STREAM +/*! + * @typedef struct XXH32_state_s XXH32_state_t + * @brief The opaque state struct for the XXH32 streaming API. + * + * @see XXH32_state_s for details. + */ +typedef struct XXH32_state_s XXH32_state_t; + +/*! + * @brief Allocates an @ref XXH32_state_t. + * + * @return An allocated pointer of @ref XXH32_state_t on success. + * @return `NULL` on failure. + * + * @note Must be freed with XXH32_freeState(). + */ +XXH_PUBLIC_API XXH_MALLOCF XXH32_state_t* XXH32_createState(void); +/*! + * @brief Frees an @ref XXH32_state_t. + * + * @param statePtr A pointer to an @ref XXH32_state_t allocated with @ref XXH32_createState(). + * + * @return @ref XXH_OK. + * + * @note @p statePtr must be allocated with XXH32_createState(). + * + */ +XXH_PUBLIC_API XXH_errorcode XXH32_freeState(XXH32_state_t* statePtr); +/*! + * @brief Copies one @ref XXH32_state_t to another. + * + * @param dst_state The state to copy to. + * @param src_state The state to copy from. + * @pre + * @p dst_state and @p src_state must not be `NULL` and must not overlap. + */ +XXH_PUBLIC_API void XXH32_copyState(XXH32_state_t* dst_state, const XXH32_state_t* src_state); + +/*! + * @brief Resets an @ref XXH32_state_t to begin a new hash. + * + * @param statePtr The state struct to reset. + * @param seed The 32-bit seed to alter the hash result predictably. + * + * @pre + * @p statePtr must not be `NULL`. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @note This function resets and seeds a state. Call it before @ref XXH32_update(). + */ +XXH_PUBLIC_API XXH_errorcode XXH32_reset (XXH32_state_t* statePtr, XXH32_hash_t seed); + +/*! + * @brief Consumes a block of @p input to an @ref XXH32_state_t. + * + * @param statePtr The state struct to update. + * @param input The block of data to be hashed, at least @p length bytes in size. + * @param length The length of @p input, in bytes. + * + * @pre + * @p statePtr must not be `NULL`. + * @pre + * The memory between @p input and @p input + @p length must be valid, + * readable, contiguous memory. However, if @p length is `0`, @p input may be + * `NULL`. In C++, this also must be *TriviallyCopyable*. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @note Call this to incrementally consume blocks of data. + */ +XXH_PUBLIC_API XXH_errorcode XXH32_update (XXH32_state_t* statePtr, const void* input, size_t length); + +/*! + * @brief Returns the calculated hash value from an @ref XXH32_state_t. + * + * @param statePtr The state struct to calculate the hash from. + * + * @pre + * @p statePtr must not be `NULL`. + * + * @return The calculated 32-bit xxHash32 value from that state. + * + * @note + * Calling XXH32_digest() will not affect @p statePtr, so you can update, + * digest, and update again. + */ +XXH_PUBLIC_API XXH_PUREF XXH32_hash_t XXH32_digest (const XXH32_state_t* statePtr); +#endif /* !XXH_NO_STREAM */ + +/******* Canonical representation *******/ + +/*! + * @brief Canonical (big endian) representation of @ref XXH32_hash_t. + */ +typedef struct { + unsigned char digest[4]; /*!< Hash bytes, big endian */ +} XXH32_canonical_t; + +/*! + * @brief Converts an @ref XXH32_hash_t to a big endian @ref XXH32_canonical_t. + * + * @param dst The @ref XXH32_canonical_t pointer to be stored to. + * @param hash The @ref XXH32_hash_t to be converted. + * + * @pre + * @p dst must not be `NULL`. + * + * @see @ref canonical_representation_example "Canonical Representation Example" + */ +XXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t* dst, XXH32_hash_t hash); + +/*! + * @brief Converts an @ref XXH32_canonical_t to a native @ref XXH32_hash_t. + * + * @param src The @ref XXH32_canonical_t to convert. + * + * @pre + * @p src must not be `NULL`. + * + * @return The converted hash. + * + * @see @ref canonical_representation_example "Canonical Representation Example" + */ +XXH_PUBLIC_API XXH_PUREF XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t* src); + + +/*! @cond Doxygen ignores this part */ +#ifdef __has_attribute +# define XXH_HAS_ATTRIBUTE(x) __has_attribute(x) +#else +# define XXH_HAS_ATTRIBUTE(x) 0 +#endif +/*! @endcond */ + +/*! @cond Doxygen ignores this part */ +/* + * C23 __STDC_VERSION__ number hasn't been specified yet. For now + * leave as `201711L` (C17 + 1). + * TODO: Update to correct value when its been specified. + */ +#define XXH_C23_VN 201711L +/*! @endcond */ + +/*! @cond Doxygen ignores this part */ +/* C-language Attributes are added in C23. */ +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= XXH_C23_VN) && defined(__has_c_attribute) +# define XXH_HAS_C_ATTRIBUTE(x) __has_c_attribute(x) +#else +# define XXH_HAS_C_ATTRIBUTE(x) 0 +#endif +/*! @endcond */ + +/*! @cond Doxygen ignores this part */ +#if defined(__cplusplus) && defined(__has_cpp_attribute) +# define XXH_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x) +#else +# define XXH_HAS_CPP_ATTRIBUTE(x) 0 +#endif +/*! @endcond */ + +/*! @cond Doxygen ignores this part */ +/* + * Define XXH_FALLTHROUGH macro for annotating switch case with the 'fallthrough' attribute + * introduced in CPP17 and C23. + * CPP17 : https://en.cppreference.com/w/cpp/language/attributes/fallthrough + * C23 : https://en.cppreference.com/w/c/language/attributes/fallthrough + */ +#if XXH_HAS_C_ATTRIBUTE(fallthrough) || XXH_HAS_CPP_ATTRIBUTE(fallthrough) +# define XXH_FALLTHROUGH [[fallthrough]] +#elif XXH_HAS_ATTRIBUTE(__fallthrough__) +# define XXH_FALLTHROUGH __attribute__ ((__fallthrough__)) +#else +# define XXH_FALLTHROUGH /* fallthrough */ +#endif +/*! @endcond */ + +/*! @cond Doxygen ignores this part */ +/* + * Define XXH_NOESCAPE for annotated pointers in public API. + * https://clang.llvm.org/docs/AttributeReference.html#noescape + * As of writing this, only supported by clang. + */ +#if XXH_HAS_ATTRIBUTE(noescape) +# define XXH_NOESCAPE __attribute__((noescape)) +#else +# define XXH_NOESCAPE +#endif +/*! @endcond */ + +#if defined (__cplusplus) +} /* end of extern "C" */ +#endif + +/*! + * @} + * @ingroup public + * @{ + */ + +#ifndef XXH_NO_LONG_LONG +/*-********************************************************************** +* 64-bit hash +************************************************************************/ +#if defined(XXH_DOXYGEN) /* don't include */ +/*! + * @brief An unsigned 64-bit integer. + * + * Not necessarily defined to `uint64_t` but functionally equivalent. + */ +typedef uint64_t XXH64_hash_t; +#elif !defined (__VMS) \ + && (defined (__cplusplus) \ + || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) ) +# ifdef _AIX +# include +# else +# include +# endif + typedef uint64_t XXH64_hash_t; +#else +# include +# if defined(__LP64__) && ULONG_MAX == 0xFFFFFFFFFFFFFFFFULL + /* LP64 ABI says uint64_t is unsigned long */ + typedef unsigned long XXH64_hash_t; +# else + /* the following type must have a width of 64-bit */ + typedef unsigned long long XXH64_hash_t; +# endif +#endif + +#if defined (__cplusplus) +extern "C" { +#endif +/*! + * @} + * + * @defgroup XXH64_family XXH64 family + * @ingroup public + * @{ + * Contains functions used in the classic 64-bit xxHash algorithm. + * + * @note + * XXH3 provides competitive speed for both 32-bit and 64-bit systems, + * and offers true 64/128 bit hash results. + * It provides better speed for systems with vector processing capabilities. + */ + +/*! + * @brief Calculates the 64-bit hash of @p input using xxHash64. + * + * @param input The block of data to be hashed, at least @p length bytes in size. + * @param length The length of @p input, in bytes. + * @param seed The 64-bit seed to alter the hash's output predictably. + * + * @pre + * The memory between @p input and @p input + @p length must be valid, + * readable, contiguous memory. However, if @p length is `0`, @p input may be + * `NULL`. In C++, this also must be *TriviallyCopyable*. + * + * @return The calculated 64-bit xxHash64 value. + * + * @see @ref single_shot_example "Single Shot Example" for an example. + */ +XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH64(XXH_NOESCAPE const void* input, size_t length, XXH64_hash_t seed); + +/******* Streaming *******/ +#ifndef XXH_NO_STREAM +/*! + * @brief The opaque state struct for the XXH64 streaming API. + * + * @see XXH64_state_s for details. + */ +typedef struct XXH64_state_s XXH64_state_t; /* incomplete type */ + +/*! + * @brief Allocates an @ref XXH64_state_t. + * + * @return An allocated pointer of @ref XXH64_state_t on success. + * @return `NULL` on failure. + * + * @note Must be freed with XXH64_freeState(). + */ +XXH_PUBLIC_API XXH_MALLOCF XXH64_state_t* XXH64_createState(void); + +/*! + * @brief Frees an @ref XXH64_state_t. + * + * @param statePtr A pointer to an @ref XXH64_state_t allocated with @ref XXH64_createState(). + * + * @return @ref XXH_OK. + * + * @note @p statePtr must be allocated with XXH64_createState(). + */ +XXH_PUBLIC_API XXH_errorcode XXH64_freeState(XXH64_state_t* statePtr); + +/*! + * @brief Copies one @ref XXH64_state_t to another. + * + * @param dst_state The state to copy to. + * @param src_state The state to copy from. + * @pre + * @p dst_state and @p src_state must not be `NULL` and must not overlap. + */ +XXH_PUBLIC_API void XXH64_copyState(XXH_NOESCAPE XXH64_state_t* dst_state, const XXH64_state_t* src_state); + +/*! + * @brief Resets an @ref XXH64_state_t to begin a new hash. + * + * @param statePtr The state struct to reset. + * @param seed The 64-bit seed to alter the hash result predictably. + * + * @pre + * @p statePtr must not be `NULL`. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @note This function resets and seeds a state. Call it before @ref XXH64_update(). + */ +XXH_PUBLIC_API XXH_errorcode XXH64_reset (XXH_NOESCAPE XXH64_state_t* statePtr, XXH64_hash_t seed); + +/*! + * @brief Consumes a block of @p input to an @ref XXH64_state_t. + * + * @param statePtr The state struct to update. + * @param input The block of data to be hashed, at least @p length bytes in size. + * @param length The length of @p input, in bytes. + * + * @pre + * @p statePtr must not be `NULL`. + * @pre + * The memory between @p input and @p input + @p length must be valid, + * readable, contiguous memory. However, if @p length is `0`, @p input may be + * `NULL`. In C++, this also must be *TriviallyCopyable*. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @note Call this to incrementally consume blocks of data. + */ +XXH_PUBLIC_API XXH_errorcode XXH64_update (XXH_NOESCAPE XXH64_state_t* statePtr, XXH_NOESCAPE const void* input, size_t length); + +/*! + * @brief Returns the calculated hash value from an @ref XXH64_state_t. + * + * @param statePtr The state struct to calculate the hash from. + * + * @pre + * @p statePtr must not be `NULL`. + * + * @return The calculated 64-bit xxHash64 value from that state. + * + * @note + * Calling XXH64_digest() will not affect @p statePtr, so you can update, + * digest, and update again. + */ +XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH64_digest (XXH_NOESCAPE const XXH64_state_t* statePtr); +#endif /* !XXH_NO_STREAM */ +/******* Canonical representation *******/ + +/*! + * @brief Canonical (big endian) representation of @ref XXH64_hash_t. + */ +typedef struct { unsigned char digest[sizeof(XXH64_hash_t)]; } XXH64_canonical_t; + +/*! + * @brief Converts an @ref XXH64_hash_t to a big endian @ref XXH64_canonical_t. + * + * @param dst The @ref XXH64_canonical_t pointer to be stored to. + * @param hash The @ref XXH64_hash_t to be converted. + * + * @pre + * @p dst must not be `NULL`. + * + * @see @ref canonical_representation_example "Canonical Representation Example" + */ +XXH_PUBLIC_API void XXH64_canonicalFromHash(XXH_NOESCAPE XXH64_canonical_t* dst, XXH64_hash_t hash); + +/*! + * @brief Converts an @ref XXH64_canonical_t to a native @ref XXH64_hash_t. + * + * @param src The @ref XXH64_canonical_t to convert. + * + * @pre + * @p src must not be `NULL`. + * + * @return The converted hash. + * + * @see @ref canonical_representation_example "Canonical Representation Example" + */ +XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH64_hashFromCanonical(XXH_NOESCAPE const XXH64_canonical_t* src); + +#ifndef XXH_NO_XXH3 + +/*! + * @} + * ************************************************************************ + * @defgroup XXH3_family XXH3 family + * @ingroup public + * @{ + * + * XXH3 is a more recent hash algorithm featuring: + * - Improved speed for both small and large inputs + * - True 64-bit and 128-bit outputs + * - SIMD acceleration + * - Improved 32-bit viability + * + * Speed analysis methodology is explained here: + * + * https://fastcompression.blogspot.com/2019/03/presenting-xxh3.html + * + * Compared to XXH64, expect XXH3 to run approximately + * ~2x faster on large inputs and >3x faster on small ones, + * exact differences vary depending on platform. + * + * XXH3's speed benefits greatly from SIMD and 64-bit arithmetic, + * but does not require it. + * Most 32-bit and 64-bit targets that can run XXH32 smoothly can run XXH3 + * at competitive speeds, even without vector support. Further details are + * explained in the implementation. + * + * XXH3 has a fast scalar implementation, but it also includes accelerated SIMD + * implementations for many common platforms: + * - AVX512 + * - AVX2 + * - SSE2 + * - ARM NEON + * - WebAssembly SIMD128 + * - POWER8 VSX + * - s390x ZVector + * This can be controlled via the @ref XXH_VECTOR macro, but it automatically + * selects the best version according to predefined macros. For the x86 family, an + * automatic runtime dispatcher is included separately in @ref xxh_x86dispatch.c. + * + * XXH3 implementation is portable: + * it has a generic C90 formulation that can be compiled on any platform, + * all implementations generate exactly the same hash value on all platforms. + * Starting from v0.8.0, it's also labelled "stable", meaning that + * any future version will also generate the same hash value. + * + * XXH3 offers 2 variants, _64bits and _128bits. + * + * When only 64 bits are needed, prefer invoking the _64bits variant, as it + * reduces the amount of mixing, resulting in faster speed on small inputs. + * It's also generally simpler to manipulate a scalar return type than a struct. + * + * The API supports one-shot hashing, streaming mode, and custom secrets. + */ +/*-********************************************************************** +* XXH3 64-bit variant +************************************************************************/ + +/*! + * @brief Calculates 64-bit unseeded variant of XXH3 hash of @p input. + * + * @param input The block of data to be hashed, at least @p length bytes in size. + * @param length The length of @p input, in bytes. + * + * @pre + * The memory between @p input and @p input + @p length must be valid, + * readable, contiguous memory. However, if @p length is `0`, @p input may be + * `NULL`. In C++, this also must be *TriviallyCopyable*. + * + * @return The calculated 64-bit XXH3 hash value. + * + * @note + * This is equivalent to @ref XXH3_64bits_withSeed() with a seed of `0`, however + * it may have slightly better performance due to constant propagation of the + * defaults. + * + * @see + * XXH3_64bits_withSeed(), XXH3_64bits_withSecret(): other seeding variants + * @see @ref single_shot_example "Single Shot Example" for an example. + */ +XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH3_64bits(XXH_NOESCAPE const void* input, size_t length); + +/*! + * @brief Calculates 64-bit seeded variant of XXH3 hash of @p input. + * + * @param input The block of data to be hashed, at least @p length bytes in size. + * @param length The length of @p input, in bytes. + * @param seed The 64-bit seed to alter the hash result predictably. + * + * @pre + * The memory between @p input and @p input + @p length must be valid, + * readable, contiguous memory. However, if @p length is `0`, @p input may be + * `NULL`. In C++, this also must be *TriviallyCopyable*. + * + * @return The calculated 64-bit XXH3 hash value. + * + * @note + * seed == 0 produces the same results as @ref XXH3_64bits(). + * + * This variant generates a custom secret on the fly based on default secret + * altered using the @p seed value. + * + * While this operation is decently fast, note that it's not completely free. + * + * @see @ref single_shot_example "Single Shot Example" for an example. + */ +XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH3_64bits_withSeed(XXH_NOESCAPE const void* input, size_t length, XXH64_hash_t seed); + +/*! + * The bare minimum size for a custom secret. + * + * @see + * XXH3_64bits_withSecret(), XXH3_64bits_reset_withSecret(), + * XXH3_128bits_withSecret(), XXH3_128bits_reset_withSecret(). + */ +#define XXH3_SECRET_SIZE_MIN 136 + +/*! + * @brief Calculates 64-bit variant of XXH3 with a custom "secret". + * + * @param data The block of data to be hashed, at least @p len bytes in size. + * @param len The length of @p data, in bytes. + * @param secret The secret data. + * @param secretSize The length of @p secret, in bytes. + * + * @return The calculated 64-bit XXH3 hash value. + * + * @pre + * The memory between @p data and @p data + @p len must be valid, + * readable, contiguous memory. However, if @p length is `0`, @p data may be + * `NULL`. In C++, this also must be *TriviallyCopyable*. + * + * It's possible to provide any blob of bytes as a "secret" to generate the hash. + * This makes it more difficult for an external actor to prepare an intentional collision. + * The main condition is that @p secretSize *must* be large enough (>= @ref XXH3_SECRET_SIZE_MIN). + * However, the quality of the secret impacts the dispersion of the hash algorithm. + * Therefore, the secret _must_ look like a bunch of random bytes. + * Avoid "trivial" or structured data such as repeated sequences or a text document. + * Whenever in doubt about the "randomness" of the blob of bytes, + * consider employing @ref XXH3_generateSecret() instead (see below). + * It will generate a proper high entropy secret derived from the blob of bytes. + * Another advantage of using XXH3_generateSecret() is that + * it guarantees that all bits within the initial blob of bytes + * will impact every bit of the output. + * This is not necessarily the case when using the blob of bytes directly + * because, when hashing _small_ inputs, only a portion of the secret is employed. + * + * @see @ref single_shot_example "Single Shot Example" for an example. + */ +XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH3_64bits_withSecret(XXH_NOESCAPE const void* data, size_t len, XXH_NOESCAPE const void* secret, size_t secretSize); + + +/******* Streaming *******/ +#ifndef XXH_NO_STREAM +/* + * Streaming requires state maintenance. + * This operation costs memory and CPU. + * As a consequence, streaming is slower than one-shot hashing. + * For better performance, prefer one-shot functions whenever applicable. + */ + +/*! + * @brief The opaque state struct for the XXH3 streaming API. + * + * @see XXH3_state_s for details. + */ +typedef struct XXH3_state_s XXH3_state_t; +XXH_PUBLIC_API XXH_MALLOCF XXH3_state_t* XXH3_createState(void); +XXH_PUBLIC_API XXH_errorcode XXH3_freeState(XXH3_state_t* statePtr); + +/*! + * @brief Copies one @ref XXH3_state_t to another. + * + * @param dst_state The state to copy to. + * @param src_state The state to copy from. + * @pre + * @p dst_state and @p src_state must not be `NULL` and must not overlap. + */ +XXH_PUBLIC_API void XXH3_copyState(XXH_NOESCAPE XXH3_state_t* dst_state, XXH_NOESCAPE const XXH3_state_t* src_state); + +/*! + * @brief Resets an @ref XXH3_state_t to begin a new hash. + * + * @param statePtr The state struct to reset. + * + * @pre + * @p statePtr must not be `NULL`. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @note + * - This function resets `statePtr` and generate a secret with default parameters. + * - Call this function before @ref XXH3_64bits_update(). + * - Digest will be equivalent to `XXH3_64bits()`. + * + */ +XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset(XXH_NOESCAPE XXH3_state_t* statePtr); + +/*! + * @brief Resets an @ref XXH3_state_t with 64-bit seed to begin a new hash. + * + * @param statePtr The state struct to reset. + * @param seed The 64-bit seed to alter the hash result predictably. + * + * @pre + * @p statePtr must not be `NULL`. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @note + * - This function resets `statePtr` and generate a secret from `seed`. + * - Call this function before @ref XXH3_64bits_update(). + * - Digest will be equivalent to `XXH3_64bits_withSeed()`. + * + */ +XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset_withSeed(XXH_NOESCAPE XXH3_state_t* statePtr, XXH64_hash_t seed); + +/*! + * @brief Resets an @ref XXH3_state_t with secret data to begin a new hash. + * + * @param statePtr The state struct to reset. + * @param secret The secret data. + * @param secretSize The length of @p secret, in bytes. + * + * @pre + * @p statePtr must not be `NULL`. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @note + * `secret` is referenced, it _must outlive_ the hash streaming session. + * + * Similar to one-shot API, `secretSize` must be >= @ref XXH3_SECRET_SIZE_MIN, + * and the quality of produced hash values depends on secret's entropy + * (secret's content should look like a bunch of random bytes). + * When in doubt about the randomness of a candidate `secret`, + * consider employing `XXH3_generateSecret()` instead (see below). + */ +XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset_withSecret(XXH_NOESCAPE XXH3_state_t* statePtr, XXH_NOESCAPE const void* secret, size_t secretSize); + +/*! + * @brief Consumes a block of @p input to an @ref XXH3_state_t. + * + * @param statePtr The state struct to update. + * @param input The block of data to be hashed, at least @p length bytes in size. + * @param length The length of @p input, in bytes. + * + * @pre + * @p statePtr must not be `NULL`. + * @pre + * The memory between @p input and @p input + @p length must be valid, + * readable, contiguous memory. However, if @p length is `0`, @p input may be + * `NULL`. In C++, this also must be *TriviallyCopyable*. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @note Call this to incrementally consume blocks of data. + */ +XXH_PUBLIC_API XXH_errorcode XXH3_64bits_update (XXH_NOESCAPE XXH3_state_t* statePtr, XXH_NOESCAPE const void* input, size_t length); + +/*! + * @brief Returns the calculated XXH3 64-bit hash value from an @ref XXH3_state_t. + * + * @param statePtr The state struct to calculate the hash from. + * + * @pre + * @p statePtr must not be `NULL`. + * + * @return The calculated XXH3 64-bit hash value from that state. + * + * @note + * Calling XXH3_64bits_digest() will not affect @p statePtr, so you can update, + * digest, and update again. + */ +XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH3_64bits_digest (XXH_NOESCAPE const XXH3_state_t* statePtr); +#endif /* !XXH_NO_STREAM */ + +/* note : canonical representation of XXH3 is the same as XXH64 + * since they both produce XXH64_hash_t values */ + + +/*-********************************************************************** +* XXH3 128-bit variant +************************************************************************/ + +/*! + * @brief The return value from 128-bit hashes. + * + * Stored in little endian order, although the fields themselves are in native + * endianness. + */ +typedef struct { + XXH64_hash_t low64; /*!< `value & 0xFFFFFFFFFFFFFFFF` */ + XXH64_hash_t high64; /*!< `value >> 64` */ +} XXH128_hash_t; + +/*! + * @brief Calculates 128-bit unseeded variant of XXH3 of @p data. + * + * @param data The block of data to be hashed, at least @p length bytes in size. + * @param len The length of @p data, in bytes. + * + * @return The calculated 128-bit variant of XXH3 value. + * + * The 128-bit variant of XXH3 has more strength, but it has a bit of overhead + * for shorter inputs. + * + * This is equivalent to @ref XXH3_128bits_withSeed() with a seed of `0`, however + * it may have slightly better performance due to constant propagation of the + * defaults. + * + * @see XXH3_128bits_withSeed(), XXH3_128bits_withSecret(): other seeding variants + * @see @ref single_shot_example "Single Shot Example" for an example. + */ +XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH3_128bits(XXH_NOESCAPE const void* data, size_t len); +/*! @brief Calculates 128-bit seeded variant of XXH3 hash of @p data. + * + * @param data The block of data to be hashed, at least @p length bytes in size. + * @param len The length of @p data, in bytes. + * @param seed The 64-bit seed to alter the hash result predictably. + * + * @return The calculated 128-bit variant of XXH3 value. + * + * @note + * seed == 0 produces the same results as @ref XXH3_64bits(). + * + * This variant generates a custom secret on the fly based on default secret + * altered using the @p seed value. + * + * While this operation is decently fast, note that it's not completely free. + * + * @see XXH3_128bits(), XXH3_128bits_withSecret(): other seeding variants + * @see @ref single_shot_example "Single Shot Example" for an example. + */ +XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH3_128bits_withSeed(XXH_NOESCAPE const void* data, size_t len, XXH64_hash_t seed); +/*! + * @brief Calculates 128-bit variant of XXH3 with a custom "secret". + * + * @param data The block of data to be hashed, at least @p len bytes in size. + * @param len The length of @p data, in bytes. + * @param secret The secret data. + * @param secretSize The length of @p secret, in bytes. + * + * @return The calculated 128-bit variant of XXH3 value. + * + * It's possible to provide any blob of bytes as a "secret" to generate the hash. + * This makes it more difficult for an external actor to prepare an intentional collision. + * The main condition is that @p secretSize *must* be large enough (>= @ref XXH3_SECRET_SIZE_MIN). + * However, the quality of the secret impacts the dispersion of the hash algorithm. + * Therefore, the secret _must_ look like a bunch of random bytes. + * Avoid "trivial" or structured data such as repeated sequences or a text document. + * Whenever in doubt about the "randomness" of the blob of bytes, + * consider employing @ref XXH3_generateSecret() instead (see below). + * It will generate a proper high entropy secret derived from the blob of bytes. + * Another advantage of using XXH3_generateSecret() is that + * it guarantees that all bits within the initial blob of bytes + * will impact every bit of the output. + * This is not necessarily the case when using the blob of bytes directly + * because, when hashing _small_ inputs, only a portion of the secret is employed. + * + * @see @ref single_shot_example "Single Shot Example" for an example. + */ +XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH3_128bits_withSecret(XXH_NOESCAPE const void* data, size_t len, XXH_NOESCAPE const void* secret, size_t secretSize); + +/******* Streaming *******/ +#ifndef XXH_NO_STREAM +/* + * Streaming requires state maintenance. + * This operation costs memory and CPU. + * As a consequence, streaming is slower than one-shot hashing. + * For better performance, prefer one-shot functions whenever applicable. + * + * XXH3_128bits uses the same XXH3_state_t as XXH3_64bits(). + * Use already declared XXH3_createState() and XXH3_freeState(). + * + * All reset and streaming functions have same meaning as their 64-bit counterpart. + */ + +/*! + * @brief Resets an @ref XXH3_state_t to begin a new hash. + * + * @param statePtr The state struct to reset. + * + * @pre + * @p statePtr must not be `NULL`. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @note + * - This function resets `statePtr` and generate a secret with default parameters. + * - Call it before @ref XXH3_128bits_update(). + * - Digest will be equivalent to `XXH3_128bits()`. + */ +XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset(XXH_NOESCAPE XXH3_state_t* statePtr); + +/*! + * @brief Resets an @ref XXH3_state_t with 64-bit seed to begin a new hash. + * + * @param statePtr The state struct to reset. + * @param seed The 64-bit seed to alter the hash result predictably. + * + * @pre + * @p statePtr must not be `NULL`. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @note + * - This function resets `statePtr` and generate a secret from `seed`. + * - Call it before @ref XXH3_128bits_update(). + * - Digest will be equivalent to `XXH3_128bits_withSeed()`. + */ +XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset_withSeed(XXH_NOESCAPE XXH3_state_t* statePtr, XXH64_hash_t seed); +/*! + * @brief Resets an @ref XXH3_state_t with secret data to begin a new hash. + * + * @param statePtr The state struct to reset. + * @param secret The secret data. + * @param secretSize The length of @p secret, in bytes. + * + * @pre + * @p statePtr must not be `NULL`. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * `secret` is referenced, it _must outlive_ the hash streaming session. + * Similar to one-shot API, `secretSize` must be >= @ref XXH3_SECRET_SIZE_MIN, + * and the quality of produced hash values depends on secret's entropy + * (secret's content should look like a bunch of random bytes). + * When in doubt about the randomness of a candidate `secret`, + * consider employing `XXH3_generateSecret()` instead (see below). + */ +XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset_withSecret(XXH_NOESCAPE XXH3_state_t* statePtr, XXH_NOESCAPE const void* secret, size_t secretSize); + +/*! + * @brief Consumes a block of @p input to an @ref XXH3_state_t. + * + * Call this to incrementally consume blocks of data. + * + * @param statePtr The state struct to update. + * @param input The block of data to be hashed, at least @p length bytes in size. + * @param length The length of @p input, in bytes. + * + * @pre + * @p statePtr must not be `NULL`. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @note + * The memory between @p input and @p input + @p length must be valid, + * readable, contiguous memory. However, if @p length is `0`, @p input may be + * `NULL`. In C++, this also must be *TriviallyCopyable*. + * + */ +XXH_PUBLIC_API XXH_errorcode XXH3_128bits_update (XXH_NOESCAPE XXH3_state_t* statePtr, XXH_NOESCAPE const void* input, size_t length); + +/*! + * @brief Returns the calculated XXH3 128-bit hash value from an @ref XXH3_state_t. + * + * @param statePtr The state struct to calculate the hash from. + * + * @pre + * @p statePtr must not be `NULL`. + * + * @return The calculated XXH3 128-bit hash value from that state. + * + * @note + * Calling XXH3_128bits_digest() will not affect @p statePtr, so you can update, + * digest, and update again. + * + */ +XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH3_128bits_digest (XXH_NOESCAPE const XXH3_state_t* statePtr); +#endif /* !XXH_NO_STREAM */ + +/* Following helper functions make it possible to compare XXH128_hast_t values. + * Since XXH128_hash_t is a structure, this capability is not offered by the language. + * Note: For better performance, these functions can be inlined using XXH_INLINE_ALL */ + +/*! + * @brief Check equality of two XXH128_hash_t values + * + * @param h1 The 128-bit hash value. + * @param h2 Another 128-bit hash value. + * + * @return `1` if `h1` and `h2` are equal. + * @return `0` if they are not. + */ +XXH_PUBLIC_API XXH_PUREF int XXH128_isEqual(XXH128_hash_t h1, XXH128_hash_t h2); + +/*! + * @brief Compares two @ref XXH128_hash_t + * + * This comparator is compatible with stdlib's `qsort()`/`bsearch()`. + * + * @param h128_1 Left-hand side value + * @param h128_2 Right-hand side value + * + * @return >0 if @p h128_1 > @p h128_2 + * @return =0 if @p h128_1 == @p h128_2 + * @return <0 if @p h128_1 < @p h128_2 + */ +XXH_PUBLIC_API XXH_PUREF int XXH128_cmp(XXH_NOESCAPE const void* h128_1, XXH_NOESCAPE const void* h128_2); + + +/******* Canonical representation *******/ +typedef struct { unsigned char digest[sizeof(XXH128_hash_t)]; } XXH128_canonical_t; + + +/*! + * @brief Converts an @ref XXH128_hash_t to a big endian @ref XXH128_canonical_t. + * + * @param dst The @ref XXH128_canonical_t pointer to be stored to. + * @param hash The @ref XXH128_hash_t to be converted. + * + * @pre + * @p dst must not be `NULL`. + * @see @ref canonical_representation_example "Canonical Representation Example" + */ +XXH_PUBLIC_API void XXH128_canonicalFromHash(XXH_NOESCAPE XXH128_canonical_t* dst, XXH128_hash_t hash); + +/*! + * @brief Converts an @ref XXH128_canonical_t to a native @ref XXH128_hash_t. + * + * @param src The @ref XXH128_canonical_t to convert. + * + * @pre + * @p src must not be `NULL`. + * + * @return The converted hash. + * @see @ref canonical_representation_example "Canonical Representation Example" + */ +XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH128_hashFromCanonical(XXH_NOESCAPE const XXH128_canonical_t* src); + + +#endif /* !XXH_NO_XXH3 */ + +#if defined (__cplusplus) +} /* extern "C" */ +#endif + +#endif /* XXH_NO_LONG_LONG */ + +/*! + * @} + */ +#endif /* XXHASH_H_5627135585666179 */ + + + +#if defined(XXH_STATIC_LINKING_ONLY) && !defined(XXHASH_H_STATIC_13879238742) +#define XXHASH_H_STATIC_13879238742 +/* **************************************************************************** + * This section contains declarations which are not guaranteed to remain stable. + * They may change in future versions, becoming incompatible with a different + * version of the library. + * These declarations should only be used with static linking. + * Never use them in association with dynamic linking! + ***************************************************************************** */ + +/* + * These definitions are only present to allow static allocation + * of XXH states, on stack or in a struct, for example. + * Never **ever** access their members directly. + */ + +/*! + * @internal + * @brief Structure for XXH32 streaming API. + * + * @note This is only defined when @ref XXH_STATIC_LINKING_ONLY, + * @ref XXH_INLINE_ALL, or @ref XXH_IMPLEMENTATION is defined. Otherwise it is + * an opaque type. This allows fields to safely be changed. + * + * Typedef'd to @ref XXH32_state_t. + * Do not access the members of this struct directly. + * @see XXH64_state_s, XXH3_state_s + */ +struct XXH32_state_s { + XXH32_hash_t total_len_32; /*!< Total length hashed, modulo 2^32 */ + XXH32_hash_t large_len; /*!< Whether the hash is >= 16 (handles @ref total_len_32 overflow) */ + XXH32_hash_t v[4]; /*!< Accumulator lanes */ + XXH32_hash_t mem32[4]; /*!< Internal buffer for partial reads. Treated as unsigned char[16]. */ + XXH32_hash_t memsize; /*!< Amount of data in @ref mem32 */ + XXH32_hash_t reserved; /*!< Reserved field. Do not read nor write to it. */ +}; /* typedef'd to XXH32_state_t */ + + +#ifndef XXH_NO_LONG_LONG /* defined when there is no 64-bit support */ + +/*! + * @internal + * @brief Structure for XXH64 streaming API. + * + * @note This is only defined when @ref XXH_STATIC_LINKING_ONLY, + * @ref XXH_INLINE_ALL, or @ref XXH_IMPLEMENTATION is defined. Otherwise it is + * an opaque type. This allows fields to safely be changed. + * + * Typedef'd to @ref XXH64_state_t. + * Do not access the members of this struct directly. + * @see XXH32_state_s, XXH3_state_s + */ +struct XXH64_state_s { + XXH64_hash_t total_len; /*!< Total length hashed. This is always 64-bit. */ + XXH64_hash_t v[4]; /*!< Accumulator lanes */ + XXH64_hash_t mem64[4]; /*!< Internal buffer for partial reads. Treated as unsigned char[32]. */ + XXH32_hash_t memsize; /*!< Amount of data in @ref mem64 */ + XXH32_hash_t reserved32; /*!< Reserved field, needed for padding anyways*/ + XXH64_hash_t reserved64; /*!< Reserved field. Do not read or write to it. */ +}; /* typedef'd to XXH64_state_t */ + +#ifndef XXH_NO_XXH3 + +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) /* >= C11 */ +# include +# define XXH_ALIGN(n) alignas(n) +#elif defined(__cplusplus) && (__cplusplus >= 201103L) /* >= C++11 */ +/* In C++ alignas() is a keyword */ +# define XXH_ALIGN(n) alignas(n) +#elif defined(__GNUC__) +# define XXH_ALIGN(n) __attribute__ ((aligned(n))) +#elif defined(_MSC_VER) +# define XXH_ALIGN(n) __declspec(align(n)) +#else +# define XXH_ALIGN(n) /* disabled */ +#endif + +/* Old GCC versions only accept the attribute after the type in structures. */ +#if !(defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) /* C11+ */ \ + && ! (defined(__cplusplus) && (__cplusplus >= 201103L)) /* >= C++11 */ \ + && defined(__GNUC__) +# define XXH_ALIGN_MEMBER(align, type) type XXH_ALIGN(align) +#else +# define XXH_ALIGN_MEMBER(align, type) XXH_ALIGN(align) type +#endif + +/*! + * @brief The size of the internal XXH3 buffer. + * + * This is the optimal update size for incremental hashing. + * + * @see XXH3_64b_update(), XXH3_128b_update(). + */ +#define XXH3_INTERNALBUFFER_SIZE 256 + +/*! + * @internal + * @brief Default size of the secret buffer (and @ref XXH3_kSecret). + * + * This is the size used in @ref XXH3_kSecret and the seeded functions. + * + * Not to be confused with @ref XXH3_SECRET_SIZE_MIN. + */ +#define XXH3_SECRET_DEFAULT_SIZE 192 + +/*! + * @internal + * @brief Structure for XXH3 streaming API. + * + * @note This is only defined when @ref XXH_STATIC_LINKING_ONLY, + * @ref XXH_INLINE_ALL, or @ref XXH_IMPLEMENTATION is defined. + * Otherwise it is an opaque type. + * Never use this definition in combination with dynamic library. + * This allows fields to safely be changed in the future. + * + * @note ** This structure has a strict alignment requirement of 64 bytes!! ** + * Do not allocate this with `malloc()` or `new`, + * it will not be sufficiently aligned. + * Use @ref XXH3_createState() and @ref XXH3_freeState(), or stack allocation. + * + * Typedef'd to @ref XXH3_state_t. + * Do never access the members of this struct directly. + * + * @see XXH3_INITSTATE() for stack initialization. + * @see XXH3_createState(), XXH3_freeState(). + * @see XXH32_state_s, XXH64_state_s + */ +struct XXH3_state_s { + XXH_ALIGN_MEMBER(64, XXH64_hash_t acc[8]); + /*!< The 8 accumulators. See @ref XXH32_state_s::v and @ref XXH64_state_s::v */ + XXH_ALIGN_MEMBER(64, unsigned char customSecret[XXH3_SECRET_DEFAULT_SIZE]); + /*!< Used to store a custom secret generated from a seed. */ + XXH_ALIGN_MEMBER(64, unsigned char buffer[XXH3_INTERNALBUFFER_SIZE]); + /*!< The internal buffer. @see XXH32_state_s::mem32 */ + XXH32_hash_t bufferedSize; + /*!< The amount of memory in @ref buffer, @see XXH32_state_s::memsize */ + XXH32_hash_t useSeed; + /*!< Reserved field. Needed for padding on 64-bit. */ + size_t nbStripesSoFar; + /*!< Number or stripes processed. */ + XXH64_hash_t totalLen; + /*!< Total length hashed. 64-bit even on 32-bit targets. */ + size_t nbStripesPerBlock; + /*!< Number of stripes per block. */ + size_t secretLimit; + /*!< Size of @ref customSecret or @ref extSecret */ + XXH64_hash_t seed; + /*!< Seed for _withSeed variants. Must be zero otherwise, @see XXH3_INITSTATE() */ + XXH64_hash_t reserved64; + /*!< Reserved field. */ + const unsigned char* extSecret; + /*!< Reference to an external secret for the _withSecret variants, NULL + * for other variants. */ + /* note: there may be some padding at the end due to alignment on 64 bytes */ +}; /* typedef'd to XXH3_state_t */ + +#undef XXH_ALIGN_MEMBER + +/*! + * @brief Initializes a stack-allocated `XXH3_state_s`. + * + * When the @ref XXH3_state_t structure is merely emplaced on stack, + * it should be initialized with XXH3_INITSTATE() or a memset() + * in case its first reset uses XXH3_NNbits_reset_withSeed(). + * This init can be omitted if the first reset uses default or _withSecret mode. + * This operation isn't necessary when the state is created with XXH3_createState(). + * Note that this doesn't prepare the state for a streaming operation, + * it's still necessary to use XXH3_NNbits_reset*() afterwards. + */ +#define XXH3_INITSTATE(XXH3_state_ptr) \ + do { \ + XXH3_state_t* tmp_xxh3_state_ptr = (XXH3_state_ptr); \ + tmp_xxh3_state_ptr->seed = 0; \ + tmp_xxh3_state_ptr->extSecret = NULL; \ + } while(0) + + +#if defined (__cplusplus) +extern "C" { +#endif + +/*! + * @brief Calculates the 128-bit hash of @p data using XXH3. + * + * @param data The block of data to be hashed, at least @p len bytes in size. + * @param len The length of @p data, in bytes. + * @param seed The 64-bit seed to alter the hash's output predictably. + * + * @pre + * The memory between @p data and @p data + @p len must be valid, + * readable, contiguous memory. However, if @p len is `0`, @p data may be + * `NULL`. In C++, this also must be *TriviallyCopyable*. + * + * @return The calculated 128-bit XXH3 value. + * + * @see @ref single_shot_example "Single Shot Example" for an example. + */ +XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH128(XXH_NOESCAPE const void* data, size_t len, XXH64_hash_t seed); + + +/* === Experimental API === */ +/* Symbols defined below must be considered tied to a specific library version. */ + +/*! + * @brief Derive a high-entropy secret from any user-defined content, named customSeed. + * + * @param secretBuffer A writable buffer for derived high-entropy secret data. + * @param secretSize Size of secretBuffer, in bytes. Must be >= XXH3_SECRET_DEFAULT_SIZE. + * @param customSeed A user-defined content. + * @param customSeedSize Size of customSeed, in bytes. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * The generated secret can be used in combination with `*_withSecret()` functions. + * The `_withSecret()` variants are useful to provide a higher level of protection + * than 64-bit seed, as it becomes much more difficult for an external actor to + * guess how to impact the calculation logic. + * + * The function accepts as input a custom seed of any length and any content, + * and derives from it a high-entropy secret of length @p secretSize into an + * already allocated buffer @p secretBuffer. + * + * The generated secret can then be used with any `*_withSecret()` variant. + * The functions @ref XXH3_128bits_withSecret(), @ref XXH3_64bits_withSecret(), + * @ref XXH3_128bits_reset_withSecret() and @ref XXH3_64bits_reset_withSecret() + * are part of this list. They all accept a `secret` parameter + * which must be large enough for implementation reasons (>= @ref XXH3_SECRET_SIZE_MIN) + * _and_ feature very high entropy (consist of random-looking bytes). + * These conditions can be a high bar to meet, so @ref XXH3_generateSecret() can + * be employed to ensure proper quality. + * + * @p customSeed can be anything. It can have any size, even small ones, + * and its content can be anything, even "poor entropy" sources such as a bunch + * of zeroes. The resulting `secret` will nonetheless provide all required qualities. + * + * @pre + * - @p secretSize must be >= @ref XXH3_SECRET_SIZE_MIN + * - When @p customSeedSize > 0, supplying NULL as customSeed is undefined behavior. + * + * Example code: + * @code{.c} + * #include + * #include + * #include + * #define XXH_STATIC_LINKING_ONLY // expose unstable API + * #include "xxhash.h" + * // Hashes argv[2] using the entropy from argv[1]. + * int main(int argc, char* argv[]) + * { + * char secret[XXH3_SECRET_SIZE_MIN]; + * if (argv != 3) { return 1; } + * XXH3_generateSecret(secret, sizeof(secret), argv[1], strlen(argv[1])); + * XXH64_hash_t h = XXH3_64bits_withSecret( + * argv[2], strlen(argv[2]), + * secret, sizeof(secret) + * ); + * printf("%016llx\n", (unsigned long long) h); + * } + * @endcode + */ +XXH_PUBLIC_API XXH_errorcode XXH3_generateSecret(XXH_NOESCAPE void* secretBuffer, size_t secretSize, XXH_NOESCAPE const void* customSeed, size_t customSeedSize); + +/*! + * @brief Generate the same secret as the _withSeed() variants. + * + * @param secretBuffer A writable buffer of @ref XXH3_SECRET_SIZE_MIN bytes + * @param seed The 64-bit seed to alter the hash result predictably. + * + * The generated secret can be used in combination with + *`*_withSecret()` and `_withSecretandSeed()` variants. + * + * Example C++ `std::string` hash class: + * @code{.cpp} + * #include + * #define XXH_STATIC_LINKING_ONLY // expose unstable API + * #include "xxhash.h" + * // Slow, seeds each time + * class HashSlow { + * XXH64_hash_t seed; + * public: + * HashSlow(XXH64_hash_t s) : seed{s} {} + * size_t operator()(const std::string& x) const { + * return size_t{XXH3_64bits_withSeed(x.c_str(), x.length(), seed)}; + * } + * }; + * // Fast, caches the seeded secret for future uses. + * class HashFast { + * unsigned char secret[XXH3_SECRET_SIZE_MIN]; + * public: + * HashFast(XXH64_hash_t s) { + * XXH3_generateSecret_fromSeed(secret, seed); + * } + * size_t operator()(const std::string& x) const { + * return size_t{ + * XXH3_64bits_withSecret(x.c_str(), x.length(), secret, sizeof(secret)) + * }; + * } + * }; + * @endcode + */ +XXH_PUBLIC_API void XXH3_generateSecret_fromSeed(XXH_NOESCAPE void* secretBuffer, XXH64_hash_t seed); + +/*! + * @brief Calculates 64/128-bit seeded variant of XXH3 hash of @p data. + * + * @param data The block of data to be hashed, at least @p len bytes in size. + * @param len The length of @p data, in bytes. + * @param secret The secret data. + * @param secretSize The length of @p secret, in bytes. + * @param seed The 64-bit seed to alter the hash result predictably. + * + * These variants generate hash values using either + * @p seed for "short" keys (< @ref XXH3_MIDSIZE_MAX = 240 bytes) + * or @p secret for "large" keys (>= @ref XXH3_MIDSIZE_MAX). + * + * This generally benefits speed, compared to `_withSeed()` or `_withSecret()`. + * `_withSeed()` has to generate the secret on the fly for "large" keys. + * It's fast, but can be perceptible for "not so large" keys (< 1 KB). + * `_withSecret()` has to generate the masks on the fly for "small" keys, + * which requires more instructions than _withSeed() variants. + * Therefore, _withSecretandSeed variant combines the best of both worlds. + * + * When @p secret has been generated by XXH3_generateSecret_fromSeed(), + * this variant produces *exactly* the same results as `_withSeed()` variant, + * hence offering only a pure speed benefit on "large" input, + * by skipping the need to regenerate the secret for every large input. + * + * Another usage scenario is to hash the secret to a 64-bit hash value, + * for example with XXH3_64bits(), which then becomes the seed, + * and then employ both the seed and the secret in _withSecretandSeed(). + * On top of speed, an added benefit is that each bit in the secret + * has a 50% chance to swap each bit in the output, via its impact to the seed. + * + * This is not guaranteed when using the secret directly in "small data" scenarios, + * because only portions of the secret are employed for small data. + */ +XXH_PUBLIC_API XXH_PUREF XXH64_hash_t +XXH3_64bits_withSecretandSeed(XXH_NOESCAPE const void* data, size_t len, + XXH_NOESCAPE const void* secret, size_t secretSize, + XXH64_hash_t seed); +/*! + * @brief Calculates 128-bit seeded variant of XXH3 hash of @p data. + * + * @param input The block of data to be hashed, at least @p len bytes in size. + * @param length The length of @p data, in bytes. + * @param secret The secret data. + * @param secretSize The length of @p secret, in bytes. + * @param seed64 The 64-bit seed to alter the hash result predictably. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @see XXH3_64bits_withSecretandSeed() + */ +XXH_PUBLIC_API XXH_PUREF XXH128_hash_t +XXH3_128bits_withSecretandSeed(XXH_NOESCAPE const void* input, size_t length, + XXH_NOESCAPE const void* secret, size_t secretSize, + XXH64_hash_t seed64); +#ifndef XXH_NO_STREAM +/*! + * @brief Resets an @ref XXH3_state_t with secret data to begin a new hash. + * + * @param statePtr A pointer to an @ref XXH3_state_t allocated with @ref XXH3_createState(). + * @param secret The secret data. + * @param secretSize The length of @p secret, in bytes. + * @param seed64 The 64-bit seed to alter the hash result predictably. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @see XXH3_64bits_withSecretandSeed() + */ +XXH_PUBLIC_API XXH_errorcode +XXH3_64bits_reset_withSecretandSeed(XXH_NOESCAPE XXH3_state_t* statePtr, + XXH_NOESCAPE const void* secret, size_t secretSize, + XXH64_hash_t seed64); +/*! + * @brief Resets an @ref XXH3_state_t with secret data to begin a new hash. + * + * @param statePtr A pointer to an @ref XXH3_state_t allocated with @ref XXH3_createState(). + * @param secret The secret data. + * @param secretSize The length of @p secret, in bytes. + * @param seed64 The 64-bit seed to alter the hash result predictably. + * + * @return @ref XXH_OK on success. + * @return @ref XXH_ERROR on failure. + * + * @see XXH3_64bits_withSecretandSeed() + */ +XXH_PUBLIC_API XXH_errorcode +XXH3_128bits_reset_withSecretandSeed(XXH_NOESCAPE XXH3_state_t* statePtr, + XXH_NOESCAPE const void* secret, size_t secretSize, + XXH64_hash_t seed64); +#endif /* !XXH_NO_STREAM */ + +#if defined (__cplusplus) +} /* extern "C" */ +#endif + +#endif /* !XXH_NO_XXH3 */ +#endif /* XXH_NO_LONG_LONG */ + +#if defined(XXH_INLINE_ALL) || defined(XXH_PRIVATE_API) +# define XXH_IMPLEMENTATION +#endif + +#endif /* defined(XXH_STATIC_LINKING_ONLY) && !defined(XXHASH_H_STATIC_13879238742) */ + + +/* ======================================================================== */ +/* ======================================================================== */ +/* ======================================================================== */ + + +/*-********************************************************************** + * xxHash implementation + *-********************************************************************** + * xxHash's implementation used to be hosted inside xxhash.c. + * + * However, inlining requires implementation to be visible to the compiler, + * hence be included alongside the header. + * Previously, implementation was hosted inside xxhash.c, + * which was then #included when inlining was activated. + * This construction created issues with a few build and install systems, + * as it required xxhash.c to be stored in /include directory. + * + * xxHash implementation is now directly integrated within xxhash.h. + * As a consequence, xxhash.c is no longer needed in /include. + * + * xxhash.c is still available and is still useful. + * In a "normal" setup, when xxhash is not inlined, + * xxhash.h only exposes the prototypes and public symbols, + * while xxhash.c can be built into an object file xxhash.o + * which can then be linked into the final binary. + ************************************************************************/ + +#if ( defined(XXH_INLINE_ALL) || defined(XXH_PRIVATE_API) \ + || defined(XXH_IMPLEMENTATION) ) && !defined(XXH_IMPLEM_13a8737387) +# define XXH_IMPLEM_13a8737387 + +/* ************************************* +* Tuning parameters +***************************************/ + +/*! + * @defgroup tuning Tuning parameters + * @{ + * + * Various macros to control xxHash's behavior. + */ +#ifdef XXH_DOXYGEN +/*! + * @brief Define this to disable 64-bit code. + * + * Useful if only using the @ref XXH32_family and you have a strict C90 compiler. + */ +# define XXH_NO_LONG_LONG +# undef XXH_NO_LONG_LONG /* don't actually */ +/*! + * @brief Controls how unaligned memory is accessed. + * + * By default, access to unaligned memory is controlled by `memcpy()`, which is + * safe and portable. + * + * Unfortunately, on some target/compiler combinations, the generated assembly + * is sub-optimal. + * + * The below switch allow selection of a different access method + * in the search for improved performance. + * + * @par Possible options: + * + * - `XXH_FORCE_MEMORY_ACCESS=0` (default): `memcpy` + * @par + * Use `memcpy()`. Safe and portable. Note that most modern compilers will + * eliminate the function call and treat it as an unaligned access. + * + * - `XXH_FORCE_MEMORY_ACCESS=1`: `__attribute__((aligned(1)))` + * @par + * Depends on compiler extensions and is therefore not portable. + * This method is safe _if_ your compiler supports it, + * and *generally* as fast or faster than `memcpy`. + * + * - `XXH_FORCE_MEMORY_ACCESS=2`: Direct cast + * @par + * Casts directly and dereferences. This method doesn't depend on the + * compiler, but it violates the C standard as it directly dereferences an + * unaligned pointer. It can generate buggy code on targets which do not + * support unaligned memory accesses, but in some circumstances, it's the + * only known way to get the most performance. + * + * - `XXH_FORCE_MEMORY_ACCESS=3`: Byteshift + * @par + * Also portable. This can generate the best code on old compilers which don't + * inline small `memcpy()` calls, and it might also be faster on big-endian + * systems which lack a native byteswap instruction. However, some compilers + * will emit literal byteshifts even if the target supports unaligned access. + * + * + * @warning + * Methods 1 and 2 rely on implementation-defined behavior. Use these with + * care, as what works on one compiler/platform/optimization level may cause + * another to read garbage data or even crash. + * + * See https://fastcompression.blogspot.com/2015/08/accessing-unaligned-memory.html for details. + * + * Prefer these methods in priority order (0 > 3 > 1 > 2) + */ +# define XXH_FORCE_MEMORY_ACCESS 0 + +/*! + * @def XXH_SIZE_OPT + * @brief Controls how much xxHash optimizes for size. + * + * xxHash, when compiled, tends to result in a rather large binary size. This + * is mostly due to heavy usage to forced inlining and constant folding of the + * @ref XXH3_family to increase performance. + * + * However, some developers prefer size over speed. This option can + * significantly reduce the size of the generated code. When using the `-Os` + * or `-Oz` options on GCC or Clang, this is defined to 1 by default, + * otherwise it is defined to 0. + * + * Most of these size optimizations can be controlled manually. + * + * This is a number from 0-2. + * - `XXH_SIZE_OPT` == 0: Default. xxHash makes no size optimizations. Speed + * comes first. + * - `XXH_SIZE_OPT` == 1: Default for `-Os` and `-Oz`. xxHash is more + * conservative and disables hacks that increase code size. It implies the + * options @ref XXH_NO_INLINE_HINTS == 1, @ref XXH_FORCE_ALIGN_CHECK == 0, + * and @ref XXH3_NEON_LANES == 8 if they are not already defined. + * - `XXH_SIZE_OPT` == 2: xxHash tries to make itself as small as possible. + * Performance may cry. For example, the single shot functions just use the + * streaming API. + */ +# define XXH_SIZE_OPT 0 + +/*! + * @def XXH_FORCE_ALIGN_CHECK + * @brief If defined to non-zero, adds a special path for aligned inputs (XXH32() + * and XXH64() only). + * + * This is an important performance trick for architectures without decent + * unaligned memory access performance. + * + * It checks for input alignment, and when conditions are met, uses a "fast + * path" employing direct 32-bit/64-bit reads, resulting in _dramatically + * faster_ read speed. + * + * The check costs one initial branch per hash, which is generally negligible, + * but not zero. + * + * Moreover, it's not useful to generate an additional code path if memory + * access uses the same instruction for both aligned and unaligned + * addresses (e.g. x86 and aarch64). + * + * In these cases, the alignment check can be removed by setting this macro to 0. + * Then the code will always use unaligned memory access. + * Align check is automatically disabled on x86, x64, ARM64, and some ARM chips + * which are platforms known to offer good unaligned memory accesses performance. + * + * It is also disabled by default when @ref XXH_SIZE_OPT >= 1. + * + * This option does not affect XXH3 (only XXH32 and XXH64). + */ +# define XXH_FORCE_ALIGN_CHECK 0 + +/*! + * @def XXH_NO_INLINE_HINTS + * @brief When non-zero, sets all functions to `static`. + * + * By default, xxHash tries to force the compiler to inline almost all internal + * functions. + * + * This can usually improve performance due to reduced jumping and improved + * constant folding, but significantly increases the size of the binary which + * might not be favorable. + * + * Additionally, sometimes the forced inlining can be detrimental to performance, + * depending on the architecture. + * + * XXH_NO_INLINE_HINTS marks all internal functions as static, giving the + * compiler full control on whether to inline or not. + * + * When not optimizing (-O0), using `-fno-inline` with GCC or Clang, or if + * @ref XXH_SIZE_OPT >= 1, this will automatically be defined. + */ +# define XXH_NO_INLINE_HINTS 0 + +/*! + * @def XXH3_INLINE_SECRET + * @brief Determines whether to inline the XXH3 withSecret code. + * + * When the secret size is known, the compiler can improve the performance + * of XXH3_64bits_withSecret() and XXH3_128bits_withSecret(). + * + * However, if the secret size is not known, it doesn't have any benefit. This + * happens when xxHash is compiled into a global symbol. Therefore, if + * @ref XXH_INLINE_ALL is *not* defined, this will be defined to 0. + * + * Additionally, this defaults to 0 on GCC 12+, which has an issue with function pointers + * that are *sometimes* force inline on -Og, and it is impossible to automatically + * detect this optimization level. + */ +# define XXH3_INLINE_SECRET 0 + +/*! + * @def XXH32_ENDJMP + * @brief Whether to use a jump for `XXH32_finalize`. + * + * For performance, `XXH32_finalize` uses multiple branches in the finalizer. + * This is generally preferable for performance, + * but depending on exact architecture, a jmp may be preferable. + * + * This setting is only possibly making a difference for very small inputs. + */ +# define XXH32_ENDJMP 0 + +/*! + * @internal + * @brief Redefines old internal names. + * + * For compatibility with code that uses xxHash's internals before the names + * were changed to improve namespacing. There is no other reason to use this. + */ +# define XXH_OLD_NAMES +# undef XXH_OLD_NAMES /* don't actually use, it is ugly. */ + +/*! + * @def XXH_NO_STREAM + * @brief Disables the streaming API. + * + * When xxHash is not inlined and the streaming functions are not used, disabling + * the streaming functions can improve code size significantly, especially with + * the @ref XXH3_family which tends to make constant folded copies of itself. + */ +# define XXH_NO_STREAM +# undef XXH_NO_STREAM /* don't actually */ +#endif /* XXH_DOXYGEN */ +/*! + * @} + */ + +#ifndef XXH_FORCE_MEMORY_ACCESS /* can be defined externally, on command line for example */ + /* prefer __packed__ structures (method 1) for GCC + * < ARMv7 with unaligned access (e.g. Raspbian armhf) still uses byte shifting, so we use memcpy + * which for some reason does unaligned loads. */ +# if defined(__GNUC__) && !(defined(__ARM_ARCH) && __ARM_ARCH < 7 && defined(__ARM_FEATURE_UNALIGNED)) +# define XXH_FORCE_MEMORY_ACCESS 1 +# endif +#endif + +#ifndef XXH_SIZE_OPT + /* default to 1 for -Os or -Oz */ +# if (defined(__GNUC__) || defined(__clang__)) && defined(__OPTIMIZE_SIZE__) +# define XXH_SIZE_OPT 1 +# else +# define XXH_SIZE_OPT 0 +# endif +#endif + +#ifndef XXH_FORCE_ALIGN_CHECK /* can be defined externally */ + /* don't check on sizeopt, x86, aarch64, or arm when unaligned access is available */ +# if XXH_SIZE_OPT >= 1 || \ + defined(__i386) || defined(__x86_64__) || defined(__aarch64__) || defined(__ARM_FEATURE_UNALIGNED) \ + || defined(_M_IX86) || defined(_M_X64) || defined(_M_ARM64) || defined(_M_ARM) /* visual */ +# define XXH_FORCE_ALIGN_CHECK 0 +# else +# define XXH_FORCE_ALIGN_CHECK 1 +# endif +#endif + +#ifndef XXH_NO_INLINE_HINTS +# if XXH_SIZE_OPT >= 1 || defined(__NO_INLINE__) /* -O0, -fno-inline */ +# define XXH_NO_INLINE_HINTS 1 +# else +# define XXH_NO_INLINE_HINTS 0 +# endif +#endif + +#ifndef XXH3_INLINE_SECRET +# if (defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 12) \ + || !defined(XXH_INLINE_ALL) +# define XXH3_INLINE_SECRET 0 +# else +# define XXH3_INLINE_SECRET 1 +# endif +#endif + +#ifndef XXH32_ENDJMP +/* generally preferable for performance */ +# define XXH32_ENDJMP 0 +#endif + +/*! + * @defgroup impl Implementation + * @{ + */ + +/* ************************************* +* Includes & Memory related functions +***************************************/ +#include /* memcmp, memcpy */ +#include /* ULLONG_MAX */ + +#if defined(XXH_NO_STREAM) +/* nothing */ +#elif defined(XXH_NO_STDLIB) + +/* When requesting to disable any mention of stdlib, + * the library loses the ability to invoked malloc / free. + * In practice, it means that functions like `XXH*_createState()` + * will always fail, and return NULL. + * This flag is useful in situations where + * xxhash.h is integrated into some kernel, embedded or limited environment + * without access to dynamic allocation. + */ + +#if defined (__cplusplus) +extern "C" { +#endif + +static XXH_CONSTF void* XXH_malloc(size_t s) { (void)s; return NULL; } +static void XXH_free(void* p) { (void)p; } + +#if defined (__cplusplus) +} /* extern "C" */ +#endif + +#else + +/* + * Modify the local functions below should you wish to use + * different memory routines for malloc() and free() + */ +#include + +#if defined (__cplusplus) +extern "C" { +#endif +/*! + * @internal + * @brief Modify this function to use a different routine than malloc(). + */ +static XXH_MALLOCF void* XXH_malloc(size_t s) { return malloc(s); } + +/*! + * @internal + * @brief Modify this function to use a different routine than free(). + */ +static void XXH_free(void* p) { free(p); } + +#if defined (__cplusplus) +} /* extern "C" */ +#endif + +#endif /* XXH_NO_STDLIB */ + +#if defined (__cplusplus) +extern "C" { +#endif +/*! + * @internal + * @brief Modify this function to use a different routine than memcpy(). + */ +static void* XXH_memcpy(void* dest, const void* src, size_t size) +{ + return memcpy(dest,src,size); +} + +#if defined (__cplusplus) +} /* extern "C" */ +#endif + +/* ************************************* +* Compiler Specific Options +***************************************/ +#ifdef _MSC_VER /* Visual Studio warning fix */ +# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ +#endif + +#if XXH_NO_INLINE_HINTS /* disable inlining hints */ +# if defined(__GNUC__) || defined(__clang__) +# define XXH_FORCE_INLINE static __attribute__((unused)) +# else +# define XXH_FORCE_INLINE static +# endif +# define XXH_NO_INLINE static +/* enable inlining hints */ +#elif defined(__GNUC__) || defined(__clang__) +# define XXH_FORCE_INLINE static __inline__ __attribute__((always_inline, unused)) +# define XXH_NO_INLINE static __attribute__((noinline)) +#elif defined(_MSC_VER) /* Visual Studio */ +# define XXH_FORCE_INLINE static __forceinline +# define XXH_NO_INLINE static __declspec(noinline) +#elif defined (__cplusplus) \ + || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) /* C99 */ +# define XXH_FORCE_INLINE static inline +# define XXH_NO_INLINE static +#else +# define XXH_FORCE_INLINE static +# define XXH_NO_INLINE static +#endif + +#if XXH3_INLINE_SECRET +# define XXH3_WITH_SECRET_INLINE XXH_FORCE_INLINE +#else +# define XXH3_WITH_SECRET_INLINE XXH_NO_INLINE +#endif + + +/* ************************************* +* Debug +***************************************/ +/*! + * @ingroup tuning + * @def XXH_DEBUGLEVEL + * @brief Sets the debugging level. + * + * XXH_DEBUGLEVEL is expected to be defined externally, typically via the + * compiler's command line options. The value must be a number. + */ +#ifndef XXH_DEBUGLEVEL +# ifdef DEBUGLEVEL /* backwards compat */ +# define XXH_DEBUGLEVEL DEBUGLEVEL +# else +# define XXH_DEBUGLEVEL 0 +# endif +#endif + +#if (XXH_DEBUGLEVEL>=1) +# include /* note: can still be disabled with NDEBUG */ +# define XXH_ASSERT(c) assert(c) +#else +# if defined(__INTEL_COMPILER) +# define XXH_ASSERT(c) XXH_ASSUME((unsigned char) (c)) +# else +# define XXH_ASSERT(c) XXH_ASSUME(c) +# endif +#endif + +/* note: use after variable declarations */ +#ifndef XXH_STATIC_ASSERT +# if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) /* C11 */ +# define XXH_STATIC_ASSERT_WITH_MESSAGE(c,m) do { _Static_assert((c),m); } while(0) +# elif defined(__cplusplus) && (__cplusplus >= 201103L) /* C++11 */ +# define XXH_STATIC_ASSERT_WITH_MESSAGE(c,m) do { static_assert((c),m); } while(0) +# else +# define XXH_STATIC_ASSERT_WITH_MESSAGE(c,m) do { struct xxh_sa { char x[(c) ? 1 : -1]; }; } while(0) +# endif +# define XXH_STATIC_ASSERT(c) XXH_STATIC_ASSERT_WITH_MESSAGE((c),#c) +#endif + +/*! + * @internal + * @def XXH_COMPILER_GUARD(var) + * @brief Used to prevent unwanted optimizations for @p var. + * + * It uses an empty GCC inline assembly statement with a register constraint + * which forces @p var into a general purpose register (eg eax, ebx, ecx + * on x86) and marks it as modified. + * + * This is used in a few places to avoid unwanted autovectorization (e.g. + * XXH32_round()). All vectorization we want is explicit via intrinsics, + * and _usually_ isn't wanted elsewhere. + * + * We also use it to prevent unwanted constant folding for AArch64 in + * XXH3_initCustomSecret_scalar(). + */ +#if defined(__GNUC__) || defined(__clang__) +# define XXH_COMPILER_GUARD(var) __asm__("" : "+r" (var)) +#else +# define XXH_COMPILER_GUARD(var) ((void)0) +#endif + +/* Specifically for NEON vectors which use the "w" constraint, on + * Clang. */ +#if defined(__clang__) && defined(__ARM_ARCH) && !defined(__wasm__) +# define XXH_COMPILER_GUARD_CLANG_NEON(var) __asm__("" : "+w" (var)) +#else +# define XXH_COMPILER_GUARD_CLANG_NEON(var) ((void)0) +#endif + +/* ************************************* +* Basic Types +***************************************/ +#if !defined (__VMS) \ + && (defined (__cplusplus) \ + || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) ) +# ifdef _AIX +# include +# else +# include +# endif + typedef uint8_t xxh_u8; +#else + typedef unsigned char xxh_u8; +#endif +typedef XXH32_hash_t xxh_u32; + +#ifdef XXH_OLD_NAMES +# warning "XXH_OLD_NAMES is planned to be removed starting v0.9. If the program depends on it, consider moving away from it by employing newer type names directly" +# define BYTE xxh_u8 +# define U8 xxh_u8 +# define U32 xxh_u32 +#endif + +#if defined (__cplusplus) +extern "C" { +#endif + +/* *** Memory access *** */ + +/*! + * @internal + * @fn xxh_u32 XXH_read32(const void* ptr) + * @brief Reads an unaligned 32-bit integer from @p ptr in native endianness. + * + * Affected by @ref XXH_FORCE_MEMORY_ACCESS. + * + * @param ptr The pointer to read from. + * @return The 32-bit native endian integer from the bytes at @p ptr. + */ + +/*! + * @internal + * @fn xxh_u32 XXH_readLE32(const void* ptr) + * @brief Reads an unaligned 32-bit little endian integer from @p ptr. + * + * Affected by @ref XXH_FORCE_MEMORY_ACCESS. + * + * @param ptr The pointer to read from. + * @return The 32-bit little endian integer from the bytes at @p ptr. + */ + +/*! + * @internal + * @fn xxh_u32 XXH_readBE32(const void* ptr) + * @brief Reads an unaligned 32-bit big endian integer from @p ptr. + * + * Affected by @ref XXH_FORCE_MEMORY_ACCESS. + * + * @param ptr The pointer to read from. + * @return The 32-bit big endian integer from the bytes at @p ptr. + */ + +/*! + * @internal + * @fn xxh_u32 XXH_readLE32_align(const void* ptr, XXH_alignment align) + * @brief Like @ref XXH_readLE32(), but has an option for aligned reads. + * + * Affected by @ref XXH_FORCE_MEMORY_ACCESS. + * Note that when @ref XXH_FORCE_ALIGN_CHECK == 0, the @p align parameter is + * always @ref XXH_alignment::XXH_unaligned. + * + * @param ptr The pointer to read from. + * @param align Whether @p ptr is aligned. + * @pre + * If @p align == @ref XXH_alignment::XXH_aligned, @p ptr must be 4 byte + * aligned. + * @return The 32-bit little endian integer from the bytes at @p ptr. + */ + +#if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==3)) +/* + * Manual byteshift. Best for old compilers which don't inline memcpy. + * We actually directly use XXH_readLE32 and XXH_readBE32. + */ +#elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==2)) + +/* + * Force direct memory access. Only works on CPU which support unaligned memory + * access in hardware. + */ +static xxh_u32 XXH_read32(const void* memPtr) { return *(const xxh_u32*) memPtr; } + +#elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==1)) + +/* + * __attribute__((aligned(1))) is supported by gcc and clang. Originally the + * documentation claimed that it only increased the alignment, but actually it + * can decrease it on gcc, clang, and icc: + * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69502, + * https://gcc.godbolt.org/z/xYez1j67Y. + */ +#ifdef XXH_OLD_NAMES +typedef union { xxh_u32 u32; } __attribute__((packed)) unalign; +#endif +static xxh_u32 XXH_read32(const void* ptr) +{ + typedef __attribute__((aligned(1))) xxh_u32 xxh_unalign32; + return *((const xxh_unalign32*)ptr); +} + +#else + +/* + * Portable and safe solution. Generally efficient. + * see: https://fastcompression.blogspot.com/2015/08/accessing-unaligned-memory.html + */ +static xxh_u32 XXH_read32(const void* memPtr) +{ + xxh_u32 val; + XXH_memcpy(&val, memPtr, sizeof(val)); + return val; +} + +#endif /* XXH_FORCE_DIRECT_MEMORY_ACCESS */ + + +/* *** Endianness *** */ + +/*! + * @ingroup tuning + * @def XXH_CPU_LITTLE_ENDIAN + * @brief Whether the target is little endian. + * + * Defined to 1 if the target is little endian, or 0 if it is big endian. + * It can be defined externally, for example on the compiler command line. + * + * If it is not defined, + * a runtime check (which is usually constant folded) is used instead. + * + * @note + * This is not necessarily defined to an integer constant. + * + * @see XXH_isLittleEndian() for the runtime check. + */ +#ifndef XXH_CPU_LITTLE_ENDIAN +/* + * Try to detect endianness automatically, to avoid the nonstandard behavior + * in `XXH_isLittleEndian()` + */ +# if defined(_WIN32) /* Windows is always little endian */ \ + || defined(__LITTLE_ENDIAN__) \ + || (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) +# define XXH_CPU_LITTLE_ENDIAN 1 +# elif defined(__BIG_ENDIAN__) \ + || (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) +# define XXH_CPU_LITTLE_ENDIAN 0 +# else +/*! + * @internal + * @brief Runtime check for @ref XXH_CPU_LITTLE_ENDIAN. + * + * Most compilers will constant fold this. + */ +static int XXH_isLittleEndian(void) +{ + /* + * Portable and well-defined behavior. + * Don't use static: it is detrimental to performance. + */ + const union { xxh_u32 u; xxh_u8 c[4]; } one = { 1 }; + return one.c[0]; +} +# define XXH_CPU_LITTLE_ENDIAN XXH_isLittleEndian() +# endif +#endif + + + + +/* **************************************** +* Compiler-specific Functions and Macros +******************************************/ +#define XXH_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) + +#ifdef __has_builtin +# define XXH_HAS_BUILTIN(x) __has_builtin(x) +#else +# define XXH_HAS_BUILTIN(x) 0 +#endif + + + +/* + * C23 and future versions have standard "unreachable()". + * Once it has been implemented reliably we can add it as an + * additional case: + * + * ``` + * #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= XXH_C23_VN) + * # include + * # ifdef unreachable + * # define XXH_UNREACHABLE() unreachable() + * # endif + * #endif + * ``` + * + * Note C++23 also has std::unreachable() which can be detected + * as follows: + * ``` + * #if defined(__cpp_lib_unreachable) && (__cpp_lib_unreachable >= 202202L) + * # include + * # define XXH_UNREACHABLE() std::unreachable() + * #endif + * ``` + * NB: `__cpp_lib_unreachable` is defined in the `` header. + * We don't use that as including `` in `extern "C"` blocks + * doesn't work on GCC12 + */ + +#if XXH_HAS_BUILTIN(__builtin_unreachable) +# define XXH_UNREACHABLE() __builtin_unreachable() + +#elif defined(_MSC_VER) +# define XXH_UNREACHABLE() __assume(0) + +#else +# define XXH_UNREACHABLE() +#endif + +#if XXH_HAS_BUILTIN(__builtin_assume) +# define XXH_ASSUME(c) __builtin_assume(c) +#else +# define XXH_ASSUME(c) if (!(c)) { XXH_UNREACHABLE(); } +#endif + +/*! + * @internal + * @def XXH_rotl32(x,r) + * @brief 32-bit rotate left. + * + * @param x The 32-bit integer to be rotated. + * @param r The number of bits to rotate. + * @pre + * @p r > 0 && @p r < 32 + * @note + * @p x and @p r may be evaluated multiple times. + * @return The rotated result. + */ +#if !defined(NO_CLANG_BUILTIN) && XXH_HAS_BUILTIN(__builtin_rotateleft32) \ + && XXH_HAS_BUILTIN(__builtin_rotateleft64) +# define XXH_rotl32 __builtin_rotateleft32 +# define XXH_rotl64 __builtin_rotateleft64 +/* Note: although _rotl exists for minGW (GCC under windows), performance seems poor */ +#elif defined(_MSC_VER) +# define XXH_rotl32(x,r) _rotl(x,r) +# define XXH_rotl64(x,r) _rotl64(x,r) +#else +# define XXH_rotl32(x,r) (((x) << (r)) | ((x) >> (32 - (r)))) +# define XXH_rotl64(x,r) (((x) << (r)) | ((x) >> (64 - (r)))) +#endif + +/*! + * @internal + * @fn xxh_u32 XXH_swap32(xxh_u32 x) + * @brief A 32-bit byteswap. + * + * @param x The 32-bit integer to byteswap. + * @return @p x, byteswapped. + */ +#if defined(_MSC_VER) /* Visual Studio */ +# define XXH_swap32 _byteswap_ulong +#elif XXH_GCC_VERSION >= 403 +# define XXH_swap32 __builtin_bswap32 +#else +static xxh_u32 XXH_swap32 (xxh_u32 x) +{ + return ((x << 24) & 0xff000000 ) | + ((x << 8) & 0x00ff0000 ) | + ((x >> 8) & 0x0000ff00 ) | + ((x >> 24) & 0x000000ff ); +} +#endif + + +/* *************************** +* Memory reads +*****************************/ + +/*! + * @internal + * @brief Enum to indicate whether a pointer is aligned. + */ +typedef enum { + XXH_aligned, /*!< Aligned */ + XXH_unaligned /*!< Possibly unaligned */ +} XXH_alignment; + +/* + * XXH_FORCE_MEMORY_ACCESS==3 is an endian-independent byteshift load. + * + * This is ideal for older compilers which don't inline memcpy. + */ +#if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==3)) + +XXH_FORCE_INLINE xxh_u32 XXH_readLE32(const void* memPtr) +{ + const xxh_u8* bytePtr = (const xxh_u8 *)memPtr; + return bytePtr[0] + | ((xxh_u32)bytePtr[1] << 8) + | ((xxh_u32)bytePtr[2] << 16) + | ((xxh_u32)bytePtr[3] << 24); +} + +XXH_FORCE_INLINE xxh_u32 XXH_readBE32(const void* memPtr) +{ + const xxh_u8* bytePtr = (const xxh_u8 *)memPtr; + return bytePtr[3] + | ((xxh_u32)bytePtr[2] << 8) + | ((xxh_u32)bytePtr[1] << 16) + | ((xxh_u32)bytePtr[0] << 24); +} + +#else +XXH_FORCE_INLINE xxh_u32 XXH_readLE32(const void* ptr) +{ + return XXH_CPU_LITTLE_ENDIAN ? XXH_read32(ptr) : XXH_swap32(XXH_read32(ptr)); +} + +static xxh_u32 XXH_readBE32(const void* ptr) +{ + return XXH_CPU_LITTLE_ENDIAN ? XXH_swap32(XXH_read32(ptr)) : XXH_read32(ptr); +} +#endif + +XXH_FORCE_INLINE xxh_u32 +XXH_readLE32_align(const void* ptr, XXH_alignment align) +{ + if (align==XXH_unaligned) { + return XXH_readLE32(ptr); + } else { + return XXH_CPU_LITTLE_ENDIAN ? *(const xxh_u32*)ptr : XXH_swap32(*(const xxh_u32*)ptr); + } +} + + +/* ************************************* +* Misc +***************************************/ +/*! @ingroup public */ +XXH_PUBLIC_API unsigned XXH_versionNumber (void) { return XXH_VERSION_NUMBER; } + + +/* ******************************************************************* +* 32-bit hash functions +*********************************************************************/ +/*! + * @} + * @defgroup XXH32_impl XXH32 implementation + * @ingroup impl + * + * Details on the XXH32 implementation. + * @{ + */ + /* #define instead of static const, to be used as initializers */ +#define XXH_PRIME32_1 0x9E3779B1U /*!< 0b10011110001101110111100110110001 */ +#define XXH_PRIME32_2 0x85EBCA77U /*!< 0b10000101111010111100101001110111 */ +#define XXH_PRIME32_3 0xC2B2AE3DU /*!< 0b11000010101100101010111000111101 */ +#define XXH_PRIME32_4 0x27D4EB2FU /*!< 0b00100111110101001110101100101111 */ +#define XXH_PRIME32_5 0x165667B1U /*!< 0b00010110010101100110011110110001 */ + +#ifdef XXH_OLD_NAMES +# define PRIME32_1 XXH_PRIME32_1 +# define PRIME32_2 XXH_PRIME32_2 +# define PRIME32_3 XXH_PRIME32_3 +# define PRIME32_4 XXH_PRIME32_4 +# define PRIME32_5 XXH_PRIME32_5 +#endif + +/*! + * @internal + * @brief Normal stripe processing routine. + * + * This shuffles the bits so that any bit from @p input impacts several bits in + * @p acc. + * + * @param acc The accumulator lane. + * @param input The stripe of input to mix. + * @return The mixed accumulator lane. + */ +static xxh_u32 XXH32_round(xxh_u32 acc, xxh_u32 input) +{ + acc += input * XXH_PRIME32_2; + acc = XXH_rotl32(acc, 13); + acc *= XXH_PRIME32_1; +#if (defined(__SSE4_1__) || defined(__aarch64__) || defined(__wasm_simd128__)) && !defined(XXH_ENABLE_AUTOVECTORIZE) + /* + * UGLY HACK: + * A compiler fence is the only thing that prevents GCC and Clang from + * autovectorizing the XXH32 loop (pragmas and attributes don't work for some + * reason) without globally disabling SSE4.1. + * + * The reason we want to avoid vectorization is because despite working on + * 4 integers at a time, there are multiple factors slowing XXH32 down on + * SSE4: + * - There's a ridiculous amount of lag from pmulld (10 cycles of latency on + * newer chips!) making it slightly slower to multiply four integers at + * once compared to four integers independently. Even when pmulld was + * fastest, Sandy/Ivy Bridge, it is still not worth it to go into SSE + * just to multiply unless doing a long operation. + * + * - Four instructions are required to rotate, + * movqda tmp, v // not required with VEX encoding + * pslld tmp, 13 // tmp <<= 13 + * psrld v, 19 // x >>= 19 + * por v, tmp // x |= tmp + * compared to one for scalar: + * roll v, 13 // reliably fast across the board + * shldl v, v, 13 // Sandy Bridge and later prefer this for some reason + * + * - Instruction level parallelism is actually more beneficial here because + * the SIMD actually serializes this operation: While v1 is rotating, v2 + * can load data, while v3 can multiply. SSE forces them to operate + * together. + * + * This is also enabled on AArch64, as Clang is *very aggressive* in vectorizing + * the loop. NEON is only faster on the A53, and with the newer cores, it is less + * than half the speed. + * + * Additionally, this is used on WASM SIMD128 because it JITs to the same + * SIMD instructions and has the same issue. + */ + XXH_COMPILER_GUARD(acc); +#endif + return acc; +} + +/*! + * @internal + * @brief Mixes all bits to finalize the hash. + * + * The final mix ensures that all input bits have a chance to impact any bit in + * the output digest, resulting in an unbiased distribution. + * + * @param hash The hash to avalanche. + * @return The avalanched hash. + */ +static xxh_u32 XXH32_avalanche(xxh_u32 hash) +{ + hash ^= hash >> 15; + hash *= XXH_PRIME32_2; + hash ^= hash >> 13; + hash *= XXH_PRIME32_3; + hash ^= hash >> 16; + return hash; +} + +#define XXH_get32bits(p) XXH_readLE32_align(p, align) + +/*! + * @internal + * @brief Processes the last 0-15 bytes of @p ptr. + * + * There may be up to 15 bytes remaining to consume from the input. + * This final stage will digest them to ensure that all input bytes are present + * in the final mix. + * + * @param hash The hash to finalize. + * @param ptr The pointer to the remaining input. + * @param len The remaining length, modulo 16. + * @param align Whether @p ptr is aligned. + * @return The finalized hash. + * @see XXH64_finalize(). + */ +static XXH_PUREF xxh_u32 +XXH32_finalize(xxh_u32 hash, const xxh_u8* ptr, size_t len, XXH_alignment align) +{ +#define XXH_PROCESS1 do { \ + hash += (*ptr++) * XXH_PRIME32_5; \ + hash = XXH_rotl32(hash, 11) * XXH_PRIME32_1; \ +} while (0) + +#define XXH_PROCESS4 do { \ + hash += XXH_get32bits(ptr) * XXH_PRIME32_3; \ + ptr += 4; \ + hash = XXH_rotl32(hash, 17) * XXH_PRIME32_4; \ +} while (0) + + if (ptr==NULL) XXH_ASSERT(len == 0); + + /* Compact rerolled version; generally faster */ + if (!XXH32_ENDJMP) { + len &= 15; + while (len >= 4) { + XXH_PROCESS4; + len -= 4; + } + while (len > 0) { + XXH_PROCESS1; + --len; + } + return XXH32_avalanche(hash); + } else { + switch(len&15) /* or switch(bEnd - p) */ { + case 12: XXH_PROCESS4; + XXH_FALLTHROUGH; /* fallthrough */ + case 8: XXH_PROCESS4; + XXH_FALLTHROUGH; /* fallthrough */ + case 4: XXH_PROCESS4; + return XXH32_avalanche(hash); + + case 13: XXH_PROCESS4; + XXH_FALLTHROUGH; /* fallthrough */ + case 9: XXH_PROCESS4; + XXH_FALLTHROUGH; /* fallthrough */ + case 5: XXH_PROCESS4; + XXH_PROCESS1; + return XXH32_avalanche(hash); + + case 14: XXH_PROCESS4; + XXH_FALLTHROUGH; /* fallthrough */ + case 10: XXH_PROCESS4; + XXH_FALLTHROUGH; /* fallthrough */ + case 6: XXH_PROCESS4; + XXH_PROCESS1; + XXH_PROCESS1; + return XXH32_avalanche(hash); + + case 15: XXH_PROCESS4; + XXH_FALLTHROUGH; /* fallthrough */ + case 11: XXH_PROCESS4; + XXH_FALLTHROUGH; /* fallthrough */ + case 7: XXH_PROCESS4; + XXH_FALLTHROUGH; /* fallthrough */ + case 3: XXH_PROCESS1; + XXH_FALLTHROUGH; /* fallthrough */ + case 2: XXH_PROCESS1; + XXH_FALLTHROUGH; /* fallthrough */ + case 1: XXH_PROCESS1; + XXH_FALLTHROUGH; /* fallthrough */ + case 0: return XXH32_avalanche(hash); + } + XXH_ASSERT(0); + return hash; /* reaching this point is deemed impossible */ + } +} + +#ifdef XXH_OLD_NAMES +# define PROCESS1 XXH_PROCESS1 +# define PROCESS4 XXH_PROCESS4 +#else +# undef XXH_PROCESS1 +# undef XXH_PROCESS4 +#endif + +/*! + * @internal + * @brief The implementation for @ref XXH32(). + * + * @param input , len , seed Directly passed from @ref XXH32(). + * @param align Whether @p input is aligned. + * @return The calculated hash. + */ +XXH_FORCE_INLINE XXH_PUREF xxh_u32 +XXH32_endian_align(const xxh_u8* input, size_t len, xxh_u32 seed, XXH_alignment align) +{ + xxh_u32 h32; + + if (input==NULL) XXH_ASSERT(len == 0); + + if (len>=16) { + const xxh_u8* const bEnd = input + len; + const xxh_u8* const limit = bEnd - 15; + xxh_u32 v1 = seed + XXH_PRIME32_1 + XXH_PRIME32_2; + xxh_u32 v2 = seed + XXH_PRIME32_2; + xxh_u32 v3 = seed + 0; + xxh_u32 v4 = seed - XXH_PRIME32_1; + + do { + v1 = XXH32_round(v1, XXH_get32bits(input)); input += 4; + v2 = XXH32_round(v2, XXH_get32bits(input)); input += 4; + v3 = XXH32_round(v3, XXH_get32bits(input)); input += 4; + v4 = XXH32_round(v4, XXH_get32bits(input)); input += 4; + } while (input < limit); + + h32 = XXH_rotl32(v1, 1) + XXH_rotl32(v2, 7) + + XXH_rotl32(v3, 12) + XXH_rotl32(v4, 18); + } else { + h32 = seed + XXH_PRIME32_5; + } + + h32 += (xxh_u32)len; + + return XXH32_finalize(h32, input, len&15, align); +} + +/*! @ingroup XXH32_family */ +XXH_PUBLIC_API XXH32_hash_t XXH32 (const void* input, size_t len, XXH32_hash_t seed) +{ +#if !defined(XXH_NO_STREAM) && XXH_SIZE_OPT >= 2 + /* Simple version, good for code maintenance, but unfortunately slow for small inputs */ + XXH32_state_t state; + XXH32_reset(&state, seed); + XXH32_update(&state, (const xxh_u8*)input, len); + return XXH32_digest(&state); +#else + if (XXH_FORCE_ALIGN_CHECK) { + if ((((size_t)input) & 3) == 0) { /* Input is 4-bytes aligned, leverage the speed benefit */ + return XXH32_endian_align((const xxh_u8*)input, len, seed, XXH_aligned); + } } + + return XXH32_endian_align((const xxh_u8*)input, len, seed, XXH_unaligned); +#endif +} + + + +/******* Hash streaming *******/ +#ifndef XXH_NO_STREAM +/*! @ingroup XXH32_family */ +XXH_PUBLIC_API XXH32_state_t* XXH32_createState(void) +{ + return (XXH32_state_t*)XXH_malloc(sizeof(XXH32_state_t)); +} +/*! @ingroup XXH32_family */ +XXH_PUBLIC_API XXH_errorcode XXH32_freeState(XXH32_state_t* statePtr) +{ + XXH_free(statePtr); + return XXH_OK; +} + +/*! @ingroup XXH32_family */ +XXH_PUBLIC_API void XXH32_copyState(XXH32_state_t* dstState, const XXH32_state_t* srcState) +{ + XXH_memcpy(dstState, srcState, sizeof(*dstState)); +} + +/*! @ingroup XXH32_family */ +XXH_PUBLIC_API XXH_errorcode XXH32_reset(XXH32_state_t* statePtr, XXH32_hash_t seed) +{ + XXH_ASSERT(statePtr != NULL); + memset(statePtr, 0, sizeof(*statePtr)); + statePtr->v[0] = seed + XXH_PRIME32_1 + XXH_PRIME32_2; + statePtr->v[1] = seed + XXH_PRIME32_2; + statePtr->v[2] = seed + 0; + statePtr->v[3] = seed - XXH_PRIME32_1; + return XXH_OK; +} + + +/*! @ingroup XXH32_family */ +XXH_PUBLIC_API XXH_errorcode +XXH32_update(XXH32_state_t* state, const void* input, size_t len) +{ + if (input==NULL) { + XXH_ASSERT(len == 0); + return XXH_OK; + } + + { const xxh_u8* p = (const xxh_u8*)input; + const xxh_u8* const bEnd = p + len; + + state->total_len_32 += (XXH32_hash_t)len; + state->large_len |= (XXH32_hash_t)((len>=16) | (state->total_len_32>=16)); + + if (state->memsize + len < 16) { /* fill in tmp buffer */ + XXH_memcpy((xxh_u8*)(state->mem32) + state->memsize, input, len); + state->memsize += (XXH32_hash_t)len; + return XXH_OK; + } + + if (state->memsize) { /* some data left from previous update */ + XXH_memcpy((xxh_u8*)(state->mem32) + state->memsize, input, 16-state->memsize); + { const xxh_u32* p32 = state->mem32; + state->v[0] = XXH32_round(state->v[0], XXH_readLE32(p32)); p32++; + state->v[1] = XXH32_round(state->v[1], XXH_readLE32(p32)); p32++; + state->v[2] = XXH32_round(state->v[2], XXH_readLE32(p32)); p32++; + state->v[3] = XXH32_round(state->v[3], XXH_readLE32(p32)); + } + p += 16-state->memsize; + state->memsize = 0; + } + + if (p <= bEnd-16) { + const xxh_u8* const limit = bEnd - 16; + + do { + state->v[0] = XXH32_round(state->v[0], XXH_readLE32(p)); p+=4; + state->v[1] = XXH32_round(state->v[1], XXH_readLE32(p)); p+=4; + state->v[2] = XXH32_round(state->v[2], XXH_readLE32(p)); p+=4; + state->v[3] = XXH32_round(state->v[3], XXH_readLE32(p)); p+=4; + } while (p<=limit); + + } + + if (p < bEnd) { + XXH_memcpy(state->mem32, p, (size_t)(bEnd-p)); + state->memsize = (unsigned)(bEnd-p); + } + } + + return XXH_OK; +} + + +/*! @ingroup XXH32_family */ +XXH_PUBLIC_API XXH32_hash_t XXH32_digest(const XXH32_state_t* state) +{ + xxh_u32 h32; + + if (state->large_len) { + h32 = XXH_rotl32(state->v[0], 1) + + XXH_rotl32(state->v[1], 7) + + XXH_rotl32(state->v[2], 12) + + XXH_rotl32(state->v[3], 18); + } else { + h32 = state->v[2] /* == seed */ + XXH_PRIME32_5; + } + + h32 += state->total_len_32; + + return XXH32_finalize(h32, (const xxh_u8*)state->mem32, state->memsize, XXH_aligned); +} +#endif /* !XXH_NO_STREAM */ + +/******* Canonical representation *******/ + +/*! @ingroup XXH32_family */ +XXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t* dst, XXH32_hash_t hash) +{ + XXH_STATIC_ASSERT(sizeof(XXH32_canonical_t) == sizeof(XXH32_hash_t)); + if (XXH_CPU_LITTLE_ENDIAN) hash = XXH_swap32(hash); + XXH_memcpy(dst, &hash, sizeof(*dst)); +} +/*! @ingroup XXH32_family */ +XXH_PUBLIC_API XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t* src) +{ + return XXH_readBE32(src); +} + + +#ifndef XXH_NO_LONG_LONG + +/* ******************************************************************* +* 64-bit hash functions +*********************************************************************/ +/*! + * @} + * @ingroup impl + * @{ + */ +/******* Memory access *******/ + +typedef XXH64_hash_t xxh_u64; + +#ifdef XXH_OLD_NAMES +# define U64 xxh_u64 +#endif + +#if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==3)) +/* + * Manual byteshift. Best for old compilers which don't inline memcpy. + * We actually directly use XXH_readLE64 and XXH_readBE64. + */ +#elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==2)) + +/* Force direct memory access. Only works on CPU which support unaligned memory access in hardware */ +static xxh_u64 XXH_read64(const void* memPtr) +{ + return *(const xxh_u64*) memPtr; +} + +#elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==1)) + +/* + * __attribute__((aligned(1))) is supported by gcc and clang. Originally the + * documentation claimed that it only increased the alignment, but actually it + * can decrease it on gcc, clang, and icc: + * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69502, + * https://gcc.godbolt.org/z/xYez1j67Y. + */ +#ifdef XXH_OLD_NAMES +typedef union { xxh_u32 u32; xxh_u64 u64; } __attribute__((packed)) unalign64; +#endif +static xxh_u64 XXH_read64(const void* ptr) +{ + typedef __attribute__((aligned(1))) xxh_u64 xxh_unalign64; + return *((const xxh_unalign64*)ptr); +} + +#else + +/* + * Portable and safe solution. Generally efficient. + * see: https://fastcompression.blogspot.com/2015/08/accessing-unaligned-memory.html + */ +static xxh_u64 XXH_read64(const void* memPtr) +{ + xxh_u64 val; + XXH_memcpy(&val, memPtr, sizeof(val)); + return val; +} + +#endif /* XXH_FORCE_DIRECT_MEMORY_ACCESS */ + +#if defined(_MSC_VER) /* Visual Studio */ +# define XXH_swap64 _byteswap_uint64 +#elif XXH_GCC_VERSION >= 403 +# define XXH_swap64 __builtin_bswap64 +#else +static xxh_u64 XXH_swap64(xxh_u64 x) +{ + return ((x << 56) & 0xff00000000000000ULL) | + ((x << 40) & 0x00ff000000000000ULL) | + ((x << 24) & 0x0000ff0000000000ULL) | + ((x << 8) & 0x000000ff00000000ULL) | + ((x >> 8) & 0x00000000ff000000ULL) | + ((x >> 24) & 0x0000000000ff0000ULL) | + ((x >> 40) & 0x000000000000ff00ULL) | + ((x >> 56) & 0x00000000000000ffULL); +} +#endif + + +/* XXH_FORCE_MEMORY_ACCESS==3 is an endian-independent byteshift load. */ +#if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==3)) + +XXH_FORCE_INLINE xxh_u64 XXH_readLE64(const void* memPtr) +{ + const xxh_u8* bytePtr = (const xxh_u8 *)memPtr; + return bytePtr[0] + | ((xxh_u64)bytePtr[1] << 8) + | ((xxh_u64)bytePtr[2] << 16) + | ((xxh_u64)bytePtr[3] << 24) + | ((xxh_u64)bytePtr[4] << 32) + | ((xxh_u64)bytePtr[5] << 40) + | ((xxh_u64)bytePtr[6] << 48) + | ((xxh_u64)bytePtr[7] << 56); +} + +XXH_FORCE_INLINE xxh_u64 XXH_readBE64(const void* memPtr) +{ + const xxh_u8* bytePtr = (const xxh_u8 *)memPtr; + return bytePtr[7] + | ((xxh_u64)bytePtr[6] << 8) + | ((xxh_u64)bytePtr[5] << 16) + | ((xxh_u64)bytePtr[4] << 24) + | ((xxh_u64)bytePtr[3] << 32) + | ((xxh_u64)bytePtr[2] << 40) + | ((xxh_u64)bytePtr[1] << 48) + | ((xxh_u64)bytePtr[0] << 56); +} + +#else +XXH_FORCE_INLINE xxh_u64 XXH_readLE64(const void* ptr) +{ + return XXH_CPU_LITTLE_ENDIAN ? XXH_read64(ptr) : XXH_swap64(XXH_read64(ptr)); +} + +static xxh_u64 XXH_readBE64(const void* ptr) +{ + return XXH_CPU_LITTLE_ENDIAN ? XXH_swap64(XXH_read64(ptr)) : XXH_read64(ptr); +} +#endif + +XXH_FORCE_INLINE xxh_u64 +XXH_readLE64_align(const void* ptr, XXH_alignment align) +{ + if (align==XXH_unaligned) + return XXH_readLE64(ptr); + else + return XXH_CPU_LITTLE_ENDIAN ? *(const xxh_u64*)ptr : XXH_swap64(*(const xxh_u64*)ptr); +} + + +/******* xxh64 *******/ +/*! + * @} + * @defgroup XXH64_impl XXH64 implementation + * @ingroup impl + * + * Details on the XXH64 implementation. + * @{ + */ +/* #define rather that static const, to be used as initializers */ +#define XXH_PRIME64_1 0x9E3779B185EBCA87ULL /*!< 0b1001111000110111011110011011000110000101111010111100101010000111 */ +#define XXH_PRIME64_2 0xC2B2AE3D27D4EB4FULL /*!< 0b1100001010110010101011100011110100100111110101001110101101001111 */ +#define XXH_PRIME64_3 0x165667B19E3779F9ULL /*!< 0b0001011001010110011001111011000110011110001101110111100111111001 */ +#define XXH_PRIME64_4 0x85EBCA77C2B2AE63ULL /*!< 0b1000010111101011110010100111011111000010101100101010111001100011 */ +#define XXH_PRIME64_5 0x27D4EB2F165667C5ULL /*!< 0b0010011111010100111010110010111100010110010101100110011111000101 */ + +#ifdef XXH_OLD_NAMES +# define PRIME64_1 XXH_PRIME64_1 +# define PRIME64_2 XXH_PRIME64_2 +# define PRIME64_3 XXH_PRIME64_3 +# define PRIME64_4 XXH_PRIME64_4 +# define PRIME64_5 XXH_PRIME64_5 +#endif + +/*! @copydoc XXH32_round */ +static xxh_u64 XXH64_round(xxh_u64 acc, xxh_u64 input) +{ + acc += input * XXH_PRIME64_2; + acc = XXH_rotl64(acc, 31); + acc *= XXH_PRIME64_1; +#if (defined(__AVX512F__)) && !defined(XXH_ENABLE_AUTOVECTORIZE) + /* + * DISABLE AUTOVECTORIZATION: + * A compiler fence is used to prevent GCC and Clang from + * autovectorizing the XXH64 loop (pragmas and attributes don't work for some + * reason) without globally disabling AVX512. + * + * Autovectorization of XXH64 tends to be detrimental, + * though the exact outcome may change depending on exact cpu and compiler version. + * For information, it has been reported as detrimental for Skylake-X, + * but possibly beneficial for Zen4. + * + * The default is to disable auto-vectorization, + * but you can select to enable it instead using `XXH_ENABLE_AUTOVECTORIZE` build variable. + */ + XXH_COMPILER_GUARD(acc); +#endif + return acc; +} + +static xxh_u64 XXH64_mergeRound(xxh_u64 acc, xxh_u64 val) +{ + val = XXH64_round(0, val); + acc ^= val; + acc = acc * XXH_PRIME64_1 + XXH_PRIME64_4; + return acc; +} + +/*! @copydoc XXH32_avalanche */ +static xxh_u64 XXH64_avalanche(xxh_u64 hash) +{ + hash ^= hash >> 33; + hash *= XXH_PRIME64_2; + hash ^= hash >> 29; + hash *= XXH_PRIME64_3; + hash ^= hash >> 32; + return hash; +} + + +#define XXH_get64bits(p) XXH_readLE64_align(p, align) + +/*! + * @internal + * @brief Processes the last 0-31 bytes of @p ptr. + * + * There may be up to 31 bytes remaining to consume from the input. + * This final stage will digest them to ensure that all input bytes are present + * in the final mix. + * + * @param hash The hash to finalize. + * @param ptr The pointer to the remaining input. + * @param len The remaining length, modulo 32. + * @param align Whether @p ptr is aligned. + * @return The finalized hash + * @see XXH32_finalize(). + */ +static XXH_PUREF xxh_u64 +XXH64_finalize(xxh_u64 hash, const xxh_u8* ptr, size_t len, XXH_alignment align) +{ + if (ptr==NULL) XXH_ASSERT(len == 0); + len &= 31; + while (len >= 8) { + xxh_u64 const k1 = XXH64_round(0, XXH_get64bits(ptr)); + ptr += 8; + hash ^= k1; + hash = XXH_rotl64(hash,27) * XXH_PRIME64_1 + XXH_PRIME64_4; + len -= 8; + } + if (len >= 4) { + hash ^= (xxh_u64)(XXH_get32bits(ptr)) * XXH_PRIME64_1; + ptr += 4; + hash = XXH_rotl64(hash, 23) * XXH_PRIME64_2 + XXH_PRIME64_3; + len -= 4; + } + while (len > 0) { + hash ^= (*ptr++) * XXH_PRIME64_5; + hash = XXH_rotl64(hash, 11) * XXH_PRIME64_1; + --len; + } + return XXH64_avalanche(hash); +} + +#ifdef XXH_OLD_NAMES +# define PROCESS1_64 XXH_PROCESS1_64 +# define PROCESS4_64 XXH_PROCESS4_64 +# define PROCESS8_64 XXH_PROCESS8_64 +#else +# undef XXH_PROCESS1_64 +# undef XXH_PROCESS4_64 +# undef XXH_PROCESS8_64 +#endif + +/*! + * @internal + * @brief The implementation for @ref XXH64(). + * + * @param input , len , seed Directly passed from @ref XXH64(). + * @param align Whether @p input is aligned. + * @return The calculated hash. + */ +XXH_FORCE_INLINE XXH_PUREF xxh_u64 +XXH64_endian_align(const xxh_u8* input, size_t len, xxh_u64 seed, XXH_alignment align) +{ + xxh_u64 h64; + if (input==NULL) XXH_ASSERT(len == 0); + + if (len>=32) { + const xxh_u8* const bEnd = input + len; + const xxh_u8* const limit = bEnd - 31; + xxh_u64 v1 = seed + XXH_PRIME64_1 + XXH_PRIME64_2; + xxh_u64 v2 = seed + XXH_PRIME64_2; + xxh_u64 v3 = seed + 0; + xxh_u64 v4 = seed - XXH_PRIME64_1; + + do { + v1 = XXH64_round(v1, XXH_get64bits(input)); input+=8; + v2 = XXH64_round(v2, XXH_get64bits(input)); input+=8; + v3 = XXH64_round(v3, XXH_get64bits(input)); input+=8; + v4 = XXH64_round(v4, XXH_get64bits(input)); input+=8; + } while (input= 2 + /* Simple version, good for code maintenance, but unfortunately slow for small inputs */ + XXH64_state_t state; + XXH64_reset(&state, seed); + XXH64_update(&state, (const xxh_u8*)input, len); + return XXH64_digest(&state); +#else + if (XXH_FORCE_ALIGN_CHECK) { + if ((((size_t)input) & 7)==0) { /* Input is aligned, let's leverage the speed advantage */ + return XXH64_endian_align((const xxh_u8*)input, len, seed, XXH_aligned); + } } + + return XXH64_endian_align((const xxh_u8*)input, len, seed, XXH_unaligned); + +#endif +} + +/******* Hash Streaming *******/ +#ifndef XXH_NO_STREAM +/*! @ingroup XXH64_family*/ +XXH_PUBLIC_API XXH64_state_t* XXH64_createState(void) +{ + return (XXH64_state_t*)XXH_malloc(sizeof(XXH64_state_t)); +} +/*! @ingroup XXH64_family */ +XXH_PUBLIC_API XXH_errorcode XXH64_freeState(XXH64_state_t* statePtr) +{ + XXH_free(statePtr); + return XXH_OK; +} + +/*! @ingroup XXH64_family */ +XXH_PUBLIC_API void XXH64_copyState(XXH_NOESCAPE XXH64_state_t* dstState, const XXH64_state_t* srcState) +{ + XXH_memcpy(dstState, srcState, sizeof(*dstState)); +} + +/*! @ingroup XXH64_family */ +XXH_PUBLIC_API XXH_errorcode XXH64_reset(XXH_NOESCAPE XXH64_state_t* statePtr, XXH64_hash_t seed) +{ + XXH_ASSERT(statePtr != NULL); + memset(statePtr, 0, sizeof(*statePtr)); + statePtr->v[0] = seed + XXH_PRIME64_1 + XXH_PRIME64_2; + statePtr->v[1] = seed + XXH_PRIME64_2; + statePtr->v[2] = seed + 0; + statePtr->v[3] = seed - XXH_PRIME64_1; + return XXH_OK; +} + +/*! @ingroup XXH64_family */ +XXH_PUBLIC_API XXH_errorcode +XXH64_update (XXH_NOESCAPE XXH64_state_t* state, XXH_NOESCAPE const void* input, size_t len) +{ + if (input==NULL) { + XXH_ASSERT(len == 0); + return XXH_OK; + } + + { const xxh_u8* p = (const xxh_u8*)input; + const xxh_u8* const bEnd = p + len; + + state->total_len += len; + + if (state->memsize + len < 32) { /* fill in tmp buffer */ + XXH_memcpy(((xxh_u8*)state->mem64) + state->memsize, input, len); + state->memsize += (xxh_u32)len; + return XXH_OK; + } + + if (state->memsize) { /* tmp buffer is full */ + XXH_memcpy(((xxh_u8*)state->mem64) + state->memsize, input, 32-state->memsize); + state->v[0] = XXH64_round(state->v[0], XXH_readLE64(state->mem64+0)); + state->v[1] = XXH64_round(state->v[1], XXH_readLE64(state->mem64+1)); + state->v[2] = XXH64_round(state->v[2], XXH_readLE64(state->mem64+2)); + state->v[3] = XXH64_round(state->v[3], XXH_readLE64(state->mem64+3)); + p += 32 - state->memsize; + state->memsize = 0; + } + + if (p+32 <= bEnd) { + const xxh_u8* const limit = bEnd - 32; + + do { + state->v[0] = XXH64_round(state->v[0], XXH_readLE64(p)); p+=8; + state->v[1] = XXH64_round(state->v[1], XXH_readLE64(p)); p+=8; + state->v[2] = XXH64_round(state->v[2], XXH_readLE64(p)); p+=8; + state->v[3] = XXH64_round(state->v[3], XXH_readLE64(p)); p+=8; + } while (p<=limit); + + } + + if (p < bEnd) { + XXH_memcpy(state->mem64, p, (size_t)(bEnd-p)); + state->memsize = (unsigned)(bEnd-p); + } + } + + return XXH_OK; +} + + +/*! @ingroup XXH64_family */ +XXH_PUBLIC_API XXH64_hash_t XXH64_digest(XXH_NOESCAPE const XXH64_state_t* state) +{ + xxh_u64 h64; + + if (state->total_len >= 32) { + h64 = XXH_rotl64(state->v[0], 1) + XXH_rotl64(state->v[1], 7) + XXH_rotl64(state->v[2], 12) + XXH_rotl64(state->v[3], 18); + h64 = XXH64_mergeRound(h64, state->v[0]); + h64 = XXH64_mergeRound(h64, state->v[1]); + h64 = XXH64_mergeRound(h64, state->v[2]); + h64 = XXH64_mergeRound(h64, state->v[3]); + } else { + h64 = state->v[2] /*seed*/ + XXH_PRIME64_5; + } + + h64 += (xxh_u64) state->total_len; + + return XXH64_finalize(h64, (const xxh_u8*)state->mem64, (size_t)state->total_len, XXH_aligned); +} +#endif /* !XXH_NO_STREAM */ + +/******* Canonical representation *******/ + +/*! @ingroup XXH64_family */ +XXH_PUBLIC_API void XXH64_canonicalFromHash(XXH_NOESCAPE XXH64_canonical_t* dst, XXH64_hash_t hash) +{ + XXH_STATIC_ASSERT(sizeof(XXH64_canonical_t) == sizeof(XXH64_hash_t)); + if (XXH_CPU_LITTLE_ENDIAN) hash = XXH_swap64(hash); + XXH_memcpy(dst, &hash, sizeof(*dst)); +} + +/*! @ingroup XXH64_family */ +XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(XXH_NOESCAPE const XXH64_canonical_t* src) +{ + return XXH_readBE64(src); +} + +#if defined (__cplusplus) +} +#endif + +#ifndef XXH_NO_XXH3 + +/* ********************************************************************* +* XXH3 +* New generation hash designed for speed on small keys and vectorization +************************************************************************ */ +/*! + * @} + * @defgroup XXH3_impl XXH3 implementation + * @ingroup impl + * @{ + */ + +/* === Compiler specifics === */ + +#if ((defined(sun) || defined(__sun)) && __cplusplus) /* Solaris includes __STDC_VERSION__ with C++. Tested with GCC 5.5 */ +# define XXH_RESTRICT /* disable */ +#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* >= C99 */ +# define XXH_RESTRICT restrict +#elif (defined (__GNUC__) && ((__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))) \ + || (defined (__clang__)) \ + || (defined (_MSC_VER) && (_MSC_VER >= 1400)) \ + || (defined (__INTEL_COMPILER) && (__INTEL_COMPILER >= 1300)) +/* + * There are a LOT more compilers that recognize __restrict but this + * covers the major ones. + */ +# define XXH_RESTRICT __restrict +#else +# define XXH_RESTRICT /* disable */ +#endif + +#if (defined(__GNUC__) && (__GNUC__ >= 3)) \ + || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) \ + || defined(__clang__) +# define XXH_likely(x) __builtin_expect(x, 1) +# define XXH_unlikely(x) __builtin_expect(x, 0) +#else +# define XXH_likely(x) (x) +# define XXH_unlikely(x) (x) +#endif + +#ifndef XXH_HAS_INCLUDE +# ifdef __has_include +/* + * Not defined as XXH_HAS_INCLUDE(x) (function-like) because + * this causes segfaults in Apple Clang 4.2 (on Mac OS X 10.7 Lion) + */ +# define XXH_HAS_INCLUDE __has_include +# else +# define XXH_HAS_INCLUDE(x) 0 +# endif +#endif + +#if defined(__GNUC__) || defined(__clang__) +# if defined(__ARM_FEATURE_SVE) +# include +# endif +# if defined(__ARM_NEON__) || defined(__ARM_NEON) \ + || (defined(_M_ARM) && _M_ARM >= 7) \ + || defined(_M_ARM64) || defined(_M_ARM64EC) \ + || (defined(__wasm_simd128__) && XXH_HAS_INCLUDE()) /* WASM SIMD128 via SIMDe */ +# define inline __inline__ /* circumvent a clang bug */ +# include +# undef inline +# elif defined(__AVX2__) +# include +# elif defined(__SSE2__) +# include +# endif +#endif + +#if defined(_MSC_VER) +# include +#endif + +/* + * One goal of XXH3 is to make it fast on both 32-bit and 64-bit, while + * remaining a true 64-bit/128-bit hash function. + * + * This is done by prioritizing a subset of 64-bit operations that can be + * emulated without too many steps on the average 32-bit machine. + * + * For example, these two lines seem similar, and run equally fast on 64-bit: + * + * xxh_u64 x; + * x ^= (x >> 47); // good + * x ^= (x >> 13); // bad + * + * However, to a 32-bit machine, there is a major difference. + * + * x ^= (x >> 47) looks like this: + * + * x.lo ^= (x.hi >> (47 - 32)); + * + * while x ^= (x >> 13) looks like this: + * + * // note: funnel shifts are not usually cheap. + * x.lo ^= (x.lo >> 13) | (x.hi << (32 - 13)); + * x.hi ^= (x.hi >> 13); + * + * The first one is significantly faster than the second, simply because the + * shift is larger than 32. This means: + * - All the bits we need are in the upper 32 bits, so we can ignore the lower + * 32 bits in the shift. + * - The shift result will always fit in the lower 32 bits, and therefore, + * we can ignore the upper 32 bits in the xor. + * + * Thanks to this optimization, XXH3 only requires these features to be efficient: + * + * - Usable unaligned access + * - A 32-bit or 64-bit ALU + * - If 32-bit, a decent ADC instruction + * - A 32 or 64-bit multiply with a 64-bit result + * - For the 128-bit variant, a decent byteswap helps short inputs. + * + * The first two are already required by XXH32, and almost all 32-bit and 64-bit + * platforms which can run XXH32 can run XXH3 efficiently. + * + * Thumb-1, the classic 16-bit only subset of ARM's instruction set, is one + * notable exception. + * + * First of all, Thumb-1 lacks support for the UMULL instruction which + * performs the important long multiply. This means numerous __aeabi_lmul + * calls. + * + * Second of all, the 8 functional registers are just not enough. + * Setup for __aeabi_lmul, byteshift loads, pointers, and all arithmetic need + * Lo registers, and this shuffling results in thousands more MOVs than A32. + * + * A32 and T32 don't have this limitation. They can access all 14 registers, + * do a 32->64 multiply with UMULL, and the flexible operand allowing free + * shifts is helpful, too. + * + * Therefore, we do a quick sanity check. + * + * If compiling Thumb-1 for a target which supports ARM instructions, we will + * emit a warning, as it is not a "sane" platform to compile for. + * + * Usually, if this happens, it is because of an accident and you probably need + * to specify -march, as you likely meant to compile for a newer architecture. + * + * Credit: large sections of the vectorial and asm source code paths + * have been contributed by @easyaspi314 + */ +#if defined(__thumb__) && !defined(__thumb2__) && defined(__ARM_ARCH_ISA_ARM) +# warning "XXH3 is highly inefficient without ARM or Thumb-2." +#endif + +/* ========================================== + * Vectorization detection + * ========================================== */ + +#ifdef XXH_DOXYGEN +/*! + * @ingroup tuning + * @brief Overrides the vectorization implementation chosen for XXH3. + * + * Can be defined to 0 to disable SIMD or any of the values mentioned in + * @ref XXH_VECTOR_TYPE. + * + * If this is not defined, it uses predefined macros to determine the best + * implementation. + */ +# define XXH_VECTOR XXH_SCALAR +/*! + * @ingroup tuning + * @brief Possible values for @ref XXH_VECTOR. + * + * Note that these are actually implemented as macros. + * + * If this is not defined, it is detected automatically. + * internal macro XXH_X86DISPATCH overrides this. + */ +enum XXH_VECTOR_TYPE /* fake enum */ { + XXH_SCALAR = 0, /*!< Portable scalar version */ + XXH_SSE2 = 1, /*!< + * SSE2 for Pentium 4, Opteron, all x86_64. + * + * @note SSE2 is also guaranteed on Windows 10, macOS, and + * Android x86. + */ + XXH_AVX2 = 2, /*!< AVX2 for Haswell and Bulldozer */ + XXH_AVX512 = 3, /*!< AVX512 for Skylake and Icelake */ + XXH_NEON = 4, /*!< + * NEON for most ARMv7-A, all AArch64, and WASM SIMD128 + * via the SIMDeverywhere polyfill provided with the + * Emscripten SDK. + */ + XXH_VSX = 5, /*!< VSX and ZVector for POWER8/z13 (64-bit) */ + XXH_SVE = 6, /*!< SVE for some ARMv8-A and ARMv9-A */ +}; +/*! + * @ingroup tuning + * @brief Selects the minimum alignment for XXH3's accumulators. + * + * When using SIMD, this should match the alignment required for said vector + * type, so, for example, 32 for AVX2. + * + * Default: Auto detected. + */ +# define XXH_ACC_ALIGN 8 +#endif + +/* Actual definition */ +#ifndef XXH_DOXYGEN +# define XXH_SCALAR 0 +# define XXH_SSE2 1 +# define XXH_AVX2 2 +# define XXH_AVX512 3 +# define XXH_NEON 4 +# define XXH_VSX 5 +# define XXH_SVE 6 +#endif + +#ifndef XXH_VECTOR /* can be defined on command line */ +# if defined(__ARM_FEATURE_SVE) +# define XXH_VECTOR XXH_SVE +# elif ( \ + defined(__ARM_NEON__) || defined(__ARM_NEON) /* gcc */ \ + || defined(_M_ARM) || defined(_M_ARM64) || defined(_M_ARM64EC) /* msvc */ \ + || (defined(__wasm_simd128__) && XXH_HAS_INCLUDE()) /* wasm simd128 via SIMDe */ \ + ) && ( \ + defined(_WIN32) || defined(__LITTLE_ENDIAN__) /* little endian only */ \ + || (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) \ + ) +# define XXH_VECTOR XXH_NEON +# elif defined(__AVX512F__) +# define XXH_VECTOR XXH_AVX512 +# elif defined(__AVX2__) +# define XXH_VECTOR XXH_AVX2 +# elif defined(__SSE2__) || defined(_M_X64) || (defined(_M_IX86_FP) && (_M_IX86_FP == 2)) +# define XXH_VECTOR XXH_SSE2 +# elif (defined(__PPC64__) && defined(__POWER8_VECTOR__)) \ + || (defined(__s390x__) && defined(__VEC__)) \ + && defined(__GNUC__) /* TODO: IBM XL */ +# define XXH_VECTOR XXH_VSX +# else +# define XXH_VECTOR XXH_SCALAR +# endif +#endif + +/* __ARM_FEATURE_SVE is only supported by GCC & Clang. */ +#if (XXH_VECTOR == XXH_SVE) && !defined(__ARM_FEATURE_SVE) +# ifdef _MSC_VER +# pragma warning(once : 4606) +# else +# warning "__ARM_FEATURE_SVE isn't supported. Use SCALAR instead." +# endif +# undef XXH_VECTOR +# define XXH_VECTOR XXH_SCALAR +#endif + +/* + * Controls the alignment of the accumulator, + * for compatibility with aligned vector loads, which are usually faster. + */ +#ifndef XXH_ACC_ALIGN +# if defined(XXH_X86DISPATCH) +# define XXH_ACC_ALIGN 64 /* for compatibility with avx512 */ +# elif XXH_VECTOR == XXH_SCALAR /* scalar */ +# define XXH_ACC_ALIGN 8 +# elif XXH_VECTOR == XXH_SSE2 /* sse2 */ +# define XXH_ACC_ALIGN 16 +# elif XXH_VECTOR == XXH_AVX2 /* avx2 */ +# define XXH_ACC_ALIGN 32 +# elif XXH_VECTOR == XXH_NEON /* neon */ +# define XXH_ACC_ALIGN 16 +# elif XXH_VECTOR == XXH_VSX /* vsx */ +# define XXH_ACC_ALIGN 16 +# elif XXH_VECTOR == XXH_AVX512 /* avx512 */ +# define XXH_ACC_ALIGN 64 +# elif XXH_VECTOR == XXH_SVE /* sve */ +# define XXH_ACC_ALIGN 64 +# endif +#endif + +#if defined(XXH_X86DISPATCH) || XXH_VECTOR == XXH_SSE2 \ + || XXH_VECTOR == XXH_AVX2 || XXH_VECTOR == XXH_AVX512 +# define XXH_SEC_ALIGN XXH_ACC_ALIGN +#elif XXH_VECTOR == XXH_SVE +# define XXH_SEC_ALIGN XXH_ACC_ALIGN +#else +# define XXH_SEC_ALIGN 8 +#endif + +#if defined(__GNUC__) || defined(__clang__) +# define XXH_ALIASING __attribute__((may_alias)) +#else +# define XXH_ALIASING /* nothing */ +#endif + +/* + * UGLY HACK: + * GCC usually generates the best code with -O3 for xxHash. + * + * However, when targeting AVX2, it is overzealous in its unrolling resulting + * in code roughly 3/4 the speed of Clang. + * + * There are other issues, such as GCC splitting _mm256_loadu_si256 into + * _mm_loadu_si128 + _mm256_inserti128_si256. This is an optimization which + * only applies to Sandy and Ivy Bridge... which don't even support AVX2. + * + * That is why when compiling the AVX2 version, it is recommended to use either + * -O2 -mavx2 -march=haswell + * or + * -O2 -mavx2 -mno-avx256-split-unaligned-load + * for decent performance, or to use Clang instead. + * + * Fortunately, we can control the first one with a pragma that forces GCC into + * -O2, but the other one we can't control without "failed to inline always + * inline function due to target mismatch" warnings. + */ +#if XXH_VECTOR == XXH_AVX2 /* AVX2 */ \ + && defined(__GNUC__) && !defined(__clang__) /* GCC, not Clang */ \ + && defined(__OPTIMIZE__) && XXH_SIZE_OPT <= 0 /* respect -O0 and -Os */ +# pragma GCC push_options +# pragma GCC optimize("-O2") +#endif + +#if defined (__cplusplus) +extern "C" { +#endif + +#if XXH_VECTOR == XXH_NEON + +/* + * UGLY HACK: While AArch64 GCC on Linux does not seem to care, on macOS, GCC -O3 + * optimizes out the entire hashLong loop because of the aliasing violation. + * + * However, GCC is also inefficient at load-store optimization with vld1q/vst1q, + * so the only option is to mark it as aliasing. + */ +typedef uint64x2_t xxh_aliasing_uint64x2_t XXH_ALIASING; + +/*! + * @internal + * @brief `vld1q_u64` but faster and alignment-safe. + * + * On AArch64, unaligned access is always safe, but on ARMv7-a, it is only + * *conditionally* safe (`vld1` has an alignment bit like `movdq[ua]` in x86). + * + * GCC for AArch64 sees `vld1q_u8` as an intrinsic instead of a load, so it + * prohibits load-store optimizations. Therefore, a direct dereference is used. + * + * Otherwise, `vld1q_u8` is used with `vreinterpretq_u8_u64` to do a safe + * unaligned load. + */ +#if defined(__aarch64__) && defined(__GNUC__) && !defined(__clang__) +XXH_FORCE_INLINE uint64x2_t XXH_vld1q_u64(void const* ptr) /* silence -Wcast-align */ +{ + return *(xxh_aliasing_uint64x2_t const *)ptr; +} +#else +XXH_FORCE_INLINE uint64x2_t XXH_vld1q_u64(void const* ptr) +{ + return vreinterpretq_u64_u8(vld1q_u8((uint8_t const*)ptr)); +} +#endif + +/*! + * @internal + * @brief `vmlal_u32` on low and high halves of a vector. + * + * This is a workaround for AArch64 GCC < 11 which implemented arm_neon.h with + * inline assembly and were therefore incapable of merging the `vget_{low, high}_u32` + * with `vmlal_u32`. + */ +#if defined(__aarch64__) && defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 11 +XXH_FORCE_INLINE uint64x2_t +XXH_vmlal_low_u32(uint64x2_t acc, uint32x4_t lhs, uint32x4_t rhs) +{ + /* Inline assembly is the only way */ + __asm__("umlal %0.2d, %1.2s, %2.2s" : "+w" (acc) : "w" (lhs), "w" (rhs)); + return acc; +} +XXH_FORCE_INLINE uint64x2_t +XXH_vmlal_high_u32(uint64x2_t acc, uint32x4_t lhs, uint32x4_t rhs) +{ + /* This intrinsic works as expected */ + return vmlal_high_u32(acc, lhs, rhs); +} +#else +/* Portable intrinsic versions */ +XXH_FORCE_INLINE uint64x2_t +XXH_vmlal_low_u32(uint64x2_t acc, uint32x4_t lhs, uint32x4_t rhs) +{ + return vmlal_u32(acc, vget_low_u32(lhs), vget_low_u32(rhs)); +} +/*! @copydoc XXH_vmlal_low_u32 + * Assume the compiler converts this to vmlal_high_u32 on aarch64 */ +XXH_FORCE_INLINE uint64x2_t +XXH_vmlal_high_u32(uint64x2_t acc, uint32x4_t lhs, uint32x4_t rhs) +{ + return vmlal_u32(acc, vget_high_u32(lhs), vget_high_u32(rhs)); +} +#endif + +/*! + * @ingroup tuning + * @brief Controls the NEON to scalar ratio for XXH3 + * + * This can be set to 2, 4, 6, or 8. + * + * ARM Cortex CPUs are _very_ sensitive to how their pipelines are used. + * + * For example, the Cortex-A73 can dispatch 3 micro-ops per cycle, but only 2 of those + * can be NEON. If you are only using NEON instructions, you are only using 2/3 of the CPU + * bandwidth. + * + * This is even more noticeable on the more advanced cores like the Cortex-A76 which + * can dispatch 8 micro-ops per cycle, but still only 2 NEON micro-ops at once. + * + * Therefore, to make the most out of the pipeline, it is beneficial to run 6 NEON lanes + * and 2 scalar lanes, which is chosen by default. + * + * This does not apply to Apple processors or 32-bit processors, which run better with + * full NEON. These will default to 8. Additionally, size-optimized builds run 8 lanes. + * + * This change benefits CPUs with large micro-op buffers without negatively affecting + * most other CPUs: + * + * | Chipset | Dispatch type | NEON only | 6:2 hybrid | Diff. | + * |:----------------------|:--------------------|----------:|-----------:|------:| + * | Snapdragon 730 (A76) | 2 NEON/8 micro-ops | 8.8 GB/s | 10.1 GB/s | ~16% | + * | Snapdragon 835 (A73) | 2 NEON/3 micro-ops | 5.1 GB/s | 5.3 GB/s | ~5% | + * | Marvell PXA1928 (A53) | In-order dual-issue | 1.9 GB/s | 1.9 GB/s | 0% | + * | Apple M1 | 4 NEON/8 micro-ops | 37.3 GB/s | 36.1 GB/s | ~-3% | + * + * It also seems to fix some bad codegen on GCC, making it almost as fast as clang. + * + * When using WASM SIMD128, if this is 2 or 6, SIMDe will scalarize 2 of the lanes meaning + * it effectively becomes worse 4. + * + * @see XXH3_accumulate_512_neon() + */ +# ifndef XXH3_NEON_LANES +# if (defined(__aarch64__) || defined(__arm64__) || defined(_M_ARM64) || defined(_M_ARM64EC)) \ + && !defined(__APPLE__) && XXH_SIZE_OPT <= 0 +# define XXH3_NEON_LANES 6 +# else +# define XXH3_NEON_LANES XXH_ACC_NB +# endif +# endif +#endif /* XXH_VECTOR == XXH_NEON */ + +#if defined (__cplusplus) +} /* extern "C" */ +#endif + +/* + * VSX and Z Vector helpers. + * + * This is very messy, and any pull requests to clean this up are welcome. + * + * There are a lot of problems with supporting VSX and s390x, due to + * inconsistent intrinsics, spotty coverage, and multiple endiannesses. + */ +#if XXH_VECTOR == XXH_VSX +/* Annoyingly, these headers _may_ define three macros: `bool`, `vector`, + * and `pixel`. This is a problem for obvious reasons. + * + * These keywords are unnecessary; the spec literally says they are + * equivalent to `__bool`, `__vector`, and `__pixel` and may be undef'd + * after including the header. + * + * We use pragma push_macro/pop_macro to keep the namespace clean. */ +# pragma push_macro("bool") +# pragma push_macro("vector") +# pragma push_macro("pixel") +/* silence potential macro redefined warnings */ +# undef bool +# undef vector +# undef pixel + +# if defined(__s390x__) +# include +# else +# include +# endif + +/* Restore the original macro values, if applicable. */ +# pragma pop_macro("pixel") +# pragma pop_macro("vector") +# pragma pop_macro("bool") + +typedef __vector unsigned long long xxh_u64x2; +typedef __vector unsigned char xxh_u8x16; +typedef __vector unsigned xxh_u32x4; + +/* + * UGLY HACK: Similar to aarch64 macOS GCC, s390x GCC has the same aliasing issue. + */ +typedef xxh_u64x2 xxh_aliasing_u64x2 XXH_ALIASING; + +# ifndef XXH_VSX_BE +# if defined(__BIG_ENDIAN__) \ + || (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) +# define XXH_VSX_BE 1 +# elif defined(__VEC_ELEMENT_REG_ORDER__) && __VEC_ELEMENT_REG_ORDER__ == __ORDER_BIG_ENDIAN__ +# warning "-maltivec=be is not recommended. Please use native endianness." +# define XXH_VSX_BE 1 +# else +# define XXH_VSX_BE 0 +# endif +# endif /* !defined(XXH_VSX_BE) */ + +# if XXH_VSX_BE +# if defined(__POWER9_VECTOR__) || (defined(__clang__) && defined(__s390x__)) +# define XXH_vec_revb vec_revb +# else +#if defined (__cplusplus) +extern "C" { +#endif +/*! + * A polyfill for POWER9's vec_revb(). + */ +XXH_FORCE_INLINE xxh_u64x2 XXH_vec_revb(xxh_u64x2 val) +{ + xxh_u8x16 const vByteSwap = { 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00, + 0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, 0x09, 0x08 }; + return vec_perm(val, val, vByteSwap); +} +#if defined (__cplusplus) +} /* extern "C" */ +#endif +# endif +# endif /* XXH_VSX_BE */ + +#if defined (__cplusplus) +extern "C" { +#endif +/*! + * Performs an unaligned vector load and byte swaps it on big endian. + */ +XXH_FORCE_INLINE xxh_u64x2 XXH_vec_loadu(const void *ptr) +{ + xxh_u64x2 ret; + XXH_memcpy(&ret, ptr, sizeof(xxh_u64x2)); +# if XXH_VSX_BE + ret = XXH_vec_revb(ret); +# endif + return ret; +} + +/* + * vec_mulo and vec_mule are very problematic intrinsics on PowerPC + * + * These intrinsics weren't added until GCC 8, despite existing for a while, + * and they are endian dependent. Also, their meaning swap depending on version. + * */ +# if defined(__s390x__) + /* s390x is always big endian, no issue on this platform */ +# define XXH_vec_mulo vec_mulo +# define XXH_vec_mule vec_mule +# elif defined(__clang__) && XXH_HAS_BUILTIN(__builtin_altivec_vmuleuw) && !defined(__ibmxl__) +/* Clang has a better way to control this, we can just use the builtin which doesn't swap. */ + /* The IBM XL Compiler (which defined __clang__) only implements the vec_* operations */ +# define XXH_vec_mulo __builtin_altivec_vmulouw +# define XXH_vec_mule __builtin_altivec_vmuleuw +# else +/* gcc needs inline assembly */ +/* Adapted from https://github.com/google/highwayhash/blob/master/highwayhash/hh_vsx.h. */ +XXH_FORCE_INLINE xxh_u64x2 XXH_vec_mulo(xxh_u32x4 a, xxh_u32x4 b) +{ + xxh_u64x2 result; + __asm__("vmulouw %0, %1, %2" : "=v" (result) : "v" (a), "v" (b)); + return result; +} +XXH_FORCE_INLINE xxh_u64x2 XXH_vec_mule(xxh_u32x4 a, xxh_u32x4 b) +{ + xxh_u64x2 result; + __asm__("vmuleuw %0, %1, %2" : "=v" (result) : "v" (a), "v" (b)); + return result; +} +# endif /* XXH_vec_mulo, XXH_vec_mule */ + +#if defined (__cplusplus) +} /* extern "C" */ +#endif + +#endif /* XXH_VECTOR == XXH_VSX */ + +#if XXH_VECTOR == XXH_SVE +#define ACCRND(acc, offset) \ +do { \ + svuint64_t input_vec = svld1_u64(mask, xinput + offset); \ + svuint64_t secret_vec = svld1_u64(mask, xsecret + offset); \ + svuint64_t mixed = sveor_u64_x(mask, secret_vec, input_vec); \ + svuint64_t swapped = svtbl_u64(input_vec, kSwap); \ + svuint64_t mixed_lo = svextw_u64_x(mask, mixed); \ + svuint64_t mixed_hi = svlsr_n_u64_x(mask, mixed, 32); \ + svuint64_t mul = svmad_u64_x(mask, mixed_lo, mixed_hi, swapped); \ + acc = svadd_u64_x(mask, acc, mul); \ +} while (0) +#endif /* XXH_VECTOR == XXH_SVE */ + +/* prefetch + * can be disabled, by declaring XXH_NO_PREFETCH build macro */ +#if defined(XXH_NO_PREFETCH) +# define XXH_PREFETCH(ptr) (void)(ptr) /* disabled */ +#else +# if XXH_SIZE_OPT >= 1 +# define XXH_PREFETCH(ptr) (void)(ptr) +# elif defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86)) /* _mm_prefetch() not defined outside of x86/x64 */ +# include /* https://msdn.microsoft.com/fr-fr/library/84szxsww(v=vs.90).aspx */ +# define XXH_PREFETCH(ptr) _mm_prefetch((const char*)(ptr), _MM_HINT_T0) +# elif defined(__GNUC__) && ( (__GNUC__ >= 4) || ( (__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) ) ) +# define XXH_PREFETCH(ptr) __builtin_prefetch((ptr), 0 /* rw==read */, 3 /* locality */) +# else +# define XXH_PREFETCH(ptr) (void)(ptr) /* disabled */ +# endif +#endif /* XXH_NO_PREFETCH */ + +#if defined (__cplusplus) +extern "C" { +#endif +/* ========================================== + * XXH3 default settings + * ========================================== */ + +#define XXH_SECRET_DEFAULT_SIZE 192 /* minimum XXH3_SECRET_SIZE_MIN */ + +#if (XXH_SECRET_DEFAULT_SIZE < XXH3_SECRET_SIZE_MIN) +# error "default keyset is not large enough" +#endif + +/*! Pseudorandom secret taken directly from FARSH. */ +XXH_ALIGN(64) static const xxh_u8 XXH3_kSecret[XXH_SECRET_DEFAULT_SIZE] = { + 0xb8, 0xfe, 0x6c, 0x39, 0x23, 0xa4, 0x4b, 0xbe, 0x7c, 0x01, 0x81, 0x2c, 0xf7, 0x21, 0xad, 0x1c, + 0xde, 0xd4, 0x6d, 0xe9, 0x83, 0x90, 0x97, 0xdb, 0x72, 0x40, 0xa4, 0xa4, 0xb7, 0xb3, 0x67, 0x1f, + 0xcb, 0x79, 0xe6, 0x4e, 0xcc, 0xc0, 0xe5, 0x78, 0x82, 0x5a, 0xd0, 0x7d, 0xcc, 0xff, 0x72, 0x21, + 0xb8, 0x08, 0x46, 0x74, 0xf7, 0x43, 0x24, 0x8e, 0xe0, 0x35, 0x90, 0xe6, 0x81, 0x3a, 0x26, 0x4c, + 0x3c, 0x28, 0x52, 0xbb, 0x91, 0xc3, 0x00, 0xcb, 0x88, 0xd0, 0x65, 0x8b, 0x1b, 0x53, 0x2e, 0xa3, + 0x71, 0x64, 0x48, 0x97, 0xa2, 0x0d, 0xf9, 0x4e, 0x38, 0x19, 0xef, 0x46, 0xa9, 0xde, 0xac, 0xd8, + 0xa8, 0xfa, 0x76, 0x3f, 0xe3, 0x9c, 0x34, 0x3f, 0xf9, 0xdc, 0xbb, 0xc7, 0xc7, 0x0b, 0x4f, 0x1d, + 0x8a, 0x51, 0xe0, 0x4b, 0xcd, 0xb4, 0x59, 0x31, 0xc8, 0x9f, 0x7e, 0xc9, 0xd9, 0x78, 0x73, 0x64, + 0xea, 0xc5, 0xac, 0x83, 0x34, 0xd3, 0xeb, 0xc3, 0xc5, 0x81, 0xa0, 0xff, 0xfa, 0x13, 0x63, 0xeb, + 0x17, 0x0d, 0xdd, 0x51, 0xb7, 0xf0, 0xda, 0x49, 0xd3, 0x16, 0x55, 0x26, 0x29, 0xd4, 0x68, 0x9e, + 0x2b, 0x16, 0xbe, 0x58, 0x7d, 0x47, 0xa1, 0xfc, 0x8f, 0xf8, 0xb8, 0xd1, 0x7a, 0xd0, 0x31, 0xce, + 0x45, 0xcb, 0x3a, 0x8f, 0x95, 0x16, 0x04, 0x28, 0xaf, 0xd7, 0xfb, 0xca, 0xbb, 0x4b, 0x40, 0x7e, +}; + +static const xxh_u64 PRIME_MX1 = 0x165667919E3779F9ULL; /*!< 0b0001011001010110011001111001000110011110001101110111100111111001 */ +static const xxh_u64 PRIME_MX2 = 0x9FB21C651E98DF25ULL; /*!< 0b1001111110110010000111000110010100011110100110001101111100100101 */ + +#ifdef XXH_OLD_NAMES +# define kSecret XXH3_kSecret +#endif + +#ifdef XXH_DOXYGEN +/*! + * @brief Calculates a 32-bit to 64-bit long multiply. + * + * Implemented as a macro. + * + * Wraps `__emulu` on MSVC x86 because it tends to call `__allmul` when it doesn't + * need to (but it shouldn't need to anyways, it is about 7 instructions to do + * a 64x64 multiply...). Since we know that this will _always_ emit `MULL`, we + * use that instead of the normal method. + * + * If you are compiling for platforms like Thumb-1 and don't have a better option, + * you may also want to write your own long multiply routine here. + * + * @param x, y Numbers to be multiplied + * @return 64-bit product of the low 32 bits of @p x and @p y. + */ +XXH_FORCE_INLINE xxh_u64 +XXH_mult32to64(xxh_u64 x, xxh_u64 y) +{ + return (x & 0xFFFFFFFF) * (y & 0xFFFFFFFF); +} +#elif defined(_MSC_VER) && defined(_M_IX86) +# define XXH_mult32to64(x, y) __emulu((unsigned)(x), (unsigned)(y)) +#else +/* + * Downcast + upcast is usually better than masking on older compilers like + * GCC 4.2 (especially 32-bit ones), all without affecting newer compilers. + * + * The other method, (x & 0xFFFFFFFF) * (y & 0xFFFFFFFF), will AND both operands + * and perform a full 64x64 multiply -- entirely redundant on 32-bit. + */ +# define XXH_mult32to64(x, y) ((xxh_u64)(xxh_u32)(x) * (xxh_u64)(xxh_u32)(y)) +#endif + +/*! + * @brief Calculates a 64->128-bit long multiply. + * + * Uses `__uint128_t` and `_umul128` if available, otherwise uses a scalar + * version. + * + * @param lhs , rhs The 64-bit integers to be multiplied + * @return The 128-bit result represented in an @ref XXH128_hash_t. + */ +static XXH128_hash_t +XXH_mult64to128(xxh_u64 lhs, xxh_u64 rhs) +{ + /* + * GCC/Clang __uint128_t method. + * + * On most 64-bit targets, GCC and Clang define a __uint128_t type. + * This is usually the best way as it usually uses a native long 64-bit + * multiply, such as MULQ on x86_64 or MUL + UMULH on aarch64. + * + * Usually. + * + * Despite being a 32-bit platform, Clang (and emscripten) define this type + * despite not having the arithmetic for it. This results in a laggy + * compiler builtin call which calculates a full 128-bit multiply. + * In that case it is best to use the portable one. + * https://github.com/Cyan4973/xxHash/issues/211#issuecomment-515575677 + */ +#if (defined(__GNUC__) || defined(__clang__)) && !defined(__wasm__) \ + && defined(__SIZEOF_INT128__) \ + || (defined(_INTEGRAL_MAX_BITS) && _INTEGRAL_MAX_BITS >= 128) + + __uint128_t const product = (__uint128_t)lhs * (__uint128_t)rhs; + XXH128_hash_t r128; + r128.low64 = (xxh_u64)(product); + r128.high64 = (xxh_u64)(product >> 64); + return r128; + + /* + * MSVC for x64's _umul128 method. + * + * xxh_u64 _umul128(xxh_u64 Multiplier, xxh_u64 Multiplicand, xxh_u64 *HighProduct); + * + * This compiles to single operand MUL on x64. + */ +#elif (defined(_M_X64) || defined(_M_IA64)) && !defined(_M_ARM64EC) + +#ifndef _MSC_VER +# pragma intrinsic(_umul128) +#endif + xxh_u64 product_high; + xxh_u64 const product_low = _umul128(lhs, rhs, &product_high); + XXH128_hash_t r128; + r128.low64 = product_low; + r128.high64 = product_high; + return r128; + + /* + * MSVC for ARM64's __umulh method. + * + * This compiles to the same MUL + UMULH as GCC/Clang's __uint128_t method. + */ +#elif defined(_M_ARM64) || defined(_M_ARM64EC) + +#ifndef _MSC_VER +# pragma intrinsic(__umulh) +#endif + XXH128_hash_t r128; + r128.low64 = lhs * rhs; + r128.high64 = __umulh(lhs, rhs); + return r128; + +#else + /* + * Portable scalar method. Optimized for 32-bit and 64-bit ALUs. + * + * This is a fast and simple grade school multiply, which is shown below + * with base 10 arithmetic instead of base 0x100000000. + * + * 9 3 // D2 lhs = 93 + * x 7 5 // D2 rhs = 75 + * ---------- + * 1 5 // D2 lo_lo = (93 % 10) * (75 % 10) = 15 + * 4 5 | // D2 hi_lo = (93 / 10) * (75 % 10) = 45 + * 2 1 | // D2 lo_hi = (93 % 10) * (75 / 10) = 21 + * + 6 3 | | // D2 hi_hi = (93 / 10) * (75 / 10) = 63 + * --------- + * 2 7 | // D2 cross = (15 / 10) + (45 % 10) + 21 = 27 + * + 6 7 | | // D2 upper = (27 / 10) + (45 / 10) + 63 = 67 + * --------- + * 6 9 7 5 // D4 res = (27 * 10) + (15 % 10) + (67 * 100) = 6975 + * + * The reasons for adding the products like this are: + * 1. It avoids manual carry tracking. Just like how + * (9 * 9) + 9 + 9 = 99, the same applies with this for UINT64_MAX. + * This avoids a lot of complexity. + * + * 2. It hints for, and on Clang, compiles to, the powerful UMAAL + * instruction available in ARM's Digital Signal Processing extension + * in 32-bit ARMv6 and later, which is shown below: + * + * void UMAAL(xxh_u32 *RdLo, xxh_u32 *RdHi, xxh_u32 Rn, xxh_u32 Rm) + * { + * xxh_u64 product = (xxh_u64)*RdLo * (xxh_u64)*RdHi + Rn + Rm; + * *RdLo = (xxh_u32)(product & 0xFFFFFFFF); + * *RdHi = (xxh_u32)(product >> 32); + * } + * + * This instruction was designed for efficient long multiplication, and + * allows this to be calculated in only 4 instructions at speeds + * comparable to some 64-bit ALUs. + * + * 3. It isn't terrible on other platforms. Usually this will be a couple + * of 32-bit ADD/ADCs. + */ + + /* First calculate all of the cross products. */ + xxh_u64 const lo_lo = XXH_mult32to64(lhs & 0xFFFFFFFF, rhs & 0xFFFFFFFF); + xxh_u64 const hi_lo = XXH_mult32to64(lhs >> 32, rhs & 0xFFFFFFFF); + xxh_u64 const lo_hi = XXH_mult32to64(lhs & 0xFFFFFFFF, rhs >> 32); + xxh_u64 const hi_hi = XXH_mult32to64(lhs >> 32, rhs >> 32); + + /* Now add the products together. These will never overflow. */ + xxh_u64 const cross = (lo_lo >> 32) + (hi_lo & 0xFFFFFFFF) + lo_hi; + xxh_u64 const upper = (hi_lo >> 32) + (cross >> 32) + hi_hi; + xxh_u64 const lower = (cross << 32) | (lo_lo & 0xFFFFFFFF); + + XXH128_hash_t r128; + r128.low64 = lower; + r128.high64 = upper; + return r128; +#endif +} + +/*! + * @brief Calculates a 64-bit to 128-bit multiply, then XOR folds it. + * + * The reason for the separate function is to prevent passing too many structs + * around by value. This will hopefully inline the multiply, but we don't force it. + * + * @param lhs , rhs The 64-bit integers to multiply + * @return The low 64 bits of the product XOR'd by the high 64 bits. + * @see XXH_mult64to128() + */ +static xxh_u64 +XXH3_mul128_fold64(xxh_u64 lhs, xxh_u64 rhs) +{ + XXH128_hash_t product = XXH_mult64to128(lhs, rhs); + return product.low64 ^ product.high64; +} + +/*! Seems to produce slightly better code on GCC for some reason. */ +XXH_FORCE_INLINE XXH_CONSTF xxh_u64 XXH_xorshift64(xxh_u64 v64, int shift) +{ + XXH_ASSERT(0 <= shift && shift < 64); + return v64 ^ (v64 >> shift); +} + +/* + * This is a fast avalanche stage, + * suitable when input bits are already partially mixed + */ +static XXH64_hash_t XXH3_avalanche(xxh_u64 h64) +{ + h64 = XXH_xorshift64(h64, 37); + h64 *= PRIME_MX1; + h64 = XXH_xorshift64(h64, 32); + return h64; +} + +/* + * This is a stronger avalanche, + * inspired by Pelle Evensen's rrmxmx + * preferable when input has not been previously mixed + */ +static XXH64_hash_t XXH3_rrmxmx(xxh_u64 h64, xxh_u64 len) +{ + /* this mix is inspired by Pelle Evensen's rrmxmx */ + h64 ^= XXH_rotl64(h64, 49) ^ XXH_rotl64(h64, 24); + h64 *= PRIME_MX2; + h64 ^= (h64 >> 35) + len ; + h64 *= PRIME_MX2; + return XXH_xorshift64(h64, 28); +} + + +/* ========================================== + * Short keys + * ========================================== + * One of the shortcomings of XXH32 and XXH64 was that their performance was + * sub-optimal on short lengths. It used an iterative algorithm which strongly + * favored lengths that were a multiple of 4 or 8. + * + * Instead of iterating over individual inputs, we use a set of single shot + * functions which piece together a range of lengths and operate in constant time. + * + * Additionally, the number of multiplies has been significantly reduced. This + * reduces latency, especially when emulating 64-bit multiplies on 32-bit. + * + * Depending on the platform, this may or may not be faster than XXH32, but it + * is almost guaranteed to be faster than XXH64. + */ + +/* + * At very short lengths, there isn't enough input to fully hide secrets, or use + * the entire secret. + * + * There is also only a limited amount of mixing we can do before significantly + * impacting performance. + * + * Therefore, we use different sections of the secret and always mix two secret + * samples with an XOR. This should have no effect on performance on the + * seedless or withSeed variants because everything _should_ be constant folded + * by modern compilers. + * + * The XOR mixing hides individual parts of the secret and increases entropy. + * + * This adds an extra layer of strength for custom secrets. + */ +XXH_FORCE_INLINE XXH_PUREF XXH64_hash_t +XXH3_len_1to3_64b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed) +{ + XXH_ASSERT(input != NULL); + XXH_ASSERT(1 <= len && len <= 3); + XXH_ASSERT(secret != NULL); + /* + * len = 1: combined = { input[0], 0x01, input[0], input[0] } + * len = 2: combined = { input[1], 0x02, input[0], input[1] } + * len = 3: combined = { input[2], 0x03, input[0], input[1] } + */ + { xxh_u8 const c1 = input[0]; + xxh_u8 const c2 = input[len >> 1]; + xxh_u8 const c3 = input[len - 1]; + xxh_u32 const combined = ((xxh_u32)c1 << 16) | ((xxh_u32)c2 << 24) + | ((xxh_u32)c3 << 0) | ((xxh_u32)len << 8); + xxh_u64 const bitflip = (XXH_readLE32(secret) ^ XXH_readLE32(secret+4)) + seed; + xxh_u64 const keyed = (xxh_u64)combined ^ bitflip; + return XXH64_avalanche(keyed); + } +} + +XXH_FORCE_INLINE XXH_PUREF XXH64_hash_t +XXH3_len_4to8_64b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed) +{ + XXH_ASSERT(input != NULL); + XXH_ASSERT(secret != NULL); + XXH_ASSERT(4 <= len && len <= 8); + seed ^= (xxh_u64)XXH_swap32((xxh_u32)seed) << 32; + { xxh_u32 const input1 = XXH_readLE32(input); + xxh_u32 const input2 = XXH_readLE32(input + len - 4); + xxh_u64 const bitflip = (XXH_readLE64(secret+8) ^ XXH_readLE64(secret+16)) - seed; + xxh_u64 const input64 = input2 + (((xxh_u64)input1) << 32); + xxh_u64 const keyed = input64 ^ bitflip; + return XXH3_rrmxmx(keyed, len); + } +} + +XXH_FORCE_INLINE XXH_PUREF XXH64_hash_t +XXH3_len_9to16_64b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed) +{ + XXH_ASSERT(input != NULL); + XXH_ASSERT(secret != NULL); + XXH_ASSERT(9 <= len && len <= 16); + { xxh_u64 const bitflip1 = (XXH_readLE64(secret+24) ^ XXH_readLE64(secret+32)) + seed; + xxh_u64 const bitflip2 = (XXH_readLE64(secret+40) ^ XXH_readLE64(secret+48)) - seed; + xxh_u64 const input_lo = XXH_readLE64(input) ^ bitflip1; + xxh_u64 const input_hi = XXH_readLE64(input + len - 8) ^ bitflip2; + xxh_u64 const acc = len + + XXH_swap64(input_lo) + input_hi + + XXH3_mul128_fold64(input_lo, input_hi); + return XXH3_avalanche(acc); + } +} + +XXH_FORCE_INLINE XXH_PUREF XXH64_hash_t +XXH3_len_0to16_64b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed) +{ + XXH_ASSERT(len <= 16); + { if (XXH_likely(len > 8)) return XXH3_len_9to16_64b(input, len, secret, seed); + if (XXH_likely(len >= 4)) return XXH3_len_4to8_64b(input, len, secret, seed); + if (len) return XXH3_len_1to3_64b(input, len, secret, seed); + return XXH64_avalanche(seed ^ (XXH_readLE64(secret+56) ^ XXH_readLE64(secret+64))); + } +} + +/* + * DISCLAIMER: There are known *seed-dependent* multicollisions here due to + * multiplication by zero, affecting hashes of lengths 17 to 240. + * + * However, they are very unlikely. + * + * Keep this in mind when using the unseeded XXH3_64bits() variant: As with all + * unseeded non-cryptographic hashes, it does not attempt to defend itself + * against specially crafted inputs, only random inputs. + * + * Compared to classic UMAC where a 1 in 2^31 chance of 4 consecutive bytes + * cancelling out the secret is taken an arbitrary number of times (addressed + * in XXH3_accumulate_512), this collision is very unlikely with random inputs + * and/or proper seeding: + * + * This only has a 1 in 2^63 chance of 8 consecutive bytes cancelling out, in a + * function that is only called up to 16 times per hash with up to 240 bytes of + * input. + * + * This is not too bad for a non-cryptographic hash function, especially with + * only 64 bit outputs. + * + * The 128-bit variant (which trades some speed for strength) is NOT affected + * by this, although it is always a good idea to use a proper seed if you care + * about strength. + */ +XXH_FORCE_INLINE xxh_u64 XXH3_mix16B(const xxh_u8* XXH_RESTRICT input, + const xxh_u8* XXH_RESTRICT secret, xxh_u64 seed64) +{ +#if defined(__GNUC__) && !defined(__clang__) /* GCC, not Clang */ \ + && defined(__i386__) && defined(__SSE2__) /* x86 + SSE2 */ \ + && !defined(XXH_ENABLE_AUTOVECTORIZE) /* Define to disable like XXH32 hack */ + /* + * UGLY HACK: + * GCC for x86 tends to autovectorize the 128-bit multiply, resulting in + * slower code. + * + * By forcing seed64 into a register, we disrupt the cost model and + * cause it to scalarize. See `XXH32_round()` + * + * FIXME: Clang's output is still _much_ faster -- On an AMD Ryzen 3600, + * XXH3_64bits @ len=240 runs at 4.6 GB/s with Clang 9, but 3.3 GB/s on + * GCC 9.2, despite both emitting scalar code. + * + * GCC generates much better scalar code than Clang for the rest of XXH3, + * which is why finding a more optimal codepath is an interest. + */ + XXH_COMPILER_GUARD(seed64); +#endif + { xxh_u64 const input_lo = XXH_readLE64(input); + xxh_u64 const input_hi = XXH_readLE64(input+8); + return XXH3_mul128_fold64( + input_lo ^ (XXH_readLE64(secret) + seed64), + input_hi ^ (XXH_readLE64(secret+8) - seed64) + ); + } +} + +/* For mid range keys, XXH3 uses a Mum-hash variant. */ +XXH_FORCE_INLINE XXH_PUREF XXH64_hash_t +XXH3_len_17to128_64b(const xxh_u8* XXH_RESTRICT input, size_t len, + const xxh_u8* XXH_RESTRICT secret, size_t secretSize, + XXH64_hash_t seed) +{ + XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN); (void)secretSize; + XXH_ASSERT(16 < len && len <= 128); + + { xxh_u64 acc = len * XXH_PRIME64_1; +#if XXH_SIZE_OPT >= 1 + /* Smaller and cleaner, but slightly slower. */ + unsigned int i = (unsigned int)(len - 1) / 32; + do { + acc += XXH3_mix16B(input+16 * i, secret+32*i, seed); + acc += XXH3_mix16B(input+len-16*(i+1), secret+32*i+16, seed); + } while (i-- != 0); +#else + if (len > 32) { + if (len > 64) { + if (len > 96) { + acc += XXH3_mix16B(input+48, secret+96, seed); + acc += XXH3_mix16B(input+len-64, secret+112, seed); + } + acc += XXH3_mix16B(input+32, secret+64, seed); + acc += XXH3_mix16B(input+len-48, secret+80, seed); + } + acc += XXH3_mix16B(input+16, secret+32, seed); + acc += XXH3_mix16B(input+len-32, secret+48, seed); + } + acc += XXH3_mix16B(input+0, secret+0, seed); + acc += XXH3_mix16B(input+len-16, secret+16, seed); +#endif + return XXH3_avalanche(acc); + } +} + +/*! + * @brief Maximum size of "short" key in bytes. + */ +#define XXH3_MIDSIZE_MAX 240 + +XXH_NO_INLINE XXH_PUREF XXH64_hash_t +XXH3_len_129to240_64b(const xxh_u8* XXH_RESTRICT input, size_t len, + const xxh_u8* XXH_RESTRICT secret, size_t secretSize, + XXH64_hash_t seed) +{ + XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN); (void)secretSize; + XXH_ASSERT(128 < len && len <= XXH3_MIDSIZE_MAX); + + #define XXH3_MIDSIZE_STARTOFFSET 3 + #define XXH3_MIDSIZE_LASTOFFSET 17 + + { xxh_u64 acc = len * XXH_PRIME64_1; + xxh_u64 acc_end; + unsigned int const nbRounds = (unsigned int)len / 16; + unsigned int i; + XXH_ASSERT(128 < len && len <= XXH3_MIDSIZE_MAX); + for (i=0; i<8; i++) { + acc += XXH3_mix16B(input+(16*i), secret+(16*i), seed); + } + /* last bytes */ + acc_end = XXH3_mix16B(input + len - 16, secret + XXH3_SECRET_SIZE_MIN - XXH3_MIDSIZE_LASTOFFSET, seed); + XXH_ASSERT(nbRounds >= 8); + acc = XXH3_avalanche(acc); +#if defined(__clang__) /* Clang */ \ + && (defined(__ARM_NEON) || defined(__ARM_NEON__)) /* NEON */ \ + && !defined(XXH_ENABLE_AUTOVECTORIZE) /* Define to disable */ + /* + * UGLY HACK: + * Clang for ARMv7-A tries to vectorize this loop, similar to GCC x86. + * In everywhere else, it uses scalar code. + * + * For 64->128-bit multiplies, even if the NEON was 100% optimal, it + * would still be slower than UMAAL (see XXH_mult64to128). + * + * Unfortunately, Clang doesn't handle the long multiplies properly and + * converts them to the nonexistent "vmulq_u64" intrinsic, which is then + * scalarized into an ugly mess of VMOV.32 instructions. + * + * This mess is difficult to avoid without turning autovectorization + * off completely, but they are usually relatively minor and/or not + * worth it to fix. + * + * This loop is the easiest to fix, as unlike XXH32, this pragma + * _actually works_ because it is a loop vectorization instead of an + * SLP vectorization. + */ + #pragma clang loop vectorize(disable) +#endif + for (i=8 ; i < nbRounds; i++) { + /* + * Prevents clang for unrolling the acc loop and interleaving with this one. + */ + XXH_COMPILER_GUARD(acc); + acc_end += XXH3_mix16B(input+(16*i), secret+(16*(i-8)) + XXH3_MIDSIZE_STARTOFFSET, seed); + } + return XXH3_avalanche(acc + acc_end); + } +} + + +/* ======= Long Keys ======= */ + +#define XXH_STRIPE_LEN 64 +#define XXH_SECRET_CONSUME_RATE 8 /* nb of secret bytes consumed at each accumulation */ +#define XXH_ACC_NB (XXH_STRIPE_LEN / sizeof(xxh_u64)) + +#ifdef XXH_OLD_NAMES +# define STRIPE_LEN XXH_STRIPE_LEN +# define ACC_NB XXH_ACC_NB +#endif + +#ifndef XXH_PREFETCH_DIST +# ifdef __clang__ +# define XXH_PREFETCH_DIST 320 +# else +# if (XXH_VECTOR == XXH_AVX512) +# define XXH_PREFETCH_DIST 512 +# else +# define XXH_PREFETCH_DIST 384 +# endif +# endif /* __clang__ */ +#endif /* XXH_PREFETCH_DIST */ + +/* + * These macros are to generate an XXH3_accumulate() function. + * The two arguments select the name suffix and target attribute. + * + * The name of this symbol is XXH3_accumulate_() and it calls + * XXH3_accumulate_512_(). + * + * It may be useful to hand implement this function if the compiler fails to + * optimize the inline function. + */ +#define XXH3_ACCUMULATE_TEMPLATE(name) \ +void \ +XXH3_accumulate_##name(xxh_u64* XXH_RESTRICT acc, \ + const xxh_u8* XXH_RESTRICT input, \ + const xxh_u8* XXH_RESTRICT secret, \ + size_t nbStripes) \ +{ \ + size_t n; \ + for (n = 0; n < nbStripes; n++ ) { \ + const xxh_u8* const in = input + n*XXH_STRIPE_LEN; \ + XXH_PREFETCH(in + XXH_PREFETCH_DIST); \ + XXH3_accumulate_512_##name( \ + acc, \ + in, \ + secret + n*XXH_SECRET_CONSUME_RATE); \ + } \ +} + + +XXH_FORCE_INLINE void XXH_writeLE64(void* dst, xxh_u64 v64) +{ + if (!XXH_CPU_LITTLE_ENDIAN) v64 = XXH_swap64(v64); + XXH_memcpy(dst, &v64, sizeof(v64)); +} + +/* Several intrinsic functions below are supposed to accept __int64 as argument, + * as documented in https://software.intel.com/sites/landingpage/IntrinsicsGuide/ . + * However, several environments do not define __int64 type, + * requiring a workaround. + */ +#if !defined (__VMS) \ + && (defined (__cplusplus) \ + || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) ) + typedef int64_t xxh_i64; +#else + /* the following type must have a width of 64-bit */ + typedef long long xxh_i64; +#endif + + +/* + * XXH3_accumulate_512 is the tightest loop for long inputs, and it is the most optimized. + * + * It is a hardened version of UMAC, based off of FARSH's implementation. + * + * This was chosen because it adapts quite well to 32-bit, 64-bit, and SIMD + * implementations, and it is ridiculously fast. + * + * We harden it by mixing the original input to the accumulators as well as the product. + * + * This means that in the (relatively likely) case of a multiply by zero, the + * original input is preserved. + * + * On 128-bit inputs, we swap 64-bit pairs when we add the input to improve + * cross-pollination, as otherwise the upper and lower halves would be + * essentially independent. + * + * This doesn't matter on 64-bit hashes since they all get merged together in + * the end, so we skip the extra step. + * + * Both XXH3_64bits and XXH3_128bits use this subroutine. + */ + +#if (XXH_VECTOR == XXH_AVX512) \ + || (defined(XXH_DISPATCH_AVX512) && XXH_DISPATCH_AVX512 != 0) + +#ifndef XXH_TARGET_AVX512 +# define XXH_TARGET_AVX512 /* disable attribute target */ +#endif + +XXH_FORCE_INLINE XXH_TARGET_AVX512 void +XXH3_accumulate_512_avx512(void* XXH_RESTRICT acc, + const void* XXH_RESTRICT input, + const void* XXH_RESTRICT secret) +{ + __m512i* const xacc = (__m512i *) acc; + XXH_ASSERT((((size_t)acc) & 63) == 0); + XXH_STATIC_ASSERT(XXH_STRIPE_LEN == sizeof(__m512i)); + + { + /* data_vec = input[0]; */ + __m512i const data_vec = _mm512_loadu_si512 (input); + /* key_vec = secret[0]; */ + __m512i const key_vec = _mm512_loadu_si512 (secret); + /* data_key = data_vec ^ key_vec; */ + __m512i const data_key = _mm512_xor_si512 (data_vec, key_vec); + /* data_key_lo = data_key >> 32; */ + __m512i const data_key_lo = _mm512_srli_epi64 (data_key, 32); + /* product = (data_key & 0xffffffff) * (data_key_lo & 0xffffffff); */ + __m512i const product = _mm512_mul_epu32 (data_key, data_key_lo); + /* xacc[0] += swap(data_vec); */ + __m512i const data_swap = _mm512_shuffle_epi32(data_vec, (_MM_PERM_ENUM)_MM_SHUFFLE(1, 0, 3, 2)); + __m512i const sum = _mm512_add_epi64(*xacc, data_swap); + /* xacc[0] += product; */ + *xacc = _mm512_add_epi64(product, sum); + } +} +XXH_FORCE_INLINE XXH_TARGET_AVX512 XXH3_ACCUMULATE_TEMPLATE(avx512) + +/* + * XXH3_scrambleAcc: Scrambles the accumulators to improve mixing. + * + * Multiplication isn't perfect, as explained by Google in HighwayHash: + * + * // Multiplication mixes/scrambles bytes 0-7 of the 64-bit result to + * // varying degrees. In descending order of goodness, bytes + * // 3 4 2 5 1 6 0 7 have quality 228 224 164 160 100 96 36 32. + * // As expected, the upper and lower bytes are much worse. + * + * Source: https://github.com/google/highwayhash/blob/0aaf66b/highwayhash/hh_avx2.h#L291 + * + * Since our algorithm uses a pseudorandom secret to add some variance into the + * mix, we don't need to (or want to) mix as often or as much as HighwayHash does. + * + * This isn't as tight as XXH3_accumulate, but still written in SIMD to avoid + * extraction. + * + * Both XXH3_64bits and XXH3_128bits use this subroutine. + */ + +XXH_FORCE_INLINE XXH_TARGET_AVX512 void +XXH3_scrambleAcc_avx512(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret) +{ + XXH_ASSERT((((size_t)acc) & 63) == 0); + XXH_STATIC_ASSERT(XXH_STRIPE_LEN == sizeof(__m512i)); + { __m512i* const xacc = (__m512i*) acc; + const __m512i prime32 = _mm512_set1_epi32((int)XXH_PRIME32_1); + + /* xacc[0] ^= (xacc[0] >> 47) */ + __m512i const acc_vec = *xacc; + __m512i const shifted = _mm512_srli_epi64 (acc_vec, 47); + /* xacc[0] ^= secret; */ + __m512i const key_vec = _mm512_loadu_si512 (secret); + __m512i const data_key = _mm512_ternarylogic_epi32(key_vec, acc_vec, shifted, 0x96 /* key_vec ^ acc_vec ^ shifted */); + + /* xacc[0] *= XXH_PRIME32_1; */ + __m512i const data_key_hi = _mm512_srli_epi64 (data_key, 32); + __m512i const prod_lo = _mm512_mul_epu32 (data_key, prime32); + __m512i const prod_hi = _mm512_mul_epu32 (data_key_hi, prime32); + *xacc = _mm512_add_epi64(prod_lo, _mm512_slli_epi64(prod_hi, 32)); + } +} + +XXH_FORCE_INLINE XXH_TARGET_AVX512 void +XXH3_initCustomSecret_avx512(void* XXH_RESTRICT customSecret, xxh_u64 seed64) +{ + XXH_STATIC_ASSERT((XXH_SECRET_DEFAULT_SIZE & 63) == 0); + XXH_STATIC_ASSERT(XXH_SEC_ALIGN == 64); + XXH_ASSERT(((size_t)customSecret & 63) == 0); + (void)(&XXH_writeLE64); + { int const nbRounds = XXH_SECRET_DEFAULT_SIZE / sizeof(__m512i); + __m512i const seed_pos = _mm512_set1_epi64((xxh_i64)seed64); + __m512i const seed = _mm512_mask_sub_epi64(seed_pos, 0xAA, _mm512_set1_epi8(0), seed_pos); + + const __m512i* const src = (const __m512i*) ((const void*) XXH3_kSecret); + __m512i* const dest = ( __m512i*) customSecret; + int i; + XXH_ASSERT(((size_t)src & 63) == 0); /* control alignment */ + XXH_ASSERT(((size_t)dest & 63) == 0); + for (i=0; i < nbRounds; ++i) { + dest[i] = _mm512_add_epi64(_mm512_load_si512(src + i), seed); + } } +} + +#endif + +#if (XXH_VECTOR == XXH_AVX2) \ + || (defined(XXH_DISPATCH_AVX2) && XXH_DISPATCH_AVX2 != 0) + +#ifndef XXH_TARGET_AVX2 +# define XXH_TARGET_AVX2 /* disable attribute target */ +#endif + +XXH_FORCE_INLINE XXH_TARGET_AVX2 void +XXH3_accumulate_512_avx2( void* XXH_RESTRICT acc, + const void* XXH_RESTRICT input, + const void* XXH_RESTRICT secret) +{ + XXH_ASSERT((((size_t)acc) & 31) == 0); + { __m256i* const xacc = (__m256i *) acc; + /* Unaligned. This is mainly for pointer arithmetic, and because + * _mm256_loadu_si256 requires a const __m256i * pointer for some reason. */ + const __m256i* const xinput = (const __m256i *) input; + /* Unaligned. This is mainly for pointer arithmetic, and because + * _mm256_loadu_si256 requires a const __m256i * pointer for some reason. */ + const __m256i* const xsecret = (const __m256i *) secret; + + size_t i; + for (i=0; i < XXH_STRIPE_LEN/sizeof(__m256i); i++) { + /* data_vec = xinput[i]; */ + __m256i const data_vec = _mm256_loadu_si256 (xinput+i); + /* key_vec = xsecret[i]; */ + __m256i const key_vec = _mm256_loadu_si256 (xsecret+i); + /* data_key = data_vec ^ key_vec; */ + __m256i const data_key = _mm256_xor_si256 (data_vec, key_vec); + /* data_key_lo = data_key >> 32; */ + __m256i const data_key_lo = _mm256_srli_epi64 (data_key, 32); + /* product = (data_key & 0xffffffff) * (data_key_lo & 0xffffffff); */ + __m256i const product = _mm256_mul_epu32 (data_key, data_key_lo); + /* xacc[i] += swap(data_vec); */ + __m256i const data_swap = _mm256_shuffle_epi32(data_vec, _MM_SHUFFLE(1, 0, 3, 2)); + __m256i const sum = _mm256_add_epi64(xacc[i], data_swap); + /* xacc[i] += product; */ + xacc[i] = _mm256_add_epi64(product, sum); + } } +} +XXH_FORCE_INLINE XXH_TARGET_AVX2 XXH3_ACCUMULATE_TEMPLATE(avx2) + +XXH_FORCE_INLINE XXH_TARGET_AVX2 void +XXH3_scrambleAcc_avx2(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret) +{ + XXH_ASSERT((((size_t)acc) & 31) == 0); + { __m256i* const xacc = (__m256i*) acc; + /* Unaligned. This is mainly for pointer arithmetic, and because + * _mm256_loadu_si256 requires a const __m256i * pointer for some reason. */ + const __m256i* const xsecret = (const __m256i *) secret; + const __m256i prime32 = _mm256_set1_epi32((int)XXH_PRIME32_1); + + size_t i; + for (i=0; i < XXH_STRIPE_LEN/sizeof(__m256i); i++) { + /* xacc[i] ^= (xacc[i] >> 47) */ + __m256i const acc_vec = xacc[i]; + __m256i const shifted = _mm256_srli_epi64 (acc_vec, 47); + __m256i const data_vec = _mm256_xor_si256 (acc_vec, shifted); + /* xacc[i] ^= xsecret; */ + __m256i const key_vec = _mm256_loadu_si256 (xsecret+i); + __m256i const data_key = _mm256_xor_si256 (data_vec, key_vec); + + /* xacc[i] *= XXH_PRIME32_1; */ + __m256i const data_key_hi = _mm256_srli_epi64 (data_key, 32); + __m256i const prod_lo = _mm256_mul_epu32 (data_key, prime32); + __m256i const prod_hi = _mm256_mul_epu32 (data_key_hi, prime32); + xacc[i] = _mm256_add_epi64(prod_lo, _mm256_slli_epi64(prod_hi, 32)); + } + } +} + +XXH_FORCE_INLINE XXH_TARGET_AVX2 void XXH3_initCustomSecret_avx2(void* XXH_RESTRICT customSecret, xxh_u64 seed64) +{ + XXH_STATIC_ASSERT((XXH_SECRET_DEFAULT_SIZE & 31) == 0); + XXH_STATIC_ASSERT((XXH_SECRET_DEFAULT_SIZE / sizeof(__m256i)) == 6); + XXH_STATIC_ASSERT(XXH_SEC_ALIGN <= 64); + (void)(&XXH_writeLE64); + XXH_PREFETCH(customSecret); + { __m256i const seed = _mm256_set_epi64x((xxh_i64)(0U - seed64), (xxh_i64)seed64, (xxh_i64)(0U - seed64), (xxh_i64)seed64); + + const __m256i* const src = (const __m256i*) ((const void*) XXH3_kSecret); + __m256i* dest = ( __m256i*) customSecret; + +# if defined(__GNUC__) || defined(__clang__) + /* + * On GCC & Clang, marking 'dest' as modified will cause the compiler: + * - do not extract the secret from sse registers in the internal loop + * - use less common registers, and avoid pushing these reg into stack + */ + XXH_COMPILER_GUARD(dest); +# endif + XXH_ASSERT(((size_t)src & 31) == 0); /* control alignment */ + XXH_ASSERT(((size_t)dest & 31) == 0); + + /* GCC -O2 need unroll loop manually */ + dest[0] = _mm256_add_epi64(_mm256_load_si256(src+0), seed); + dest[1] = _mm256_add_epi64(_mm256_load_si256(src+1), seed); + dest[2] = _mm256_add_epi64(_mm256_load_si256(src+2), seed); + dest[3] = _mm256_add_epi64(_mm256_load_si256(src+3), seed); + dest[4] = _mm256_add_epi64(_mm256_load_si256(src+4), seed); + dest[5] = _mm256_add_epi64(_mm256_load_si256(src+5), seed); + } +} + +#endif + +/* x86dispatch always generates SSE2 */ +#if (XXH_VECTOR == XXH_SSE2) || defined(XXH_X86DISPATCH) + +#ifndef XXH_TARGET_SSE2 +# define XXH_TARGET_SSE2 /* disable attribute target */ +#endif + +XXH_FORCE_INLINE XXH_TARGET_SSE2 void +XXH3_accumulate_512_sse2( void* XXH_RESTRICT acc, + const void* XXH_RESTRICT input, + const void* XXH_RESTRICT secret) +{ + /* SSE2 is just a half-scale version of the AVX2 version. */ + XXH_ASSERT((((size_t)acc) & 15) == 0); + { __m128i* const xacc = (__m128i *) acc; + /* Unaligned. This is mainly for pointer arithmetic, and because + * _mm_loadu_si128 requires a const __m128i * pointer for some reason. */ + const __m128i* const xinput = (const __m128i *) input; + /* Unaligned. This is mainly for pointer arithmetic, and because + * _mm_loadu_si128 requires a const __m128i * pointer for some reason. */ + const __m128i* const xsecret = (const __m128i *) secret; + + size_t i; + for (i=0; i < XXH_STRIPE_LEN/sizeof(__m128i); i++) { + /* data_vec = xinput[i]; */ + __m128i const data_vec = _mm_loadu_si128 (xinput+i); + /* key_vec = xsecret[i]; */ + __m128i const key_vec = _mm_loadu_si128 (xsecret+i); + /* data_key = data_vec ^ key_vec; */ + __m128i const data_key = _mm_xor_si128 (data_vec, key_vec); + /* data_key_lo = data_key >> 32; */ + __m128i const data_key_lo = _mm_shuffle_epi32 (data_key, _MM_SHUFFLE(0, 3, 0, 1)); + /* product = (data_key & 0xffffffff) * (data_key_lo & 0xffffffff); */ + __m128i const product = _mm_mul_epu32 (data_key, data_key_lo); + /* xacc[i] += swap(data_vec); */ + __m128i const data_swap = _mm_shuffle_epi32(data_vec, _MM_SHUFFLE(1,0,3,2)); + __m128i const sum = _mm_add_epi64(xacc[i], data_swap); + /* xacc[i] += product; */ + xacc[i] = _mm_add_epi64(product, sum); + } } +} +XXH_FORCE_INLINE XXH_TARGET_SSE2 XXH3_ACCUMULATE_TEMPLATE(sse2) + +XXH_FORCE_INLINE XXH_TARGET_SSE2 void +XXH3_scrambleAcc_sse2(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret) +{ + XXH_ASSERT((((size_t)acc) & 15) == 0); + { __m128i* const xacc = (__m128i*) acc; + /* Unaligned. This is mainly for pointer arithmetic, and because + * _mm_loadu_si128 requires a const __m128i * pointer for some reason. */ + const __m128i* const xsecret = (const __m128i *) secret; + const __m128i prime32 = _mm_set1_epi32((int)XXH_PRIME32_1); + + size_t i; + for (i=0; i < XXH_STRIPE_LEN/sizeof(__m128i); i++) { + /* xacc[i] ^= (xacc[i] >> 47) */ + __m128i const acc_vec = xacc[i]; + __m128i const shifted = _mm_srli_epi64 (acc_vec, 47); + __m128i const data_vec = _mm_xor_si128 (acc_vec, shifted); + /* xacc[i] ^= xsecret[i]; */ + __m128i const key_vec = _mm_loadu_si128 (xsecret+i); + __m128i const data_key = _mm_xor_si128 (data_vec, key_vec); + + /* xacc[i] *= XXH_PRIME32_1; */ + __m128i const data_key_hi = _mm_shuffle_epi32 (data_key, _MM_SHUFFLE(0, 3, 0, 1)); + __m128i const prod_lo = _mm_mul_epu32 (data_key, prime32); + __m128i const prod_hi = _mm_mul_epu32 (data_key_hi, prime32); + xacc[i] = _mm_add_epi64(prod_lo, _mm_slli_epi64(prod_hi, 32)); + } + } +} + +XXH_FORCE_INLINE XXH_TARGET_SSE2 void XXH3_initCustomSecret_sse2(void* XXH_RESTRICT customSecret, xxh_u64 seed64) +{ + XXH_STATIC_ASSERT((XXH_SECRET_DEFAULT_SIZE & 15) == 0); + (void)(&XXH_writeLE64); + { int const nbRounds = XXH_SECRET_DEFAULT_SIZE / sizeof(__m128i); + +# if defined(_MSC_VER) && defined(_M_IX86) && _MSC_VER < 1900 + /* MSVC 32bit mode does not support _mm_set_epi64x before 2015 */ + XXH_ALIGN(16) const xxh_i64 seed64x2[2] = { (xxh_i64)seed64, (xxh_i64)(0U - seed64) }; + __m128i const seed = _mm_load_si128((__m128i const*)seed64x2); +# else + __m128i const seed = _mm_set_epi64x((xxh_i64)(0U - seed64), (xxh_i64)seed64); +# endif + int i; + + const void* const src16 = XXH3_kSecret; + __m128i* dst16 = (__m128i*) customSecret; +# if defined(__GNUC__) || defined(__clang__) + /* + * On GCC & Clang, marking 'dest' as modified will cause the compiler: + * - do not extract the secret from sse registers in the internal loop + * - use less common registers, and avoid pushing these reg into stack + */ + XXH_COMPILER_GUARD(dst16); +# endif + XXH_ASSERT(((size_t)src16 & 15) == 0); /* control alignment */ + XXH_ASSERT(((size_t)dst16 & 15) == 0); + + for (i=0; i < nbRounds; ++i) { + dst16[i] = _mm_add_epi64(_mm_load_si128((const __m128i *)src16+i), seed); + } } +} + +#endif + +#if (XXH_VECTOR == XXH_NEON) + +/* forward declarations for the scalar routines */ +XXH_FORCE_INLINE void +XXH3_scalarRound(void* XXH_RESTRICT acc, void const* XXH_RESTRICT input, + void const* XXH_RESTRICT secret, size_t lane); + +XXH_FORCE_INLINE void +XXH3_scalarScrambleRound(void* XXH_RESTRICT acc, + void const* XXH_RESTRICT secret, size_t lane); + +/*! + * @internal + * @brief The bulk processing loop for NEON and WASM SIMD128. + * + * The NEON code path is actually partially scalar when running on AArch64. This + * is to optimize the pipelining and can have up to 15% speedup depending on the + * CPU, and it also mitigates some GCC codegen issues. + * + * @see XXH3_NEON_LANES for configuring this and details about this optimization. + * + * NEON's 32-bit to 64-bit long multiply takes a half vector of 32-bit + * integers instead of the other platforms which mask full 64-bit vectors, + * so the setup is more complicated than just shifting right. + * + * Additionally, there is an optimization for 4 lanes at once noted below. + * + * Since, as stated, the most optimal amount of lanes for Cortexes is 6, + * there needs to be *three* versions of the accumulate operation used + * for the remaining 2 lanes. + * + * WASM's SIMD128 uses SIMDe's arm_neon.h polyfill because the intrinsics overlap + * nearly perfectly. + */ + +XXH_FORCE_INLINE void +XXH3_accumulate_512_neon( void* XXH_RESTRICT acc, + const void* XXH_RESTRICT input, + const void* XXH_RESTRICT secret) +{ + XXH_ASSERT((((size_t)acc) & 15) == 0); + XXH_STATIC_ASSERT(XXH3_NEON_LANES > 0 && XXH3_NEON_LANES <= XXH_ACC_NB && XXH3_NEON_LANES % 2 == 0); + { /* GCC for darwin arm64 does not like aliasing here */ + xxh_aliasing_uint64x2_t* const xacc = (xxh_aliasing_uint64x2_t*) acc; + /* We don't use a uint32x4_t pointer because it causes bus errors on ARMv7. */ + uint8_t const* xinput = (const uint8_t *) input; + uint8_t const* xsecret = (const uint8_t *) secret; + + size_t i; +#ifdef __wasm_simd128__ + /* + * On WASM SIMD128, Clang emits direct address loads when XXH3_kSecret + * is constant propagated, which results in it converting it to this + * inside the loop: + * + * a = v128.load(XXH3_kSecret + 0 + $secret_offset, offset = 0) + * b = v128.load(XXH3_kSecret + 16 + $secret_offset, offset = 0) + * ... + * + * This requires a full 32-bit address immediate (and therefore a 6 byte + * instruction) as well as an add for each offset. + * + * Putting an asm guard prevents it from folding (at the cost of losing + * the alignment hint), and uses the free offset in `v128.load` instead + * of adding secret_offset each time which overall reduces code size by + * about a kilobyte and improves performance. + */ + XXH_COMPILER_GUARD(xsecret); +#endif + /* Scalar lanes use the normal scalarRound routine */ + for (i = XXH3_NEON_LANES; i < XXH_ACC_NB; i++) { + XXH3_scalarRound(acc, input, secret, i); + } + i = 0; + /* 4 NEON lanes at a time. */ + for (; i+1 < XXH3_NEON_LANES / 2; i+=2) { + /* data_vec = xinput[i]; */ + uint64x2_t data_vec_1 = XXH_vld1q_u64(xinput + (i * 16)); + uint64x2_t data_vec_2 = XXH_vld1q_u64(xinput + ((i+1) * 16)); + /* key_vec = xsecret[i]; */ + uint64x2_t key_vec_1 = XXH_vld1q_u64(xsecret + (i * 16)); + uint64x2_t key_vec_2 = XXH_vld1q_u64(xsecret + ((i+1) * 16)); + /* data_swap = swap(data_vec) */ + uint64x2_t data_swap_1 = vextq_u64(data_vec_1, data_vec_1, 1); + uint64x2_t data_swap_2 = vextq_u64(data_vec_2, data_vec_2, 1); + /* data_key = data_vec ^ key_vec; */ + uint64x2_t data_key_1 = veorq_u64(data_vec_1, key_vec_1); + uint64x2_t data_key_2 = veorq_u64(data_vec_2, key_vec_2); + + /* + * If we reinterpret the 64x2 vectors as 32x4 vectors, we can use a + * de-interleave operation for 4 lanes in 1 step with `vuzpq_u32` to + * get one vector with the low 32 bits of each lane, and one vector + * with the high 32 bits of each lane. + * + * The intrinsic returns a double vector because the original ARMv7-a + * instruction modified both arguments in place. AArch64 and SIMD128 emit + * two instructions from this intrinsic. + * + * [ dk11L | dk11H | dk12L | dk12H ] -> [ dk11L | dk12L | dk21L | dk22L ] + * [ dk21L | dk21H | dk22L | dk22H ] -> [ dk11H | dk12H | dk21H | dk22H ] + */ + uint32x4x2_t unzipped = vuzpq_u32( + vreinterpretq_u32_u64(data_key_1), + vreinterpretq_u32_u64(data_key_2) + ); + /* data_key_lo = data_key & 0xFFFFFFFF */ + uint32x4_t data_key_lo = unzipped.val[0]; + /* data_key_hi = data_key >> 32 */ + uint32x4_t data_key_hi = unzipped.val[1]; + /* + * Then, we can split the vectors horizontally and multiply which, as for most + * widening intrinsics, have a variant that works on both high half vectors + * for free on AArch64. A similar instruction is available on SIMD128. + * + * sum = data_swap + (u64x2) data_key_lo * (u64x2) data_key_hi + */ + uint64x2_t sum_1 = XXH_vmlal_low_u32(data_swap_1, data_key_lo, data_key_hi); + uint64x2_t sum_2 = XXH_vmlal_high_u32(data_swap_2, data_key_lo, data_key_hi); + /* + * Clang reorders + * a += b * c; // umlal swap.2d, dkl.2s, dkh.2s + * c += a; // add acc.2d, acc.2d, swap.2d + * to + * c += a; // add acc.2d, acc.2d, swap.2d + * c += b * c; // umlal acc.2d, dkl.2s, dkh.2s + * + * While it would make sense in theory since the addition is faster, + * for reasons likely related to umlal being limited to certain NEON + * pipelines, this is worse. A compiler guard fixes this. + */ + XXH_COMPILER_GUARD_CLANG_NEON(sum_1); + XXH_COMPILER_GUARD_CLANG_NEON(sum_2); + /* xacc[i] = acc_vec + sum; */ + xacc[i] = vaddq_u64(xacc[i], sum_1); + xacc[i+1] = vaddq_u64(xacc[i+1], sum_2); + } + /* Operate on the remaining NEON lanes 2 at a time. */ + for (; i < XXH3_NEON_LANES / 2; i++) { + /* data_vec = xinput[i]; */ + uint64x2_t data_vec = XXH_vld1q_u64(xinput + (i * 16)); + /* key_vec = xsecret[i]; */ + uint64x2_t key_vec = XXH_vld1q_u64(xsecret + (i * 16)); + /* acc_vec_2 = swap(data_vec) */ + uint64x2_t data_swap = vextq_u64(data_vec, data_vec, 1); + /* data_key = data_vec ^ key_vec; */ + uint64x2_t data_key = veorq_u64(data_vec, key_vec); + /* For two lanes, just use VMOVN and VSHRN. */ + /* data_key_lo = data_key & 0xFFFFFFFF; */ + uint32x2_t data_key_lo = vmovn_u64(data_key); + /* data_key_hi = data_key >> 32; */ + uint32x2_t data_key_hi = vshrn_n_u64(data_key, 32); + /* sum = data_swap + (u64x2) data_key_lo * (u64x2) data_key_hi; */ + uint64x2_t sum = vmlal_u32(data_swap, data_key_lo, data_key_hi); + /* Same Clang workaround as before */ + XXH_COMPILER_GUARD_CLANG_NEON(sum); + /* xacc[i] = acc_vec + sum; */ + xacc[i] = vaddq_u64 (xacc[i], sum); + } + } +} +XXH_FORCE_INLINE XXH3_ACCUMULATE_TEMPLATE(neon) + +XXH_FORCE_INLINE void +XXH3_scrambleAcc_neon(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret) +{ + XXH_ASSERT((((size_t)acc) & 15) == 0); + + { xxh_aliasing_uint64x2_t* xacc = (xxh_aliasing_uint64x2_t*) acc; + uint8_t const* xsecret = (uint8_t const*) secret; + + size_t i; + /* WASM uses operator overloads and doesn't need these. */ +#ifndef __wasm_simd128__ + /* { prime32_1, prime32_1 } */ + uint32x2_t const kPrimeLo = vdup_n_u32(XXH_PRIME32_1); + /* { 0, prime32_1, 0, prime32_1 } */ + uint32x4_t const kPrimeHi = vreinterpretq_u32_u64(vdupq_n_u64((xxh_u64)XXH_PRIME32_1 << 32)); +#endif + + /* AArch64 uses both scalar and neon at the same time */ + for (i = XXH3_NEON_LANES; i < XXH_ACC_NB; i++) { + XXH3_scalarScrambleRound(acc, secret, i); + } + for (i=0; i < XXH3_NEON_LANES / 2; i++) { + /* xacc[i] ^= (xacc[i] >> 47); */ + uint64x2_t acc_vec = xacc[i]; + uint64x2_t shifted = vshrq_n_u64(acc_vec, 47); + uint64x2_t data_vec = veorq_u64(acc_vec, shifted); + + /* xacc[i] ^= xsecret[i]; */ + uint64x2_t key_vec = XXH_vld1q_u64(xsecret + (i * 16)); + uint64x2_t data_key = veorq_u64(data_vec, key_vec); + /* xacc[i] *= XXH_PRIME32_1 */ +#ifdef __wasm_simd128__ + /* SIMD128 has multiply by u64x2, use it instead of expanding and scalarizing */ + xacc[i] = data_key * XXH_PRIME32_1; +#else + /* + * Expanded version with portable NEON intrinsics + * + * lo(x) * lo(y) + (hi(x) * lo(y) << 32) + * + * prod_hi = hi(data_key) * lo(prime) << 32 + * + * Since we only need 32 bits of this multiply a trick can be used, reinterpreting the vector + * as a uint32x4_t and multiplying by { 0, prime, 0, prime } to cancel out the unwanted bits + * and avoid the shift. + */ + uint32x4_t prod_hi = vmulq_u32 (vreinterpretq_u32_u64(data_key), kPrimeHi); + /* Extract low bits for vmlal_u32 */ + uint32x2_t data_key_lo = vmovn_u64(data_key); + /* xacc[i] = prod_hi + lo(data_key) * XXH_PRIME32_1; */ + xacc[i] = vmlal_u32(vreinterpretq_u64_u32(prod_hi), data_key_lo, kPrimeLo); +#endif + } + } +} +#endif + +#if (XXH_VECTOR == XXH_VSX) + +XXH_FORCE_INLINE void +XXH3_accumulate_512_vsx( void* XXH_RESTRICT acc, + const void* XXH_RESTRICT input, + const void* XXH_RESTRICT secret) +{ + /* presumed aligned */ + xxh_aliasing_u64x2* const xacc = (xxh_aliasing_u64x2*) acc; + xxh_u8 const* const xinput = (xxh_u8 const*) input; /* no alignment restriction */ + xxh_u8 const* const xsecret = (xxh_u8 const*) secret; /* no alignment restriction */ + xxh_u64x2 const v32 = { 32, 32 }; + size_t i; + for (i = 0; i < XXH_STRIPE_LEN / sizeof(xxh_u64x2); i++) { + /* data_vec = xinput[i]; */ + xxh_u64x2 const data_vec = XXH_vec_loadu(xinput + 16*i); + /* key_vec = xsecret[i]; */ + xxh_u64x2 const key_vec = XXH_vec_loadu(xsecret + 16*i); + xxh_u64x2 const data_key = data_vec ^ key_vec; + /* shuffled = (data_key << 32) | (data_key >> 32); */ + xxh_u32x4 const shuffled = (xxh_u32x4)vec_rl(data_key, v32); + /* product = ((xxh_u64x2)data_key & 0xFFFFFFFF) * ((xxh_u64x2)shuffled & 0xFFFFFFFF); */ + xxh_u64x2 const product = XXH_vec_mulo((xxh_u32x4)data_key, shuffled); + /* acc_vec = xacc[i]; */ + xxh_u64x2 acc_vec = xacc[i]; + acc_vec += product; + + /* swap high and low halves */ +#ifdef __s390x__ + acc_vec += vec_permi(data_vec, data_vec, 2); +#else + acc_vec += vec_xxpermdi(data_vec, data_vec, 2); +#endif + xacc[i] = acc_vec; + } +} +XXH_FORCE_INLINE XXH3_ACCUMULATE_TEMPLATE(vsx) + +XXH_FORCE_INLINE void +XXH3_scrambleAcc_vsx(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret) +{ + XXH_ASSERT((((size_t)acc) & 15) == 0); + + { xxh_aliasing_u64x2* const xacc = (xxh_aliasing_u64x2*) acc; + const xxh_u8* const xsecret = (const xxh_u8*) secret; + /* constants */ + xxh_u64x2 const v32 = { 32, 32 }; + xxh_u64x2 const v47 = { 47, 47 }; + xxh_u32x4 const prime = { XXH_PRIME32_1, XXH_PRIME32_1, XXH_PRIME32_1, XXH_PRIME32_1 }; + size_t i; + for (i = 0; i < XXH_STRIPE_LEN / sizeof(xxh_u64x2); i++) { + /* xacc[i] ^= (xacc[i] >> 47); */ + xxh_u64x2 const acc_vec = xacc[i]; + xxh_u64x2 const data_vec = acc_vec ^ (acc_vec >> v47); + + /* xacc[i] ^= xsecret[i]; */ + xxh_u64x2 const key_vec = XXH_vec_loadu(xsecret + 16*i); + xxh_u64x2 const data_key = data_vec ^ key_vec; + + /* xacc[i] *= XXH_PRIME32_1 */ + /* prod_lo = ((xxh_u64x2)data_key & 0xFFFFFFFF) * ((xxh_u64x2)prime & 0xFFFFFFFF); */ + xxh_u64x2 const prod_even = XXH_vec_mule((xxh_u32x4)data_key, prime); + /* prod_hi = ((xxh_u64x2)data_key >> 32) * ((xxh_u64x2)prime >> 32); */ + xxh_u64x2 const prod_odd = XXH_vec_mulo((xxh_u32x4)data_key, prime); + xacc[i] = prod_odd + (prod_even << v32); + } } +} + +#endif + +#if (XXH_VECTOR == XXH_SVE) + +XXH_FORCE_INLINE void +XXH3_accumulate_512_sve( void* XXH_RESTRICT acc, + const void* XXH_RESTRICT input, + const void* XXH_RESTRICT secret) +{ + uint64_t *xacc = (uint64_t *)acc; + const uint64_t *xinput = (const uint64_t *)(const void *)input; + const uint64_t *xsecret = (const uint64_t *)(const void *)secret; + svuint64_t kSwap = sveor_n_u64_z(svptrue_b64(), svindex_u64(0, 1), 1); + uint64_t element_count = svcntd(); + if (element_count >= 8) { + svbool_t mask = svptrue_pat_b64(SV_VL8); + svuint64_t vacc = svld1_u64(mask, xacc); + ACCRND(vacc, 0); + svst1_u64(mask, xacc, vacc); + } else if (element_count == 2) { /* sve128 */ + svbool_t mask = svptrue_pat_b64(SV_VL2); + svuint64_t acc0 = svld1_u64(mask, xacc + 0); + svuint64_t acc1 = svld1_u64(mask, xacc + 2); + svuint64_t acc2 = svld1_u64(mask, xacc + 4); + svuint64_t acc3 = svld1_u64(mask, xacc + 6); + ACCRND(acc0, 0); + ACCRND(acc1, 2); + ACCRND(acc2, 4); + ACCRND(acc3, 6); + svst1_u64(mask, xacc + 0, acc0); + svst1_u64(mask, xacc + 2, acc1); + svst1_u64(mask, xacc + 4, acc2); + svst1_u64(mask, xacc + 6, acc3); + } else { + svbool_t mask = svptrue_pat_b64(SV_VL4); + svuint64_t acc0 = svld1_u64(mask, xacc + 0); + svuint64_t acc1 = svld1_u64(mask, xacc + 4); + ACCRND(acc0, 0); + ACCRND(acc1, 4); + svst1_u64(mask, xacc + 0, acc0); + svst1_u64(mask, xacc + 4, acc1); + } +} + +XXH_FORCE_INLINE void +XXH3_accumulate_sve(xxh_u64* XXH_RESTRICT acc, + const xxh_u8* XXH_RESTRICT input, + const xxh_u8* XXH_RESTRICT secret, + size_t nbStripes) +{ + if (nbStripes != 0) { + uint64_t *xacc = (uint64_t *)acc; + const uint64_t *xinput = (const uint64_t *)(const void *)input; + const uint64_t *xsecret = (const uint64_t *)(const void *)secret; + svuint64_t kSwap = sveor_n_u64_z(svptrue_b64(), svindex_u64(0, 1), 1); + uint64_t element_count = svcntd(); + if (element_count >= 8) { + svbool_t mask = svptrue_pat_b64(SV_VL8); + svuint64_t vacc = svld1_u64(mask, xacc + 0); + do { + /* svprfd(svbool_t, void *, enum svfprop); */ + svprfd(mask, xinput + 128, SV_PLDL1STRM); + ACCRND(vacc, 0); + xinput += 8; + xsecret += 1; + nbStripes--; + } while (nbStripes != 0); + + svst1_u64(mask, xacc + 0, vacc); + } else if (element_count == 2) { /* sve128 */ + svbool_t mask = svptrue_pat_b64(SV_VL2); + svuint64_t acc0 = svld1_u64(mask, xacc + 0); + svuint64_t acc1 = svld1_u64(mask, xacc + 2); + svuint64_t acc2 = svld1_u64(mask, xacc + 4); + svuint64_t acc3 = svld1_u64(mask, xacc + 6); + do { + svprfd(mask, xinput + 128, SV_PLDL1STRM); + ACCRND(acc0, 0); + ACCRND(acc1, 2); + ACCRND(acc2, 4); + ACCRND(acc3, 6); + xinput += 8; + xsecret += 1; + nbStripes--; + } while (nbStripes != 0); + + svst1_u64(mask, xacc + 0, acc0); + svst1_u64(mask, xacc + 2, acc1); + svst1_u64(mask, xacc + 4, acc2); + svst1_u64(mask, xacc + 6, acc3); + } else { + svbool_t mask = svptrue_pat_b64(SV_VL4); + svuint64_t acc0 = svld1_u64(mask, xacc + 0); + svuint64_t acc1 = svld1_u64(mask, xacc + 4); + do { + svprfd(mask, xinput + 128, SV_PLDL1STRM); + ACCRND(acc0, 0); + ACCRND(acc1, 4); + xinput += 8; + xsecret += 1; + nbStripes--; + } while (nbStripes != 0); + + svst1_u64(mask, xacc + 0, acc0); + svst1_u64(mask, xacc + 4, acc1); + } + } +} + +#endif + +/* scalar variants - universal */ + +#if defined(__aarch64__) && (defined(__GNUC__) || defined(__clang__)) +/* + * In XXH3_scalarRound(), GCC and Clang have a similar codegen issue, where they + * emit an excess mask and a full 64-bit multiply-add (MADD X-form). + * + * While this might not seem like much, as AArch64 is a 64-bit architecture, only + * big Cortex designs have a full 64-bit multiplier. + * + * On the little cores, the smaller 32-bit multiplier is used, and full 64-bit + * multiplies expand to 2-3 multiplies in microcode. This has a major penalty + * of up to 4 latency cycles and 2 stall cycles in the multiply pipeline. + * + * Thankfully, AArch64 still provides the 32-bit long multiply-add (UMADDL) which does + * not have this penalty and does the mask automatically. + */ +XXH_FORCE_INLINE xxh_u64 +XXH_mult32to64_add64(xxh_u64 lhs, xxh_u64 rhs, xxh_u64 acc) +{ + xxh_u64 ret; + /* note: %x = 64-bit register, %w = 32-bit register */ + __asm__("umaddl %x0, %w1, %w2, %x3" : "=r" (ret) : "r" (lhs), "r" (rhs), "r" (acc)); + return ret; +} +#else +XXH_FORCE_INLINE xxh_u64 +XXH_mult32to64_add64(xxh_u64 lhs, xxh_u64 rhs, xxh_u64 acc) +{ + return XXH_mult32to64((xxh_u32)lhs, (xxh_u32)rhs) + acc; +} +#endif + +/*! + * @internal + * @brief Scalar round for @ref XXH3_accumulate_512_scalar(). + * + * This is extracted to its own function because the NEON path uses a combination + * of NEON and scalar. + */ +XXH_FORCE_INLINE void +XXH3_scalarRound(void* XXH_RESTRICT acc, + void const* XXH_RESTRICT input, + void const* XXH_RESTRICT secret, + size_t lane) +{ + xxh_u64* xacc = (xxh_u64*) acc; + xxh_u8 const* xinput = (xxh_u8 const*) input; + xxh_u8 const* xsecret = (xxh_u8 const*) secret; + XXH_ASSERT(lane < XXH_ACC_NB); + XXH_ASSERT(((size_t)acc & (XXH_ACC_ALIGN-1)) == 0); + { + xxh_u64 const data_val = XXH_readLE64(xinput + lane * 8); + xxh_u64 const data_key = data_val ^ XXH_readLE64(xsecret + lane * 8); + xacc[lane ^ 1] += data_val; /* swap adjacent lanes */ + xacc[lane] = XXH_mult32to64_add64(data_key /* & 0xFFFFFFFF */, data_key >> 32, xacc[lane]); + } +} + +/*! + * @internal + * @brief Processes a 64 byte block of data using the scalar path. + */ +XXH_FORCE_INLINE void +XXH3_accumulate_512_scalar(void* XXH_RESTRICT acc, + const void* XXH_RESTRICT input, + const void* XXH_RESTRICT secret) +{ + size_t i; + /* ARM GCC refuses to unroll this loop, resulting in a 24% slowdown on ARMv6. */ +#if defined(__GNUC__) && !defined(__clang__) \ + && (defined(__arm__) || defined(__thumb2__)) \ + && defined(__ARM_FEATURE_UNALIGNED) /* no unaligned access just wastes bytes */ \ + && XXH_SIZE_OPT <= 0 +# pragma GCC unroll 8 +#endif + for (i=0; i < XXH_ACC_NB; i++) { + XXH3_scalarRound(acc, input, secret, i); + } +} +XXH_FORCE_INLINE XXH3_ACCUMULATE_TEMPLATE(scalar) + +/*! + * @internal + * @brief Scalar scramble step for @ref XXH3_scrambleAcc_scalar(). + * + * This is extracted to its own function because the NEON path uses a combination + * of NEON and scalar. + */ +XXH_FORCE_INLINE void +XXH3_scalarScrambleRound(void* XXH_RESTRICT acc, + void const* XXH_RESTRICT secret, + size_t lane) +{ + xxh_u64* const xacc = (xxh_u64*) acc; /* presumed aligned */ + const xxh_u8* const xsecret = (const xxh_u8*) secret; /* no alignment restriction */ + XXH_ASSERT((((size_t)acc) & (XXH_ACC_ALIGN-1)) == 0); + XXH_ASSERT(lane < XXH_ACC_NB); + { + xxh_u64 const key64 = XXH_readLE64(xsecret + lane * 8); + xxh_u64 acc64 = xacc[lane]; + acc64 = XXH_xorshift64(acc64, 47); + acc64 ^= key64; + acc64 *= XXH_PRIME32_1; + xacc[lane] = acc64; + } +} + +/*! + * @internal + * @brief Scrambles the accumulators after a large chunk has been read + */ +XXH_FORCE_INLINE void +XXH3_scrambleAcc_scalar(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret) +{ + size_t i; + for (i=0; i < XXH_ACC_NB; i++) { + XXH3_scalarScrambleRound(acc, secret, i); + } +} + +XXH_FORCE_INLINE void +XXH3_initCustomSecret_scalar(void* XXH_RESTRICT customSecret, xxh_u64 seed64) +{ + /* + * We need a separate pointer for the hack below, + * which requires a non-const pointer. + * Any decent compiler will optimize this out otherwise. + */ + const xxh_u8* kSecretPtr = XXH3_kSecret; + XXH_STATIC_ASSERT((XXH_SECRET_DEFAULT_SIZE & 15) == 0); + +#if defined(__GNUC__) && defined(__aarch64__) + /* + * UGLY HACK: + * GCC and Clang generate a bunch of MOV/MOVK pairs for aarch64, and they are + * placed sequentially, in order, at the top of the unrolled loop. + * + * While MOVK is great for generating constants (2 cycles for a 64-bit + * constant compared to 4 cycles for LDR), it fights for bandwidth with + * the arithmetic instructions. + * + * I L S + * MOVK + * MOVK + * MOVK + * MOVK + * ADD + * SUB STR + * STR + * By forcing loads from memory (as the asm line causes the compiler to assume + * that XXH3_kSecretPtr has been changed), the pipelines are used more + * efficiently: + * I L S + * LDR + * ADD LDR + * SUB STR + * STR + * + * See XXH3_NEON_LANES for details on the pipsline. + * + * XXH3_64bits_withSeed, len == 256, Snapdragon 835 + * without hack: 2654.4 MB/s + * with hack: 3202.9 MB/s + */ + XXH_COMPILER_GUARD(kSecretPtr); +#endif + { int const nbRounds = XXH_SECRET_DEFAULT_SIZE / 16; + int i; + for (i=0; i < nbRounds; i++) { + /* + * The asm hack causes the compiler to assume that kSecretPtr aliases with + * customSecret, and on aarch64, this prevented LDP from merging two + * loads together for free. Putting the loads together before the stores + * properly generates LDP. + */ + xxh_u64 lo = XXH_readLE64(kSecretPtr + 16*i) + seed64; + xxh_u64 hi = XXH_readLE64(kSecretPtr + 16*i + 8) - seed64; + XXH_writeLE64((xxh_u8*)customSecret + 16*i, lo); + XXH_writeLE64((xxh_u8*)customSecret + 16*i + 8, hi); + } } +} + + +typedef void (*XXH3_f_accumulate)(xxh_u64* XXH_RESTRICT, const xxh_u8* XXH_RESTRICT, const xxh_u8* XXH_RESTRICT, size_t); +typedef void (*XXH3_f_scrambleAcc)(void* XXH_RESTRICT, const void*); +typedef void (*XXH3_f_initCustomSecret)(void* XXH_RESTRICT, xxh_u64); + + +#if (XXH_VECTOR == XXH_AVX512) + +#define XXH3_accumulate_512 XXH3_accumulate_512_avx512 +#define XXH3_accumulate XXH3_accumulate_avx512 +#define XXH3_scrambleAcc XXH3_scrambleAcc_avx512 +#define XXH3_initCustomSecret XXH3_initCustomSecret_avx512 + +#elif (XXH_VECTOR == XXH_AVX2) + +#define XXH3_accumulate_512 XXH3_accumulate_512_avx2 +#define XXH3_accumulate XXH3_accumulate_avx2 +#define XXH3_scrambleAcc XXH3_scrambleAcc_avx2 +#define XXH3_initCustomSecret XXH3_initCustomSecret_avx2 + +#elif (XXH_VECTOR == XXH_SSE2) + +#define XXH3_accumulate_512 XXH3_accumulate_512_sse2 +#define XXH3_accumulate XXH3_accumulate_sse2 +#define XXH3_scrambleAcc XXH3_scrambleAcc_sse2 +#define XXH3_initCustomSecret XXH3_initCustomSecret_sse2 + +#elif (XXH_VECTOR == XXH_NEON) + +#define XXH3_accumulate_512 XXH3_accumulate_512_neon +#define XXH3_accumulate XXH3_accumulate_neon +#define XXH3_scrambleAcc XXH3_scrambleAcc_neon +#define XXH3_initCustomSecret XXH3_initCustomSecret_scalar + +#elif (XXH_VECTOR == XXH_VSX) + +#define XXH3_accumulate_512 XXH3_accumulate_512_vsx +#define XXH3_accumulate XXH3_accumulate_vsx +#define XXH3_scrambleAcc XXH3_scrambleAcc_vsx +#define XXH3_initCustomSecret XXH3_initCustomSecret_scalar + +#elif (XXH_VECTOR == XXH_SVE) +#define XXH3_accumulate_512 XXH3_accumulate_512_sve +#define XXH3_accumulate XXH3_accumulate_sve +#define XXH3_scrambleAcc XXH3_scrambleAcc_scalar +#define XXH3_initCustomSecret XXH3_initCustomSecret_scalar + +#else /* scalar */ + +#define XXH3_accumulate_512 XXH3_accumulate_512_scalar +#define XXH3_accumulate XXH3_accumulate_scalar +#define XXH3_scrambleAcc XXH3_scrambleAcc_scalar +#define XXH3_initCustomSecret XXH3_initCustomSecret_scalar + +#endif + +#if XXH_SIZE_OPT >= 1 /* don't do SIMD for initialization */ +# undef XXH3_initCustomSecret +# define XXH3_initCustomSecret XXH3_initCustomSecret_scalar +#endif + +XXH_FORCE_INLINE void +XXH3_hashLong_internal_loop(xxh_u64* XXH_RESTRICT acc, + const xxh_u8* XXH_RESTRICT input, size_t len, + const xxh_u8* XXH_RESTRICT secret, size_t secretSize, + XXH3_f_accumulate f_acc, + XXH3_f_scrambleAcc f_scramble) +{ + size_t const nbStripesPerBlock = (secretSize - XXH_STRIPE_LEN) / XXH_SECRET_CONSUME_RATE; + size_t const block_len = XXH_STRIPE_LEN * nbStripesPerBlock; + size_t const nb_blocks = (len - 1) / block_len; + + size_t n; + + XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN); + + for (n = 0; n < nb_blocks; n++) { + f_acc(acc, input + n*block_len, secret, nbStripesPerBlock); + f_scramble(acc, secret + secretSize - XXH_STRIPE_LEN); + } + + /* last partial block */ + XXH_ASSERT(len > XXH_STRIPE_LEN); + { size_t const nbStripes = ((len - 1) - (block_len * nb_blocks)) / XXH_STRIPE_LEN; + XXH_ASSERT(nbStripes <= (secretSize / XXH_SECRET_CONSUME_RATE)); + f_acc(acc, input + nb_blocks*block_len, secret, nbStripes); + + /* last stripe */ + { const xxh_u8* const p = input + len - XXH_STRIPE_LEN; +#define XXH_SECRET_LASTACC_START 7 /* not aligned on 8, last secret is different from acc & scrambler */ + XXH3_accumulate_512(acc, p, secret + secretSize - XXH_STRIPE_LEN - XXH_SECRET_LASTACC_START); + } } +} + +XXH_FORCE_INLINE xxh_u64 +XXH3_mix2Accs(const xxh_u64* XXH_RESTRICT acc, const xxh_u8* XXH_RESTRICT secret) +{ + return XXH3_mul128_fold64( + acc[0] ^ XXH_readLE64(secret), + acc[1] ^ XXH_readLE64(secret+8) ); +} + +static XXH64_hash_t +XXH3_mergeAccs(const xxh_u64* XXH_RESTRICT acc, const xxh_u8* XXH_RESTRICT secret, xxh_u64 start) +{ + xxh_u64 result64 = start; + size_t i = 0; + + for (i = 0; i < 4; i++) { + result64 += XXH3_mix2Accs(acc+2*i, secret + 16*i); +#if defined(__clang__) /* Clang */ \ + && (defined(__arm__) || defined(__thumb__)) /* ARMv7 */ \ + && (defined(__ARM_NEON) || defined(__ARM_NEON__)) /* NEON */ \ + && !defined(XXH_ENABLE_AUTOVECTORIZE) /* Define to disable */ + /* + * UGLY HACK: + * Prevent autovectorization on Clang ARMv7-a. Exact same problem as + * the one in XXH3_len_129to240_64b. Speeds up shorter keys > 240b. + * XXH3_64bits, len == 256, Snapdragon 835: + * without hack: 2063.7 MB/s + * with hack: 2560.7 MB/s + */ + XXH_COMPILER_GUARD(result64); +#endif + } + + return XXH3_avalanche(result64); +} + +#define XXH3_INIT_ACC { XXH_PRIME32_3, XXH_PRIME64_1, XXH_PRIME64_2, XXH_PRIME64_3, \ + XXH_PRIME64_4, XXH_PRIME32_2, XXH_PRIME64_5, XXH_PRIME32_1 } + +XXH_FORCE_INLINE XXH64_hash_t +XXH3_hashLong_64b_internal(const void* XXH_RESTRICT input, size_t len, + const void* XXH_RESTRICT secret, size_t secretSize, + XXH3_f_accumulate f_acc, + XXH3_f_scrambleAcc f_scramble) +{ + XXH_ALIGN(XXH_ACC_ALIGN) xxh_u64 acc[XXH_ACC_NB] = XXH3_INIT_ACC; + + XXH3_hashLong_internal_loop(acc, (const xxh_u8*)input, len, (const xxh_u8*)secret, secretSize, f_acc, f_scramble); + + /* converge into final hash */ + XXH_STATIC_ASSERT(sizeof(acc) == 64); + /* do not align on 8, so that the secret is different from the accumulator */ +#define XXH_SECRET_MERGEACCS_START 11 + XXH_ASSERT(secretSize >= sizeof(acc) + XXH_SECRET_MERGEACCS_START); + return XXH3_mergeAccs(acc, (const xxh_u8*)secret + XXH_SECRET_MERGEACCS_START, (xxh_u64)len * XXH_PRIME64_1); +} + +/* + * It's important for performance to transmit secret's size (when it's static) + * so that the compiler can properly optimize the vectorized loop. + * This makes a big performance difference for "medium" keys (<1 KB) when using AVX instruction set. + * When the secret size is unknown, or on GCC 12 where the mix of NO_INLINE and FORCE_INLINE + * breaks -Og, this is XXH_NO_INLINE. + */ +XXH3_WITH_SECRET_INLINE XXH64_hash_t +XXH3_hashLong_64b_withSecret(const void* XXH_RESTRICT input, size_t len, + XXH64_hash_t seed64, const xxh_u8* XXH_RESTRICT secret, size_t secretLen) +{ + (void)seed64; + return XXH3_hashLong_64b_internal(input, len, secret, secretLen, XXH3_accumulate, XXH3_scrambleAcc); +} + +/* + * It's preferable for performance that XXH3_hashLong is not inlined, + * as it results in a smaller function for small data, easier to the instruction cache. + * Note that inside this no_inline function, we do inline the internal loop, + * and provide a statically defined secret size to allow optimization of vector loop. + */ +XXH_NO_INLINE XXH_PUREF XXH64_hash_t +XXH3_hashLong_64b_default(const void* XXH_RESTRICT input, size_t len, + XXH64_hash_t seed64, const xxh_u8* XXH_RESTRICT secret, size_t secretLen) +{ + (void)seed64; (void)secret; (void)secretLen; + return XXH3_hashLong_64b_internal(input, len, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_accumulate, XXH3_scrambleAcc); +} + +/* + * XXH3_hashLong_64b_withSeed(): + * Generate a custom key based on alteration of default XXH3_kSecret with the seed, + * and then use this key for long mode hashing. + * + * This operation is decently fast but nonetheless costs a little bit of time. + * Try to avoid it whenever possible (typically when seed==0). + * + * It's important for performance that XXH3_hashLong is not inlined. Not sure + * why (uop cache maybe?), but the difference is large and easily measurable. + */ +XXH_FORCE_INLINE XXH64_hash_t +XXH3_hashLong_64b_withSeed_internal(const void* input, size_t len, + XXH64_hash_t seed, + XXH3_f_accumulate f_acc, + XXH3_f_scrambleAcc f_scramble, + XXH3_f_initCustomSecret f_initSec) +{ +#if XXH_SIZE_OPT <= 0 + if (seed == 0) + return XXH3_hashLong_64b_internal(input, len, + XXH3_kSecret, sizeof(XXH3_kSecret), + f_acc, f_scramble); +#endif + { XXH_ALIGN(XXH_SEC_ALIGN) xxh_u8 secret[XXH_SECRET_DEFAULT_SIZE]; + f_initSec(secret, seed); + return XXH3_hashLong_64b_internal(input, len, secret, sizeof(secret), + f_acc, f_scramble); + } +} + +/* + * It's important for performance that XXH3_hashLong is not inlined. + */ +XXH_NO_INLINE XXH64_hash_t +XXH3_hashLong_64b_withSeed(const void* XXH_RESTRICT input, size_t len, + XXH64_hash_t seed, const xxh_u8* XXH_RESTRICT secret, size_t secretLen) +{ + (void)secret; (void)secretLen; + return XXH3_hashLong_64b_withSeed_internal(input, len, seed, + XXH3_accumulate, XXH3_scrambleAcc, XXH3_initCustomSecret); +} + + +typedef XXH64_hash_t (*XXH3_hashLong64_f)(const void* XXH_RESTRICT, size_t, + XXH64_hash_t, const xxh_u8* XXH_RESTRICT, size_t); + +XXH_FORCE_INLINE XXH64_hash_t +XXH3_64bits_internal(const void* XXH_RESTRICT input, size_t len, + XXH64_hash_t seed64, const void* XXH_RESTRICT secret, size_t secretLen, + XXH3_hashLong64_f f_hashLong) +{ + XXH_ASSERT(secretLen >= XXH3_SECRET_SIZE_MIN); + /* + * If an action is to be taken if `secretLen` condition is not respected, + * it should be done here. + * For now, it's a contract pre-condition. + * Adding a check and a branch here would cost performance at every hash. + * Also, note that function signature doesn't offer room to return an error. + */ + if (len <= 16) + return XXH3_len_0to16_64b((const xxh_u8*)input, len, (const xxh_u8*)secret, seed64); + if (len <= 128) + return XXH3_len_17to128_64b((const xxh_u8*)input, len, (const xxh_u8*)secret, secretLen, seed64); + if (len <= XXH3_MIDSIZE_MAX) + return XXH3_len_129to240_64b((const xxh_u8*)input, len, (const xxh_u8*)secret, secretLen, seed64); + return f_hashLong(input, len, seed64, (const xxh_u8*)secret, secretLen); +} + + +/* === Public entry point === */ + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH64_hash_t XXH3_64bits(XXH_NOESCAPE const void* input, size_t length) +{ + return XXH3_64bits_internal(input, length, 0, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_hashLong_64b_default); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH64_hash_t +XXH3_64bits_withSecret(XXH_NOESCAPE const void* input, size_t length, XXH_NOESCAPE const void* secret, size_t secretSize) +{ + return XXH3_64bits_internal(input, length, 0, secret, secretSize, XXH3_hashLong_64b_withSecret); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH64_hash_t +XXH3_64bits_withSeed(XXH_NOESCAPE const void* input, size_t length, XXH64_hash_t seed) +{ + return XXH3_64bits_internal(input, length, seed, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_hashLong_64b_withSeed); +} + +XXH_PUBLIC_API XXH64_hash_t +XXH3_64bits_withSecretandSeed(XXH_NOESCAPE const void* input, size_t length, XXH_NOESCAPE const void* secret, size_t secretSize, XXH64_hash_t seed) +{ + if (length <= XXH3_MIDSIZE_MAX) + return XXH3_64bits_internal(input, length, seed, XXH3_kSecret, sizeof(XXH3_kSecret), NULL); + return XXH3_hashLong_64b_withSecret(input, length, seed, (const xxh_u8*)secret, secretSize); +} + + +/* === XXH3 streaming === */ +#ifndef XXH_NO_STREAM +/* + * Malloc's a pointer that is always aligned to align. + * + * This must be freed with `XXH_alignedFree()`. + * + * malloc typically guarantees 16 byte alignment on 64-bit systems and 8 byte + * alignment on 32-bit. This isn't enough for the 32 byte aligned loads in AVX2 + * or on 32-bit, the 16 byte aligned loads in SSE2 and NEON. + * + * This underalignment previously caused a rather obvious crash which went + * completely unnoticed due to XXH3_createState() not actually being tested. + * Credit to RedSpah for noticing this bug. + * + * The alignment is done manually: Functions like posix_memalign or _mm_malloc + * are avoided: To maintain portability, we would have to write a fallback + * like this anyways, and besides, testing for the existence of library + * functions without relying on external build tools is impossible. + * + * The method is simple: Overallocate, manually align, and store the offset + * to the original behind the returned pointer. + * + * Align must be a power of 2 and 8 <= align <= 128. + */ +static XXH_MALLOCF void* XXH_alignedMalloc(size_t s, size_t align) +{ + XXH_ASSERT(align <= 128 && align >= 8); /* range check */ + XXH_ASSERT((align & (align-1)) == 0); /* power of 2 */ + XXH_ASSERT(s != 0 && s < (s + align)); /* empty/overflow */ + { /* Overallocate to make room for manual realignment and an offset byte */ + xxh_u8* base = (xxh_u8*)XXH_malloc(s + align); + if (base != NULL) { + /* + * Get the offset needed to align this pointer. + * + * Even if the returned pointer is aligned, there will always be + * at least one byte to store the offset to the original pointer. + */ + size_t offset = align - ((size_t)base & (align - 1)); /* base % align */ + /* Add the offset for the now-aligned pointer */ + xxh_u8* ptr = base + offset; + + XXH_ASSERT((size_t)ptr % align == 0); + + /* Store the offset immediately before the returned pointer. */ + ptr[-1] = (xxh_u8)offset; + return ptr; + } + return NULL; + } +} +/* + * Frees an aligned pointer allocated by XXH_alignedMalloc(). Don't pass + * normal malloc'd pointers, XXH_alignedMalloc has a specific data layout. + */ +static void XXH_alignedFree(void* p) +{ + if (p != NULL) { + xxh_u8* ptr = (xxh_u8*)p; + /* Get the offset byte we added in XXH_malloc. */ + xxh_u8 offset = ptr[-1]; + /* Free the original malloc'd pointer */ + xxh_u8* base = ptr - offset; + XXH_free(base); + } +} +/*! @ingroup XXH3_family */ +/*! + * @brief Allocate an @ref XXH3_state_t. + * + * @return An allocated pointer of @ref XXH3_state_t on success. + * @return `NULL` on failure. + * + * @note Must be freed with XXH3_freeState(). + */ +XXH_PUBLIC_API XXH3_state_t* XXH3_createState(void) +{ + XXH3_state_t* const state = (XXH3_state_t*)XXH_alignedMalloc(sizeof(XXH3_state_t), 64); + if (state==NULL) return NULL; + XXH3_INITSTATE(state); + return state; +} + +/*! @ingroup XXH3_family */ +/*! + * @brief Frees an @ref XXH3_state_t. + * + * @param statePtr A pointer to an @ref XXH3_state_t allocated with @ref XXH3_createState(). + * + * @return @ref XXH_OK. + * + * @note Must be allocated with XXH3_createState(). + */ +XXH_PUBLIC_API XXH_errorcode XXH3_freeState(XXH3_state_t* statePtr) +{ + XXH_alignedFree(statePtr); + return XXH_OK; +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API void +XXH3_copyState(XXH_NOESCAPE XXH3_state_t* dst_state, XXH_NOESCAPE const XXH3_state_t* src_state) +{ + XXH_memcpy(dst_state, src_state, sizeof(*dst_state)); +} + +static void +XXH3_reset_internal(XXH3_state_t* statePtr, + XXH64_hash_t seed, + const void* secret, size_t secretSize) +{ + size_t const initStart = offsetof(XXH3_state_t, bufferedSize); + size_t const initLength = offsetof(XXH3_state_t, nbStripesPerBlock) - initStart; + XXH_ASSERT(offsetof(XXH3_state_t, nbStripesPerBlock) > initStart); + XXH_ASSERT(statePtr != NULL); + /* set members from bufferedSize to nbStripesPerBlock (excluded) to 0 */ + memset((char*)statePtr + initStart, 0, initLength); + statePtr->acc[0] = XXH_PRIME32_3; + statePtr->acc[1] = XXH_PRIME64_1; + statePtr->acc[2] = XXH_PRIME64_2; + statePtr->acc[3] = XXH_PRIME64_3; + statePtr->acc[4] = XXH_PRIME64_4; + statePtr->acc[5] = XXH_PRIME32_2; + statePtr->acc[6] = XXH_PRIME64_5; + statePtr->acc[7] = XXH_PRIME32_1; + statePtr->seed = seed; + statePtr->useSeed = (seed != 0); + statePtr->extSecret = (const unsigned char*)secret; + XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN); + statePtr->secretLimit = secretSize - XXH_STRIPE_LEN; + statePtr->nbStripesPerBlock = statePtr->secretLimit / XXH_SECRET_CONSUME_RATE; +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH_errorcode +XXH3_64bits_reset(XXH_NOESCAPE XXH3_state_t* statePtr) +{ + if (statePtr == NULL) return XXH_ERROR; + XXH3_reset_internal(statePtr, 0, XXH3_kSecret, XXH_SECRET_DEFAULT_SIZE); + return XXH_OK; +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH_errorcode +XXH3_64bits_reset_withSecret(XXH_NOESCAPE XXH3_state_t* statePtr, XXH_NOESCAPE const void* secret, size_t secretSize) +{ + if (statePtr == NULL) return XXH_ERROR; + XXH3_reset_internal(statePtr, 0, secret, secretSize); + if (secret == NULL) return XXH_ERROR; + if (secretSize < XXH3_SECRET_SIZE_MIN) return XXH_ERROR; + return XXH_OK; +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH_errorcode +XXH3_64bits_reset_withSeed(XXH_NOESCAPE XXH3_state_t* statePtr, XXH64_hash_t seed) +{ + if (statePtr == NULL) return XXH_ERROR; + if (seed==0) return XXH3_64bits_reset(statePtr); + if ((seed != statePtr->seed) || (statePtr->extSecret != NULL)) + XXH3_initCustomSecret(statePtr->customSecret, seed); + XXH3_reset_internal(statePtr, seed, NULL, XXH_SECRET_DEFAULT_SIZE); + return XXH_OK; +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH_errorcode +XXH3_64bits_reset_withSecretandSeed(XXH_NOESCAPE XXH3_state_t* statePtr, XXH_NOESCAPE const void* secret, size_t secretSize, XXH64_hash_t seed64) +{ + if (statePtr == NULL) return XXH_ERROR; + if (secret == NULL) return XXH_ERROR; + if (secretSize < XXH3_SECRET_SIZE_MIN) return XXH_ERROR; + XXH3_reset_internal(statePtr, seed64, secret, secretSize); + statePtr->useSeed = 1; /* always, even if seed64==0 */ + return XXH_OK; +} + +/*! + * @internal + * @brief Processes a large input for XXH3_update() and XXH3_digest_long(). + * + * Unlike XXH3_hashLong_internal_loop(), this can process data that overlaps a block. + * + * @param acc Pointer to the 8 accumulator lanes + * @param nbStripesSoFarPtr In/out pointer to the number of leftover stripes in the block* + * @param nbStripesPerBlock Number of stripes in a block + * @param input Input pointer + * @param nbStripes Number of stripes to process + * @param secret Secret pointer + * @param secretLimit Offset of the last block in @p secret + * @param f_acc Pointer to an XXH3_accumulate implementation + * @param f_scramble Pointer to an XXH3_scrambleAcc implementation + * @return Pointer past the end of @p input after processing + */ +XXH_FORCE_INLINE const xxh_u8 * +XXH3_consumeStripes(xxh_u64* XXH_RESTRICT acc, + size_t* XXH_RESTRICT nbStripesSoFarPtr, size_t nbStripesPerBlock, + const xxh_u8* XXH_RESTRICT input, size_t nbStripes, + const xxh_u8* XXH_RESTRICT secret, size_t secretLimit, + XXH3_f_accumulate f_acc, + XXH3_f_scrambleAcc f_scramble) +{ + const xxh_u8* initialSecret = secret + *nbStripesSoFarPtr * XXH_SECRET_CONSUME_RATE; + /* Process full blocks */ + if (nbStripes >= (nbStripesPerBlock - *nbStripesSoFarPtr)) { + /* Process the initial partial block... */ + size_t nbStripesThisIter = nbStripesPerBlock - *nbStripesSoFarPtr; + + do { + /* Accumulate and scramble */ + f_acc(acc, input, initialSecret, nbStripesThisIter); + f_scramble(acc, secret + secretLimit); + input += nbStripesThisIter * XXH_STRIPE_LEN; + nbStripes -= nbStripesThisIter; + /* Then continue the loop with the full block size */ + nbStripesThisIter = nbStripesPerBlock; + initialSecret = secret; + } while (nbStripes >= nbStripesPerBlock); + *nbStripesSoFarPtr = 0; + } + /* Process a partial block */ + if (nbStripes > 0) { + f_acc(acc, input, initialSecret, nbStripes); + input += nbStripes * XXH_STRIPE_LEN; + *nbStripesSoFarPtr += nbStripes; + } + /* Return end pointer */ + return input; +} + +#ifndef XXH3_STREAM_USE_STACK +# if XXH_SIZE_OPT <= 0 && !defined(__clang__) /* clang doesn't need additional stack space */ +# define XXH3_STREAM_USE_STACK 1 +# endif +#endif +/* + * Both XXH3_64bits_update and XXH3_128bits_update use this routine. + */ +XXH_FORCE_INLINE XXH_errorcode +XXH3_update(XXH3_state_t* XXH_RESTRICT const state, + const xxh_u8* XXH_RESTRICT input, size_t len, + XXH3_f_accumulate f_acc, + XXH3_f_scrambleAcc f_scramble) +{ + if (input==NULL) { + XXH_ASSERT(len == 0); + return XXH_OK; + } + + XXH_ASSERT(state != NULL); + { const xxh_u8* const bEnd = input + len; + const unsigned char* const secret = (state->extSecret == NULL) ? state->customSecret : state->extSecret; +#if defined(XXH3_STREAM_USE_STACK) && XXH3_STREAM_USE_STACK >= 1 + /* For some reason, gcc and MSVC seem to suffer greatly + * when operating accumulators directly into state. + * Operating into stack space seems to enable proper optimization. + * clang, on the other hand, doesn't seem to need this trick */ + XXH_ALIGN(XXH_ACC_ALIGN) xxh_u64 acc[8]; + XXH_memcpy(acc, state->acc, sizeof(acc)); +#else + xxh_u64* XXH_RESTRICT const acc = state->acc; +#endif + state->totalLen += len; + XXH_ASSERT(state->bufferedSize <= XXH3_INTERNALBUFFER_SIZE); + + /* small input : just fill in tmp buffer */ + if (len <= XXH3_INTERNALBUFFER_SIZE - state->bufferedSize) { + XXH_memcpy(state->buffer + state->bufferedSize, input, len); + state->bufferedSize += (XXH32_hash_t)len; + return XXH_OK; + } + + /* total input is now > XXH3_INTERNALBUFFER_SIZE */ + #define XXH3_INTERNALBUFFER_STRIPES (XXH3_INTERNALBUFFER_SIZE / XXH_STRIPE_LEN) + XXH_STATIC_ASSERT(XXH3_INTERNALBUFFER_SIZE % XXH_STRIPE_LEN == 0); /* clean multiple */ + + /* + * Internal buffer is partially filled (always, except at beginning) + * Complete it, then consume it. + */ + if (state->bufferedSize) { + size_t const loadSize = XXH3_INTERNALBUFFER_SIZE - state->bufferedSize; + XXH_memcpy(state->buffer + state->bufferedSize, input, loadSize); + input += loadSize; + XXH3_consumeStripes(acc, + &state->nbStripesSoFar, state->nbStripesPerBlock, + state->buffer, XXH3_INTERNALBUFFER_STRIPES, + secret, state->secretLimit, + f_acc, f_scramble); + state->bufferedSize = 0; + } + XXH_ASSERT(input < bEnd); + if (bEnd - input > XXH3_INTERNALBUFFER_SIZE) { + size_t nbStripes = (size_t)(bEnd - 1 - input) / XXH_STRIPE_LEN; + input = XXH3_consumeStripes(acc, + &state->nbStripesSoFar, state->nbStripesPerBlock, + input, nbStripes, + secret, state->secretLimit, + f_acc, f_scramble); + XXH_memcpy(state->buffer + sizeof(state->buffer) - XXH_STRIPE_LEN, input - XXH_STRIPE_LEN, XXH_STRIPE_LEN); + + } + /* Some remaining input (always) : buffer it */ + XXH_ASSERT(input < bEnd); + XXH_ASSERT(bEnd - input <= XXH3_INTERNALBUFFER_SIZE); + XXH_ASSERT(state->bufferedSize == 0); + XXH_memcpy(state->buffer, input, (size_t)(bEnd-input)); + state->bufferedSize = (XXH32_hash_t)(bEnd-input); +#if defined(XXH3_STREAM_USE_STACK) && XXH3_STREAM_USE_STACK >= 1 + /* save stack accumulators into state */ + XXH_memcpy(state->acc, acc, sizeof(acc)); +#endif + } + + return XXH_OK; +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH_errorcode +XXH3_64bits_update(XXH_NOESCAPE XXH3_state_t* state, XXH_NOESCAPE const void* input, size_t len) +{ + return XXH3_update(state, (const xxh_u8*)input, len, + XXH3_accumulate, XXH3_scrambleAcc); +} + + +XXH_FORCE_INLINE void +XXH3_digest_long (XXH64_hash_t* acc, + const XXH3_state_t* state, + const unsigned char* secret) +{ + xxh_u8 lastStripe[XXH_STRIPE_LEN]; + const xxh_u8* lastStripePtr; + + /* + * Digest on a local copy. This way, the state remains unaltered, and it can + * continue ingesting more input afterwards. + */ + XXH_memcpy(acc, state->acc, sizeof(state->acc)); + if (state->bufferedSize >= XXH_STRIPE_LEN) { + /* Consume remaining stripes then point to remaining data in buffer */ + size_t const nbStripes = (state->bufferedSize - 1) / XXH_STRIPE_LEN; + size_t nbStripesSoFar = state->nbStripesSoFar; + XXH3_consumeStripes(acc, + &nbStripesSoFar, state->nbStripesPerBlock, + state->buffer, nbStripes, + secret, state->secretLimit, + XXH3_accumulate, XXH3_scrambleAcc); + lastStripePtr = state->buffer + state->bufferedSize - XXH_STRIPE_LEN; + } else { /* bufferedSize < XXH_STRIPE_LEN */ + /* Copy to temp buffer */ + size_t const catchupSize = XXH_STRIPE_LEN - state->bufferedSize; + XXH_ASSERT(state->bufferedSize > 0); /* there is always some input buffered */ + XXH_memcpy(lastStripe, state->buffer + sizeof(state->buffer) - catchupSize, catchupSize); + XXH_memcpy(lastStripe + catchupSize, state->buffer, state->bufferedSize); + lastStripePtr = lastStripe; + } + /* Last stripe */ + XXH3_accumulate_512(acc, + lastStripePtr, + secret + state->secretLimit - XXH_SECRET_LASTACC_START); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH64_hash_t XXH3_64bits_digest (XXH_NOESCAPE const XXH3_state_t* state) +{ + const unsigned char* const secret = (state->extSecret == NULL) ? state->customSecret : state->extSecret; + if (state->totalLen > XXH3_MIDSIZE_MAX) { + XXH_ALIGN(XXH_ACC_ALIGN) XXH64_hash_t acc[XXH_ACC_NB]; + XXH3_digest_long(acc, state, secret); + return XXH3_mergeAccs(acc, + secret + XXH_SECRET_MERGEACCS_START, + (xxh_u64)state->totalLen * XXH_PRIME64_1); + } + /* totalLen <= XXH3_MIDSIZE_MAX: digesting a short input */ + if (state->useSeed) + return XXH3_64bits_withSeed(state->buffer, (size_t)state->totalLen, state->seed); + return XXH3_64bits_withSecret(state->buffer, (size_t)(state->totalLen), + secret, state->secretLimit + XXH_STRIPE_LEN); +} +#endif /* !XXH_NO_STREAM */ + + +/* ========================================== + * XXH3 128 bits (a.k.a XXH128) + * ========================================== + * XXH3's 128-bit variant has better mixing and strength than the 64-bit variant, + * even without counting the significantly larger output size. + * + * For example, extra steps are taken to avoid the seed-dependent collisions + * in 17-240 byte inputs (See XXH3_mix16B and XXH128_mix32B). + * + * This strength naturally comes at the cost of some speed, especially on short + * lengths. Note that longer hashes are about as fast as the 64-bit version + * due to it using only a slight modification of the 64-bit loop. + * + * XXH128 is also more oriented towards 64-bit machines. It is still extremely + * fast for a _128-bit_ hash on 32-bit (it usually clears XXH64). + */ + +XXH_FORCE_INLINE XXH_PUREF XXH128_hash_t +XXH3_len_1to3_128b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed) +{ + /* A doubled version of 1to3_64b with different constants. */ + XXH_ASSERT(input != NULL); + XXH_ASSERT(1 <= len && len <= 3); + XXH_ASSERT(secret != NULL); + /* + * len = 1: combinedl = { input[0], 0x01, input[0], input[0] } + * len = 2: combinedl = { input[1], 0x02, input[0], input[1] } + * len = 3: combinedl = { input[2], 0x03, input[0], input[1] } + */ + { xxh_u8 const c1 = input[0]; + xxh_u8 const c2 = input[len >> 1]; + xxh_u8 const c3 = input[len - 1]; + xxh_u32 const combinedl = ((xxh_u32)c1 <<16) | ((xxh_u32)c2 << 24) + | ((xxh_u32)c3 << 0) | ((xxh_u32)len << 8); + xxh_u32 const combinedh = XXH_rotl32(XXH_swap32(combinedl), 13); + xxh_u64 const bitflipl = (XXH_readLE32(secret) ^ XXH_readLE32(secret+4)) + seed; + xxh_u64 const bitfliph = (XXH_readLE32(secret+8) ^ XXH_readLE32(secret+12)) - seed; + xxh_u64 const keyed_lo = (xxh_u64)combinedl ^ bitflipl; + xxh_u64 const keyed_hi = (xxh_u64)combinedh ^ bitfliph; + XXH128_hash_t h128; + h128.low64 = XXH64_avalanche(keyed_lo); + h128.high64 = XXH64_avalanche(keyed_hi); + return h128; + } +} + +XXH_FORCE_INLINE XXH_PUREF XXH128_hash_t +XXH3_len_4to8_128b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed) +{ + XXH_ASSERT(input != NULL); + XXH_ASSERT(secret != NULL); + XXH_ASSERT(4 <= len && len <= 8); + seed ^= (xxh_u64)XXH_swap32((xxh_u32)seed) << 32; + { xxh_u32 const input_lo = XXH_readLE32(input); + xxh_u32 const input_hi = XXH_readLE32(input + len - 4); + xxh_u64 const input_64 = input_lo + ((xxh_u64)input_hi << 32); + xxh_u64 const bitflip = (XXH_readLE64(secret+16) ^ XXH_readLE64(secret+24)) + seed; + xxh_u64 const keyed = input_64 ^ bitflip; + + /* Shift len to the left to ensure it is even, this avoids even multiplies. */ + XXH128_hash_t m128 = XXH_mult64to128(keyed, XXH_PRIME64_1 + (len << 2)); + + m128.high64 += (m128.low64 << 1); + m128.low64 ^= (m128.high64 >> 3); + + m128.low64 = XXH_xorshift64(m128.low64, 35); + m128.low64 *= PRIME_MX2; + m128.low64 = XXH_xorshift64(m128.low64, 28); + m128.high64 = XXH3_avalanche(m128.high64); + return m128; + } +} + +XXH_FORCE_INLINE XXH_PUREF XXH128_hash_t +XXH3_len_9to16_128b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed) +{ + XXH_ASSERT(input != NULL); + XXH_ASSERT(secret != NULL); + XXH_ASSERT(9 <= len && len <= 16); + { xxh_u64 const bitflipl = (XXH_readLE64(secret+32) ^ XXH_readLE64(secret+40)) - seed; + xxh_u64 const bitfliph = (XXH_readLE64(secret+48) ^ XXH_readLE64(secret+56)) + seed; + xxh_u64 const input_lo = XXH_readLE64(input); + xxh_u64 input_hi = XXH_readLE64(input + len - 8); + XXH128_hash_t m128 = XXH_mult64to128(input_lo ^ input_hi ^ bitflipl, XXH_PRIME64_1); + /* + * Put len in the middle of m128 to ensure that the length gets mixed to + * both the low and high bits in the 128x64 multiply below. + */ + m128.low64 += (xxh_u64)(len - 1) << 54; + input_hi ^= bitfliph; + /* + * Add the high 32 bits of input_hi to the high 32 bits of m128, then + * add the long product of the low 32 bits of input_hi and XXH_PRIME32_2 to + * the high 64 bits of m128. + * + * The best approach to this operation is different on 32-bit and 64-bit. + */ + if (sizeof(void *) < sizeof(xxh_u64)) { /* 32-bit */ + /* + * 32-bit optimized version, which is more readable. + * + * On 32-bit, it removes an ADC and delays a dependency between the two + * halves of m128.high64, but it generates an extra mask on 64-bit. + */ + m128.high64 += (input_hi & 0xFFFFFFFF00000000ULL) + XXH_mult32to64((xxh_u32)input_hi, XXH_PRIME32_2); + } else { + /* + * 64-bit optimized (albeit more confusing) version. + * + * Uses some properties of addition and multiplication to remove the mask: + * + * Let: + * a = input_hi.lo = (input_hi & 0x00000000FFFFFFFF) + * b = input_hi.hi = (input_hi & 0xFFFFFFFF00000000) + * c = XXH_PRIME32_2 + * + * a + (b * c) + * Inverse Property: x + y - x == y + * a + (b * (1 + c - 1)) + * Distributive Property: x * (y + z) == (x * y) + (x * z) + * a + (b * 1) + (b * (c - 1)) + * Identity Property: x * 1 == x + * a + b + (b * (c - 1)) + * + * Substitute a, b, and c: + * input_hi.hi + input_hi.lo + ((xxh_u64)input_hi.lo * (XXH_PRIME32_2 - 1)) + * + * Since input_hi.hi + input_hi.lo == input_hi, we get this: + * input_hi + ((xxh_u64)input_hi.lo * (XXH_PRIME32_2 - 1)) + */ + m128.high64 += input_hi + XXH_mult32to64((xxh_u32)input_hi, XXH_PRIME32_2 - 1); + } + /* m128 ^= XXH_swap64(m128 >> 64); */ + m128.low64 ^= XXH_swap64(m128.high64); + + { /* 128x64 multiply: h128 = m128 * XXH_PRIME64_2; */ + XXH128_hash_t h128 = XXH_mult64to128(m128.low64, XXH_PRIME64_2); + h128.high64 += m128.high64 * XXH_PRIME64_2; + + h128.low64 = XXH3_avalanche(h128.low64); + h128.high64 = XXH3_avalanche(h128.high64); + return h128; + } } +} + +/* + * Assumption: `secret` size is >= XXH3_SECRET_SIZE_MIN + */ +XXH_FORCE_INLINE XXH_PUREF XXH128_hash_t +XXH3_len_0to16_128b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed) +{ + XXH_ASSERT(len <= 16); + { if (len > 8) return XXH3_len_9to16_128b(input, len, secret, seed); + if (len >= 4) return XXH3_len_4to8_128b(input, len, secret, seed); + if (len) return XXH3_len_1to3_128b(input, len, secret, seed); + { XXH128_hash_t h128; + xxh_u64 const bitflipl = XXH_readLE64(secret+64) ^ XXH_readLE64(secret+72); + xxh_u64 const bitfliph = XXH_readLE64(secret+80) ^ XXH_readLE64(secret+88); + h128.low64 = XXH64_avalanche(seed ^ bitflipl); + h128.high64 = XXH64_avalanche( seed ^ bitfliph); + return h128; + } } +} + +/* + * A bit slower than XXH3_mix16B, but handles multiply by zero better. + */ +XXH_FORCE_INLINE XXH128_hash_t +XXH128_mix32B(XXH128_hash_t acc, const xxh_u8* input_1, const xxh_u8* input_2, + const xxh_u8* secret, XXH64_hash_t seed) +{ + acc.low64 += XXH3_mix16B (input_1, secret+0, seed); + acc.low64 ^= XXH_readLE64(input_2) + XXH_readLE64(input_2 + 8); + acc.high64 += XXH3_mix16B (input_2, secret+16, seed); + acc.high64 ^= XXH_readLE64(input_1) + XXH_readLE64(input_1 + 8); + return acc; +} + + +XXH_FORCE_INLINE XXH_PUREF XXH128_hash_t +XXH3_len_17to128_128b(const xxh_u8* XXH_RESTRICT input, size_t len, + const xxh_u8* XXH_RESTRICT secret, size_t secretSize, + XXH64_hash_t seed) +{ + XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN); (void)secretSize; + XXH_ASSERT(16 < len && len <= 128); + + { XXH128_hash_t acc; + acc.low64 = len * XXH_PRIME64_1; + acc.high64 = 0; + +#if XXH_SIZE_OPT >= 1 + { + /* Smaller, but slightly slower. */ + unsigned int i = (unsigned int)(len - 1) / 32; + do { + acc = XXH128_mix32B(acc, input+16*i, input+len-16*(i+1), secret+32*i, seed); + } while (i-- != 0); + } +#else + if (len > 32) { + if (len > 64) { + if (len > 96) { + acc = XXH128_mix32B(acc, input+48, input+len-64, secret+96, seed); + } + acc = XXH128_mix32B(acc, input+32, input+len-48, secret+64, seed); + } + acc = XXH128_mix32B(acc, input+16, input+len-32, secret+32, seed); + } + acc = XXH128_mix32B(acc, input, input+len-16, secret, seed); +#endif + { XXH128_hash_t h128; + h128.low64 = acc.low64 + acc.high64; + h128.high64 = (acc.low64 * XXH_PRIME64_1) + + (acc.high64 * XXH_PRIME64_4) + + ((len - seed) * XXH_PRIME64_2); + h128.low64 = XXH3_avalanche(h128.low64); + h128.high64 = (XXH64_hash_t)0 - XXH3_avalanche(h128.high64); + return h128; + } + } +} + +XXH_NO_INLINE XXH_PUREF XXH128_hash_t +XXH3_len_129to240_128b(const xxh_u8* XXH_RESTRICT input, size_t len, + const xxh_u8* XXH_RESTRICT secret, size_t secretSize, + XXH64_hash_t seed) +{ + XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN); (void)secretSize; + XXH_ASSERT(128 < len && len <= XXH3_MIDSIZE_MAX); + + { XXH128_hash_t acc; + unsigned i; + acc.low64 = len * XXH_PRIME64_1; + acc.high64 = 0; + /* + * We set as `i` as offset + 32. We do this so that unchanged + * `len` can be used as upper bound. This reaches a sweet spot + * where both x86 and aarch64 get simple agen and good codegen + * for the loop. + */ + for (i = 32; i < 160; i += 32) { + acc = XXH128_mix32B(acc, + input + i - 32, + input + i - 16, + secret + i - 32, + seed); + } + acc.low64 = XXH3_avalanche(acc.low64); + acc.high64 = XXH3_avalanche(acc.high64); + /* + * NB: `i <= len` will duplicate the last 32-bytes if + * len % 32 was zero. This is an unfortunate necessity to keep + * the hash result stable. + */ + for (i=160; i <= len; i += 32) { + acc = XXH128_mix32B(acc, + input + i - 32, + input + i - 16, + secret + XXH3_MIDSIZE_STARTOFFSET + i - 160, + seed); + } + /* last bytes */ + acc = XXH128_mix32B(acc, + input + len - 16, + input + len - 32, + secret + XXH3_SECRET_SIZE_MIN - XXH3_MIDSIZE_LASTOFFSET - 16, + (XXH64_hash_t)0 - seed); + + { XXH128_hash_t h128; + h128.low64 = acc.low64 + acc.high64; + h128.high64 = (acc.low64 * XXH_PRIME64_1) + + (acc.high64 * XXH_PRIME64_4) + + ((len - seed) * XXH_PRIME64_2); + h128.low64 = XXH3_avalanche(h128.low64); + h128.high64 = (XXH64_hash_t)0 - XXH3_avalanche(h128.high64); + return h128; + } + } +} + +XXH_FORCE_INLINE XXH128_hash_t +XXH3_hashLong_128b_internal(const void* XXH_RESTRICT input, size_t len, + const xxh_u8* XXH_RESTRICT secret, size_t secretSize, + XXH3_f_accumulate f_acc, + XXH3_f_scrambleAcc f_scramble) +{ + XXH_ALIGN(XXH_ACC_ALIGN) xxh_u64 acc[XXH_ACC_NB] = XXH3_INIT_ACC; + + XXH3_hashLong_internal_loop(acc, (const xxh_u8*)input, len, secret, secretSize, f_acc, f_scramble); + + /* converge into final hash */ + XXH_STATIC_ASSERT(sizeof(acc) == 64); + XXH_ASSERT(secretSize >= sizeof(acc) + XXH_SECRET_MERGEACCS_START); + { XXH128_hash_t h128; + h128.low64 = XXH3_mergeAccs(acc, + secret + XXH_SECRET_MERGEACCS_START, + (xxh_u64)len * XXH_PRIME64_1); + h128.high64 = XXH3_mergeAccs(acc, + secret + secretSize + - sizeof(acc) - XXH_SECRET_MERGEACCS_START, + ~((xxh_u64)len * XXH_PRIME64_2)); + return h128; + } +} + +/* + * It's important for performance that XXH3_hashLong() is not inlined. + */ +XXH_NO_INLINE XXH_PUREF XXH128_hash_t +XXH3_hashLong_128b_default(const void* XXH_RESTRICT input, size_t len, + XXH64_hash_t seed64, + const void* XXH_RESTRICT secret, size_t secretLen) +{ + (void)seed64; (void)secret; (void)secretLen; + return XXH3_hashLong_128b_internal(input, len, XXH3_kSecret, sizeof(XXH3_kSecret), + XXH3_accumulate, XXH3_scrambleAcc); +} + +/* + * It's important for performance to pass @p secretLen (when it's static) + * to the compiler, so that it can properly optimize the vectorized loop. + * + * When the secret size is unknown, or on GCC 12 where the mix of NO_INLINE and FORCE_INLINE + * breaks -Og, this is XXH_NO_INLINE. + */ +XXH3_WITH_SECRET_INLINE XXH128_hash_t +XXH3_hashLong_128b_withSecret(const void* XXH_RESTRICT input, size_t len, + XXH64_hash_t seed64, + const void* XXH_RESTRICT secret, size_t secretLen) +{ + (void)seed64; + return XXH3_hashLong_128b_internal(input, len, (const xxh_u8*)secret, secretLen, + XXH3_accumulate, XXH3_scrambleAcc); +} + +XXH_FORCE_INLINE XXH128_hash_t +XXH3_hashLong_128b_withSeed_internal(const void* XXH_RESTRICT input, size_t len, + XXH64_hash_t seed64, + XXH3_f_accumulate f_acc, + XXH3_f_scrambleAcc f_scramble, + XXH3_f_initCustomSecret f_initSec) +{ + if (seed64 == 0) + return XXH3_hashLong_128b_internal(input, len, + XXH3_kSecret, sizeof(XXH3_kSecret), + f_acc, f_scramble); + { XXH_ALIGN(XXH_SEC_ALIGN) xxh_u8 secret[XXH_SECRET_DEFAULT_SIZE]; + f_initSec(secret, seed64); + return XXH3_hashLong_128b_internal(input, len, (const xxh_u8*)secret, sizeof(secret), + f_acc, f_scramble); + } +} + +/* + * It's important for performance that XXH3_hashLong is not inlined. + */ +XXH_NO_INLINE XXH128_hash_t +XXH3_hashLong_128b_withSeed(const void* input, size_t len, + XXH64_hash_t seed64, const void* XXH_RESTRICT secret, size_t secretLen) +{ + (void)secret; (void)secretLen; + return XXH3_hashLong_128b_withSeed_internal(input, len, seed64, + XXH3_accumulate, XXH3_scrambleAcc, XXH3_initCustomSecret); +} + +typedef XXH128_hash_t (*XXH3_hashLong128_f)(const void* XXH_RESTRICT, size_t, + XXH64_hash_t, const void* XXH_RESTRICT, size_t); + +XXH_FORCE_INLINE XXH128_hash_t +XXH3_128bits_internal(const void* input, size_t len, + XXH64_hash_t seed64, const void* XXH_RESTRICT secret, size_t secretLen, + XXH3_hashLong128_f f_hl128) +{ + XXH_ASSERT(secretLen >= XXH3_SECRET_SIZE_MIN); + /* + * If an action is to be taken if `secret` conditions are not respected, + * it should be done here. + * For now, it's a contract pre-condition. + * Adding a check and a branch here would cost performance at every hash. + */ + if (len <= 16) + return XXH3_len_0to16_128b((const xxh_u8*)input, len, (const xxh_u8*)secret, seed64); + if (len <= 128) + return XXH3_len_17to128_128b((const xxh_u8*)input, len, (const xxh_u8*)secret, secretLen, seed64); + if (len <= XXH3_MIDSIZE_MAX) + return XXH3_len_129to240_128b((const xxh_u8*)input, len, (const xxh_u8*)secret, secretLen, seed64); + return f_hl128(input, len, seed64, secret, secretLen); +} + + +/* === Public XXH128 API === */ + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH128_hash_t XXH3_128bits(XXH_NOESCAPE const void* input, size_t len) +{ + return XXH3_128bits_internal(input, len, 0, + XXH3_kSecret, sizeof(XXH3_kSecret), + XXH3_hashLong_128b_default); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH128_hash_t +XXH3_128bits_withSecret(XXH_NOESCAPE const void* input, size_t len, XXH_NOESCAPE const void* secret, size_t secretSize) +{ + return XXH3_128bits_internal(input, len, 0, + (const xxh_u8*)secret, secretSize, + XXH3_hashLong_128b_withSecret); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH128_hash_t +XXH3_128bits_withSeed(XXH_NOESCAPE const void* input, size_t len, XXH64_hash_t seed) +{ + return XXH3_128bits_internal(input, len, seed, + XXH3_kSecret, sizeof(XXH3_kSecret), + XXH3_hashLong_128b_withSeed); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH128_hash_t +XXH3_128bits_withSecretandSeed(XXH_NOESCAPE const void* input, size_t len, XXH_NOESCAPE const void* secret, size_t secretSize, XXH64_hash_t seed) +{ + if (len <= XXH3_MIDSIZE_MAX) + return XXH3_128bits_internal(input, len, seed, XXH3_kSecret, sizeof(XXH3_kSecret), NULL); + return XXH3_hashLong_128b_withSecret(input, len, seed, secret, secretSize); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH128_hash_t +XXH128(XXH_NOESCAPE const void* input, size_t len, XXH64_hash_t seed) +{ + return XXH3_128bits_withSeed(input, len, seed); +} + + +/* === XXH3 128-bit streaming === */ +#ifndef XXH_NO_STREAM +/* + * All initialization and update functions are identical to 64-bit streaming variant. + * The only difference is the finalization routine. + */ + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH_errorcode +XXH3_128bits_reset(XXH_NOESCAPE XXH3_state_t* statePtr) +{ + return XXH3_64bits_reset(statePtr); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH_errorcode +XXH3_128bits_reset_withSecret(XXH_NOESCAPE XXH3_state_t* statePtr, XXH_NOESCAPE const void* secret, size_t secretSize) +{ + return XXH3_64bits_reset_withSecret(statePtr, secret, secretSize); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH_errorcode +XXH3_128bits_reset_withSeed(XXH_NOESCAPE XXH3_state_t* statePtr, XXH64_hash_t seed) +{ + return XXH3_64bits_reset_withSeed(statePtr, seed); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH_errorcode +XXH3_128bits_reset_withSecretandSeed(XXH_NOESCAPE XXH3_state_t* statePtr, XXH_NOESCAPE const void* secret, size_t secretSize, XXH64_hash_t seed) +{ + return XXH3_64bits_reset_withSecretandSeed(statePtr, secret, secretSize, seed); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH_errorcode +XXH3_128bits_update(XXH_NOESCAPE XXH3_state_t* state, XXH_NOESCAPE const void* input, size_t len) +{ + return XXH3_64bits_update(state, input, len); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH128_hash_t XXH3_128bits_digest (XXH_NOESCAPE const XXH3_state_t* state) +{ + const unsigned char* const secret = (state->extSecret == NULL) ? state->customSecret : state->extSecret; + if (state->totalLen > XXH3_MIDSIZE_MAX) { + XXH_ALIGN(XXH_ACC_ALIGN) XXH64_hash_t acc[XXH_ACC_NB]; + XXH3_digest_long(acc, state, secret); + XXH_ASSERT(state->secretLimit + XXH_STRIPE_LEN >= sizeof(acc) + XXH_SECRET_MERGEACCS_START); + { XXH128_hash_t h128; + h128.low64 = XXH3_mergeAccs(acc, + secret + XXH_SECRET_MERGEACCS_START, + (xxh_u64)state->totalLen * XXH_PRIME64_1); + h128.high64 = XXH3_mergeAccs(acc, + secret + state->secretLimit + XXH_STRIPE_LEN + - sizeof(acc) - XXH_SECRET_MERGEACCS_START, + ~((xxh_u64)state->totalLen * XXH_PRIME64_2)); + return h128; + } + } + /* len <= XXH3_MIDSIZE_MAX : short code */ + if (state->seed) + return XXH3_128bits_withSeed(state->buffer, (size_t)state->totalLen, state->seed); + return XXH3_128bits_withSecret(state->buffer, (size_t)(state->totalLen), + secret, state->secretLimit + XXH_STRIPE_LEN); +} +#endif /* !XXH_NO_STREAM */ +/* 128-bit utility functions */ + +/* return : 1 is equal, 0 if different */ +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API int XXH128_isEqual(XXH128_hash_t h1, XXH128_hash_t h2) +{ + /* note : XXH128_hash_t is compact, it has no padding byte */ + return !(memcmp(&h1, &h2, sizeof(h1))); +} + +/* This prototype is compatible with stdlib's qsort(). + * @return : >0 if *h128_1 > *h128_2 + * <0 if *h128_1 < *h128_2 + * =0 if *h128_1 == *h128_2 */ +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API int XXH128_cmp(XXH_NOESCAPE const void* h128_1, XXH_NOESCAPE const void* h128_2) +{ + XXH128_hash_t const h1 = *(const XXH128_hash_t*)h128_1; + XXH128_hash_t const h2 = *(const XXH128_hash_t*)h128_2; + int const hcmp = (h1.high64 > h2.high64) - (h2.high64 > h1.high64); + /* note : bets that, in most cases, hash values are different */ + if (hcmp) return hcmp; + return (h1.low64 > h2.low64) - (h2.low64 > h1.low64); +} + + +/*====== Canonical representation ======*/ +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API void +XXH128_canonicalFromHash(XXH_NOESCAPE XXH128_canonical_t* dst, XXH128_hash_t hash) +{ + XXH_STATIC_ASSERT(sizeof(XXH128_canonical_t) == sizeof(XXH128_hash_t)); + if (XXH_CPU_LITTLE_ENDIAN) { + hash.high64 = XXH_swap64(hash.high64); + hash.low64 = XXH_swap64(hash.low64); + } + XXH_memcpy(dst, &hash.high64, sizeof(hash.high64)); + XXH_memcpy((char*)dst + sizeof(hash.high64), &hash.low64, sizeof(hash.low64)); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH128_hash_t +XXH128_hashFromCanonical(XXH_NOESCAPE const XXH128_canonical_t* src) +{ + XXH128_hash_t h; + h.high64 = XXH_readBE64(src); + h.low64 = XXH_readBE64(src->digest + 8); + return h; +} + + + +/* ========================================== + * Secret generators + * ========================================== + */ +#define XXH_MIN(x, y) (((x) > (y)) ? (y) : (x)) + +XXH_FORCE_INLINE void XXH3_combine16(void* dst, XXH128_hash_t h128) +{ + XXH_writeLE64( dst, XXH_readLE64(dst) ^ h128.low64 ); + XXH_writeLE64( (char*)dst+8, XXH_readLE64((char*)dst+8) ^ h128.high64 ); +} + +/*! @ingroup XXH3_family */ +XXH_PUBLIC_API XXH_errorcode +XXH3_generateSecret(XXH_NOESCAPE void* secretBuffer, size_t secretSize, XXH_NOESCAPE const void* customSeed, size_t customSeedSize) +{ +#if (XXH_DEBUGLEVEL >= 1) + XXH_ASSERT(secretBuffer != NULL); + XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN); +#else + /* production mode, assert() are disabled */ + if (secretBuffer == NULL) return XXH_ERROR; + if (secretSize < XXH3_SECRET_SIZE_MIN) return XXH_ERROR; +#endif + + if (customSeedSize == 0) { + customSeed = XXH3_kSecret; + customSeedSize = XXH_SECRET_DEFAULT_SIZE; + } +#if (XXH_DEBUGLEVEL >= 1) + XXH_ASSERT(customSeed != NULL); +#else + if (customSeed == NULL) return XXH_ERROR; +#endif + + /* Fill secretBuffer with a copy of customSeed - repeat as needed */ + { size_t pos = 0; + while (pos < secretSize) { + size_t const toCopy = XXH_MIN((secretSize - pos), customSeedSize); + memcpy((char*)secretBuffer + pos, customSeed, toCopy); + pos += toCopy; + } } + + { size_t const nbSeg16 = secretSize / 16; + size_t n; + XXH128_canonical_t scrambler; + XXH128_canonicalFromHash(&scrambler, XXH128(customSeed, customSeedSize, 0)); + for (n=0; n + +/* weak symbol support + * For now, enable conservatively: + * - Only GNUC + * - Only ELF + * - Only x86-64, i386, aarch64 and risc-v. + * Also, explicitly disable on platforms known not to work so they aren't + * forgotten in the future. + */ +#if !defined(ZSTD_HAVE_WEAK_SYMBOLS) && \ + defined(__GNUC__) && defined(__ELF__) && \ + (defined(__x86_64__) || defined(_M_X64) || defined(__i386__) || \ + defined(_M_IX86) || defined(__aarch64__) || defined(__riscv)) && \ + !defined(__APPLE__) && !defined(_WIN32) && !defined(__MINGW32__) && \ + !defined(__CYGWIN__) && !defined(_AIX) +# define ZSTD_HAVE_WEAK_SYMBOLS 1 +#else +# define ZSTD_HAVE_WEAK_SYMBOLS 0 +#endif +#if ZSTD_HAVE_WEAK_SYMBOLS +# define ZSTD_WEAK_ATTR __attribute__((__weak__)) +#else +# define ZSTD_WEAK_ATTR +#endif + +/* Only enable tracing when weak symbols are available. */ +#ifndef ZSTD_TRACE +# define ZSTD_TRACE ZSTD_HAVE_WEAK_SYMBOLS +#endif + +#if ZSTD_TRACE + +struct ZSTD_CCtx_s; +struct ZSTD_DCtx_s; +struct ZSTD_CCtx_params_s; + +typedef struct { + /** + * ZSTD_VERSION_NUMBER + * + * This is guaranteed to be the first member of ZSTD_trace. + * Otherwise, this struct is not stable between versions. If + * the version number does not match your expectation, you + * should not interpret the rest of the struct. + */ + unsigned version; + /** + * Non-zero if streaming (de)compression is used. + */ + int streaming; + /** + * The dictionary ID. + */ + unsigned dictionaryID; + /** + * Is the dictionary cold? + * Only set on decompression. + */ + int dictionaryIsCold; + /** + * The dictionary size or zero if no dictionary. + */ + size_t dictionarySize; + /** + * The uncompressed size of the data. + */ + size_t uncompressedSize; + /** + * The compressed size of the data. + */ + size_t compressedSize; + /** + * The fully resolved CCtx parameters (NULL on decompression). + */ + struct ZSTD_CCtx_params_s const* params; + /** + * The ZSTD_CCtx pointer (NULL on decompression). + */ + struct ZSTD_CCtx_s const* cctx; + /** + * The ZSTD_DCtx pointer (NULL on compression). + */ + struct ZSTD_DCtx_s const* dctx; +} ZSTD_Trace; + +/** + * A tracing context. It must be 0 when tracing is disabled. + * Otherwise, any non-zero value returned by a tracing begin() + * function is presented to any subsequent calls to end(). + * + * Any non-zero value is treated as tracing is enabled and not + * interpreted by the library. + * + * Two possible uses are: + * * A timestamp for when the begin() function was called. + * * A unique key identifying the (de)compression, like the + * address of the [dc]ctx pointer if you need to track + * more information than just a timestamp. + */ +typedef unsigned long long ZSTD_TraceCtx; + +/** + * Trace the beginning of a compression call. + * @param cctx The dctx pointer for the compression. + * It can be used as a key to map begin() to end(). + * @returns Non-zero if tracing is enabled. The return value is + * passed to ZSTD_trace_compress_end(). + */ +ZSTD_WEAK_ATTR ZSTD_TraceCtx ZSTD_trace_compress_begin( + struct ZSTD_CCtx_s const* cctx); + +/** + * Trace the end of a compression call. + * @param ctx The return value of ZSTD_trace_compress_begin(). + * @param trace The zstd tracing info. + */ +ZSTD_WEAK_ATTR void ZSTD_trace_compress_end( + ZSTD_TraceCtx ctx, + ZSTD_Trace const* trace); + +/** + * Trace the beginning of a decompression call. + * @param dctx The dctx pointer for the decompression. + * It can be used as a key to map begin() to end(). + * @returns Non-zero if tracing is enabled. The return value is + * passed to ZSTD_trace_compress_end(). + */ +ZSTD_WEAK_ATTR ZSTD_TraceCtx ZSTD_trace_decompress_begin( + struct ZSTD_DCtx_s const* dctx); + +/** + * Trace the end of a decompression call. + * @param ctx The return value of ZSTD_trace_decompress_begin(). + * @param trace The zstd tracing info. + */ +ZSTD_WEAK_ATTR void ZSTD_trace_decompress_end( + ZSTD_TraceCtx ctx, + ZSTD_Trace const* trace); + +#endif /* ZSTD_TRACE */ + +#endif /* ZSTD_TRACE_H */ +/**** ended inlining zstd_trace.h ****/ +#else +# define ZSTD_TRACE 0 +#endif + +/* ---- static assert (debug) --- */ +#define ZSTD_STATIC_ASSERT(c) DEBUG_STATIC_ASSERT(c) +#define ZSTD_isError ERR_isError /* for inlining */ +#define FSE_isError ERR_isError +#define HUF_isError ERR_isError + + +/*-************************************* +* shared macros +***************************************/ +#undef MIN +#undef MAX +#define MIN(a,b) ((a)<(b) ? (a) : (b)) +#define MAX(a,b) ((a)>(b) ? (a) : (b)) +#define BOUNDED(min,val,max) (MAX(min,MIN(val,max))) + + +/*-************************************* +* Common constants +***************************************/ +#define ZSTD_OPT_NUM (1<<12) + +#define ZSTD_REP_NUM 3 /* number of repcodes */ +static UNUSED_ATTR const U32 repStartValue[ZSTD_REP_NUM] = { 1, 4, 8 }; + +#define KB *(1 <<10) +#define MB *(1 <<20) +#define GB *(1U<<30) + +#define BIT7 128 +#define BIT6 64 +#define BIT5 32 +#define BIT4 16 +#define BIT1 2 +#define BIT0 1 + +#define ZSTD_WINDOWLOG_ABSOLUTEMIN 10 +static UNUSED_ATTR const size_t ZSTD_fcs_fieldSize[4] = { 0, 2, 4, 8 }; +static UNUSED_ATTR const size_t ZSTD_did_fieldSize[4] = { 0, 1, 2, 4 }; + +#define ZSTD_FRAMEIDSIZE 4 /* magic number size */ + +#define ZSTD_BLOCKHEADERSIZE 3 /* C standard doesn't allow `static const` variable to be init using another `static const` variable */ +static UNUSED_ATTR const size_t ZSTD_blockHeaderSize = ZSTD_BLOCKHEADERSIZE; +typedef enum { bt_raw, bt_rle, bt_compressed, bt_reserved } blockType_e; + +#define ZSTD_FRAMECHECKSUMSIZE 4 + +#define MIN_SEQUENCES_SIZE 1 /* nbSeq==0 */ +#define MIN_CBLOCK_SIZE (1 /*litCSize*/ + 1 /* RLE or RAW */) /* for a non-null block */ +#define MIN_LITERALS_FOR_4_STREAMS 6 + +typedef enum { set_basic, set_rle, set_compressed, set_repeat } SymbolEncodingType_e; + +#define LONGNBSEQ 0x7F00 + +#define MINMATCH 3 + +#define Litbits 8 +#define LitHufLog 11 +#define MaxLit ((1<= WILDCOPY_VECLEN || diff <= -WILDCOPY_VECLEN); + /* Separate out the first COPY16() call because the copy length is + * almost certain to be short, so the branches have different + * probabilities. Since it is almost certain to be short, only do + * one COPY16() in the first call. Then, do two calls per loop since + * at that point it is more likely to have a high trip count. + */ + ZSTD_copy16(op, ip); + if (16 >= length) return; + op += 16; + ip += 16; + do { + COPY16(op, ip); + COPY16(op, ip); + } + while (op < oend); + } +} + +MEM_STATIC size_t ZSTD_limitCopy(void* dst, size_t dstCapacity, const void* src, size_t srcSize) +{ + size_t const length = MIN(dstCapacity, srcSize); + if (length > 0) { + ZSTD_memcpy(dst, src, length); + } + return length; +} + +/* define "workspace is too large" as this number of times larger than needed */ +#define ZSTD_WORKSPACETOOLARGE_FACTOR 3 + +/* when workspace is continuously too large + * during at least this number of times, + * context's memory usage is considered wasteful, + * because it's sized to handle a worst case scenario which rarely happens. + * In which case, resize it down to free some memory */ +#define ZSTD_WORKSPACETOOLARGE_MAXDURATION 128 + +/* Controls whether the input/output buffer is buffered or stable. */ +typedef enum { + ZSTD_bm_buffered = 0, /* Buffer the input/output */ + ZSTD_bm_stable = 1 /* ZSTD_inBuffer/ZSTD_outBuffer is stable */ +} ZSTD_bufferMode_e; + + +/*-******************************************* +* Private declarations +*********************************************/ + +/** + * Contains the compressed frame size and an upper-bound for the decompressed frame size. + * Note: before using `compressedSize`, check for errors using ZSTD_isError(). + * similarly, before using `decompressedBound`, check for errors using: + * `decompressedBound != ZSTD_CONTENTSIZE_ERROR` + */ +typedef struct { + size_t nbBlocks; + size_t compressedSize; + unsigned long long decompressedBound; +} ZSTD_frameSizeInfo; /* decompress & legacy */ + +/* ZSTD_invalidateRepCodes() : + * ensures next compression will not use repcodes from previous block. + * Note : only works with regular variant; + * do not use with extDict variant ! */ +void ZSTD_invalidateRepCodes(ZSTD_CCtx* cctx); /* zstdmt, adaptive_compression (shouldn't get this definition from here) */ + + +typedef struct { + blockType_e blockType; + U32 lastBlock; + U32 origSize; +} blockProperties_t; /* declared here for decompress and fullbench */ + +/*! ZSTD_getcBlockSize() : + * Provides the size of compressed block from block header `src` */ +/* Used by: decompress, fullbench */ +size_t ZSTD_getcBlockSize(const void* src, size_t srcSize, + blockProperties_t* bpPtr); + +/*! ZSTD_decodeSeqHeaders() : + * decode sequence header from src */ +/* Used by: zstd_decompress_block, fullbench */ +size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr, + const void* src, size_t srcSize); + +/** + * @returns true iff the CPU supports dynamic BMI2 dispatch. + */ +MEM_STATIC int ZSTD_cpuSupportsBmi2(void) +{ + ZSTD_cpuid_t cpuid = ZSTD_cpuid(); + return ZSTD_cpuid_bmi1(cpuid) && ZSTD_cpuid_bmi2(cpuid); +} + +#endif /* ZSTD_CCOMMON_H_MODULE */ +/**** ended inlining zstd_internal.h ****/ + + +/*-**************************************** +* Version +******************************************/ +unsigned ZSTD_versionNumber(void) { return ZSTD_VERSION_NUMBER; } + +const char* ZSTD_versionString(void) { return ZSTD_VERSION_STRING; } + + +/*-**************************************** +* ZSTD Error Management +******************************************/ +#undef ZSTD_isError /* defined within zstd_internal.h */ +/*! ZSTD_isError() : + * tells if a return value is an error code + * symbol is required for external callers */ +unsigned ZSTD_isError(size_t code) { return ERR_isError(code); } + +/*! ZSTD_getErrorName() : + * provides error code string from function result (useful for debugging) */ +const char* ZSTD_getErrorName(size_t code) { return ERR_getErrorName(code); } + +/*! ZSTD_getError() : + * convert a `size_t` function result into a proper ZSTD_errorCode enum */ +ZSTD_ErrorCode ZSTD_getErrorCode(size_t code) { return ERR_getErrorCode(code); } + +/*! ZSTD_getErrorString() : + * provides error code string from enum */ +const char* ZSTD_getErrorString(ZSTD_ErrorCode code) { return ERR_getErrorString(code); } +/**** ended inlining common/zstd_common.c ****/ + +/**** start inlining decompress/huf_decompress.c ****/ +/* ****************************************************************** + * huff0 huffman decoder, + * part of Finite State Entropy library + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * You can contact the author at : + * - FSE+HUF source repository : https://github.com/Cyan4973/FiniteStateEntropy + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. +****************************************************************** */ + +/* ************************************************************** +* Dependencies +****************************************************************/ +/**** skipping file: ../common/zstd_deps.h ****/ +/**** skipping file: ../common/compiler.h ****/ +/**** skipping file: ../common/bitstream.h ****/ +/**** skipping file: ../common/fse.h ****/ +/**** skipping file: ../common/huf.h ****/ +/**** skipping file: ../common/error_private.h ****/ +/**** skipping file: ../common/zstd_internal.h ****/ +/**** skipping file: ../common/bits.h ****/ + +/* ************************************************************** +* Constants +****************************************************************/ + +#define HUF_DECODER_FAST_TABLELOG 11 + +/* ************************************************************** +* Macros +****************************************************************/ + +#ifdef HUF_DISABLE_FAST_DECODE +# define HUF_ENABLE_FAST_DECODE 0 +#else +# define HUF_ENABLE_FAST_DECODE 1 +#endif + +/* These two optional macros force the use one way or another of the two + * Huffman decompression implementations. You can't force in both directions + * at the same time. + */ +#if defined(HUF_FORCE_DECOMPRESS_X1) && \ + defined(HUF_FORCE_DECOMPRESS_X2) +#error "Cannot force the use of the X1 and X2 decoders at the same time!" +#endif + +/* When DYNAMIC_BMI2 is enabled, fast decoders are only called when bmi2 is + * supported at runtime, so we can add the BMI2 target attribute. + * When it is disabled, we will still get BMI2 if it is enabled statically. + */ +#if DYNAMIC_BMI2 +# define HUF_FAST_BMI2_ATTRS BMI2_TARGET_ATTRIBUTE +#else +# define HUF_FAST_BMI2_ATTRS +#endif + +#ifdef __cplusplus +# define HUF_EXTERN_C extern "C" +#else +# define HUF_EXTERN_C +#endif +#define HUF_ASM_DECL HUF_EXTERN_C + +#if DYNAMIC_BMI2 +# define HUF_NEED_BMI2_FUNCTION 1 +#else +# define HUF_NEED_BMI2_FUNCTION 0 +#endif + +/* ************************************************************** +* Error Management +****************************************************************/ +#define HUF_isError ERR_isError + + +/* ************************************************************** +* Byte alignment for workSpace management +****************************************************************/ +#define HUF_ALIGN(x, a) HUF_ALIGN_MASK((x), (a) - 1) +#define HUF_ALIGN_MASK(x, mask) (((x) + (mask)) & ~(mask)) + + +/* ************************************************************** +* BMI2 Variant Wrappers +****************************************************************/ +typedef size_t (*HUF_DecompressUsingDTableFn)(void *dst, size_t dstSize, + const void *cSrc, + size_t cSrcSize, + const HUF_DTable *DTable); + +#if DYNAMIC_BMI2 + +#define HUF_DGEN(fn) \ + \ + static size_t fn##_default( \ + void* dst, size_t dstSize, \ + const void* cSrc, size_t cSrcSize, \ + const HUF_DTable* DTable) \ + { \ + return fn##_body(dst, dstSize, cSrc, cSrcSize, DTable); \ + } \ + \ + static BMI2_TARGET_ATTRIBUTE size_t fn##_bmi2( \ + void* dst, size_t dstSize, \ + const void* cSrc, size_t cSrcSize, \ + const HUF_DTable* DTable) \ + { \ + return fn##_body(dst, dstSize, cSrc, cSrcSize, DTable); \ + } \ + \ + static size_t fn(void* dst, size_t dstSize, void const* cSrc, \ + size_t cSrcSize, HUF_DTable const* DTable, int flags) \ + { \ + if (flags & HUF_flags_bmi2) { \ + return fn##_bmi2(dst, dstSize, cSrc, cSrcSize, DTable); \ + } \ + return fn##_default(dst, dstSize, cSrc, cSrcSize, DTable); \ + } + +#else + +#define HUF_DGEN(fn) \ + static size_t fn(void* dst, size_t dstSize, void const* cSrc, \ + size_t cSrcSize, HUF_DTable const* DTable, int flags) \ + { \ + (void)flags; \ + return fn##_body(dst, dstSize, cSrc, cSrcSize, DTable); \ + } + +#endif + + +/*-***************************/ +/* generic DTableDesc */ +/*-***************************/ +typedef struct { BYTE maxTableLog; BYTE tableType; BYTE tableLog; BYTE reserved; } DTableDesc; + +static DTableDesc HUF_getDTableDesc(const HUF_DTable* table) +{ + DTableDesc dtd; + ZSTD_memcpy(&dtd, table, sizeof(dtd)); + return dtd; +} + +static size_t HUF_initFastDStream(BYTE const* ip) { + BYTE const lastByte = ip[7]; + size_t const bitsConsumed = lastByte ? 8 - ZSTD_highbit32(lastByte) : 0; + size_t const value = MEM_readLEST(ip) | 1; + assert(bitsConsumed <= 8); + assert(sizeof(size_t) == 8); + return value << bitsConsumed; +} + + +/** + * The input/output arguments to the Huffman fast decoding loop: + * + * ip [in/out] - The input pointers, must be updated to reflect what is consumed. + * op [in/out] - The output pointers, must be updated to reflect what is written. + * bits [in/out] - The bitstream containers, must be updated to reflect the current state. + * dt [in] - The decoding table. + * ilowest [in] - The beginning of the valid range of the input. Decoders may read + * down to this pointer. It may be below iend[0]. + * oend [in] - The end of the output stream. op[3] must not cross oend. + * iend [in] - The end of each input stream. ip[i] may cross iend[i], + * as long as it is above ilowest, but that indicates corruption. + */ +typedef struct { + BYTE const* ip[4]; + BYTE* op[4]; + U64 bits[4]; + void const* dt; + BYTE const* ilowest; + BYTE* oend; + BYTE const* iend[4]; +} HUF_DecompressFastArgs; + +typedef void (*HUF_DecompressFastLoopFn)(HUF_DecompressFastArgs*); + +/** + * Initializes args for the fast decoding loop. + * @returns 1 on success + * 0 if the fallback implementation should be used. + * Or an error code on failure. + */ +static size_t HUF_DecompressFastArgs_init(HUF_DecompressFastArgs* args, void* dst, size_t dstSize, void const* src, size_t srcSize, const HUF_DTable* DTable) +{ + void const* dt = DTable + 1; + U32 const dtLog = HUF_getDTableDesc(DTable).tableLog; + + const BYTE* const istart = (const BYTE*)src; + + BYTE* const oend = ZSTD_maybeNullPtrAdd((BYTE*)dst, dstSize); + + /* The fast decoding loop assumes 64-bit little-endian. + * This condition is false on x32. + */ + if (!MEM_isLittleEndian() || MEM_32bits()) + return 0; + + /* Avoid nullptr addition */ + if (dstSize == 0) + return 0; + assert(dst != NULL); + + /* strict minimum : jump table + 1 byte per stream */ + if (srcSize < 10) + return ERROR(corruption_detected); + + /* Must have at least 8 bytes per stream because we don't handle initializing smaller bit containers. + * If table log is not correct at this point, fallback to the old decoder. + * On small inputs we don't have enough data to trigger the fast loop, so use the old decoder. + */ + if (dtLog != HUF_DECODER_FAST_TABLELOG) + return 0; + + /* Read the jump table. */ + { + size_t const length1 = MEM_readLE16(istart); + size_t const length2 = MEM_readLE16(istart+2); + size_t const length3 = MEM_readLE16(istart+4); + size_t const length4 = srcSize - (length1 + length2 + length3 + 6); + args->iend[0] = istart + 6; /* jumpTable */ + args->iend[1] = args->iend[0] + length1; + args->iend[2] = args->iend[1] + length2; + args->iend[3] = args->iend[2] + length3; + + /* HUF_initFastDStream() requires this, and this small of an input + * won't benefit from the ASM loop anyways. + */ + if (length1 < 8 || length2 < 8 || length3 < 8 || length4 < 8) + return 0; + if (length4 > srcSize) return ERROR(corruption_detected); /* overflow */ + } + /* ip[] contains the position that is currently loaded into bits[]. */ + args->ip[0] = args->iend[1] - sizeof(U64); + args->ip[1] = args->iend[2] - sizeof(U64); + args->ip[2] = args->iend[3] - sizeof(U64); + args->ip[3] = (BYTE const*)src + srcSize - sizeof(U64); + + /* op[] contains the output pointers. */ + args->op[0] = (BYTE*)dst; + args->op[1] = args->op[0] + (dstSize+3)/4; + args->op[2] = args->op[1] + (dstSize+3)/4; + args->op[3] = args->op[2] + (dstSize+3)/4; + + /* No point to call the ASM loop for tiny outputs. */ + if (args->op[3] >= oend) + return 0; + + /* bits[] is the bit container. + * It is read from the MSB down to the LSB. + * It is shifted left as it is read, and zeros are + * shifted in. After the lowest valid bit a 1 is + * set, so that CountTrailingZeros(bits[]) can be used + * to count how many bits we've consumed. + */ + args->bits[0] = HUF_initFastDStream(args->ip[0]); + args->bits[1] = HUF_initFastDStream(args->ip[1]); + args->bits[2] = HUF_initFastDStream(args->ip[2]); + args->bits[3] = HUF_initFastDStream(args->ip[3]); + + /* The decoders must be sure to never read beyond ilowest. + * This is lower than iend[0], but allowing decoders to read + * down to ilowest can allow an extra iteration or two in the + * fast loop. + */ + args->ilowest = istart; + + args->oend = oend; + args->dt = dt; + + return 1; +} + +static size_t HUF_initRemainingDStream(BIT_DStream_t* bit, HUF_DecompressFastArgs const* args, int stream, BYTE* segmentEnd) +{ + /* Validate that we haven't overwritten. */ + if (args->op[stream] > segmentEnd) + return ERROR(corruption_detected); + /* Validate that we haven't read beyond iend[]. + * Note that ip[] may be < iend[] because the MSB is + * the next bit to read, and we may have consumed 100% + * of the stream, so down to iend[i] - 8 is valid. + */ + if (args->ip[stream] < args->iend[stream] - 8) + return ERROR(corruption_detected); + + /* Construct the BIT_DStream_t. */ + assert(sizeof(size_t) == 8); + bit->bitContainer = MEM_readLEST(args->ip[stream]); + bit->bitsConsumed = ZSTD_countTrailingZeros64(args->bits[stream]); + bit->start = (const char*)args->ilowest; + bit->limitPtr = bit->start + sizeof(size_t); + bit->ptr = (const char*)args->ip[stream]; + + return 0; +} + +/* Calls X(N) for each stream 0, 1, 2, 3. */ +#define HUF_4X_FOR_EACH_STREAM(X) \ + do { \ + X(0); \ + X(1); \ + X(2); \ + X(3); \ + } while (0) + +/* Calls X(N, var) for each stream 0, 1, 2, 3. */ +#define HUF_4X_FOR_EACH_STREAM_WITH_VAR(X, var) \ + do { \ + X(0, (var)); \ + X(1, (var)); \ + X(2, (var)); \ + X(3, (var)); \ + } while (0) + + +#ifndef HUF_FORCE_DECOMPRESS_X2 + +/*-***************************/ +/* single-symbol decoding */ +/*-***************************/ +typedef struct { BYTE nbBits; BYTE byte; } HUF_DEltX1; /* single-symbol decoding */ + +/** + * Packs 4 HUF_DEltX1 structs into a U64. This is used to lay down 4 entries at + * a time. + */ +static U64 HUF_DEltX1_set4(BYTE symbol, BYTE nbBits) { + U64 D4; + if (MEM_isLittleEndian()) { + D4 = (U64)((symbol << 8) + nbBits); + } else { + D4 = (U64)(symbol + (nbBits << 8)); + } + assert(D4 < (1U << 16)); + D4 *= 0x0001000100010001ULL; + return D4; +} + +/** + * Increase the tableLog to targetTableLog and rescales the stats. + * If tableLog > targetTableLog this is a no-op. + * @returns New tableLog + */ +static U32 HUF_rescaleStats(BYTE* huffWeight, U32* rankVal, U32 nbSymbols, U32 tableLog, U32 targetTableLog) +{ + if (tableLog > targetTableLog) + return tableLog; + if (tableLog < targetTableLog) { + U32 const scale = targetTableLog - tableLog; + U32 s; + /* Increase the weight for all non-zero probability symbols by scale. */ + for (s = 0; s < nbSymbols; ++s) { + huffWeight[s] += (BYTE)((huffWeight[s] == 0) ? 0 : scale); + } + /* Update rankVal to reflect the new weights. + * All weights except 0 get moved to weight + scale. + * Weights [1, scale] are empty. + */ + for (s = targetTableLog; s > scale; --s) { + rankVal[s] = rankVal[s - scale]; + } + for (s = scale; s > 0; --s) { + rankVal[s] = 0; + } + } + return targetTableLog; +} + +typedef struct { + U32 rankVal[HUF_TABLELOG_ABSOLUTEMAX + 1]; + U32 rankStart[HUF_TABLELOG_ABSOLUTEMAX + 1]; + U32 statsWksp[HUF_READ_STATS_WORKSPACE_SIZE_U32]; + BYTE symbols[HUF_SYMBOLVALUE_MAX + 1]; + BYTE huffWeight[HUF_SYMBOLVALUE_MAX + 1]; +} HUF_ReadDTableX1_Workspace; + +size_t HUF_readDTableX1_wksp(HUF_DTable* DTable, const void* src, size_t srcSize, void* workSpace, size_t wkspSize, int flags) +{ + U32 tableLog = 0; + U32 nbSymbols = 0; + size_t iSize; + void* const dtPtr = DTable + 1; + HUF_DEltX1* const dt = (HUF_DEltX1*)dtPtr; + HUF_ReadDTableX1_Workspace* wksp = (HUF_ReadDTableX1_Workspace*)workSpace; + + DEBUG_STATIC_ASSERT(HUF_DECOMPRESS_WORKSPACE_SIZE >= sizeof(*wksp)); + if (sizeof(*wksp) > wkspSize) return ERROR(tableLog_tooLarge); + + DEBUG_STATIC_ASSERT(sizeof(DTableDesc) == sizeof(HUF_DTable)); + /* ZSTD_memset(huffWeight, 0, sizeof(huffWeight)); */ /* is not necessary, even though some analyzer complain ... */ + + iSize = HUF_readStats_wksp(wksp->huffWeight, HUF_SYMBOLVALUE_MAX + 1, wksp->rankVal, &nbSymbols, &tableLog, src, srcSize, wksp->statsWksp, sizeof(wksp->statsWksp), flags); + if (HUF_isError(iSize)) return iSize; + + + /* Table header */ + { DTableDesc dtd = HUF_getDTableDesc(DTable); + U32 const maxTableLog = dtd.maxTableLog + 1; + U32 const targetTableLog = MIN(maxTableLog, HUF_DECODER_FAST_TABLELOG); + tableLog = HUF_rescaleStats(wksp->huffWeight, wksp->rankVal, nbSymbols, tableLog, targetTableLog); + if (tableLog > (U32)(dtd.maxTableLog+1)) return ERROR(tableLog_tooLarge); /* DTable too small, Huffman tree cannot fit in */ + dtd.tableType = 0; + dtd.tableLog = (BYTE)tableLog; + ZSTD_memcpy(DTable, &dtd, sizeof(dtd)); + } + + /* Compute symbols and rankStart given rankVal: + * + * rankVal already contains the number of values of each weight. + * + * symbols contains the symbols ordered by weight. First are the rankVal[0] + * weight 0 symbols, followed by the rankVal[1] weight 1 symbols, and so on. + * symbols[0] is filled (but unused) to avoid a branch. + * + * rankStart contains the offset where each rank belongs in the DTable. + * rankStart[0] is not filled because there are no entries in the table for + * weight 0. + */ + { int n; + U32 nextRankStart = 0; + int const unroll = 4; + int const nLimit = (int)nbSymbols - unroll + 1; + for (n=0; n<(int)tableLog+1; n++) { + U32 const curr = nextRankStart; + nextRankStart += wksp->rankVal[n]; + wksp->rankStart[n] = curr; + } + for (n=0; n < nLimit; n += unroll) { + int u; + for (u=0; u < unroll; ++u) { + size_t const w = wksp->huffWeight[n+u]; + wksp->symbols[wksp->rankStart[w]++] = (BYTE)(n+u); + } + } + for (; n < (int)nbSymbols; ++n) { + size_t const w = wksp->huffWeight[n]; + wksp->symbols[wksp->rankStart[w]++] = (BYTE)n; + } + } + + /* fill DTable + * We fill all entries of each weight in order. + * That way length is a constant for each iteration of the outer loop. + * We can switch based on the length to a different inner loop which is + * optimized for that particular case. + */ + { U32 w; + int symbol = wksp->rankVal[0]; + int rankStart = 0; + for (w=1; wrankVal[w]; + int const length = (1 << w) >> 1; + int uStart = rankStart; + BYTE const nbBits = (BYTE)(tableLog + 1 - w); + int s; + int u; + switch (length) { + case 1: + for (s=0; ssymbols[symbol + s]; + D.nbBits = nbBits; + dt[uStart] = D; + uStart += 1; + } + break; + case 2: + for (s=0; ssymbols[symbol + s]; + D.nbBits = nbBits; + dt[uStart+0] = D; + dt[uStart+1] = D; + uStart += 2; + } + break; + case 4: + for (s=0; ssymbols[symbol + s], nbBits); + MEM_write64(dt + uStart, D4); + uStart += 4; + } + break; + case 8: + for (s=0; ssymbols[symbol + s], nbBits); + MEM_write64(dt + uStart, D4); + MEM_write64(dt + uStart + 4, D4); + uStart += 8; + } + break; + default: + for (s=0; ssymbols[symbol + s], nbBits); + for (u=0; u < length; u += 16) { + MEM_write64(dt + uStart + u + 0, D4); + MEM_write64(dt + uStart + u + 4, D4); + MEM_write64(dt + uStart + u + 8, D4); + MEM_write64(dt + uStart + u + 12, D4); + } + assert(u == length); + uStart += length; + } + break; + } + symbol += symbolCount; + rankStart += symbolCount * length; + } + } + return iSize; +} + +FORCE_INLINE_TEMPLATE BYTE +HUF_decodeSymbolX1(BIT_DStream_t* Dstream, const HUF_DEltX1* dt, const U32 dtLog) +{ + size_t const val = BIT_lookBitsFast(Dstream, dtLog); /* note : dtLog >= 1 */ + BYTE const c = dt[val].byte; + BIT_skipBits(Dstream, dt[val].nbBits); + return c; +} + +#define HUF_DECODE_SYMBOLX1_0(ptr, DStreamPtr) \ + do { *ptr++ = HUF_decodeSymbolX1(DStreamPtr, dt, dtLog); } while (0) + +#define HUF_DECODE_SYMBOLX1_1(ptr, DStreamPtr) \ + do { \ + if (MEM_64bits() || (HUF_TABLELOG_MAX<=12)) \ + HUF_DECODE_SYMBOLX1_0(ptr, DStreamPtr); \ + } while (0) + +#define HUF_DECODE_SYMBOLX1_2(ptr, DStreamPtr) \ + do { \ + if (MEM_64bits()) \ + HUF_DECODE_SYMBOLX1_0(ptr, DStreamPtr); \ + } while (0) + +HINT_INLINE size_t +HUF_decodeStreamX1(BYTE* p, BIT_DStream_t* const bitDPtr, BYTE* const pEnd, const HUF_DEltX1* const dt, const U32 dtLog) +{ + BYTE* const pStart = p; + + /* up to 4 symbols at a time */ + if ((pEnd - p) > 3) { + while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p < pEnd-3)) { + HUF_DECODE_SYMBOLX1_2(p, bitDPtr); + HUF_DECODE_SYMBOLX1_1(p, bitDPtr); + HUF_DECODE_SYMBOLX1_2(p, bitDPtr); + HUF_DECODE_SYMBOLX1_0(p, bitDPtr); + } + } else { + BIT_reloadDStream(bitDPtr); + } + + /* [0-3] symbols remaining */ + if (MEM_32bits()) + while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p < pEnd)) + HUF_DECODE_SYMBOLX1_0(p, bitDPtr); + + /* no more data to retrieve from bitstream, no need to reload */ + while (p < pEnd) + HUF_DECODE_SYMBOLX1_0(p, bitDPtr); + + return (size_t)(pEnd-pStart); +} + +FORCE_INLINE_TEMPLATE size_t +HUF_decompress1X1_usingDTable_internal_body( + void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize, + const HUF_DTable* DTable) +{ + BYTE* op = (BYTE*)dst; + BYTE* const oend = ZSTD_maybeNullPtrAdd(op, dstSize); + const void* dtPtr = DTable + 1; + const HUF_DEltX1* const dt = (const HUF_DEltX1*)dtPtr; + BIT_DStream_t bitD; + DTableDesc const dtd = HUF_getDTableDesc(DTable); + U32 const dtLog = dtd.tableLog; + + CHECK_F( BIT_initDStream(&bitD, cSrc, cSrcSize) ); + + HUF_decodeStreamX1(op, &bitD, oend, dt, dtLog); + + if (!BIT_endOfDStream(&bitD)) return ERROR(corruption_detected); + + return dstSize; +} + +/* HUF_decompress4X1_usingDTable_internal_body(): + * Conditions : + * @dstSize >= 6 + */ +FORCE_INLINE_TEMPLATE size_t +HUF_decompress4X1_usingDTable_internal_body( + void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize, + const HUF_DTable* DTable) +{ + /* Check */ + if (cSrcSize < 10) return ERROR(corruption_detected); /* strict minimum : jump table + 1 byte per stream */ + if (dstSize < 6) return ERROR(corruption_detected); /* stream 4-split doesn't work */ + + { const BYTE* const istart = (const BYTE*) cSrc; + BYTE* const ostart = (BYTE*) dst; + BYTE* const oend = ostart + dstSize; + BYTE* const olimit = oend - 3; + const void* const dtPtr = DTable + 1; + const HUF_DEltX1* const dt = (const HUF_DEltX1*)dtPtr; + + /* Init */ + BIT_DStream_t bitD1; + BIT_DStream_t bitD2; + BIT_DStream_t bitD3; + BIT_DStream_t bitD4; + size_t const length1 = MEM_readLE16(istart); + size_t const length2 = MEM_readLE16(istart+2); + size_t const length3 = MEM_readLE16(istart+4); + size_t const length4 = cSrcSize - (length1 + length2 + length3 + 6); + const BYTE* const istart1 = istart + 6; /* jumpTable */ + const BYTE* const istart2 = istart1 + length1; + const BYTE* const istart3 = istart2 + length2; + const BYTE* const istart4 = istart3 + length3; + const size_t segmentSize = (dstSize+3) / 4; + BYTE* const opStart2 = ostart + segmentSize; + BYTE* const opStart3 = opStart2 + segmentSize; + BYTE* const opStart4 = opStart3 + segmentSize; + BYTE* op1 = ostart; + BYTE* op2 = opStart2; + BYTE* op3 = opStart3; + BYTE* op4 = opStart4; + DTableDesc const dtd = HUF_getDTableDesc(DTable); + U32 const dtLog = dtd.tableLog; + U32 endSignal = 1; + + if (length4 > cSrcSize) return ERROR(corruption_detected); /* overflow */ + if (opStart4 > oend) return ERROR(corruption_detected); /* overflow */ + assert(dstSize >= 6); /* validated above */ + CHECK_F( BIT_initDStream(&bitD1, istart1, length1) ); + CHECK_F( BIT_initDStream(&bitD2, istart2, length2) ); + CHECK_F( BIT_initDStream(&bitD3, istart3, length3) ); + CHECK_F( BIT_initDStream(&bitD4, istart4, length4) ); + + /* up to 16 symbols per loop (4 symbols per stream) in 64-bit mode */ + if ((size_t)(oend - op4) >= sizeof(size_t)) { + for ( ; (endSignal) & (op4 < olimit) ; ) { + HUF_DECODE_SYMBOLX1_2(op1, &bitD1); + HUF_DECODE_SYMBOLX1_2(op2, &bitD2); + HUF_DECODE_SYMBOLX1_2(op3, &bitD3); + HUF_DECODE_SYMBOLX1_2(op4, &bitD4); + HUF_DECODE_SYMBOLX1_1(op1, &bitD1); + HUF_DECODE_SYMBOLX1_1(op2, &bitD2); + HUF_DECODE_SYMBOLX1_1(op3, &bitD3); + HUF_DECODE_SYMBOLX1_1(op4, &bitD4); + HUF_DECODE_SYMBOLX1_2(op1, &bitD1); + HUF_DECODE_SYMBOLX1_2(op2, &bitD2); + HUF_DECODE_SYMBOLX1_2(op3, &bitD3); + HUF_DECODE_SYMBOLX1_2(op4, &bitD4); + HUF_DECODE_SYMBOLX1_0(op1, &bitD1); + HUF_DECODE_SYMBOLX1_0(op2, &bitD2); + HUF_DECODE_SYMBOLX1_0(op3, &bitD3); + HUF_DECODE_SYMBOLX1_0(op4, &bitD4); + endSignal &= BIT_reloadDStreamFast(&bitD1) == BIT_DStream_unfinished; + endSignal &= BIT_reloadDStreamFast(&bitD2) == BIT_DStream_unfinished; + endSignal &= BIT_reloadDStreamFast(&bitD3) == BIT_DStream_unfinished; + endSignal &= BIT_reloadDStreamFast(&bitD4) == BIT_DStream_unfinished; + } + } + + /* check corruption */ + /* note : should not be necessary : op# advance in lock step, and we control op4. + * but curiously, binary generated by gcc 7.2 & 7.3 with -mbmi2 runs faster when >=1 test is present */ + if (op1 > opStart2) return ERROR(corruption_detected); + if (op2 > opStart3) return ERROR(corruption_detected); + if (op3 > opStart4) return ERROR(corruption_detected); + /* note : op4 supposed already verified within main loop */ + + /* finish bitStreams one by one */ + HUF_decodeStreamX1(op1, &bitD1, opStart2, dt, dtLog); + HUF_decodeStreamX1(op2, &bitD2, opStart3, dt, dtLog); + HUF_decodeStreamX1(op3, &bitD3, opStart4, dt, dtLog); + HUF_decodeStreamX1(op4, &bitD4, oend, dt, dtLog); + + /* check */ + { U32 const endCheck = BIT_endOfDStream(&bitD1) & BIT_endOfDStream(&bitD2) & BIT_endOfDStream(&bitD3) & BIT_endOfDStream(&bitD4); + if (!endCheck) return ERROR(corruption_detected); } + + /* decoded size */ + return dstSize; + } +} + +#if HUF_NEED_BMI2_FUNCTION +static BMI2_TARGET_ATTRIBUTE +size_t HUF_decompress4X1_usingDTable_internal_bmi2(void* dst, size_t dstSize, void const* cSrc, + size_t cSrcSize, HUF_DTable const* DTable) { + return HUF_decompress4X1_usingDTable_internal_body(dst, dstSize, cSrc, cSrcSize, DTable); +} +#endif + +static +size_t HUF_decompress4X1_usingDTable_internal_default(void* dst, size_t dstSize, void const* cSrc, + size_t cSrcSize, HUF_DTable const* DTable) { + return HUF_decompress4X1_usingDTable_internal_body(dst, dstSize, cSrc, cSrcSize, DTable); +} + +#if ZSTD_ENABLE_ASM_X86_64_BMI2 + +HUF_ASM_DECL void HUF_decompress4X1_usingDTable_internal_fast_asm_loop(HUF_DecompressFastArgs* args) ZSTDLIB_HIDDEN; + +#endif + +static HUF_FAST_BMI2_ATTRS +void HUF_decompress4X1_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs* args) +{ + U64 bits[4]; + BYTE const* ip[4]; + BYTE* op[4]; + U16 const* const dtable = (U16 const*)args->dt; + BYTE* const oend = args->oend; + BYTE const* const ilowest = args->ilowest; + + /* Copy the arguments to local variables */ + ZSTD_memcpy(&bits, &args->bits, sizeof(bits)); + ZSTD_memcpy((void*)(&ip), &args->ip, sizeof(ip)); + ZSTD_memcpy(&op, &args->op, sizeof(op)); + + assert(MEM_isLittleEndian()); + assert(!MEM_32bits()); + + for (;;) { + BYTE* olimit; + int stream; + + /* Assert loop preconditions */ +#ifndef NDEBUG + for (stream = 0; stream < 4; ++stream) { + assert(op[stream] <= (stream == 3 ? oend : op[stream + 1])); + assert(ip[stream] >= ilowest); + } +#endif + /* Compute olimit */ + { + /* Each iteration produces 5 output symbols per stream */ + size_t const oiters = (size_t)(oend - op[3]) / 5; + /* Each iteration consumes up to 11 bits * 5 = 55 bits < 7 bytes + * per stream. + */ + size_t const iiters = (size_t)(ip[0] - ilowest) / 7; + /* We can safely run iters iterations before running bounds checks */ + size_t const iters = MIN(oiters, iiters); + size_t const symbols = iters * 5; + + /* We can simply check that op[3] < olimit, instead of checking all + * of our bounds, since we can't hit the other bounds until we've run + * iters iterations, which only happens when op[3] == olimit. + */ + olimit = op[3] + symbols; + + /* Exit fast decoding loop once we reach the end. */ + if (op[3] == olimit) + break; + + /* Exit the decoding loop if any input pointer has crossed the + * previous one. This indicates corruption, and a precondition + * to our loop is that ip[i] >= ip[0]. + */ + for (stream = 1; stream < 4; ++stream) { + if (ip[stream] < ip[stream - 1]) + goto _out; + } + } + +#ifndef NDEBUG + for (stream = 1; stream < 4; ++stream) { + assert(ip[stream] >= ip[stream - 1]); + } +#endif + +#define HUF_4X1_DECODE_SYMBOL(_stream, _symbol) \ + do { \ + int const index = (int)(bits[(_stream)] >> 53); \ + int const entry = (int)dtable[index]; \ + bits[(_stream)] <<= (entry & 0x3F); \ + op[(_stream)][(_symbol)] = (BYTE)((entry >> 8) & 0xFF); \ + } while (0) + +#define HUF_4X1_RELOAD_STREAM(_stream) \ + do { \ + int const ctz = ZSTD_countTrailingZeros64(bits[(_stream)]); \ + int const nbBits = ctz & 7; \ + int const nbBytes = ctz >> 3; \ + op[(_stream)] += 5; \ + ip[(_stream)] -= nbBytes; \ + bits[(_stream)] = MEM_read64(ip[(_stream)]) | 1; \ + bits[(_stream)] <<= nbBits; \ + } while (0) + + /* Manually unroll the loop because compilers don't consistently + * unroll the inner loops, which destroys performance. + */ + do { + /* Decode 5 symbols in each of the 4 streams */ + HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 0); + HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 1); + HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 2); + HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 3); + HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 4); + + /* Reload each of the 4 the bitstreams */ + HUF_4X_FOR_EACH_STREAM(HUF_4X1_RELOAD_STREAM); + } while (op[3] < olimit); + +#undef HUF_4X1_DECODE_SYMBOL +#undef HUF_4X1_RELOAD_STREAM + } + +_out: + + /* Save the final values of each of the state variables back to args. */ + ZSTD_memcpy(&args->bits, &bits, sizeof(bits)); + ZSTD_memcpy((void*)(&args->ip), &ip, sizeof(ip)); + ZSTD_memcpy(&args->op, &op, sizeof(op)); +} + +/** + * @returns @p dstSize on success (>= 6) + * 0 if the fallback implementation should be used + * An error if an error occurred + */ +static HUF_FAST_BMI2_ATTRS +size_t +HUF_decompress4X1_usingDTable_internal_fast( + void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize, + const HUF_DTable* DTable, + HUF_DecompressFastLoopFn loopFn) +{ + void const* dt = DTable + 1; + BYTE const* const ilowest = (BYTE const*)cSrc; + BYTE* const oend = ZSTD_maybeNullPtrAdd((BYTE*)dst, dstSize); + HUF_DecompressFastArgs args; + { size_t const ret = HUF_DecompressFastArgs_init(&args, dst, dstSize, cSrc, cSrcSize, DTable); + FORWARD_IF_ERROR(ret, "Failed to init fast loop args"); + if (ret == 0) + return 0; + } + + assert(args.ip[0] >= args.ilowest); + loopFn(&args); + + /* Our loop guarantees that ip[] >= ilowest and that we haven't + * overwritten any op[]. + */ + assert(args.ip[0] >= ilowest); + assert(args.ip[0] >= ilowest); + assert(args.ip[1] >= ilowest); + assert(args.ip[2] >= ilowest); + assert(args.ip[3] >= ilowest); + assert(args.op[3] <= oend); + + assert(ilowest == args.ilowest); + assert(ilowest + 6 == args.iend[0]); + (void)ilowest; + + /* finish bit streams one by one. */ + { size_t const segmentSize = (dstSize+3) / 4; + BYTE* segmentEnd = (BYTE*)dst; + int i; + for (i = 0; i < 4; ++i) { + BIT_DStream_t bit; + if (segmentSize <= (size_t)(oend - segmentEnd)) + segmentEnd += segmentSize; + else + segmentEnd = oend; + FORWARD_IF_ERROR(HUF_initRemainingDStream(&bit, &args, i, segmentEnd), "corruption"); + /* Decompress and validate that we've produced exactly the expected length. */ + args.op[i] += HUF_decodeStreamX1(args.op[i], &bit, segmentEnd, (HUF_DEltX1 const*)dt, HUF_DECODER_FAST_TABLELOG); + if (args.op[i] != segmentEnd) return ERROR(corruption_detected); + } + } + + /* decoded size */ + assert(dstSize != 0); + return dstSize; +} + +HUF_DGEN(HUF_decompress1X1_usingDTable_internal) + +static size_t HUF_decompress4X1_usingDTable_internal(void* dst, size_t dstSize, void const* cSrc, + size_t cSrcSize, HUF_DTable const* DTable, int flags) +{ + HUF_DecompressUsingDTableFn fallbackFn = HUF_decompress4X1_usingDTable_internal_default; + HUF_DecompressFastLoopFn loopFn = HUF_decompress4X1_usingDTable_internal_fast_c_loop; + +#if DYNAMIC_BMI2 + if (flags & HUF_flags_bmi2) { + fallbackFn = HUF_decompress4X1_usingDTable_internal_bmi2; +# if ZSTD_ENABLE_ASM_X86_64_BMI2 + if (!(flags & HUF_flags_disableAsm)) { + loopFn = HUF_decompress4X1_usingDTable_internal_fast_asm_loop; + } +# endif + } else { + return fallbackFn(dst, dstSize, cSrc, cSrcSize, DTable); + } +#endif + +#if ZSTD_ENABLE_ASM_X86_64_BMI2 && defined(__BMI2__) + if (!(flags & HUF_flags_disableAsm)) { + loopFn = HUF_decompress4X1_usingDTable_internal_fast_asm_loop; + } +#endif + + if (HUF_ENABLE_FAST_DECODE && !(flags & HUF_flags_disableFast)) { + size_t const ret = HUF_decompress4X1_usingDTable_internal_fast(dst, dstSize, cSrc, cSrcSize, DTable, loopFn); + if (ret != 0) + return ret; + } + return fallbackFn(dst, dstSize, cSrc, cSrcSize, DTable); +} + +static size_t HUF_decompress4X1_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize, + void* workSpace, size_t wkspSize, int flags) +{ + const BYTE* ip = (const BYTE*) cSrc; + + size_t const hSize = HUF_readDTableX1_wksp(dctx, cSrc, cSrcSize, workSpace, wkspSize, flags); + if (HUF_isError(hSize)) return hSize; + if (hSize >= cSrcSize) return ERROR(srcSize_wrong); + ip += hSize; cSrcSize -= hSize; + + return HUF_decompress4X1_usingDTable_internal(dst, dstSize, ip, cSrcSize, dctx, flags); +} + +#endif /* HUF_FORCE_DECOMPRESS_X2 */ + + +#ifndef HUF_FORCE_DECOMPRESS_X1 + +/* *************************/ +/* double-symbols decoding */ +/* *************************/ + +typedef struct { U16 sequence; BYTE nbBits; BYTE length; } HUF_DEltX2; /* double-symbols decoding */ +typedef struct { BYTE symbol; } sortedSymbol_t; +typedef U32 rankValCol_t[HUF_TABLELOG_MAX + 1]; +typedef rankValCol_t rankVal_t[HUF_TABLELOG_MAX]; + +/** + * Constructs a HUF_DEltX2 in a U32. + */ +static U32 HUF_buildDEltX2U32(U32 symbol, U32 nbBits, U32 baseSeq, int level) +{ + U32 seq; + DEBUG_STATIC_ASSERT(offsetof(HUF_DEltX2, sequence) == 0); + DEBUG_STATIC_ASSERT(offsetof(HUF_DEltX2, nbBits) == 2); + DEBUG_STATIC_ASSERT(offsetof(HUF_DEltX2, length) == 3); + DEBUG_STATIC_ASSERT(sizeof(HUF_DEltX2) == sizeof(U32)); + if (MEM_isLittleEndian()) { + seq = level == 1 ? symbol : (baseSeq + (symbol << 8)); + return seq + (nbBits << 16) + ((U32)level << 24); + } else { + seq = level == 1 ? (symbol << 8) : ((baseSeq << 8) + symbol); + return (seq << 16) + (nbBits << 8) + (U32)level; + } +} + +/** + * Constructs a HUF_DEltX2. + */ +static HUF_DEltX2 HUF_buildDEltX2(U32 symbol, U32 nbBits, U32 baseSeq, int level) +{ + HUF_DEltX2 DElt; + U32 const val = HUF_buildDEltX2U32(symbol, nbBits, baseSeq, level); + DEBUG_STATIC_ASSERT(sizeof(DElt) == sizeof(val)); + ZSTD_memcpy(&DElt, &val, sizeof(val)); + return DElt; +} + +/** + * Constructs 2 HUF_DEltX2s and packs them into a U64. + */ +static U64 HUF_buildDEltX2U64(U32 symbol, U32 nbBits, U16 baseSeq, int level) +{ + U32 DElt = HUF_buildDEltX2U32(symbol, nbBits, baseSeq, level); + return (U64)DElt + ((U64)DElt << 32); +} + +/** + * Fills the DTable rank with all the symbols from [begin, end) that are each + * nbBits long. + * + * @param DTableRank The start of the rank in the DTable. + * @param begin The first symbol to fill (inclusive). + * @param end The last symbol to fill (exclusive). + * @param nbBits Each symbol is nbBits long. + * @param tableLog The table log. + * @param baseSeq If level == 1 { 0 } else { the first level symbol } + * @param level The level in the table. Must be 1 or 2. + */ +static void HUF_fillDTableX2ForWeight( + HUF_DEltX2* DTableRank, + sortedSymbol_t const* begin, sortedSymbol_t const* end, + U32 nbBits, U32 tableLog, + U16 baseSeq, int const level) +{ + U32 const length = 1U << ((tableLog - nbBits) & 0x1F /* quiet static-analyzer */); + const sortedSymbol_t* ptr; + assert(level >= 1 && level <= 2); + switch (length) { + case 1: + for (ptr = begin; ptr != end; ++ptr) { + HUF_DEltX2 const DElt = HUF_buildDEltX2(ptr->symbol, nbBits, baseSeq, level); + *DTableRank++ = DElt; + } + break; + case 2: + for (ptr = begin; ptr != end; ++ptr) { + HUF_DEltX2 const DElt = HUF_buildDEltX2(ptr->symbol, nbBits, baseSeq, level); + DTableRank[0] = DElt; + DTableRank[1] = DElt; + DTableRank += 2; + } + break; + case 4: + for (ptr = begin; ptr != end; ++ptr) { + U64 const DEltX2 = HUF_buildDEltX2U64(ptr->symbol, nbBits, baseSeq, level); + ZSTD_memcpy(DTableRank + 0, &DEltX2, sizeof(DEltX2)); + ZSTD_memcpy(DTableRank + 2, &DEltX2, sizeof(DEltX2)); + DTableRank += 4; + } + break; + case 8: + for (ptr = begin; ptr != end; ++ptr) { + U64 const DEltX2 = HUF_buildDEltX2U64(ptr->symbol, nbBits, baseSeq, level); + ZSTD_memcpy(DTableRank + 0, &DEltX2, sizeof(DEltX2)); + ZSTD_memcpy(DTableRank + 2, &DEltX2, sizeof(DEltX2)); + ZSTD_memcpy(DTableRank + 4, &DEltX2, sizeof(DEltX2)); + ZSTD_memcpy(DTableRank + 6, &DEltX2, sizeof(DEltX2)); + DTableRank += 8; + } + break; + default: + for (ptr = begin; ptr != end; ++ptr) { + U64 const DEltX2 = HUF_buildDEltX2U64(ptr->symbol, nbBits, baseSeq, level); + HUF_DEltX2* const DTableRankEnd = DTableRank + length; + for (; DTableRank != DTableRankEnd; DTableRank += 8) { + ZSTD_memcpy(DTableRank + 0, &DEltX2, sizeof(DEltX2)); + ZSTD_memcpy(DTableRank + 2, &DEltX2, sizeof(DEltX2)); + ZSTD_memcpy(DTableRank + 4, &DEltX2, sizeof(DEltX2)); + ZSTD_memcpy(DTableRank + 6, &DEltX2, sizeof(DEltX2)); + } + } + break; + } +} + +/* HUF_fillDTableX2Level2() : + * `rankValOrigin` must be a table of at least (HUF_TABLELOG_MAX + 1) U32 */ +static void HUF_fillDTableX2Level2(HUF_DEltX2* DTable, U32 targetLog, const U32 consumedBits, + const U32* rankVal, const int minWeight, const int maxWeight1, + const sortedSymbol_t* sortedSymbols, U32 const* rankStart, + U32 nbBitsBaseline, U16 baseSeq) +{ + /* Fill skipped values (all positions up to rankVal[minWeight]). + * These are positions only get a single symbol because the combined weight + * is too large. + */ + if (minWeight>1) { + U32 const length = 1U << ((targetLog - consumedBits) & 0x1F /* quiet static-analyzer */); + U64 const DEltX2 = HUF_buildDEltX2U64(baseSeq, consumedBits, /* baseSeq */ 0, /* level */ 1); + int const skipSize = rankVal[minWeight]; + assert(length > 1); + assert((U32)skipSize < length); + switch (length) { + case 2: + assert(skipSize == 1); + ZSTD_memcpy(DTable, &DEltX2, sizeof(DEltX2)); + break; + case 4: + assert(skipSize <= 4); + ZSTD_memcpy(DTable + 0, &DEltX2, sizeof(DEltX2)); + ZSTD_memcpy(DTable + 2, &DEltX2, sizeof(DEltX2)); + break; + default: + { + int i; + for (i = 0; i < skipSize; i += 8) { + ZSTD_memcpy(DTable + i + 0, &DEltX2, sizeof(DEltX2)); + ZSTD_memcpy(DTable + i + 2, &DEltX2, sizeof(DEltX2)); + ZSTD_memcpy(DTable + i + 4, &DEltX2, sizeof(DEltX2)); + ZSTD_memcpy(DTable + i + 6, &DEltX2, sizeof(DEltX2)); + } + } + } + } + + /* Fill each of the second level symbols by weight. */ + { + int w; + for (w = minWeight; w < maxWeight1; ++w) { + int const begin = rankStart[w]; + int const end = rankStart[w+1]; + U32 const nbBits = nbBitsBaseline - w; + U32 const totalBits = nbBits + consumedBits; + HUF_fillDTableX2ForWeight( + DTable + rankVal[w], + sortedSymbols + begin, sortedSymbols + end, + totalBits, targetLog, + baseSeq, /* level */ 2); + } + } +} + +static void HUF_fillDTableX2(HUF_DEltX2* DTable, const U32 targetLog, + const sortedSymbol_t* sortedList, + const U32* rankStart, rankValCol_t* rankValOrigin, const U32 maxWeight, + const U32 nbBitsBaseline) +{ + U32* const rankVal = rankValOrigin[0]; + const int scaleLog = nbBitsBaseline - targetLog; /* note : targetLog >= srcLog, hence scaleLog <= 1 */ + const U32 minBits = nbBitsBaseline - maxWeight; + int w; + int const wEnd = (int)maxWeight + 1; + + /* Fill DTable in order of weight. */ + for (w = 1; w < wEnd; ++w) { + int const begin = (int)rankStart[w]; + int const end = (int)rankStart[w+1]; + U32 const nbBits = nbBitsBaseline - w; + + if (targetLog-nbBits >= minBits) { + /* Enough room for a second symbol. */ + int start = rankVal[w]; + U32 const length = 1U << ((targetLog - nbBits) & 0x1F /* quiet static-analyzer */); + int minWeight = nbBits + scaleLog; + int s; + if (minWeight < 1) minWeight = 1; + /* Fill the DTable for every symbol of weight w. + * These symbols get at least 1 second symbol. + */ + for (s = begin; s != end; ++s) { + HUF_fillDTableX2Level2( + DTable + start, targetLog, nbBits, + rankValOrigin[nbBits], minWeight, wEnd, + sortedList, rankStart, + nbBitsBaseline, sortedList[s].symbol); + start += length; + } + } else { + /* Only a single symbol. */ + HUF_fillDTableX2ForWeight( + DTable + rankVal[w], + sortedList + begin, sortedList + end, + nbBits, targetLog, + /* baseSeq */ 0, /* level */ 1); + } + } +} + +typedef struct { + rankValCol_t rankVal[HUF_TABLELOG_MAX]; + U32 rankStats[HUF_TABLELOG_MAX + 1]; + U32 rankStart0[HUF_TABLELOG_MAX + 3]; + sortedSymbol_t sortedSymbol[HUF_SYMBOLVALUE_MAX + 1]; + BYTE weightList[HUF_SYMBOLVALUE_MAX + 1]; + U32 calleeWksp[HUF_READ_STATS_WORKSPACE_SIZE_U32]; +} HUF_ReadDTableX2_Workspace; + +size_t HUF_readDTableX2_wksp(HUF_DTable* DTable, + const void* src, size_t srcSize, + void* workSpace, size_t wkspSize, int flags) +{ + U32 tableLog, maxW, nbSymbols; + DTableDesc dtd = HUF_getDTableDesc(DTable); + U32 maxTableLog = dtd.maxTableLog; + size_t iSize; + void* dtPtr = DTable+1; /* force compiler to avoid strict-aliasing */ + HUF_DEltX2* const dt = (HUF_DEltX2*)dtPtr; + U32 *rankStart; + + HUF_ReadDTableX2_Workspace* const wksp = (HUF_ReadDTableX2_Workspace*)workSpace; + + if (sizeof(*wksp) > wkspSize) return ERROR(GENERIC); + + rankStart = wksp->rankStart0 + 1; + ZSTD_memset(wksp->rankStats, 0, sizeof(wksp->rankStats)); + ZSTD_memset(wksp->rankStart0, 0, sizeof(wksp->rankStart0)); + + DEBUG_STATIC_ASSERT(sizeof(HUF_DEltX2) == sizeof(HUF_DTable)); /* if compiler fails here, assertion is wrong */ + if (maxTableLog > HUF_TABLELOG_MAX) return ERROR(tableLog_tooLarge); + /* ZSTD_memset(weightList, 0, sizeof(weightList)); */ /* is not necessary, even though some analyzer complain ... */ + + iSize = HUF_readStats_wksp(wksp->weightList, HUF_SYMBOLVALUE_MAX + 1, wksp->rankStats, &nbSymbols, &tableLog, src, srcSize, wksp->calleeWksp, sizeof(wksp->calleeWksp), flags); + if (HUF_isError(iSize)) return iSize; + + /* check result */ + if (tableLog > maxTableLog) return ERROR(tableLog_tooLarge); /* DTable can't fit code depth */ + if (tableLog <= HUF_DECODER_FAST_TABLELOG && maxTableLog > HUF_DECODER_FAST_TABLELOG) maxTableLog = HUF_DECODER_FAST_TABLELOG; + + /* find maxWeight */ + for (maxW = tableLog; wksp->rankStats[maxW]==0; maxW--) {} /* necessarily finds a solution before 0 */ + + /* Get start index of each weight */ + { U32 w, nextRankStart = 0; + for (w=1; wrankStats[w]; + rankStart[w] = curr; + } + rankStart[0] = nextRankStart; /* put all 0w symbols at the end of sorted list*/ + rankStart[maxW+1] = nextRankStart; + } + + /* sort symbols by weight */ + { U32 s; + for (s=0; sweightList[s]; + U32 const r = rankStart[w]++; + wksp->sortedSymbol[r].symbol = (BYTE)s; + } + rankStart[0] = 0; /* forget 0w symbols; this is beginning of weight(1) */ + } + + /* Build rankVal */ + { U32* const rankVal0 = wksp->rankVal[0]; + { int const rescale = (maxTableLog-tableLog) - 1; /* tableLog <= maxTableLog */ + U32 nextRankVal = 0; + U32 w; + for (w=1; wrankStats[w] << (w+rescale); + rankVal0[w] = curr; + } } + { U32 const minBits = tableLog+1 - maxW; + U32 consumed; + for (consumed = minBits; consumed < maxTableLog - minBits + 1; consumed++) { + U32* const rankValPtr = wksp->rankVal[consumed]; + U32 w; + for (w = 1; w < maxW+1; w++) { + rankValPtr[w] = rankVal0[w] >> consumed; + } } } } + + HUF_fillDTableX2(dt, maxTableLog, + wksp->sortedSymbol, + wksp->rankStart0, wksp->rankVal, maxW, + tableLog+1); + + dtd.tableLog = (BYTE)maxTableLog; + dtd.tableType = 1; + ZSTD_memcpy(DTable, &dtd, sizeof(dtd)); + return iSize; +} + + +FORCE_INLINE_TEMPLATE U32 +HUF_decodeSymbolX2(void* op, BIT_DStream_t* DStream, const HUF_DEltX2* dt, const U32 dtLog) +{ + size_t const val = BIT_lookBitsFast(DStream, dtLog); /* note : dtLog >= 1 */ + ZSTD_memcpy(op, &dt[val].sequence, 2); + BIT_skipBits(DStream, dt[val].nbBits); + return dt[val].length; +} + +FORCE_INLINE_TEMPLATE U32 +HUF_decodeLastSymbolX2(void* op, BIT_DStream_t* DStream, const HUF_DEltX2* dt, const U32 dtLog) +{ + size_t const val = BIT_lookBitsFast(DStream, dtLog); /* note : dtLog >= 1 */ + ZSTD_memcpy(op, &dt[val].sequence, 1); + if (dt[val].length==1) { + BIT_skipBits(DStream, dt[val].nbBits); + } else { + if (DStream->bitsConsumed < (sizeof(DStream->bitContainer)*8)) { + BIT_skipBits(DStream, dt[val].nbBits); + if (DStream->bitsConsumed > (sizeof(DStream->bitContainer)*8)) + /* ugly hack; works only because it's the last symbol. Note : can't easily extract nbBits from just this symbol */ + DStream->bitsConsumed = (sizeof(DStream->bitContainer)*8); + } + } + return 1; +} + +#define HUF_DECODE_SYMBOLX2_0(ptr, DStreamPtr) \ + do { ptr += HUF_decodeSymbolX2(ptr, DStreamPtr, dt, dtLog); } while (0) + +#define HUF_DECODE_SYMBOLX2_1(ptr, DStreamPtr) \ + do { \ + if (MEM_64bits() || (HUF_TABLELOG_MAX<=12)) \ + ptr += HUF_decodeSymbolX2(ptr, DStreamPtr, dt, dtLog); \ + } while (0) + +#define HUF_DECODE_SYMBOLX2_2(ptr, DStreamPtr) \ + do { \ + if (MEM_64bits()) \ + ptr += HUF_decodeSymbolX2(ptr, DStreamPtr, dt, dtLog); \ + } while (0) + +HINT_INLINE size_t +HUF_decodeStreamX2(BYTE* p, BIT_DStream_t* bitDPtr, BYTE* const pEnd, + const HUF_DEltX2* const dt, const U32 dtLog) +{ + BYTE* const pStart = p; + + /* up to 8 symbols at a time */ + if ((size_t)(pEnd - p) >= sizeof(bitDPtr->bitContainer)) { + if (dtLog <= 11 && MEM_64bits()) { + /* up to 10 symbols at a time */ + while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p < pEnd-9)) { + HUF_DECODE_SYMBOLX2_0(p, bitDPtr); + HUF_DECODE_SYMBOLX2_0(p, bitDPtr); + HUF_DECODE_SYMBOLX2_0(p, bitDPtr); + HUF_DECODE_SYMBOLX2_0(p, bitDPtr); + HUF_DECODE_SYMBOLX2_0(p, bitDPtr); + } + } else { + /* up to 8 symbols at a time */ + while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p < pEnd-(sizeof(bitDPtr->bitContainer)-1))) { + HUF_DECODE_SYMBOLX2_2(p, bitDPtr); + HUF_DECODE_SYMBOLX2_1(p, bitDPtr); + HUF_DECODE_SYMBOLX2_2(p, bitDPtr); + HUF_DECODE_SYMBOLX2_0(p, bitDPtr); + } + } + } else { + BIT_reloadDStream(bitDPtr); + } + + /* closer to end : up to 2 symbols at a time */ + if ((size_t)(pEnd - p) >= 2) { + while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p <= pEnd-2)) + HUF_DECODE_SYMBOLX2_0(p, bitDPtr); + + while (p <= pEnd-2) + HUF_DECODE_SYMBOLX2_0(p, bitDPtr); /* no need to reload : reached the end of DStream */ + } + + if (p < pEnd) + p += HUF_decodeLastSymbolX2(p, bitDPtr, dt, dtLog); + + return p-pStart; +} + +FORCE_INLINE_TEMPLATE size_t +HUF_decompress1X2_usingDTable_internal_body( + void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize, + const HUF_DTable* DTable) +{ + BIT_DStream_t bitD; + + /* Init */ + CHECK_F( BIT_initDStream(&bitD, cSrc, cSrcSize) ); + + /* decode */ + { BYTE* const ostart = (BYTE*) dst; + BYTE* const oend = ZSTD_maybeNullPtrAdd(ostart, dstSize); + const void* const dtPtr = DTable+1; /* force compiler to not use strict-aliasing */ + const HUF_DEltX2* const dt = (const HUF_DEltX2*)dtPtr; + DTableDesc const dtd = HUF_getDTableDesc(DTable); + HUF_decodeStreamX2(ostart, &bitD, oend, dt, dtd.tableLog); + } + + /* check */ + if (!BIT_endOfDStream(&bitD)) return ERROR(corruption_detected); + + /* decoded size */ + return dstSize; +} + +/* HUF_decompress4X2_usingDTable_internal_body(): + * Conditions: + * @dstSize >= 6 + */ +FORCE_INLINE_TEMPLATE size_t +HUF_decompress4X2_usingDTable_internal_body( + void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize, + const HUF_DTable* DTable) +{ + if (cSrcSize < 10) return ERROR(corruption_detected); /* strict minimum : jump table + 1 byte per stream */ + if (dstSize < 6) return ERROR(corruption_detected); /* stream 4-split doesn't work */ + + { const BYTE* const istart = (const BYTE*) cSrc; + BYTE* const ostart = (BYTE*) dst; + BYTE* const oend = ostart + dstSize; + BYTE* const olimit = oend - (sizeof(size_t)-1); + const void* const dtPtr = DTable+1; + const HUF_DEltX2* const dt = (const HUF_DEltX2*)dtPtr; + + /* Init */ + BIT_DStream_t bitD1; + BIT_DStream_t bitD2; + BIT_DStream_t bitD3; + BIT_DStream_t bitD4; + size_t const length1 = MEM_readLE16(istart); + size_t const length2 = MEM_readLE16(istart+2); + size_t const length3 = MEM_readLE16(istart+4); + size_t const length4 = cSrcSize - (length1 + length2 + length3 + 6); + const BYTE* const istart1 = istart + 6; /* jumpTable */ + const BYTE* const istart2 = istart1 + length1; + const BYTE* const istart3 = istart2 + length2; + const BYTE* const istart4 = istart3 + length3; + size_t const segmentSize = (dstSize+3) / 4; + BYTE* const opStart2 = ostart + segmentSize; + BYTE* const opStart3 = opStart2 + segmentSize; + BYTE* const opStart4 = opStart3 + segmentSize; + BYTE* op1 = ostart; + BYTE* op2 = opStart2; + BYTE* op3 = opStart3; + BYTE* op4 = opStart4; + U32 endSignal = 1; + DTableDesc const dtd = HUF_getDTableDesc(DTable); + U32 const dtLog = dtd.tableLog; + + if (length4 > cSrcSize) return ERROR(corruption_detected); /* overflow */ + if (opStart4 > oend) return ERROR(corruption_detected); /* overflow */ + assert(dstSize >= 6 /* validated above */); + CHECK_F( BIT_initDStream(&bitD1, istart1, length1) ); + CHECK_F( BIT_initDStream(&bitD2, istart2, length2) ); + CHECK_F( BIT_initDStream(&bitD3, istart3, length3) ); + CHECK_F( BIT_initDStream(&bitD4, istart4, length4) ); + + /* 16-32 symbols per loop (4-8 symbols per stream) */ + if ((size_t)(oend - op4) >= sizeof(size_t)) { + for ( ; (endSignal) & (op4 < olimit); ) { +#if defined(__clang__) && (defined(__x86_64__) || defined(__i386__)) + HUF_DECODE_SYMBOLX2_2(op1, &bitD1); + HUF_DECODE_SYMBOLX2_1(op1, &bitD1); + HUF_DECODE_SYMBOLX2_2(op1, &bitD1); + HUF_DECODE_SYMBOLX2_0(op1, &bitD1); + HUF_DECODE_SYMBOLX2_2(op2, &bitD2); + HUF_DECODE_SYMBOLX2_1(op2, &bitD2); + HUF_DECODE_SYMBOLX2_2(op2, &bitD2); + HUF_DECODE_SYMBOLX2_0(op2, &bitD2); + endSignal &= BIT_reloadDStreamFast(&bitD1) == BIT_DStream_unfinished; + endSignal &= BIT_reloadDStreamFast(&bitD2) == BIT_DStream_unfinished; + HUF_DECODE_SYMBOLX2_2(op3, &bitD3); + HUF_DECODE_SYMBOLX2_1(op3, &bitD3); + HUF_DECODE_SYMBOLX2_2(op3, &bitD3); + HUF_DECODE_SYMBOLX2_0(op3, &bitD3); + HUF_DECODE_SYMBOLX2_2(op4, &bitD4); + HUF_DECODE_SYMBOLX2_1(op4, &bitD4); + HUF_DECODE_SYMBOLX2_2(op4, &bitD4); + HUF_DECODE_SYMBOLX2_0(op4, &bitD4); + endSignal &= BIT_reloadDStreamFast(&bitD3) == BIT_DStream_unfinished; + endSignal &= BIT_reloadDStreamFast(&bitD4) == BIT_DStream_unfinished; +#else + HUF_DECODE_SYMBOLX2_2(op1, &bitD1); + HUF_DECODE_SYMBOLX2_2(op2, &bitD2); + HUF_DECODE_SYMBOLX2_2(op3, &bitD3); + HUF_DECODE_SYMBOLX2_2(op4, &bitD4); + HUF_DECODE_SYMBOLX2_1(op1, &bitD1); + HUF_DECODE_SYMBOLX2_1(op2, &bitD2); + HUF_DECODE_SYMBOLX2_1(op3, &bitD3); + HUF_DECODE_SYMBOLX2_1(op4, &bitD4); + HUF_DECODE_SYMBOLX2_2(op1, &bitD1); + HUF_DECODE_SYMBOLX2_2(op2, &bitD2); + HUF_DECODE_SYMBOLX2_2(op3, &bitD3); + HUF_DECODE_SYMBOLX2_2(op4, &bitD4); + HUF_DECODE_SYMBOLX2_0(op1, &bitD1); + HUF_DECODE_SYMBOLX2_0(op2, &bitD2); + HUF_DECODE_SYMBOLX2_0(op3, &bitD3); + HUF_DECODE_SYMBOLX2_0(op4, &bitD4); + endSignal = (U32)LIKELY((U32) + (BIT_reloadDStreamFast(&bitD1) == BIT_DStream_unfinished) + & (BIT_reloadDStreamFast(&bitD2) == BIT_DStream_unfinished) + & (BIT_reloadDStreamFast(&bitD3) == BIT_DStream_unfinished) + & (BIT_reloadDStreamFast(&bitD4) == BIT_DStream_unfinished)); +#endif + } + } + + /* check corruption */ + if (op1 > opStart2) return ERROR(corruption_detected); + if (op2 > opStart3) return ERROR(corruption_detected); + if (op3 > opStart4) return ERROR(corruption_detected); + /* note : op4 already verified within main loop */ + + /* finish bitStreams one by one */ + HUF_decodeStreamX2(op1, &bitD1, opStart2, dt, dtLog); + HUF_decodeStreamX2(op2, &bitD2, opStart3, dt, dtLog); + HUF_decodeStreamX2(op3, &bitD3, opStart4, dt, dtLog); + HUF_decodeStreamX2(op4, &bitD4, oend, dt, dtLog); + + /* check */ + { U32 const endCheck = BIT_endOfDStream(&bitD1) & BIT_endOfDStream(&bitD2) & BIT_endOfDStream(&bitD3) & BIT_endOfDStream(&bitD4); + if (!endCheck) return ERROR(corruption_detected); } + + /* decoded size */ + return dstSize; + } +} + +#if HUF_NEED_BMI2_FUNCTION +static BMI2_TARGET_ATTRIBUTE +size_t HUF_decompress4X2_usingDTable_internal_bmi2(void* dst, size_t dstSize, void const* cSrc, + size_t cSrcSize, HUF_DTable const* DTable) { + return HUF_decompress4X2_usingDTable_internal_body(dst, dstSize, cSrc, cSrcSize, DTable); +} +#endif + +static +size_t HUF_decompress4X2_usingDTable_internal_default(void* dst, size_t dstSize, void const* cSrc, + size_t cSrcSize, HUF_DTable const* DTable) { + return HUF_decompress4X2_usingDTable_internal_body(dst, dstSize, cSrc, cSrcSize, DTable); +} + +#if ZSTD_ENABLE_ASM_X86_64_BMI2 + +HUF_ASM_DECL void HUF_decompress4X2_usingDTable_internal_fast_asm_loop(HUF_DecompressFastArgs* args) ZSTDLIB_HIDDEN; + +#endif + +static HUF_FAST_BMI2_ATTRS +void HUF_decompress4X2_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs* args) +{ + U64 bits[4]; + BYTE const* ip[4]; + BYTE* op[4]; + BYTE* oend[4]; + HUF_DEltX2 const* const dtable = (HUF_DEltX2 const*)args->dt; + BYTE const* const ilowest = args->ilowest; + + /* Copy the arguments to local registers. */ + ZSTD_memcpy(&bits, &args->bits, sizeof(bits)); + ZSTD_memcpy((void*)(&ip), &args->ip, sizeof(ip)); + ZSTD_memcpy(&op, &args->op, sizeof(op)); + + oend[0] = op[1]; + oend[1] = op[2]; + oend[2] = op[3]; + oend[3] = args->oend; + + assert(MEM_isLittleEndian()); + assert(!MEM_32bits()); + + for (;;) { + BYTE* olimit; + int stream; + + /* Assert loop preconditions */ +#ifndef NDEBUG + for (stream = 0; stream < 4; ++stream) { + assert(op[stream] <= oend[stream]); + assert(ip[stream] >= ilowest); + } +#endif + /* Compute olimit */ + { + /* Each loop does 5 table lookups for each of the 4 streams. + * Each table lookup consumes up to 11 bits of input, and produces + * up to 2 bytes of output. + */ + /* We can consume up to 7 bytes of input per iteration per stream. + * We also know that each input pointer is >= ip[0]. So we can run + * iters loops before running out of input. + */ + size_t iters = (size_t)(ip[0] - ilowest) / 7; + /* Each iteration can produce up to 10 bytes of output per stream. + * Each output stream my advance at different rates. So take the + * minimum number of safe iterations among all the output streams. + */ + for (stream = 0; stream < 4; ++stream) { + size_t const oiters = (size_t)(oend[stream] - op[stream]) / 10; + iters = MIN(iters, oiters); + } + + /* Each iteration produces at least 5 output symbols. So until + * op[3] crosses olimit, we know we haven't executed iters + * iterations yet. This saves us maintaining an iters counter, + * at the expense of computing the remaining # of iterations + * more frequently. + */ + olimit = op[3] + (iters * 5); + + /* Exit the fast decoding loop once we reach the end. */ + if (op[3] == olimit) + break; + + /* Exit the decoding loop if any input pointer has crossed the + * previous one. This indicates corruption, and a precondition + * to our loop is that ip[i] >= ip[0]. + */ + for (stream = 1; stream < 4; ++stream) { + if (ip[stream] < ip[stream - 1]) + goto _out; + } + } + +#ifndef NDEBUG + for (stream = 1; stream < 4; ++stream) { + assert(ip[stream] >= ip[stream - 1]); + } +#endif + +#define HUF_4X2_DECODE_SYMBOL(_stream, _decode3) \ + do { \ + if ((_decode3) || (_stream) != 3) { \ + int const index = (int)(bits[(_stream)] >> 53); \ + HUF_DEltX2 const entry = dtable[index]; \ + MEM_write16(op[(_stream)], entry.sequence); \ + bits[(_stream)] <<= (entry.nbBits) & 0x3F; \ + op[(_stream)] += (entry.length); \ + } \ + } while (0) + +#define HUF_4X2_RELOAD_STREAM(_stream) \ + do { \ + HUF_4X2_DECODE_SYMBOL(3, 1); \ + { \ + int const ctz = ZSTD_countTrailingZeros64(bits[(_stream)]); \ + int const nbBits = ctz & 7; \ + int const nbBytes = ctz >> 3; \ + ip[(_stream)] -= nbBytes; \ + bits[(_stream)] = MEM_read64(ip[(_stream)]) | 1; \ + bits[(_stream)] <<= nbBits; \ + } \ + } while (0) + + /* Manually unroll the loop because compilers don't consistently + * unroll the inner loops, which destroys performance. + */ + do { + /* Decode 5 symbols from each of the first 3 streams. + * The final stream will be decoded during the reload phase + * to reduce register pressure. + */ + HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X2_DECODE_SYMBOL, 0); + HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X2_DECODE_SYMBOL, 0); + HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X2_DECODE_SYMBOL, 0); + HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X2_DECODE_SYMBOL, 0); + HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X2_DECODE_SYMBOL, 0); + + /* Decode one symbol from the final stream */ + HUF_4X2_DECODE_SYMBOL(3, 1); + + /* Decode 4 symbols from the final stream & reload bitstreams. + * The final stream is reloaded last, meaning that all 5 symbols + * are decoded from the final stream before it is reloaded. + */ + HUF_4X_FOR_EACH_STREAM(HUF_4X2_RELOAD_STREAM); + } while (op[3] < olimit); + } + +#undef HUF_4X2_DECODE_SYMBOL +#undef HUF_4X2_RELOAD_STREAM + +_out: + + /* Save the final values of each of the state variables back to args. */ + ZSTD_memcpy(&args->bits, &bits, sizeof(bits)); + ZSTD_memcpy((void*)(&args->ip), &ip, sizeof(ip)); + ZSTD_memcpy(&args->op, &op, sizeof(op)); +} + + +static HUF_FAST_BMI2_ATTRS size_t +HUF_decompress4X2_usingDTable_internal_fast( + void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize, + const HUF_DTable* DTable, + HUF_DecompressFastLoopFn loopFn) { + void const* dt = DTable + 1; + const BYTE* const ilowest = (const BYTE*)cSrc; + BYTE* const oend = ZSTD_maybeNullPtrAdd((BYTE*)dst, dstSize); + HUF_DecompressFastArgs args; + { + size_t const ret = HUF_DecompressFastArgs_init(&args, dst, dstSize, cSrc, cSrcSize, DTable); + FORWARD_IF_ERROR(ret, "Failed to init asm args"); + if (ret == 0) + return 0; + } + + assert(args.ip[0] >= args.ilowest); + loopFn(&args); + + /* note : op4 already verified within main loop */ + assert(args.ip[0] >= ilowest); + assert(args.ip[1] >= ilowest); + assert(args.ip[2] >= ilowest); + assert(args.ip[3] >= ilowest); + assert(args.op[3] <= oend); + + assert(ilowest == args.ilowest); + assert(ilowest + 6 == args.iend[0]); + (void)ilowest; + + /* finish bitStreams one by one */ + { + size_t const segmentSize = (dstSize+3) / 4; + BYTE* segmentEnd = (BYTE*)dst; + int i; + for (i = 0; i < 4; ++i) { + BIT_DStream_t bit; + if (segmentSize <= (size_t)(oend - segmentEnd)) + segmentEnd += segmentSize; + else + segmentEnd = oend; + FORWARD_IF_ERROR(HUF_initRemainingDStream(&bit, &args, i, segmentEnd), "corruption"); + args.op[i] += HUF_decodeStreamX2(args.op[i], &bit, segmentEnd, (HUF_DEltX2 const*)dt, HUF_DECODER_FAST_TABLELOG); + if (args.op[i] != segmentEnd) + return ERROR(corruption_detected); + } + } + + /* decoded size */ + return dstSize; +} + +static size_t HUF_decompress4X2_usingDTable_internal(void* dst, size_t dstSize, void const* cSrc, + size_t cSrcSize, HUF_DTable const* DTable, int flags) +{ + HUF_DecompressUsingDTableFn fallbackFn = HUF_decompress4X2_usingDTable_internal_default; + HUF_DecompressFastLoopFn loopFn = HUF_decompress4X2_usingDTable_internal_fast_c_loop; + +#if DYNAMIC_BMI2 + if (flags & HUF_flags_bmi2) { + fallbackFn = HUF_decompress4X2_usingDTable_internal_bmi2; +# if ZSTD_ENABLE_ASM_X86_64_BMI2 + if (!(flags & HUF_flags_disableAsm)) { + loopFn = HUF_decompress4X2_usingDTable_internal_fast_asm_loop; + } +# endif + } else { + return fallbackFn(dst, dstSize, cSrc, cSrcSize, DTable); + } +#endif + +#if ZSTD_ENABLE_ASM_X86_64_BMI2 && defined(__BMI2__) + if (!(flags & HUF_flags_disableAsm)) { + loopFn = HUF_decompress4X2_usingDTable_internal_fast_asm_loop; + } +#endif + + if (HUF_ENABLE_FAST_DECODE && !(flags & HUF_flags_disableFast)) { + size_t const ret = HUF_decompress4X2_usingDTable_internal_fast(dst, dstSize, cSrc, cSrcSize, DTable, loopFn); + if (ret != 0) + return ret; + } + return fallbackFn(dst, dstSize, cSrc, cSrcSize, DTable); +} + +HUF_DGEN(HUF_decompress1X2_usingDTable_internal) + +size_t HUF_decompress1X2_DCtx_wksp(HUF_DTable* DCtx, void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize, + void* workSpace, size_t wkspSize, int flags) +{ + const BYTE* ip = (const BYTE*) cSrc; + + size_t const hSize = HUF_readDTableX2_wksp(DCtx, cSrc, cSrcSize, + workSpace, wkspSize, flags); + if (HUF_isError(hSize)) return hSize; + if (hSize >= cSrcSize) return ERROR(srcSize_wrong); + ip += hSize; cSrcSize -= hSize; + + return HUF_decompress1X2_usingDTable_internal(dst, dstSize, ip, cSrcSize, DCtx, flags); +} + +static size_t HUF_decompress4X2_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize, + void* workSpace, size_t wkspSize, int flags) +{ + const BYTE* ip = (const BYTE*) cSrc; + + size_t hSize = HUF_readDTableX2_wksp(dctx, cSrc, cSrcSize, + workSpace, wkspSize, flags); + if (HUF_isError(hSize)) return hSize; + if (hSize >= cSrcSize) return ERROR(srcSize_wrong); + ip += hSize; cSrcSize -= hSize; + + return HUF_decompress4X2_usingDTable_internal(dst, dstSize, ip, cSrcSize, dctx, flags); +} + +#endif /* HUF_FORCE_DECOMPRESS_X1 */ + + +/* ***********************************/ +/* Universal decompression selectors */ +/* ***********************************/ + + +#if !defined(HUF_FORCE_DECOMPRESS_X1) && !defined(HUF_FORCE_DECOMPRESS_X2) +typedef struct { U32 tableTime; U32 decode256Time; } algo_time_t; +static const algo_time_t algoTime[16 /* Quantization */][2 /* single, double */] = +{ + /* single, double, quad */ + {{0,0}, {1,1}}, /* Q==0 : impossible */ + {{0,0}, {1,1}}, /* Q==1 : impossible */ + {{ 150,216}, { 381,119}}, /* Q == 2 : 12-18% */ + {{ 170,205}, { 514,112}}, /* Q == 3 : 18-25% */ + {{ 177,199}, { 539,110}}, /* Q == 4 : 25-32% */ + {{ 197,194}, { 644,107}}, /* Q == 5 : 32-38% */ + {{ 221,192}, { 735,107}}, /* Q == 6 : 38-44% */ + {{ 256,189}, { 881,106}}, /* Q == 7 : 44-50% */ + {{ 359,188}, {1167,109}}, /* Q == 8 : 50-56% */ + {{ 582,187}, {1570,114}}, /* Q == 9 : 56-62% */ + {{ 688,187}, {1712,122}}, /* Q ==10 : 62-69% */ + {{ 825,186}, {1965,136}}, /* Q ==11 : 69-75% */ + {{ 976,185}, {2131,150}}, /* Q ==12 : 75-81% */ + {{1180,186}, {2070,175}}, /* Q ==13 : 81-87% */ + {{1377,185}, {1731,202}}, /* Q ==14 : 87-93% */ + {{1412,185}, {1695,202}}, /* Q ==15 : 93-99% */ +}; +#endif + +/** HUF_selectDecoder() : + * Tells which decoder is likely to decode faster, + * based on a set of pre-computed metrics. + * @return : 0==HUF_decompress4X1, 1==HUF_decompress4X2 . + * Assumption : 0 < dstSize <= 128 KB */ +U32 HUF_selectDecoder (size_t dstSize, size_t cSrcSize) +{ + assert(dstSize > 0); + assert(dstSize <= 128*1024); +#if defined(HUF_FORCE_DECOMPRESS_X1) + (void)dstSize; + (void)cSrcSize; + return 0; +#elif defined(HUF_FORCE_DECOMPRESS_X2) + (void)dstSize; + (void)cSrcSize; + return 1; +#else + /* decoder timing evaluation */ + { U32 const Q = (cSrcSize >= dstSize) ? 15 : (U32)(cSrcSize * 16 / dstSize); /* Q < 16 */ + U32 const D256 = (U32)(dstSize >> 8); + U32 const DTime0 = algoTime[Q][0].tableTime + (algoTime[Q][0].decode256Time * D256); + U32 DTime1 = algoTime[Q][1].tableTime + (algoTime[Q][1].decode256Time * D256); + DTime1 += DTime1 >> 5; /* small advantage to algorithm using less memory, to reduce cache eviction */ + return DTime1 < DTime0; + } +#endif +} + +size_t HUF_decompress1X_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize, + void* workSpace, size_t wkspSize, int flags) +{ + /* validation checks */ + if (dstSize == 0) return ERROR(dstSize_tooSmall); + if (cSrcSize > dstSize) return ERROR(corruption_detected); /* invalid */ + if (cSrcSize == dstSize) { ZSTD_memcpy(dst, cSrc, dstSize); return dstSize; } /* not compressed */ + if (cSrcSize == 1) { ZSTD_memset(dst, *(const BYTE*)cSrc, dstSize); return dstSize; } /* RLE */ + + { U32 const algoNb = HUF_selectDecoder(dstSize, cSrcSize); +#if defined(HUF_FORCE_DECOMPRESS_X1) + (void)algoNb; + assert(algoNb == 0); + return HUF_decompress1X1_DCtx_wksp(dctx, dst, dstSize, cSrc, + cSrcSize, workSpace, wkspSize, flags); +#elif defined(HUF_FORCE_DECOMPRESS_X2) + (void)algoNb; + assert(algoNb == 1); + return HUF_decompress1X2_DCtx_wksp(dctx, dst, dstSize, cSrc, + cSrcSize, workSpace, wkspSize, flags); +#else + return algoNb ? HUF_decompress1X2_DCtx_wksp(dctx, dst, dstSize, cSrc, + cSrcSize, workSpace, wkspSize, flags): + HUF_decompress1X1_DCtx_wksp(dctx, dst, dstSize, cSrc, + cSrcSize, workSpace, wkspSize, flags); +#endif + } +} + + +size_t HUF_decompress1X_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable, int flags) +{ + DTableDesc const dtd = HUF_getDTableDesc(DTable); +#if defined(HUF_FORCE_DECOMPRESS_X1) + (void)dtd; + assert(dtd.tableType == 0); + return HUF_decompress1X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, flags); +#elif defined(HUF_FORCE_DECOMPRESS_X2) + (void)dtd; + assert(dtd.tableType == 1); + return HUF_decompress1X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, flags); +#else + return dtd.tableType ? HUF_decompress1X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, flags) : + HUF_decompress1X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, flags); +#endif +} + +#ifndef HUF_FORCE_DECOMPRESS_X2 +size_t HUF_decompress1X1_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int flags) +{ + const BYTE* ip = (const BYTE*) cSrc; + + size_t const hSize = HUF_readDTableX1_wksp(dctx, cSrc, cSrcSize, workSpace, wkspSize, flags); + if (HUF_isError(hSize)) return hSize; + if (hSize >= cSrcSize) return ERROR(srcSize_wrong); + ip += hSize; cSrcSize -= hSize; + + return HUF_decompress1X1_usingDTable_internal(dst, dstSize, ip, cSrcSize, dctx, flags); +} +#endif + +size_t HUF_decompress4X_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable, int flags) +{ + DTableDesc const dtd = HUF_getDTableDesc(DTable); +#if defined(HUF_FORCE_DECOMPRESS_X1) + (void)dtd; + assert(dtd.tableType == 0); + return HUF_decompress4X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, flags); +#elif defined(HUF_FORCE_DECOMPRESS_X2) + (void)dtd; + assert(dtd.tableType == 1); + return HUF_decompress4X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, flags); +#else + return dtd.tableType ? HUF_decompress4X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, flags) : + HUF_decompress4X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, flags); +#endif +} + +size_t HUF_decompress4X_hufOnly_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int flags) +{ + /* validation checks */ + if (dstSize == 0) return ERROR(dstSize_tooSmall); + if (cSrcSize == 0) return ERROR(corruption_detected); + + { U32 const algoNb = HUF_selectDecoder(dstSize, cSrcSize); +#if defined(HUF_FORCE_DECOMPRESS_X1) + (void)algoNb; + assert(algoNb == 0); + return HUF_decompress4X1_DCtx_wksp(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize, flags); +#elif defined(HUF_FORCE_DECOMPRESS_X2) + (void)algoNb; + assert(algoNb == 1); + return HUF_decompress4X2_DCtx_wksp(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize, flags); +#else + return algoNb ? HUF_decompress4X2_DCtx_wksp(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize, flags) : + HUF_decompress4X1_DCtx_wksp(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize, flags); +#endif + } +} +/**** ended inlining decompress/huf_decompress.c ****/ +/**** start inlining decompress/zstd_ddict.c ****/ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +/* zstd_ddict.c : + * concentrates all logic that needs to know the internals of ZSTD_DDict object */ + +/*-******************************************************* +* Dependencies +*********************************************************/ +/**** start inlining ../common/allocations.h ****/ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +/* This file provides custom allocation primitives + */ + +#define ZSTD_DEPS_NEED_MALLOC +/**** skipping file: zstd_deps.h ****/ + +/**** skipping file: compiler.h ****/ +#define ZSTD_STATIC_LINKING_ONLY +/**** skipping file: ../zstd.h ****/ + +#ifndef ZSTD_ALLOCATIONS_H +#define ZSTD_ALLOCATIONS_H + +/* custom memory allocation functions */ + +MEM_STATIC void* ZSTD_customMalloc(size_t size, ZSTD_customMem customMem) +{ + if (customMem.customAlloc) + return customMem.customAlloc(customMem.opaque, size); + return ZSTD_malloc(size); +} + +MEM_STATIC void* ZSTD_customCalloc(size_t size, ZSTD_customMem customMem) +{ + if (customMem.customAlloc) { + /* calloc implemented as malloc+memset; + * not as efficient as calloc, but next best guess for custom malloc */ + void* const ptr = customMem.customAlloc(customMem.opaque, size); + ZSTD_memset(ptr, 0, size); + return ptr; + } + return ZSTD_calloc(1, size); +} + +MEM_STATIC void ZSTD_customFree(void* ptr, ZSTD_customMem customMem) +{ + if (ptr!=NULL) { + if (customMem.customFree) + customMem.customFree(customMem.opaque, ptr); + else + ZSTD_free(ptr); + } +} + +#endif /* ZSTD_ALLOCATIONS_H */ +/**** ended inlining ../common/allocations.h ****/ +/**** skipping file: ../common/zstd_deps.h ****/ +/**** skipping file: ../common/cpu.h ****/ +/**** skipping file: ../common/mem.h ****/ +#define FSE_STATIC_LINKING_ONLY +/**** skipping file: ../common/fse.h ****/ +/**** skipping file: ../common/huf.h ****/ +/**** start inlining zstd_decompress_internal.h ****/ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + + +/* zstd_decompress_internal: + * objects and definitions shared within lib/decompress modules */ + + #ifndef ZSTD_DECOMPRESS_INTERNAL_H + #define ZSTD_DECOMPRESS_INTERNAL_H + + +/*-******************************************************* + * Dependencies + *********************************************************/ +/**** skipping file: ../common/mem.h ****/ +/**** skipping file: ../common/zstd_internal.h ****/ + + + +/*-******************************************************* + * Constants + *********************************************************/ +static UNUSED_ATTR const U32 LL_base[MaxLL+1] = { + 0, 1, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15, + 16, 18, 20, 22, 24, 28, 32, 40, + 48, 64, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000, + 0x2000, 0x4000, 0x8000, 0x10000 }; + +static UNUSED_ATTR const U32 OF_base[MaxOff+1] = { + 0, 1, 1, 5, 0xD, 0x1D, 0x3D, 0x7D, + 0xFD, 0x1FD, 0x3FD, 0x7FD, 0xFFD, 0x1FFD, 0x3FFD, 0x7FFD, + 0xFFFD, 0x1FFFD, 0x3FFFD, 0x7FFFD, 0xFFFFD, 0x1FFFFD, 0x3FFFFD, 0x7FFFFD, + 0xFFFFFD, 0x1FFFFFD, 0x3FFFFFD, 0x7FFFFFD, 0xFFFFFFD, 0x1FFFFFFD, 0x3FFFFFFD, 0x7FFFFFFD }; + +static UNUSED_ATTR const U8 OF_bits[MaxOff+1] = { + 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 }; + +static UNUSED_ATTR const U32 ML_base[MaxML+1] = { + 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, 37, 39, 41, 43, 47, 51, 59, + 67, 83, 99, 0x83, 0x103, 0x203, 0x403, 0x803, + 0x1003, 0x2003, 0x4003, 0x8003, 0x10003 }; + + +/*-******************************************************* + * Decompression types + *********************************************************/ + typedef struct { + U32 fastMode; + U32 tableLog; + } ZSTD_seqSymbol_header; + + typedef struct { + U16 nextState; + BYTE nbAdditionalBits; + BYTE nbBits; + U32 baseValue; + } ZSTD_seqSymbol; + + #define SEQSYMBOL_TABLE_SIZE(log) (1 + (1 << (log))) + +#define ZSTD_BUILD_FSE_TABLE_WKSP_SIZE (sizeof(S16) * (MaxSeq + 1) + (1u << MaxFSELog) + sizeof(U64)) +#define ZSTD_BUILD_FSE_TABLE_WKSP_SIZE_U32 ((ZSTD_BUILD_FSE_TABLE_WKSP_SIZE + sizeof(U32) - 1) / sizeof(U32)) +#define ZSTD_HUFFDTABLE_CAPACITY_LOG 12 + +typedef struct { + ZSTD_seqSymbol LLTable[SEQSYMBOL_TABLE_SIZE(LLFSELog)]; /* Note : Space reserved for FSE Tables */ + ZSTD_seqSymbol OFTable[SEQSYMBOL_TABLE_SIZE(OffFSELog)]; /* is also used as temporary workspace while building hufTable during DDict creation */ + ZSTD_seqSymbol MLTable[SEQSYMBOL_TABLE_SIZE(MLFSELog)]; /* and therefore must be at least HUF_DECOMPRESS_WORKSPACE_SIZE large */ + HUF_DTable hufTable[HUF_DTABLE_SIZE(ZSTD_HUFFDTABLE_CAPACITY_LOG)]; /* can accommodate HUF_decompress4X */ + U32 rep[ZSTD_REP_NUM]; + U32 workspace[ZSTD_BUILD_FSE_TABLE_WKSP_SIZE_U32]; +} ZSTD_entropyDTables_t; + +typedef enum { ZSTDds_getFrameHeaderSize, ZSTDds_decodeFrameHeader, + ZSTDds_decodeBlockHeader, ZSTDds_decompressBlock, + ZSTDds_decompressLastBlock, ZSTDds_checkChecksum, + ZSTDds_decodeSkippableHeader, ZSTDds_skipFrame } ZSTD_dStage; + +typedef enum { zdss_init=0, zdss_loadHeader, + zdss_read, zdss_load, zdss_flush } ZSTD_dStreamStage; + +typedef enum { + ZSTD_use_indefinitely = -1, /* Use the dictionary indefinitely */ + ZSTD_dont_use = 0, /* Do not use the dictionary (if one exists free it) */ + ZSTD_use_once = 1 /* Use the dictionary once and set to ZSTD_dont_use */ +} ZSTD_dictUses_e; + +/* Hashset for storing references to multiple ZSTD_DDict within ZSTD_DCtx */ +typedef struct { + const ZSTD_DDict** ddictPtrTable; + size_t ddictPtrTableSize; + size_t ddictPtrCount; +} ZSTD_DDictHashSet; + +#ifndef ZSTD_DECODER_INTERNAL_BUFFER +# define ZSTD_DECODER_INTERNAL_BUFFER (1 << 16) +#endif + +#define ZSTD_LBMIN 64 +#define ZSTD_LBMAX (128 << 10) + +/* extra buffer, compensates when dst is not large enough to store litBuffer */ +#define ZSTD_LITBUFFEREXTRASIZE BOUNDED(ZSTD_LBMIN, ZSTD_DECODER_INTERNAL_BUFFER, ZSTD_LBMAX) + +typedef enum { + ZSTD_not_in_dst = 0, /* Stored entirely within litExtraBuffer */ + ZSTD_in_dst = 1, /* Stored entirely within dst (in memory after current output write) */ + ZSTD_split = 2 /* Split between litExtraBuffer and dst */ +} ZSTD_litLocation_e; + +struct ZSTD_DCtx_s +{ + const ZSTD_seqSymbol* LLTptr; + const ZSTD_seqSymbol* MLTptr; + const ZSTD_seqSymbol* OFTptr; + const HUF_DTable* HUFptr; + ZSTD_entropyDTables_t entropy; + U32 workspace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32]; /* space needed when building huffman tables */ + const void* previousDstEnd; /* detect continuity */ + const void* prefixStart; /* start of current segment */ + const void* virtualStart; /* virtual start of previous segment if it was just before current one */ + const void* dictEnd; /* end of previous segment */ + size_t expected; + ZSTD_FrameHeader fParams; + U64 processedCSize; + U64 decodedSize; + blockType_e bType; /* used in ZSTD_decompressContinue(), store blockType between block header decoding and block decompression stages */ + ZSTD_dStage stage; + U32 litEntropy; + U32 fseEntropy; + XXH64_state_t xxhState; + size_t headerSize; + ZSTD_format_e format; + ZSTD_forceIgnoreChecksum_e forceIgnoreChecksum; /* User specified: if == 1, will ignore checksums in compressed frame. Default == 0 */ + U32 validateChecksum; /* if == 1, will validate checksum. Is == 1 if (fParams.checksumFlag == 1) and (forceIgnoreChecksum == 0). */ + const BYTE* litPtr; + ZSTD_customMem customMem; + size_t litSize; + size_t rleSize; + size_t staticSize; + int isFrameDecompression; +#if DYNAMIC_BMI2 + int bmi2; /* == 1 if the CPU supports BMI2 and 0 otherwise. CPU support is determined dynamically once per context lifetime. */ +#endif + + /* dictionary */ + ZSTD_DDict* ddictLocal; + const ZSTD_DDict* ddict; /* set by ZSTD_initDStream_usingDDict(), or ZSTD_DCtx_refDDict() */ + U32 dictID; + int ddictIsCold; /* if == 1 : dictionary is "new" for working context, and presumed "cold" (not in cpu cache) */ + ZSTD_dictUses_e dictUses; + ZSTD_DDictHashSet* ddictSet; /* Hash set for multiple ddicts */ + ZSTD_refMultipleDDicts_e refMultipleDDicts; /* User specified: if == 1, will allow references to multiple DDicts. Default == 0 (disabled) */ + int disableHufAsm; + int maxBlockSizeParam; + + /* streaming */ + ZSTD_dStreamStage streamStage; + char* inBuff; + size_t inBuffSize; + size_t inPos; + size_t maxWindowSize; + char* outBuff; + size_t outBuffSize; + size_t outStart; + size_t outEnd; + size_t lhSize; +#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1) + void* legacyContext; + U32 previousLegacyVersion; + U32 legacyVersion; +#endif + U32 hostageByte; + int noForwardProgress; + ZSTD_bufferMode_e outBufferMode; + ZSTD_outBuffer expectedOutBuffer; + + /* workspace */ + BYTE* litBuffer; + const BYTE* litBufferEnd; + ZSTD_litLocation_e litBufferLocation; + BYTE litExtraBuffer[ZSTD_LITBUFFEREXTRASIZE + WILDCOPY_OVERLENGTH]; /* literal buffer can be split between storage within dst and within this scratch buffer */ + BYTE headerBuffer[ZSTD_FRAMEHEADERSIZE_MAX]; + + size_t oversizedDuration; + +#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION + void const* dictContentBeginForFuzzing; + void const* dictContentEndForFuzzing; +#endif + + /* Tracing */ +#if ZSTD_TRACE + ZSTD_TraceCtx traceCtx; +#endif +}; /* typedef'd to ZSTD_DCtx within "zstd.h" */ + +MEM_STATIC int ZSTD_DCtx_get_bmi2(const struct ZSTD_DCtx_s *dctx) { +#if DYNAMIC_BMI2 + return dctx->bmi2; +#else + (void)dctx; + return 0; +#endif +} + +/*-******************************************************* + * Shared internal functions + *********************************************************/ + +/*! ZSTD_loadDEntropy() : + * dict : must point at beginning of a valid zstd dictionary. + * @return : size of dictionary header (size of magic number + dict ID + entropy tables) */ +size_t ZSTD_loadDEntropy(ZSTD_entropyDTables_t* entropy, + const void* const dict, size_t const dictSize); + +/*! ZSTD_checkContinuity() : + * check if next `dst` follows previous position, where decompression ended. + * If yes, do nothing (continue on current segment). + * If not, classify previous segment as "external dictionary", and start a new segment. + * This function cannot fail. */ +void ZSTD_checkContinuity(ZSTD_DCtx* dctx, const void* dst, size_t dstSize); + + +#endif /* ZSTD_DECOMPRESS_INTERNAL_H */ +/**** ended inlining zstd_decompress_internal.h ****/ +/**** start inlining zstd_ddict.h ****/ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + + +#ifndef ZSTD_DDICT_H +#define ZSTD_DDICT_H + +/*-******************************************************* + * Dependencies + *********************************************************/ +/**** skipping file: ../common/zstd_deps.h ****/ +/**** skipping file: ../zstd.h ****/ + + +/*-******************************************************* + * Interface + *********************************************************/ + +/* note: several prototypes are already published in `zstd.h` : + * ZSTD_createDDict() + * ZSTD_createDDict_byReference() + * ZSTD_createDDict_advanced() + * ZSTD_freeDDict() + * ZSTD_initStaticDDict() + * ZSTD_sizeof_DDict() + * ZSTD_estimateDDictSize() + * ZSTD_getDictID_fromDict() + */ + +const void* ZSTD_DDict_dictContent(const ZSTD_DDict* ddict); +size_t ZSTD_DDict_dictSize(const ZSTD_DDict* ddict); + +void ZSTD_copyDDictParameters(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict); + + + +#endif /* ZSTD_DDICT_H */ +/**** ended inlining zstd_ddict.h ****/ + +#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1) +/**** start inlining ../legacy/zstd_legacy.h ****/ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTD_LEGACY_H +#define ZSTD_LEGACY_H + +#if defined (__cplusplus) +extern "C" { +#endif + +/* ************************************* +* Includes +***************************************/ +/**** skipping file: ../common/mem.h ****/ +/**** skipping file: ../common/error_private.h ****/ +/**** skipping file: ../common/zstd_internal.h ****/ + +#if !defined (ZSTD_LEGACY_SUPPORT) || (ZSTD_LEGACY_SUPPORT == 0) +# undef ZSTD_LEGACY_SUPPORT +# define ZSTD_LEGACY_SUPPORT 8 +#endif + +#if (ZSTD_LEGACY_SUPPORT <= 1) +/**** start inlining zstd_v01.h ****/ +/* + * Copyright (c) Yann Collet, Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTD_V01_H_28739879432 +#define ZSTD_V01_H_28739879432 + +#if defined (__cplusplus) +extern "C" { +#endif + +/* ************************************* +* Includes +***************************************/ +#include /* size_t */ + + +/* ************************************* +* Simple one-step function +***************************************/ +/** +ZSTDv01_decompress() : decompress ZSTD frames compliant with v0.1.x format + compressedSize : is the exact source size + maxOriginalSize : is the size of the 'dst' buffer, which must be already allocated. + It must be equal or larger than originalSize, otherwise decompression will fail. + return : the number of bytes decompressed into destination buffer (originalSize) + or an errorCode if it fails (which can be tested using ZSTDv01_isError()) +*/ +size_t ZSTDv01_decompress( void* dst, size_t maxOriginalSize, + const void* src, size_t compressedSize); + + /** + ZSTDv01_findFrameSizeInfoLegacy() : get the source length and decompressed bound of a ZSTD frame compliant with v0.1.x format + srcSize : The size of the 'src' buffer, at least as large as the frame pointed to by 'src' + cSize (output parameter) : the number of bytes that would be read to decompress this frame + or an error code if it fails (which can be tested using ZSTDv01_isError()) + dBound (output parameter) : an upper-bound for the decompressed size of the data in the frame + or ZSTD_CONTENTSIZE_ERROR if an error occurs + + note : assumes `cSize` and `dBound` are _not_ NULL. + */ +void ZSTDv01_findFrameSizeInfoLegacy(const void *src, size_t srcSize, + size_t* cSize, unsigned long long* dBound); + +/** +ZSTDv01_isError() : tells if the result of ZSTDv01_decompress() is an error +*/ +unsigned ZSTDv01_isError(size_t code); + + +/* ************************************* +* Advanced functions +***************************************/ +typedef struct ZSTDv01_Dctx_s ZSTDv01_Dctx; +ZSTDv01_Dctx* ZSTDv01_createDCtx(void); +size_t ZSTDv01_freeDCtx(ZSTDv01_Dctx* dctx); + +size_t ZSTDv01_decompressDCtx(void* ctx, + void* dst, size_t maxOriginalSize, + const void* src, size_t compressedSize); + +/* ************************************* +* Streaming functions +***************************************/ +size_t ZSTDv01_resetDCtx(ZSTDv01_Dctx* dctx); + +size_t ZSTDv01_nextSrcSizeToDecompress(ZSTDv01_Dctx* dctx); +size_t ZSTDv01_decompressContinue(ZSTDv01_Dctx* dctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize); +/** + Use above functions alternatively. + ZSTD_nextSrcSizeToDecompress() tells how much bytes to provide as 'srcSize' to ZSTD_decompressContinue(). + ZSTD_decompressContinue() will use previous data blocks to improve compression if they are located prior to current block. + Result is the number of bytes regenerated within 'dst'. + It can be zero, which is not an error; it just means ZSTD_decompressContinue() has decoded some header. +*/ + +/* ************************************* +* Prefix - version detection +***************************************/ +#define ZSTDv01_magicNumber 0xFD2FB51E /* Big Endian version */ +#define ZSTDv01_magicNumberLE 0x1EB52FFD /* Little Endian version */ + + +#if defined (__cplusplus) +} +#endif + +#endif /* ZSTD_V01_H_28739879432 */ +/**** ended inlining zstd_v01.h ****/ +#endif +#if (ZSTD_LEGACY_SUPPORT <= 2) +/**** start inlining zstd_v02.h ****/ +/* + * Copyright (c) Yann Collet, Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTD_V02_H_4174539423 +#define ZSTD_V02_H_4174539423 + +#if defined (__cplusplus) +extern "C" { +#endif + +/* ************************************* +* Includes +***************************************/ +#include /* size_t */ + + +/* ************************************* +* Simple one-step function +***************************************/ +/** +ZSTDv02_decompress() : decompress ZSTD frames compliant with v0.2.x format + compressedSize : is the exact source size + maxOriginalSize : is the size of the 'dst' buffer, which must be already allocated. + It must be equal or larger than originalSize, otherwise decompression will fail. + return : the number of bytes decompressed into destination buffer (originalSize) + or an errorCode if it fails (which can be tested using ZSTDv01_isError()) +*/ +size_t ZSTDv02_decompress( void* dst, size_t maxOriginalSize, + const void* src, size_t compressedSize); + + /** + ZSTDv02_findFrameSizeInfoLegacy() : get the source length and decompressed bound of a ZSTD frame compliant with v0.2.x format + srcSize : The size of the 'src' buffer, at least as large as the frame pointed to by 'src' + cSize (output parameter) : the number of bytes that would be read to decompress this frame + or an error code if it fails (which can be tested using ZSTDv01_isError()) + dBound (output parameter) : an upper-bound for the decompressed size of the data in the frame + or ZSTD_CONTENTSIZE_ERROR if an error occurs + + note : assumes `cSize` and `dBound` are _not_ NULL. + */ +void ZSTDv02_findFrameSizeInfoLegacy(const void *src, size_t srcSize, + size_t* cSize, unsigned long long* dBound); + +/** +ZSTDv02_isError() : tells if the result of ZSTDv02_decompress() is an error +*/ +unsigned ZSTDv02_isError(size_t code); + + +/* ************************************* +* Advanced functions +***************************************/ +typedef struct ZSTDv02_Dctx_s ZSTDv02_Dctx; +ZSTDv02_Dctx* ZSTDv02_createDCtx(void); +size_t ZSTDv02_freeDCtx(ZSTDv02_Dctx* dctx); + +size_t ZSTDv02_decompressDCtx(void* ctx, + void* dst, size_t maxOriginalSize, + const void* src, size_t compressedSize); + +/* ************************************* +* Streaming functions +***************************************/ +size_t ZSTDv02_resetDCtx(ZSTDv02_Dctx* dctx); + +size_t ZSTDv02_nextSrcSizeToDecompress(ZSTDv02_Dctx* dctx); +size_t ZSTDv02_decompressContinue(ZSTDv02_Dctx* dctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize); +/** + Use above functions alternatively. + ZSTD_nextSrcSizeToDecompress() tells how much bytes to provide as 'srcSize' to ZSTD_decompressContinue(). + ZSTD_decompressContinue() will use previous data blocks to improve compression if they are located prior to current block. + Result is the number of bytes regenerated within 'dst'. + It can be zero, which is not an error; it just means ZSTD_decompressContinue() has decoded some header. +*/ + +/* ************************************* +* Prefix - version detection +***************************************/ +#define ZSTDv02_magicNumber 0xFD2FB522 /* v0.2 */ + + +#if defined (__cplusplus) +} +#endif + +#endif /* ZSTD_V02_H_4174539423 */ +/**** ended inlining zstd_v02.h ****/ +#endif +#if (ZSTD_LEGACY_SUPPORT <= 3) +/**** start inlining zstd_v03.h ****/ +/* + * Copyright (c) Yann Collet, Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTD_V03_H_298734209782 +#define ZSTD_V03_H_298734209782 + +#if defined (__cplusplus) +extern "C" { +#endif + +/* ************************************* +* Includes +***************************************/ +#include /* size_t */ + + +/* ************************************* +* Simple one-step function +***************************************/ +/** +ZSTDv03_decompress() : decompress ZSTD frames compliant with v0.3.x format + compressedSize : is the exact source size + maxOriginalSize : is the size of the 'dst' buffer, which must be already allocated. + It must be equal or larger than originalSize, otherwise decompression will fail. + return : the number of bytes decompressed into destination buffer (originalSize) + or an errorCode if it fails (which can be tested using ZSTDv01_isError()) +*/ +size_t ZSTDv03_decompress( void* dst, size_t maxOriginalSize, + const void* src, size_t compressedSize); + + /** + ZSTDv03_findFrameSizeInfoLegacy() : get the source length and decompressed bound of a ZSTD frame compliant with v0.3.x format + srcSize : The size of the 'src' buffer, at least as large as the frame pointed to by 'src' + cSize (output parameter) : the number of bytes that would be read to decompress this frame + or an error code if it fails (which can be tested using ZSTDv01_isError()) + dBound (output parameter) : an upper-bound for the decompressed size of the data in the frame + or ZSTD_CONTENTSIZE_ERROR if an error occurs + + note : assumes `cSize` and `dBound` are _not_ NULL. + */ + void ZSTDv03_findFrameSizeInfoLegacy(const void *src, size_t srcSize, + size_t* cSize, unsigned long long* dBound); + + /** +ZSTDv03_isError() : tells if the result of ZSTDv03_decompress() is an error +*/ +unsigned ZSTDv03_isError(size_t code); + + +/* ************************************* +* Advanced functions +***************************************/ +typedef struct ZSTDv03_Dctx_s ZSTDv03_Dctx; +ZSTDv03_Dctx* ZSTDv03_createDCtx(void); +size_t ZSTDv03_freeDCtx(ZSTDv03_Dctx* dctx); + +size_t ZSTDv03_decompressDCtx(void* ctx, + void* dst, size_t maxOriginalSize, + const void* src, size_t compressedSize); + +/* ************************************* +* Streaming functions +***************************************/ +size_t ZSTDv03_resetDCtx(ZSTDv03_Dctx* dctx); + +size_t ZSTDv03_nextSrcSizeToDecompress(ZSTDv03_Dctx* dctx); +size_t ZSTDv03_decompressContinue(ZSTDv03_Dctx* dctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize); +/** + Use above functions alternatively. + ZSTD_nextSrcSizeToDecompress() tells how much bytes to provide as 'srcSize' to ZSTD_decompressContinue(). + ZSTD_decompressContinue() will use previous data blocks to improve compression if they are located prior to current block. + Result is the number of bytes regenerated within 'dst'. + It can be zero, which is not an error; it just means ZSTD_decompressContinue() has decoded some header. +*/ + +/* ************************************* +* Prefix - version detection +***************************************/ +#define ZSTDv03_magicNumber 0xFD2FB523 /* v0.3 */ + + +#if defined (__cplusplus) +} +#endif + +#endif /* ZSTD_V03_H_298734209782 */ +/**** ended inlining zstd_v03.h ****/ +#endif +#if (ZSTD_LEGACY_SUPPORT <= 4) +/**** start inlining zstd_v04.h ****/ +/* + * Copyright (c) Yann Collet, Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTD_V04_H_91868324769238 +#define ZSTD_V04_H_91868324769238 + +#if defined (__cplusplus) +extern "C" { +#endif + +/* ************************************* +* Includes +***************************************/ +#include /* size_t */ + + +/* ************************************* +* Simple one-step function +***************************************/ +/** +ZSTDv04_decompress() : decompress ZSTD frames compliant with v0.4.x format + compressedSize : is the exact source size + maxOriginalSize : is the size of the 'dst' buffer, which must be already allocated. + It must be equal or larger than originalSize, otherwise decompression will fail. + return : the number of bytes decompressed into destination buffer (originalSize) + or an errorCode if it fails (which can be tested using ZSTDv01_isError()) +*/ +size_t ZSTDv04_decompress( void* dst, size_t maxOriginalSize, + const void* src, size_t compressedSize); + + /** + ZSTDv04_findFrameSizeInfoLegacy() : get the source length and decompressed bound of a ZSTD frame compliant with v0.4.x format + srcSize : The size of the 'src' buffer, at least as large as the frame pointed to by 'src' + cSize (output parameter) : the number of bytes that would be read to decompress this frame + or an error code if it fails (which can be tested using ZSTDv01_isError()) + dBound (output parameter) : an upper-bound for the decompressed size of the data in the frame + or ZSTD_CONTENTSIZE_ERROR if an error occurs + + note : assumes `cSize` and `dBound` are _not_ NULL. + */ + void ZSTDv04_findFrameSizeInfoLegacy(const void *src, size_t srcSize, + size_t* cSize, unsigned long long* dBound); + +/** +ZSTDv04_isError() : tells if the result of ZSTDv04_decompress() is an error +*/ +unsigned ZSTDv04_isError(size_t code); + + +/* ************************************* +* Advanced functions +***************************************/ +typedef struct ZSTDv04_Dctx_s ZSTDv04_Dctx; +ZSTDv04_Dctx* ZSTDv04_createDCtx(void); +size_t ZSTDv04_freeDCtx(ZSTDv04_Dctx* dctx); + +size_t ZSTDv04_decompressDCtx(ZSTDv04_Dctx* dctx, + void* dst, size_t maxOriginalSize, + const void* src, size_t compressedSize); + + +/* ************************************* +* Direct Streaming +***************************************/ +size_t ZSTDv04_resetDCtx(ZSTDv04_Dctx* dctx); + +size_t ZSTDv04_nextSrcSizeToDecompress(ZSTDv04_Dctx* dctx); +size_t ZSTDv04_decompressContinue(ZSTDv04_Dctx* dctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize); +/** + Use above functions alternatively. + ZSTD_nextSrcSizeToDecompress() tells how much bytes to provide as 'srcSize' to ZSTD_decompressContinue(). + ZSTD_decompressContinue() will use previous data blocks to improve compression if they are located prior to current block. + Result is the number of bytes regenerated within 'dst'. + It can be zero, which is not an error; it just means ZSTD_decompressContinue() has decoded some header. +*/ + + +/* ************************************* +* Buffered Streaming +***************************************/ +typedef struct ZBUFFv04_DCtx_s ZBUFFv04_DCtx; +ZBUFFv04_DCtx* ZBUFFv04_createDCtx(void); +size_t ZBUFFv04_freeDCtx(ZBUFFv04_DCtx* dctx); + +size_t ZBUFFv04_decompressInit(ZBUFFv04_DCtx* dctx); +size_t ZBUFFv04_decompressWithDictionary(ZBUFFv04_DCtx* dctx, const void* dict, size_t dictSize); + +size_t ZBUFFv04_decompressContinue(ZBUFFv04_DCtx* dctx, void* dst, size_t* maxDstSizePtr, const void* src, size_t* srcSizePtr); + +/** ************************************************ +* Streaming decompression +* +* A ZBUFF_DCtx object is required to track streaming operation. +* Use ZBUFF_createDCtx() and ZBUFF_freeDCtx() to create/release resources. +* Use ZBUFF_decompressInit() to start a new decompression operation. +* ZBUFF_DCtx objects can be reused multiple times. +* +* Optionally, a reference to a static dictionary can be set, using ZBUFF_decompressWithDictionary() +* It must be the same content as the one set during compression phase. +* Dictionary content must remain accessible during the decompression process. +* +* Use ZBUFF_decompressContinue() repetitively to consume your input. +* *srcSizePtr and *maxDstSizePtr can be any size. +* The function will report how many bytes were read or written by modifying *srcSizePtr and *maxDstSizePtr. +* Note that it may not consume the entire input, in which case it's up to the caller to present remaining input again. +* The content of dst will be overwritten (up to *maxDstSizePtr) at each function call, so save its content if it matters or change dst. +* @return : a hint to preferred nb of bytes to use as input for next function call (it's only a hint, to improve latency) +* or 0 when a frame is completely decoded +* or an error code, which can be tested using ZBUFF_isError(). +* +* Hint : recommended buffer sizes (not compulsory) : ZBUFF_recommendedDInSize / ZBUFF_recommendedDOutSize +* output : ZBUFF_recommendedDOutSize==128 KB block size is the internal unit, it ensures it's always possible to write a full block when it's decoded. +* input : ZBUFF_recommendedDInSize==128Kb+3; just follow indications from ZBUFF_decompressContinue() to minimize latency. It should always be <= 128 KB + 3 . +* **************************************************/ +unsigned ZBUFFv04_isError(size_t errorCode); +const char* ZBUFFv04_getErrorName(size_t errorCode); + + +/** The below functions provide recommended buffer sizes for Compression or Decompression operations. +* These sizes are not compulsory, they just tend to offer better latency */ +size_t ZBUFFv04_recommendedDInSize(void); +size_t ZBUFFv04_recommendedDOutSize(void); + + +/* ************************************* +* Prefix - version detection +***************************************/ +#define ZSTDv04_magicNumber 0xFD2FB524 /* v0.4 */ + + +#if defined (__cplusplus) +} +#endif + +#endif /* ZSTD_V04_H_91868324769238 */ +/**** ended inlining zstd_v04.h ****/ +#endif +#if (ZSTD_LEGACY_SUPPORT <= 5) +/**** start inlining zstd_v05.h ****/ +/* + * Copyright (c) Yann Collet, Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTDv05_H +#define ZSTDv05_H + +#if defined (__cplusplus) +extern "C" { +#endif + +/*-************************************* +* Dependencies +***************************************/ +#include /* size_t */ +/**** skipping file: ../common/mem.h ****/ + + +/* ************************************* +* Simple functions +***************************************/ +/*! ZSTDv05_decompress() : + `compressedSize` : is the _exact_ size of the compressed blob, otherwise decompression will fail. + `dstCapacity` must be large enough, equal or larger than originalSize. + @return : the number of bytes decompressed into `dst` (<= `dstCapacity`), + or an errorCode if it fails (which can be tested using ZSTDv05_isError()) */ +size_t ZSTDv05_decompress( void* dst, size_t dstCapacity, + const void* src, size_t compressedSize); + + /** + ZSTDv05_findFrameSizeInfoLegacy() : get the source length and decompressed bound of a ZSTD frame compliant with v0.5.x format + srcSize : The size of the 'src' buffer, at least as large as the frame pointed to by 'src' + cSize (output parameter) : the number of bytes that would be read to decompress this frame + or an error code if it fails (which can be tested using ZSTDv01_isError()) + dBound (output parameter) : an upper-bound for the decompressed size of the data in the frame + or ZSTD_CONTENTSIZE_ERROR if an error occurs + + note : assumes `cSize` and `dBound` are _not_ NULL. + */ +void ZSTDv05_findFrameSizeInfoLegacy(const void *src, size_t srcSize, + size_t* cSize, unsigned long long* dBound); + +/* ************************************* +* Helper functions +***************************************/ +/* Error Management */ +unsigned ZSTDv05_isError(size_t code); /*!< tells if a `size_t` function result is an error code */ +const char* ZSTDv05_getErrorName(size_t code); /*!< provides readable string for an error code */ + + +/* ************************************* +* Explicit memory management +***************************************/ +/** Decompression context */ +typedef struct ZSTDv05_DCtx_s ZSTDv05_DCtx; +ZSTDv05_DCtx* ZSTDv05_createDCtx(void); +size_t ZSTDv05_freeDCtx(ZSTDv05_DCtx* dctx); /*!< @return : errorCode */ + +/** ZSTDv05_decompressDCtx() : +* Same as ZSTDv05_decompress(), but requires an already allocated ZSTDv05_DCtx (see ZSTDv05_createDCtx()) */ +size_t ZSTDv05_decompressDCtx(ZSTDv05_DCtx* ctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); + + +/*-*********************** +* Simple Dictionary API +*************************/ +/*! ZSTDv05_decompress_usingDict() : +* Decompression using a pre-defined Dictionary content (see dictBuilder). +* Dictionary must be identical to the one used during compression, otherwise regenerated data will be corrupted. +* Note : dict can be NULL, in which case, it's equivalent to ZSTDv05_decompressDCtx() */ +size_t ZSTDv05_decompress_usingDict(ZSTDv05_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const void* dict,size_t dictSize); + +/*-************************ +* Advanced Streaming API +***************************/ +typedef enum { ZSTDv05_fast, ZSTDv05_greedy, ZSTDv05_lazy, ZSTDv05_lazy2, ZSTDv05_btlazy2, ZSTDv05_opt, ZSTDv05_btopt } ZSTDv05_strategy; +typedef struct { + U64 srcSize; + U32 windowLog; /* the only useful information to retrieve */ + U32 contentLog; U32 hashLog; U32 searchLog; U32 searchLength; U32 targetLength; ZSTDv05_strategy strategy; +} ZSTDv05_parameters; +size_t ZSTDv05_getFrameParams(ZSTDv05_parameters* params, const void* src, size_t srcSize); + +size_t ZSTDv05_decompressBegin_usingDict(ZSTDv05_DCtx* dctx, const void* dict, size_t dictSize); +void ZSTDv05_copyDCtx(ZSTDv05_DCtx* dstDCtx, const ZSTDv05_DCtx* srcDCtx); +size_t ZSTDv05_nextSrcSizeToDecompress(ZSTDv05_DCtx* dctx); +size_t ZSTDv05_decompressContinue(ZSTDv05_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); + + +/*-*********************** +* ZBUFF API +*************************/ +typedef struct ZBUFFv05_DCtx_s ZBUFFv05_DCtx; +ZBUFFv05_DCtx* ZBUFFv05_createDCtx(void); +size_t ZBUFFv05_freeDCtx(ZBUFFv05_DCtx* dctx); + +size_t ZBUFFv05_decompressInit(ZBUFFv05_DCtx* dctx); +size_t ZBUFFv05_decompressInitDictionary(ZBUFFv05_DCtx* dctx, const void* dict, size_t dictSize); + +size_t ZBUFFv05_decompressContinue(ZBUFFv05_DCtx* dctx, + void* dst, size_t* dstCapacityPtr, + const void* src, size_t* srcSizePtr); + +/*-*************************************************************************** +* Streaming decompression +* +* A ZBUFFv05_DCtx object is required to track streaming operations. +* Use ZBUFFv05_createDCtx() and ZBUFFv05_freeDCtx() to create/release resources. +* Use ZBUFFv05_decompressInit() to start a new decompression operation, +* or ZBUFFv05_decompressInitDictionary() if decompression requires a dictionary. +* Note that ZBUFFv05_DCtx objects can be reused multiple times. +* +* Use ZBUFFv05_decompressContinue() repetitively to consume your input. +* *srcSizePtr and *dstCapacityPtr can be any size. +* The function will report how many bytes were read or written by modifying *srcSizePtr and *dstCapacityPtr. +* Note that it may not consume the entire input, in which case it's up to the caller to present remaining input again. +* The content of @dst will be overwritten (up to *dstCapacityPtr) at each function call, so save its content if it matters or change @dst. +* @return : a hint to preferred nb of bytes to use as input for next function call (it's only a hint, to help latency) +* or 0 when a frame is completely decoded +* or an error code, which can be tested using ZBUFFv05_isError(). +* +* Hint : recommended buffer sizes (not compulsory) : ZBUFFv05_recommendedDInSize() / ZBUFFv05_recommendedDOutSize() +* output : ZBUFFv05_recommendedDOutSize==128 KB block size is the internal unit, it ensures it's always possible to write a full block when decoded. +* input : ZBUFFv05_recommendedDInSize==128Kb+3; just follow indications from ZBUFFv05_decompressContinue() to minimize latency. It should always be <= 128 KB + 3 . +* *******************************************************************************/ + + +/* ************************************* +* Tool functions +***************************************/ +unsigned ZBUFFv05_isError(size_t errorCode); +const char* ZBUFFv05_getErrorName(size_t errorCode); + +/** Functions below provide recommended buffer sizes for Compression or Decompression operations. +* These sizes are just hints, and tend to offer better latency */ +size_t ZBUFFv05_recommendedDInSize(void); +size_t ZBUFFv05_recommendedDOutSize(void); + + + +/*-************************************* +* Constants +***************************************/ +#define ZSTDv05_MAGICNUMBER 0xFD2FB525 /* v0.5 */ + + + + +#if defined (__cplusplus) +} +#endif + +#endif /* ZSTDv0505_H */ +/**** ended inlining zstd_v05.h ****/ +#endif +#if (ZSTD_LEGACY_SUPPORT <= 6) +/**** start inlining zstd_v06.h ****/ +/* + * Copyright (c) Yann Collet, Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTDv06_H +#define ZSTDv06_H + +#if defined (__cplusplus) +extern "C" { +#endif + +/*====== Dependency ======*/ +#include /* size_t */ + + +/*====== Export for Windows ======*/ +/*! +* ZSTDv06_DLL_EXPORT : +* Enable exporting of functions when building a Windows DLL +*/ +#if defined(_WIN32) && defined(ZSTDv06_DLL_EXPORT) && (ZSTDv06_DLL_EXPORT==1) +# define ZSTDLIBv06_API __declspec(dllexport) +#else +# define ZSTDLIBv06_API +#endif + + +/* ************************************* +* Simple functions +***************************************/ +/*! ZSTDv06_decompress() : + `compressedSize` : is the _exact_ size of the compressed blob, otherwise decompression will fail. + `dstCapacity` must be large enough, equal or larger than originalSize. + @return : the number of bytes decompressed into `dst` (<= `dstCapacity`), + or an errorCode if it fails (which can be tested using ZSTDv06_isError()) */ +ZSTDLIBv06_API size_t ZSTDv06_decompress( void* dst, size_t dstCapacity, + const void* src, size_t compressedSize); + +/** +ZSTDv06_findFrameSizeInfoLegacy() : get the source length and decompressed bound of a ZSTD frame compliant with v0.6.x format + srcSize : The size of the 'src' buffer, at least as large as the frame pointed to by 'src' + cSize (output parameter) : the number of bytes that would be read to decompress this frame + or an error code if it fails (which can be tested using ZSTDv01_isError()) + dBound (output parameter) : an upper-bound for the decompressed size of the data in the frame + or ZSTD_CONTENTSIZE_ERROR if an error occurs + + note : assumes `cSize` and `dBound` are _not_ NULL. +*/ +void ZSTDv06_findFrameSizeInfoLegacy(const void *src, size_t srcSize, + size_t* cSize, unsigned long long* dBound); + +/* ************************************* +* Helper functions +***************************************/ +ZSTDLIBv06_API size_t ZSTDv06_compressBound(size_t srcSize); /*!< maximum compressed size (worst case scenario) */ + +/* Error Management */ +ZSTDLIBv06_API unsigned ZSTDv06_isError(size_t code); /*!< tells if a `size_t` function result is an error code */ +ZSTDLIBv06_API const char* ZSTDv06_getErrorName(size_t code); /*!< provides readable string for an error code */ + + +/* ************************************* +* Explicit memory management +***************************************/ +/** Decompression context */ +typedef struct ZSTDv06_DCtx_s ZSTDv06_DCtx; +ZSTDLIBv06_API ZSTDv06_DCtx* ZSTDv06_createDCtx(void); +ZSTDLIBv06_API size_t ZSTDv06_freeDCtx(ZSTDv06_DCtx* dctx); /*!< @return : errorCode */ + +/** ZSTDv06_decompressDCtx() : +* Same as ZSTDv06_decompress(), but requires an already allocated ZSTDv06_DCtx (see ZSTDv06_createDCtx()) */ +ZSTDLIBv06_API size_t ZSTDv06_decompressDCtx(ZSTDv06_DCtx* ctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); + + +/*-*********************** +* Dictionary API +*************************/ +/*! ZSTDv06_decompress_usingDict() : +* Decompression using a pre-defined Dictionary content (see dictBuilder). +* Dictionary must be identical to the one used during compression, otherwise regenerated data will be corrupted. +* Note : dict can be NULL, in which case, it's equivalent to ZSTDv06_decompressDCtx() */ +ZSTDLIBv06_API size_t ZSTDv06_decompress_usingDict(ZSTDv06_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const void* dict,size_t dictSize); + + +/*-************************ +* Advanced Streaming API +***************************/ +struct ZSTDv06_frameParams_s { unsigned long long frameContentSize; unsigned windowLog; }; +typedef struct ZSTDv06_frameParams_s ZSTDv06_frameParams; + +ZSTDLIBv06_API size_t ZSTDv06_getFrameParams(ZSTDv06_frameParams* fparamsPtr, const void* src, size_t srcSize); /**< doesn't consume input */ +ZSTDLIBv06_API size_t ZSTDv06_decompressBegin_usingDict(ZSTDv06_DCtx* dctx, const void* dict, size_t dictSize); +ZSTDLIBv06_API void ZSTDv06_copyDCtx(ZSTDv06_DCtx* dctx, const ZSTDv06_DCtx* preparedDCtx); + +ZSTDLIBv06_API size_t ZSTDv06_nextSrcSizeToDecompress(ZSTDv06_DCtx* dctx); +ZSTDLIBv06_API size_t ZSTDv06_decompressContinue(ZSTDv06_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); + + + +/* ************************************* +* ZBUFF API +***************************************/ + +typedef struct ZBUFFv06_DCtx_s ZBUFFv06_DCtx; +ZSTDLIBv06_API ZBUFFv06_DCtx* ZBUFFv06_createDCtx(void); +ZSTDLIBv06_API size_t ZBUFFv06_freeDCtx(ZBUFFv06_DCtx* dctx); + +ZSTDLIBv06_API size_t ZBUFFv06_decompressInit(ZBUFFv06_DCtx* dctx); +ZSTDLIBv06_API size_t ZBUFFv06_decompressInitDictionary(ZBUFFv06_DCtx* dctx, const void* dict, size_t dictSize); + +ZSTDLIBv06_API size_t ZBUFFv06_decompressContinue(ZBUFFv06_DCtx* dctx, + void* dst, size_t* dstCapacityPtr, + const void* src, size_t* srcSizePtr); + +/*-*************************************************************************** +* Streaming decompression howto +* +* A ZBUFFv06_DCtx object is required to track streaming operations. +* Use ZBUFFv06_createDCtx() and ZBUFFv06_freeDCtx() to create/release resources. +* Use ZBUFFv06_decompressInit() to start a new decompression operation, +* or ZBUFFv06_decompressInitDictionary() if decompression requires a dictionary. +* Note that ZBUFFv06_DCtx objects can be re-init multiple times. +* +* Use ZBUFFv06_decompressContinue() repetitively to consume your input. +* *srcSizePtr and *dstCapacityPtr can be any size. +* The function will report how many bytes were read or written by modifying *srcSizePtr and *dstCapacityPtr. +* Note that it may not consume the entire input, in which case it's up to the caller to present remaining input again. +* The content of `dst` will be overwritten (up to *dstCapacityPtr) at each function call, so save its content if it matters, or change `dst`. +* @return : a hint to preferred nb of bytes to use as input for next function call (it's only a hint, to help latency), +* or 0 when a frame is completely decoded, +* or an error code, which can be tested using ZBUFFv06_isError(). +* +* Hint : recommended buffer sizes (not compulsory) : ZBUFFv06_recommendedDInSize() and ZBUFFv06_recommendedDOutSize() +* output : ZBUFFv06_recommendedDOutSize== 128 KB block size is the internal unit, it ensures it's always possible to write a full block when decoded. +* input : ZBUFFv06_recommendedDInSize == 128KB + 3; +* just follow indications from ZBUFFv06_decompressContinue() to minimize latency. It should always be <= 128 KB + 3 . +* *******************************************************************************/ + + +/* ************************************* +* Tool functions +***************************************/ +ZSTDLIBv06_API unsigned ZBUFFv06_isError(size_t errorCode); +ZSTDLIBv06_API const char* ZBUFFv06_getErrorName(size_t errorCode); + +/** Functions below provide recommended buffer sizes for Compression or Decompression operations. +* These sizes are just hints, they tend to offer better latency */ +ZSTDLIBv06_API size_t ZBUFFv06_recommendedDInSize(void); +ZSTDLIBv06_API size_t ZBUFFv06_recommendedDOutSize(void); + + +/*-************************************* +* Constants +***************************************/ +#define ZSTDv06_MAGICNUMBER 0xFD2FB526 /* v0.6 */ + + + +#if defined (__cplusplus) +} +#endif + +#endif /* ZSTDv06_BUFFERED_H */ +/**** ended inlining zstd_v06.h ****/ +#endif +#if (ZSTD_LEGACY_SUPPORT <= 7) +/**** start inlining zstd_v07.h ****/ +/* + * Copyright (c) Yann Collet, Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTDv07_H_235446 +#define ZSTDv07_H_235446 + +#if defined (__cplusplus) +extern "C" { +#endif + +/*====== Dependency ======*/ +#include /* size_t */ + + +/*====== Export for Windows ======*/ +/*! +* ZSTDv07_DLL_EXPORT : +* Enable exporting of functions when building a Windows DLL +*/ +#if defined(_WIN32) && defined(ZSTDv07_DLL_EXPORT) && (ZSTDv07_DLL_EXPORT==1) +# define ZSTDLIBv07_API __declspec(dllexport) +#else +# define ZSTDLIBv07_API +#endif + + +/* ************************************* +* Simple API +***************************************/ +/*! ZSTDv07_getDecompressedSize() : +* @return : decompressed size if known, 0 otherwise. + note 1 : if `0`, follow up with ZSTDv07_getFrameParams() to know precise failure cause. + note 2 : decompressed size could be wrong or intentionally modified ! + always ensure results fit within application's authorized limits */ +unsigned long long ZSTDv07_getDecompressedSize(const void* src, size_t srcSize); + +/*! ZSTDv07_decompress() : + `compressedSize` : must be _exact_ size of compressed input, otherwise decompression will fail. + `dstCapacity` must be equal or larger than originalSize. + @return : the number of bytes decompressed into `dst` (<= `dstCapacity`), + or an errorCode if it fails (which can be tested using ZSTDv07_isError()) */ +ZSTDLIBv07_API size_t ZSTDv07_decompress( void* dst, size_t dstCapacity, + const void* src, size_t compressedSize); + +/** +ZSTDv07_findFrameSizeInfoLegacy() : get the source length and decompressed bound of a ZSTD frame compliant with v0.7.x format + srcSize : The size of the 'src' buffer, at least as large as the frame pointed to by 'src' + cSize (output parameter) : the number of bytes that would be read to decompress this frame + or an error code if it fails (which can be tested using ZSTDv01_isError()) + dBound (output parameter) : an upper-bound for the decompressed size of the data in the frame + or ZSTD_CONTENTSIZE_ERROR if an error occurs + + note : assumes `cSize` and `dBound` are _not_ NULL. +*/ +void ZSTDv07_findFrameSizeInfoLegacy(const void *src, size_t srcSize, + size_t* cSize, unsigned long long* dBound); + +/*====== Helper functions ======*/ +ZSTDLIBv07_API unsigned ZSTDv07_isError(size_t code); /*!< tells if a `size_t` function result is an error code */ +ZSTDLIBv07_API const char* ZSTDv07_getErrorName(size_t code); /*!< provides readable string from an error code */ + + +/*-************************************* +* Explicit memory management +***************************************/ +/** Decompression context */ +typedef struct ZSTDv07_DCtx_s ZSTDv07_DCtx; +ZSTDLIBv07_API ZSTDv07_DCtx* ZSTDv07_createDCtx(void); +ZSTDLIBv07_API size_t ZSTDv07_freeDCtx(ZSTDv07_DCtx* dctx); /*!< @return : errorCode */ + +/** ZSTDv07_decompressDCtx() : +* Same as ZSTDv07_decompress(), requires an allocated ZSTDv07_DCtx (see ZSTDv07_createDCtx()) */ +ZSTDLIBv07_API size_t ZSTDv07_decompressDCtx(ZSTDv07_DCtx* ctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); + + +/*-************************ +* Simple dictionary API +***************************/ +/*! ZSTDv07_decompress_usingDict() : +* Decompression using a pre-defined Dictionary content (see dictBuilder). +* Dictionary must be identical to the one used during compression. +* Note : This function load the dictionary, resulting in a significant startup time */ +ZSTDLIBv07_API size_t ZSTDv07_decompress_usingDict(ZSTDv07_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const void* dict,size_t dictSize); + + +/*-************************** +* Advanced Dictionary API +****************************/ +/*! ZSTDv07_createDDict() : +* Create a digested dictionary, ready to start decompression operation without startup delay. +* `dict` can be released after creation */ +typedef struct ZSTDv07_DDict_s ZSTDv07_DDict; +ZSTDLIBv07_API ZSTDv07_DDict* ZSTDv07_createDDict(const void* dict, size_t dictSize); +ZSTDLIBv07_API size_t ZSTDv07_freeDDict(ZSTDv07_DDict* ddict); + +/*! ZSTDv07_decompress_usingDDict() : +* Decompression using a pre-digested Dictionary +* Faster startup than ZSTDv07_decompress_usingDict(), recommended when same dictionary is used multiple times. */ +ZSTDLIBv07_API size_t ZSTDv07_decompress_usingDDict(ZSTDv07_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const ZSTDv07_DDict* ddict); + +typedef struct { + unsigned long long frameContentSize; + unsigned windowSize; + unsigned dictID; + unsigned checksumFlag; +} ZSTDv07_frameParams; + +ZSTDLIBv07_API size_t ZSTDv07_getFrameParams(ZSTDv07_frameParams* fparamsPtr, const void* src, size_t srcSize); /**< doesn't consume input */ + + + + +/* ************************************* +* Streaming functions +***************************************/ +typedef struct ZBUFFv07_DCtx_s ZBUFFv07_DCtx; +ZSTDLIBv07_API ZBUFFv07_DCtx* ZBUFFv07_createDCtx(void); +ZSTDLIBv07_API size_t ZBUFFv07_freeDCtx(ZBUFFv07_DCtx* dctx); + +ZSTDLIBv07_API size_t ZBUFFv07_decompressInit(ZBUFFv07_DCtx* dctx); +ZSTDLIBv07_API size_t ZBUFFv07_decompressInitDictionary(ZBUFFv07_DCtx* dctx, const void* dict, size_t dictSize); + +ZSTDLIBv07_API size_t ZBUFFv07_decompressContinue(ZBUFFv07_DCtx* dctx, + void* dst, size_t* dstCapacityPtr, + const void* src, size_t* srcSizePtr); + +/*-*************************************************************************** +* Streaming decompression howto +* +* A ZBUFFv07_DCtx object is required to track streaming operations. +* Use ZBUFFv07_createDCtx() and ZBUFFv07_freeDCtx() to create/release resources. +* Use ZBUFFv07_decompressInit() to start a new decompression operation, +* or ZBUFFv07_decompressInitDictionary() if decompression requires a dictionary. +* Note that ZBUFFv07_DCtx objects can be re-init multiple times. +* +* Use ZBUFFv07_decompressContinue() repetitively to consume your input. +* *srcSizePtr and *dstCapacityPtr can be any size. +* The function will report how many bytes were read or written by modifying *srcSizePtr and *dstCapacityPtr. +* Note that it may not consume the entire input, in which case it's up to the caller to present remaining input again. +* The content of `dst` will be overwritten (up to *dstCapacityPtr) at each function call, so save its content if it matters, or change `dst`. +* @return : a hint to preferred nb of bytes to use as input for next function call (it's only a hint, to help latency), +* or 0 when a frame is completely decoded, +* or an error code, which can be tested using ZBUFFv07_isError(). +* +* Hint : recommended buffer sizes (not compulsory) : ZBUFFv07_recommendedDInSize() and ZBUFFv07_recommendedDOutSize() +* output : ZBUFFv07_recommendedDOutSize== 128 KB block size is the internal unit, it ensures it's always possible to write a full block when decoded. +* input : ZBUFFv07_recommendedDInSize == 128KB + 3; +* just follow indications from ZBUFFv07_decompressContinue() to minimize latency. It should always be <= 128 KB + 3 . +* *******************************************************************************/ + + +/* ************************************* +* Tool functions +***************************************/ +ZSTDLIBv07_API unsigned ZBUFFv07_isError(size_t errorCode); +ZSTDLIBv07_API const char* ZBUFFv07_getErrorName(size_t errorCode); + +/** Functions below provide recommended buffer sizes for Compression or Decompression operations. +* These sizes are just hints, they tend to offer better latency */ +ZSTDLIBv07_API size_t ZBUFFv07_recommendedDInSize(void); +ZSTDLIBv07_API size_t ZBUFFv07_recommendedDOutSize(void); + + +/*-************************************* +* Constants +***************************************/ +#define ZSTDv07_MAGICNUMBER 0xFD2FB527 /* v0.7 */ + + +#if defined (__cplusplus) +} +#endif + +#endif /* ZSTDv07_H_235446 */ +/**** ended inlining zstd_v07.h ****/ +#endif + +/** ZSTD_isLegacy() : + @return : > 0 if supported by legacy decoder. 0 otherwise. + return value is the version. +*/ +MEM_STATIC unsigned ZSTD_isLegacy(const void* src, size_t srcSize) +{ + U32 magicNumberLE; + if (srcSize<4) return 0; + magicNumberLE = MEM_readLE32(src); + switch(magicNumberLE) + { +#if (ZSTD_LEGACY_SUPPORT <= 1) + case ZSTDv01_magicNumberLE:return 1; +#endif +#if (ZSTD_LEGACY_SUPPORT <= 2) + case ZSTDv02_magicNumber : return 2; +#endif +#if (ZSTD_LEGACY_SUPPORT <= 3) + case ZSTDv03_magicNumber : return 3; +#endif +#if (ZSTD_LEGACY_SUPPORT <= 4) + case ZSTDv04_magicNumber : return 4; +#endif +#if (ZSTD_LEGACY_SUPPORT <= 5) + case ZSTDv05_MAGICNUMBER : return 5; +#endif +#if (ZSTD_LEGACY_SUPPORT <= 6) + case ZSTDv06_MAGICNUMBER : return 6; +#endif +#if (ZSTD_LEGACY_SUPPORT <= 7) + case ZSTDv07_MAGICNUMBER : return 7; +#endif + default : return 0; + } +} + + +MEM_STATIC unsigned long long ZSTD_getDecompressedSize_legacy(const void* src, size_t srcSize) +{ + U32 const version = ZSTD_isLegacy(src, srcSize); + if (version < 5) return 0; /* no decompressed size in frame header, or not a legacy format */ +#if (ZSTD_LEGACY_SUPPORT <= 5) + if (version==5) { + ZSTDv05_parameters fParams; + size_t const frResult = ZSTDv05_getFrameParams(&fParams, src, srcSize); + if (frResult != 0) return 0; + return fParams.srcSize; + } +#endif +#if (ZSTD_LEGACY_SUPPORT <= 6) + if (version==6) { + ZSTDv06_frameParams fParams; + size_t const frResult = ZSTDv06_getFrameParams(&fParams, src, srcSize); + if (frResult != 0) return 0; + return fParams.frameContentSize; + } +#endif +#if (ZSTD_LEGACY_SUPPORT <= 7) + if (version==7) { + ZSTDv07_frameParams fParams; + size_t const frResult = ZSTDv07_getFrameParams(&fParams, src, srcSize); + if (frResult != 0) return 0; + return fParams.frameContentSize; + } +#endif + return 0; /* should not be possible */ +} + + +MEM_STATIC size_t ZSTD_decompressLegacy( + void* dst, size_t dstCapacity, + const void* src, size_t compressedSize, + const void* dict,size_t dictSize) +{ + U32 const version = ZSTD_isLegacy(src, compressedSize); + char x; + /* Avoid passing NULL to legacy decoding. */ + if (dst == NULL) { + assert(dstCapacity == 0); + dst = &x; + } + if (src == NULL) { + assert(compressedSize == 0); + src = &x; + } + if (dict == NULL) { + assert(dictSize == 0); + dict = &x; + } + (void)dst; (void)dstCapacity; (void)dict; (void)dictSize; /* unused when ZSTD_LEGACY_SUPPORT >= 8 */ + switch(version) + { +#if (ZSTD_LEGACY_SUPPORT <= 1) + case 1 : + return ZSTDv01_decompress(dst, dstCapacity, src, compressedSize); +#endif +#if (ZSTD_LEGACY_SUPPORT <= 2) + case 2 : + return ZSTDv02_decompress(dst, dstCapacity, src, compressedSize); +#endif +#if (ZSTD_LEGACY_SUPPORT <= 3) + case 3 : + return ZSTDv03_decompress(dst, dstCapacity, src, compressedSize); +#endif +#if (ZSTD_LEGACY_SUPPORT <= 4) + case 4 : + return ZSTDv04_decompress(dst, dstCapacity, src, compressedSize); +#endif +#if (ZSTD_LEGACY_SUPPORT <= 5) + case 5 : + { size_t result; + ZSTDv05_DCtx* const zd = ZSTDv05_createDCtx(); + if (zd==NULL) return ERROR(memory_allocation); + result = ZSTDv05_decompress_usingDict(zd, dst, dstCapacity, src, compressedSize, dict, dictSize); + ZSTDv05_freeDCtx(zd); + return result; + } +#endif +#if (ZSTD_LEGACY_SUPPORT <= 6) + case 6 : + { size_t result; + ZSTDv06_DCtx* const zd = ZSTDv06_createDCtx(); + if (zd==NULL) return ERROR(memory_allocation); + result = ZSTDv06_decompress_usingDict(zd, dst, dstCapacity, src, compressedSize, dict, dictSize); + ZSTDv06_freeDCtx(zd); + return result; + } +#endif +#if (ZSTD_LEGACY_SUPPORT <= 7) + case 7 : + { size_t result; + ZSTDv07_DCtx* const zd = ZSTDv07_createDCtx(); + if (zd==NULL) return ERROR(memory_allocation); + result = ZSTDv07_decompress_usingDict(zd, dst, dstCapacity, src, compressedSize, dict, dictSize); + ZSTDv07_freeDCtx(zd); + return result; + } +#endif + default : + return ERROR(prefix_unknown); + } +} + +MEM_STATIC ZSTD_frameSizeInfo ZSTD_findFrameSizeInfoLegacy(const void *src, size_t srcSize) +{ + ZSTD_frameSizeInfo frameSizeInfo; + U32 const version = ZSTD_isLegacy(src, srcSize); + switch(version) + { +#if (ZSTD_LEGACY_SUPPORT <= 1) + case 1 : + ZSTDv01_findFrameSizeInfoLegacy(src, srcSize, + &frameSizeInfo.compressedSize, + &frameSizeInfo.decompressedBound); + break; +#endif +#if (ZSTD_LEGACY_SUPPORT <= 2) + case 2 : + ZSTDv02_findFrameSizeInfoLegacy(src, srcSize, + &frameSizeInfo.compressedSize, + &frameSizeInfo.decompressedBound); + break; +#endif +#if (ZSTD_LEGACY_SUPPORT <= 3) + case 3 : + ZSTDv03_findFrameSizeInfoLegacy(src, srcSize, + &frameSizeInfo.compressedSize, + &frameSizeInfo.decompressedBound); + break; +#endif +#if (ZSTD_LEGACY_SUPPORT <= 4) + case 4 : + ZSTDv04_findFrameSizeInfoLegacy(src, srcSize, + &frameSizeInfo.compressedSize, + &frameSizeInfo.decompressedBound); + break; +#endif +#if (ZSTD_LEGACY_SUPPORT <= 5) + case 5 : + ZSTDv05_findFrameSizeInfoLegacy(src, srcSize, + &frameSizeInfo.compressedSize, + &frameSizeInfo.decompressedBound); + break; +#endif +#if (ZSTD_LEGACY_SUPPORT <= 6) + case 6 : + ZSTDv06_findFrameSizeInfoLegacy(src, srcSize, + &frameSizeInfo.compressedSize, + &frameSizeInfo.decompressedBound); + break; +#endif +#if (ZSTD_LEGACY_SUPPORT <= 7) + case 7 : + ZSTDv07_findFrameSizeInfoLegacy(src, srcSize, + &frameSizeInfo.compressedSize, + &frameSizeInfo.decompressedBound); + break; +#endif + default : + frameSizeInfo.compressedSize = ERROR(prefix_unknown); + frameSizeInfo.decompressedBound = ZSTD_CONTENTSIZE_ERROR; + break; + } + if (!ZSTD_isError(frameSizeInfo.compressedSize) && frameSizeInfo.compressedSize > srcSize) { + frameSizeInfo.compressedSize = ERROR(srcSize_wrong); + frameSizeInfo.decompressedBound = ZSTD_CONTENTSIZE_ERROR; + } + /* In all cases, decompressedBound == nbBlocks * ZSTD_BLOCKSIZE_MAX. + * So we can compute nbBlocks without having to change every function. + */ + if (frameSizeInfo.decompressedBound != ZSTD_CONTENTSIZE_ERROR) { + assert((frameSizeInfo.decompressedBound & (ZSTD_BLOCKSIZE_MAX - 1)) == 0); + frameSizeInfo.nbBlocks = (size_t)(frameSizeInfo.decompressedBound / ZSTD_BLOCKSIZE_MAX); + } + return frameSizeInfo; +} + +MEM_STATIC size_t ZSTD_findFrameCompressedSizeLegacy(const void *src, size_t srcSize) +{ + ZSTD_frameSizeInfo frameSizeInfo = ZSTD_findFrameSizeInfoLegacy(src, srcSize); + return frameSizeInfo.compressedSize; +} + +MEM_STATIC size_t ZSTD_freeLegacyStreamContext(void* legacyContext, U32 version) +{ + switch(version) + { + default : + case 1 : + case 2 : + case 3 : + (void)legacyContext; + return ERROR(version_unsupported); +#if (ZSTD_LEGACY_SUPPORT <= 4) + case 4 : return ZBUFFv04_freeDCtx((ZBUFFv04_DCtx*)legacyContext); +#endif +#if (ZSTD_LEGACY_SUPPORT <= 5) + case 5 : return ZBUFFv05_freeDCtx((ZBUFFv05_DCtx*)legacyContext); +#endif +#if (ZSTD_LEGACY_SUPPORT <= 6) + case 6 : return ZBUFFv06_freeDCtx((ZBUFFv06_DCtx*)legacyContext); +#endif +#if (ZSTD_LEGACY_SUPPORT <= 7) + case 7 : return ZBUFFv07_freeDCtx((ZBUFFv07_DCtx*)legacyContext); +#endif + } +} + + +MEM_STATIC size_t ZSTD_initLegacyStream(void** legacyContext, U32 prevVersion, U32 newVersion, + const void* dict, size_t dictSize) +{ + char x; + /* Avoid passing NULL to legacy decoding. */ + if (dict == NULL) { + assert(dictSize == 0); + dict = &x; + } + DEBUGLOG(5, "ZSTD_initLegacyStream for v0.%u", newVersion); + if (prevVersion != newVersion) ZSTD_freeLegacyStreamContext(*legacyContext, prevVersion); + switch(newVersion) + { + default : + case 1 : + case 2 : + case 3 : + (void)dict; (void)dictSize; + return 0; +#if (ZSTD_LEGACY_SUPPORT <= 4) + case 4 : + { + ZBUFFv04_DCtx* dctx = (prevVersion != newVersion) ? ZBUFFv04_createDCtx() : (ZBUFFv04_DCtx*)*legacyContext; + if (dctx==NULL) return ERROR(memory_allocation); + ZBUFFv04_decompressInit(dctx); + ZBUFFv04_decompressWithDictionary(dctx, dict, dictSize); + *legacyContext = dctx; + return 0; + } +#endif +#if (ZSTD_LEGACY_SUPPORT <= 5) + case 5 : + { + ZBUFFv05_DCtx* dctx = (prevVersion != newVersion) ? ZBUFFv05_createDCtx() : (ZBUFFv05_DCtx*)*legacyContext; + if (dctx==NULL) return ERROR(memory_allocation); + ZBUFFv05_decompressInitDictionary(dctx, dict, dictSize); + *legacyContext = dctx; + return 0; + } +#endif +#if (ZSTD_LEGACY_SUPPORT <= 6) + case 6 : + { + ZBUFFv06_DCtx* dctx = (prevVersion != newVersion) ? ZBUFFv06_createDCtx() : (ZBUFFv06_DCtx*)*legacyContext; + if (dctx==NULL) return ERROR(memory_allocation); + ZBUFFv06_decompressInitDictionary(dctx, dict, dictSize); + *legacyContext = dctx; + return 0; + } +#endif +#if (ZSTD_LEGACY_SUPPORT <= 7) + case 7 : + { + ZBUFFv07_DCtx* dctx = (prevVersion != newVersion) ? ZBUFFv07_createDCtx() : (ZBUFFv07_DCtx*)*legacyContext; + if (dctx==NULL) return ERROR(memory_allocation); + ZBUFFv07_decompressInitDictionary(dctx, dict, dictSize); + *legacyContext = dctx; + return 0; + } +#endif + } +} + + + +MEM_STATIC size_t ZSTD_decompressLegacyStream(void* legacyContext, U32 version, + ZSTD_outBuffer* output, ZSTD_inBuffer* input) +{ + static char x; + /* Avoid passing NULL to legacy decoding. */ + if (output->dst == NULL) { + assert(output->size == 0); + output->dst = &x; + } + if (input->src == NULL) { + assert(input->size == 0); + input->src = &x; + } + DEBUGLOG(5, "ZSTD_decompressLegacyStream for v0.%u", version); + switch(version) + { + default : + case 1 : + case 2 : + case 3 : + (void)legacyContext; (void)output; (void)input; + return ERROR(version_unsupported); +#if (ZSTD_LEGACY_SUPPORT <= 4) + case 4 : + { + ZBUFFv04_DCtx* dctx = (ZBUFFv04_DCtx*) legacyContext; + const void* src = (const char*)input->src + input->pos; + size_t readSize = input->size - input->pos; + void* dst = (char*)output->dst + output->pos; + size_t decodedSize = output->size - output->pos; + size_t const hintSize = ZBUFFv04_decompressContinue(dctx, dst, &decodedSize, src, &readSize); + output->pos += decodedSize; + input->pos += readSize; + return hintSize; + } +#endif +#if (ZSTD_LEGACY_SUPPORT <= 5) + case 5 : + { + ZBUFFv05_DCtx* dctx = (ZBUFFv05_DCtx*) legacyContext; + const void* src = (const char*)input->src + input->pos; + size_t readSize = input->size - input->pos; + void* dst = (char*)output->dst + output->pos; + size_t decodedSize = output->size - output->pos; + size_t const hintSize = ZBUFFv05_decompressContinue(dctx, dst, &decodedSize, src, &readSize); + output->pos += decodedSize; + input->pos += readSize; + return hintSize; + } +#endif +#if (ZSTD_LEGACY_SUPPORT <= 6) + case 6 : + { + ZBUFFv06_DCtx* dctx = (ZBUFFv06_DCtx*) legacyContext; + const void* src = (const char*)input->src + input->pos; + size_t readSize = input->size - input->pos; + void* dst = (char*)output->dst + output->pos; + size_t decodedSize = output->size - output->pos; + size_t const hintSize = ZBUFFv06_decompressContinue(dctx, dst, &decodedSize, src, &readSize); + output->pos += decodedSize; + input->pos += readSize; + return hintSize; + } +#endif +#if (ZSTD_LEGACY_SUPPORT <= 7) + case 7 : + { + ZBUFFv07_DCtx* dctx = (ZBUFFv07_DCtx*) legacyContext; + const void* src = (const char*)input->src + input->pos; + size_t readSize = input->size - input->pos; + void* dst = (char*)output->dst + output->pos; + size_t decodedSize = output->size - output->pos; + size_t const hintSize = ZBUFFv07_decompressContinue(dctx, dst, &decodedSize, src, &readSize); + output->pos += decodedSize; + input->pos += readSize; + return hintSize; + } +#endif + } +} + + +#if defined (__cplusplus) +} +#endif + +#endif /* ZSTD_LEGACY_H */ +/**** ended inlining ../legacy/zstd_legacy.h ****/ +#endif + + + +/*-******************************************************* +* Types +*********************************************************/ +struct ZSTD_DDict_s { + void* dictBuffer; + const void* dictContent; + size_t dictSize; + ZSTD_entropyDTables_t entropy; + U32 dictID; + U32 entropyPresent; + ZSTD_customMem cMem; +}; /* typedef'd to ZSTD_DDict within "zstd.h" */ + +const void* ZSTD_DDict_dictContent(const ZSTD_DDict* ddict) +{ + assert(ddict != NULL); + return ddict->dictContent; +} + +size_t ZSTD_DDict_dictSize(const ZSTD_DDict* ddict) +{ + assert(ddict != NULL); + return ddict->dictSize; +} + +void ZSTD_copyDDictParameters(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict) +{ + DEBUGLOG(4, "ZSTD_copyDDictParameters"); + assert(dctx != NULL); + assert(ddict != NULL); + dctx->dictID = ddict->dictID; + dctx->prefixStart = ddict->dictContent; + dctx->virtualStart = ddict->dictContent; + dctx->dictEnd = (const BYTE*)ddict->dictContent + ddict->dictSize; + dctx->previousDstEnd = dctx->dictEnd; +#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION + dctx->dictContentBeginForFuzzing = dctx->prefixStart; + dctx->dictContentEndForFuzzing = dctx->previousDstEnd; +#endif + if (ddict->entropyPresent) { + dctx->litEntropy = 1; + dctx->fseEntropy = 1; + dctx->LLTptr = ddict->entropy.LLTable; + dctx->MLTptr = ddict->entropy.MLTable; + dctx->OFTptr = ddict->entropy.OFTable; + dctx->HUFptr = ddict->entropy.hufTable; + dctx->entropy.rep[0] = ddict->entropy.rep[0]; + dctx->entropy.rep[1] = ddict->entropy.rep[1]; + dctx->entropy.rep[2] = ddict->entropy.rep[2]; + } else { + dctx->litEntropy = 0; + dctx->fseEntropy = 0; + } +} + + +static size_t +ZSTD_loadEntropy_intoDDict(ZSTD_DDict* ddict, + ZSTD_dictContentType_e dictContentType) +{ + ddict->dictID = 0; + ddict->entropyPresent = 0; + if (dictContentType == ZSTD_dct_rawContent) return 0; + + if (ddict->dictSize < 8) { + if (dictContentType == ZSTD_dct_fullDict) + return ERROR(dictionary_corrupted); /* only accept specified dictionaries */ + return 0; /* pure content mode */ + } + { U32 const magic = MEM_readLE32(ddict->dictContent); + if (magic != ZSTD_MAGIC_DICTIONARY) { + if (dictContentType == ZSTD_dct_fullDict) + return ERROR(dictionary_corrupted); /* only accept specified dictionaries */ + return 0; /* pure content mode */ + } + } + ddict->dictID = MEM_readLE32((const char*)ddict->dictContent + ZSTD_FRAMEIDSIZE); + + /* load entropy tables */ + RETURN_ERROR_IF(ZSTD_isError(ZSTD_loadDEntropy( + &ddict->entropy, ddict->dictContent, ddict->dictSize)), + dictionary_corrupted, ""); + ddict->entropyPresent = 1; + return 0; +} + + +static size_t ZSTD_initDDict_internal(ZSTD_DDict* ddict, + const void* dict, size_t dictSize, + ZSTD_dictLoadMethod_e dictLoadMethod, + ZSTD_dictContentType_e dictContentType) +{ + if ((dictLoadMethod == ZSTD_dlm_byRef) || (!dict) || (!dictSize)) { + ddict->dictBuffer = NULL; + ddict->dictContent = dict; + if (!dict) dictSize = 0; + } else { + void* const internalBuffer = ZSTD_customMalloc(dictSize, ddict->cMem); + ddict->dictBuffer = internalBuffer; + ddict->dictContent = internalBuffer; + if (!internalBuffer) return ERROR(memory_allocation); + ZSTD_memcpy(internalBuffer, dict, dictSize); + } + ddict->dictSize = dictSize; + ddict->entropy.hufTable[0] = (HUF_DTable)((ZSTD_HUFFDTABLE_CAPACITY_LOG)*0x1000001); /* cover both little and big endian */ + + /* parse dictionary content */ + FORWARD_IF_ERROR( ZSTD_loadEntropy_intoDDict(ddict, dictContentType) , ""); + + return 0; +} + +ZSTD_DDict* ZSTD_createDDict_advanced(const void* dict, size_t dictSize, + ZSTD_dictLoadMethod_e dictLoadMethod, + ZSTD_dictContentType_e dictContentType, + ZSTD_customMem customMem) +{ + if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL; + + { ZSTD_DDict* const ddict = (ZSTD_DDict*) ZSTD_customMalloc(sizeof(ZSTD_DDict), customMem); + if (ddict == NULL) return NULL; + ddict->cMem = customMem; + { size_t const initResult = ZSTD_initDDict_internal(ddict, + dict, dictSize, + dictLoadMethod, dictContentType); + if (ZSTD_isError(initResult)) { + ZSTD_freeDDict(ddict); + return NULL; + } } + return ddict; + } +} + +/*! ZSTD_createDDict() : +* Create a digested dictionary, to start decompression without startup delay. +* `dict` content is copied inside DDict. +* Consequently, `dict` can be released after `ZSTD_DDict` creation */ +ZSTD_DDict* ZSTD_createDDict(const void* dict, size_t dictSize) +{ + ZSTD_customMem const allocator = { NULL, NULL, NULL }; + return ZSTD_createDDict_advanced(dict, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto, allocator); +} + +/*! ZSTD_createDDict_byReference() : + * Create a digested dictionary, to start decompression without startup delay. + * Dictionary content is simply referenced, it will be accessed during decompression. + * Warning : dictBuffer must outlive DDict (DDict must be freed before dictBuffer) */ +ZSTD_DDict* ZSTD_createDDict_byReference(const void* dictBuffer, size_t dictSize) +{ + ZSTD_customMem const allocator = { NULL, NULL, NULL }; + return ZSTD_createDDict_advanced(dictBuffer, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto, allocator); +} + + +const ZSTD_DDict* ZSTD_initStaticDDict( + void* sBuffer, size_t sBufferSize, + const void* dict, size_t dictSize, + ZSTD_dictLoadMethod_e dictLoadMethod, + ZSTD_dictContentType_e dictContentType) +{ + size_t const neededSpace = sizeof(ZSTD_DDict) + + (dictLoadMethod == ZSTD_dlm_byRef ? 0 : dictSize); + ZSTD_DDict* const ddict = (ZSTD_DDict*)sBuffer; + assert(sBuffer != NULL); + assert(dict != NULL); + if ((size_t)sBuffer & 7) return NULL; /* 8-aligned */ + if (sBufferSize < neededSpace) return NULL; + if (dictLoadMethod == ZSTD_dlm_byCopy) { + ZSTD_memcpy(ddict+1, dict, dictSize); /* local copy */ + dict = ddict+1; + } + if (ZSTD_isError( ZSTD_initDDict_internal(ddict, + dict, dictSize, + ZSTD_dlm_byRef, dictContentType) )) + return NULL; + return ddict; +} + + +size_t ZSTD_freeDDict(ZSTD_DDict* ddict) +{ + if (ddict==NULL) return 0; /* support free on NULL */ + { ZSTD_customMem const cMem = ddict->cMem; + ZSTD_customFree(ddict->dictBuffer, cMem); + ZSTD_customFree(ddict, cMem); + return 0; + } +} + +/*! ZSTD_estimateDDictSize() : + * Estimate amount of memory that will be needed to create a dictionary for decompression. + * Note : dictionary created by reference using ZSTD_dlm_byRef are smaller */ +size_t ZSTD_estimateDDictSize(size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod) +{ + return sizeof(ZSTD_DDict) + (dictLoadMethod == ZSTD_dlm_byRef ? 0 : dictSize); +} + +size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict) +{ + if (ddict==NULL) return 0; /* support sizeof on NULL */ + return sizeof(*ddict) + (ddict->dictBuffer ? ddict->dictSize : 0) ; +} + +/*! ZSTD_getDictID_fromDDict() : + * Provides the dictID of the dictionary loaded into `ddict`. + * If @return == 0, the dictionary is not conformant to Zstandard specification, or empty. + * Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */ +unsigned ZSTD_getDictID_fromDDict(const ZSTD_DDict* ddict) +{ + if (ddict==NULL) return 0; + return ddict->dictID; +} +/**** ended inlining decompress/zstd_ddict.c ****/ +/**** start inlining decompress/zstd_decompress.c ****/ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + + +/* *************************************************************** +* Tuning parameters +*****************************************************************/ +/*! + * HEAPMODE : + * Select how default decompression function ZSTD_decompress() allocates its context, + * on stack (0), or into heap (1, default; requires malloc()). + * Note that functions with explicit context such as ZSTD_decompressDCtx() are unaffected. + */ +#ifndef ZSTD_HEAPMODE +# define ZSTD_HEAPMODE 1 +#endif + +/*! +* LEGACY_SUPPORT : +* if set to 1+, ZSTD_decompress() can decode older formats (v0.1+) +*/ +#ifndef ZSTD_LEGACY_SUPPORT +# define ZSTD_LEGACY_SUPPORT 0 +#endif + +/*! + * MAXWINDOWSIZE_DEFAULT : + * maximum window size accepted by DStream __by default__. + * Frames requiring more memory will be rejected. + * It's possible to set a different limit using ZSTD_DCtx_setMaxWindowSize(). + */ +#ifndef ZSTD_MAXWINDOWSIZE_DEFAULT +# define ZSTD_MAXWINDOWSIZE_DEFAULT (((U32)1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT) + 1) +#endif + +/*! + * NO_FORWARD_PROGRESS_MAX : + * maximum allowed nb of calls to ZSTD_decompressStream() + * without any forward progress + * (defined as: no byte read from input, and no byte flushed to output) + * before triggering an error. + */ +#ifndef ZSTD_NO_FORWARD_PROGRESS_MAX +# define ZSTD_NO_FORWARD_PROGRESS_MAX 16 +#endif + + +/*-******************************************************* +* Dependencies +*********************************************************/ +/**** skipping file: ../common/zstd_deps.h ****/ +/**** skipping file: ../common/allocations.h ****/ +/**** skipping file: ../common/error_private.h ****/ +/**** skipping file: ../common/zstd_internal.h ****/ +/**** skipping file: ../common/mem.h ****/ +/**** skipping file: ../common/bits.h ****/ +#define FSE_STATIC_LINKING_ONLY +/**** skipping file: ../common/fse.h ****/ +/**** skipping file: ../common/huf.h ****/ +/**** skipping file: ../common/xxhash.h ****/ +/**** skipping file: zstd_decompress_internal.h ****/ +/**** skipping file: zstd_ddict.h ****/ +/**** start inlining zstd_decompress_block.h ****/ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + + +#ifndef ZSTD_DEC_BLOCK_H +#define ZSTD_DEC_BLOCK_H + +/*-******************************************************* + * Dependencies + *********************************************************/ +/**** skipping file: ../common/zstd_deps.h ****/ +/**** skipping file: ../zstd.h ****/ +/**** skipping file: ../common/zstd_internal.h ****/ +/**** skipping file: zstd_decompress_internal.h ****/ + + +/* === Prototypes === */ + +/* note: prototypes already published within `zstd.h` : + * ZSTD_decompressBlock() + */ + +/* note: prototypes already published within `zstd_internal.h` : + * ZSTD_getcBlockSize() + * ZSTD_decodeSeqHeaders() + */ + + + /* Streaming state is used to inform allocation of the literal buffer */ +typedef enum { + not_streaming = 0, + is_streaming = 1 +} streaming_operation; + +/* ZSTD_decompressBlock_internal() : + * decompress block, starting at `src`, + * into destination buffer `dst`. + * @return : decompressed block size, + * or an error code (which can be tested using ZSTD_isError()) + */ +size_t ZSTD_decompressBlock_internal(ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, const streaming_operation streaming); + +/* ZSTD_buildFSETable() : + * generate FSE decoding table for one symbol (ll, ml or off) + * this function must be called with valid parameters only + * (dt is large enough, normalizedCounter distribution total is a power of 2, max is within range, etc.) + * in which case it cannot fail. + * The workspace must be 4-byte aligned and at least ZSTD_BUILD_FSE_TABLE_WKSP_SIZE bytes, which is + * defined in zstd_decompress_internal.h. + * Internal use only. + */ +void ZSTD_buildFSETable(ZSTD_seqSymbol* dt, + const short* normalizedCounter, unsigned maxSymbolValue, + const U32* baseValue, const U8* nbAdditionalBits, + unsigned tableLog, void* wksp, size_t wkspSize, + int bmi2); + +/* Internal definition of ZSTD_decompressBlock() to avoid deprecation warnings. */ +size_t ZSTD_decompressBlock_deprecated(ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize); + + +#endif /* ZSTD_DEC_BLOCK_H */ +/**** ended inlining zstd_decompress_block.h ****/ + +#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1) +/**** skipping file: ../legacy/zstd_legacy.h ****/ +#endif + + + +/************************************* + * Multiple DDicts Hashset internals * + *************************************/ + +#define DDICT_HASHSET_MAX_LOAD_FACTOR_COUNT_MULT 4 +#define DDICT_HASHSET_MAX_LOAD_FACTOR_SIZE_MULT 3 /* These two constants represent SIZE_MULT/COUNT_MULT load factor without using a float. + * Currently, that means a 0.75 load factor. + * So, if count * COUNT_MULT / size * SIZE_MULT != 0, then we've exceeded + * the load factor of the ddict hash set. + */ + +#define DDICT_HASHSET_TABLE_BASE_SIZE 64 +#define DDICT_HASHSET_RESIZE_FACTOR 2 + +/* Hash function to determine starting position of dict insertion within the table + * Returns an index between [0, hashSet->ddictPtrTableSize] + */ +static size_t ZSTD_DDictHashSet_getIndex(const ZSTD_DDictHashSet* hashSet, U32 dictID) { + const U64 hash = XXH64(&dictID, sizeof(U32), 0); + /* DDict ptr table size is a multiple of 2, use size - 1 as mask to get index within [0, hashSet->ddictPtrTableSize) */ + return hash & (hashSet->ddictPtrTableSize - 1); +} + +/* Adds DDict to a hashset without resizing it. + * If inserting a DDict with a dictID that already exists in the set, replaces the one in the set. + * Returns 0 if successful, or a zstd error code if something went wrong. + */ +static size_t ZSTD_DDictHashSet_emplaceDDict(ZSTD_DDictHashSet* hashSet, const ZSTD_DDict* ddict) { + const U32 dictID = ZSTD_getDictID_fromDDict(ddict); + size_t idx = ZSTD_DDictHashSet_getIndex(hashSet, dictID); + const size_t idxRangeMask = hashSet->ddictPtrTableSize - 1; + RETURN_ERROR_IF(hashSet->ddictPtrCount == hashSet->ddictPtrTableSize, GENERIC, "Hash set is full!"); + DEBUGLOG(4, "Hashed index: for dictID: %u is %zu", dictID, idx); + while (hashSet->ddictPtrTable[idx] != NULL) { + /* Replace existing ddict if inserting ddict with same dictID */ + if (ZSTD_getDictID_fromDDict(hashSet->ddictPtrTable[idx]) == dictID) { + DEBUGLOG(4, "DictID already exists, replacing rather than adding"); + hashSet->ddictPtrTable[idx] = ddict; + return 0; + } + idx &= idxRangeMask; + idx++; + } + DEBUGLOG(4, "Final idx after probing for dictID %u is: %zu", dictID, idx); + hashSet->ddictPtrTable[idx] = ddict; + hashSet->ddictPtrCount++; + return 0; +} + +/* Expands hash table by factor of DDICT_HASHSET_RESIZE_FACTOR and + * rehashes all values, allocates new table, frees old table. + * Returns 0 on success, otherwise a zstd error code. + */ +static size_t ZSTD_DDictHashSet_expand(ZSTD_DDictHashSet* hashSet, ZSTD_customMem customMem) { + size_t newTableSize = hashSet->ddictPtrTableSize * DDICT_HASHSET_RESIZE_FACTOR; + const ZSTD_DDict** newTable = (const ZSTD_DDict**)ZSTD_customCalloc(sizeof(ZSTD_DDict*) * newTableSize, customMem); + const ZSTD_DDict** oldTable = hashSet->ddictPtrTable; + size_t oldTableSize = hashSet->ddictPtrTableSize; + size_t i; + + DEBUGLOG(4, "Expanding DDict hash table! Old size: %zu new size: %zu", oldTableSize, newTableSize); + RETURN_ERROR_IF(!newTable, memory_allocation, "Expanded hashset allocation failed!"); + hashSet->ddictPtrTable = newTable; + hashSet->ddictPtrTableSize = newTableSize; + hashSet->ddictPtrCount = 0; + for (i = 0; i < oldTableSize; ++i) { + if (oldTable[i] != NULL) { + FORWARD_IF_ERROR(ZSTD_DDictHashSet_emplaceDDict(hashSet, oldTable[i]), ""); + } + } + ZSTD_customFree((void*)oldTable, customMem); + DEBUGLOG(4, "Finished re-hash"); + return 0; +} + +/* Fetches a DDict with the given dictID + * Returns the ZSTD_DDict* with the requested dictID. If it doesn't exist, then returns NULL. + */ +static const ZSTD_DDict* ZSTD_DDictHashSet_getDDict(ZSTD_DDictHashSet* hashSet, U32 dictID) { + size_t idx = ZSTD_DDictHashSet_getIndex(hashSet, dictID); + const size_t idxRangeMask = hashSet->ddictPtrTableSize - 1; + DEBUGLOG(4, "Hashed index: for dictID: %u is %zu", dictID, idx); + for (;;) { + size_t currDictID = ZSTD_getDictID_fromDDict(hashSet->ddictPtrTable[idx]); + if (currDictID == dictID || currDictID == 0) { + /* currDictID == 0 implies a NULL ddict entry */ + break; + } else { + idx &= idxRangeMask; /* Goes to start of table when we reach the end */ + idx++; + } + } + DEBUGLOG(4, "Final idx after probing for dictID %u is: %zu", dictID, idx); + return hashSet->ddictPtrTable[idx]; +} + +/* Allocates space for and returns a ddict hash set + * The hash set's ZSTD_DDict* table has all values automatically set to NULL to begin with. + * Returns NULL if allocation failed. + */ +static ZSTD_DDictHashSet* ZSTD_createDDictHashSet(ZSTD_customMem customMem) { + ZSTD_DDictHashSet* ret = (ZSTD_DDictHashSet*)ZSTD_customMalloc(sizeof(ZSTD_DDictHashSet), customMem); + DEBUGLOG(4, "Allocating new hash set"); + if (!ret) + return NULL; + ret->ddictPtrTable = (const ZSTD_DDict**)ZSTD_customCalloc(DDICT_HASHSET_TABLE_BASE_SIZE * sizeof(ZSTD_DDict*), customMem); + if (!ret->ddictPtrTable) { + ZSTD_customFree(ret, customMem); + return NULL; + } + ret->ddictPtrTableSize = DDICT_HASHSET_TABLE_BASE_SIZE; + ret->ddictPtrCount = 0; + return ret; +} + +/* Frees the table of ZSTD_DDict* within a hashset, then frees the hashset itself. + * Note: The ZSTD_DDict* within the table are NOT freed. + */ +static void ZSTD_freeDDictHashSet(ZSTD_DDictHashSet* hashSet, ZSTD_customMem customMem) { + DEBUGLOG(4, "Freeing ddict hash set"); + if (hashSet && hashSet->ddictPtrTable) { + ZSTD_customFree((void*)hashSet->ddictPtrTable, customMem); + } + if (hashSet) { + ZSTD_customFree(hashSet, customMem); + } +} + +/* Public function: Adds a DDict into the ZSTD_DDictHashSet, possibly triggering a resize of the hash set. + * Returns 0 on success, or a ZSTD error. + */ +static size_t ZSTD_DDictHashSet_addDDict(ZSTD_DDictHashSet* hashSet, const ZSTD_DDict* ddict, ZSTD_customMem customMem) { + DEBUGLOG(4, "Adding dict ID: %u to hashset with - Count: %zu Tablesize: %zu", ZSTD_getDictID_fromDDict(ddict), hashSet->ddictPtrCount, hashSet->ddictPtrTableSize); + if (hashSet->ddictPtrCount * DDICT_HASHSET_MAX_LOAD_FACTOR_COUNT_MULT / hashSet->ddictPtrTableSize * DDICT_HASHSET_MAX_LOAD_FACTOR_SIZE_MULT != 0) { + FORWARD_IF_ERROR(ZSTD_DDictHashSet_expand(hashSet, customMem), ""); + } + FORWARD_IF_ERROR(ZSTD_DDictHashSet_emplaceDDict(hashSet, ddict), ""); + return 0; +} + +/*-************************************************************* +* Context management +***************************************************************/ +size_t ZSTD_sizeof_DCtx (const ZSTD_DCtx* dctx) +{ + if (dctx==NULL) return 0; /* support sizeof NULL */ + return sizeof(*dctx) + + ZSTD_sizeof_DDict(dctx->ddictLocal) + + dctx->inBuffSize + dctx->outBuffSize; +} + +size_t ZSTD_estimateDCtxSize(void) { return sizeof(ZSTD_DCtx); } + + +static size_t ZSTD_startingInputLength(ZSTD_format_e format) +{ + size_t const startingInputLength = ZSTD_FRAMEHEADERSIZE_PREFIX(format); + /* only supports formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless */ + assert( (format == ZSTD_f_zstd1) || (format == ZSTD_f_zstd1_magicless) ); + return startingInputLength; +} + +static void ZSTD_DCtx_resetParameters(ZSTD_DCtx* dctx) +{ + assert(dctx->streamStage == zdss_init); + dctx->format = ZSTD_f_zstd1; + dctx->maxWindowSize = ZSTD_MAXWINDOWSIZE_DEFAULT; + dctx->outBufferMode = ZSTD_bm_buffered; + dctx->forceIgnoreChecksum = ZSTD_d_validateChecksum; + dctx->refMultipleDDicts = ZSTD_rmd_refSingleDDict; + dctx->disableHufAsm = 0; + dctx->maxBlockSizeParam = 0; +} + +static void ZSTD_initDCtx_internal(ZSTD_DCtx* dctx) +{ + dctx->staticSize = 0; + dctx->ddict = NULL; + dctx->ddictLocal = NULL; + dctx->dictEnd = NULL; + dctx->ddictIsCold = 0; + dctx->dictUses = ZSTD_dont_use; + dctx->inBuff = NULL; + dctx->inBuffSize = 0; + dctx->outBuffSize = 0; + dctx->streamStage = zdss_init; +#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1) + dctx->legacyContext = NULL; + dctx->previousLegacyVersion = 0; +#endif + dctx->noForwardProgress = 0; + dctx->oversizedDuration = 0; + dctx->isFrameDecompression = 1; +#if DYNAMIC_BMI2 + dctx->bmi2 = ZSTD_cpuSupportsBmi2(); +#endif + dctx->ddictSet = NULL; + ZSTD_DCtx_resetParameters(dctx); +#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION + dctx->dictContentEndForFuzzing = NULL; +#endif +} + +ZSTD_DCtx* ZSTD_initStaticDCtx(void *workspace, size_t workspaceSize) +{ + ZSTD_DCtx* const dctx = (ZSTD_DCtx*) workspace; + + if ((size_t)workspace & 7) return NULL; /* 8-aligned */ + if (workspaceSize < sizeof(ZSTD_DCtx)) return NULL; /* minimum size */ + + ZSTD_initDCtx_internal(dctx); + dctx->staticSize = workspaceSize; + dctx->inBuff = (char*)(dctx+1); + return dctx; +} + +static ZSTD_DCtx* ZSTD_createDCtx_internal(ZSTD_customMem customMem) { + if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL; + + { ZSTD_DCtx* const dctx = (ZSTD_DCtx*)ZSTD_customMalloc(sizeof(*dctx), customMem); + if (!dctx) return NULL; + dctx->customMem = customMem; + ZSTD_initDCtx_internal(dctx); + return dctx; + } +} + +ZSTD_DCtx* ZSTD_createDCtx_advanced(ZSTD_customMem customMem) +{ + return ZSTD_createDCtx_internal(customMem); +} + +ZSTD_DCtx* ZSTD_createDCtx(void) +{ + DEBUGLOG(3, "ZSTD_createDCtx"); + return ZSTD_createDCtx_internal(ZSTD_defaultCMem); +} + +static void ZSTD_clearDict(ZSTD_DCtx* dctx) +{ + ZSTD_freeDDict(dctx->ddictLocal); + dctx->ddictLocal = NULL; + dctx->ddict = NULL; + dctx->dictUses = ZSTD_dont_use; +} + +size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx) +{ + if (dctx==NULL) return 0; /* support free on NULL */ + RETURN_ERROR_IF(dctx->staticSize, memory_allocation, "not compatible with static DCtx"); + { ZSTD_customMem const cMem = dctx->customMem; + ZSTD_clearDict(dctx); + ZSTD_customFree(dctx->inBuff, cMem); + dctx->inBuff = NULL; +#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1) + if (dctx->legacyContext) + ZSTD_freeLegacyStreamContext(dctx->legacyContext, dctx->previousLegacyVersion); +#endif + if (dctx->ddictSet) { + ZSTD_freeDDictHashSet(dctx->ddictSet, cMem); + dctx->ddictSet = NULL; + } + ZSTD_customFree(dctx, cMem); + return 0; + } +} + +/* no longer useful */ +void ZSTD_copyDCtx(ZSTD_DCtx* dstDCtx, const ZSTD_DCtx* srcDCtx) +{ + size_t const toCopy = (size_t)((char*)(&dstDCtx->inBuff) - (char*)dstDCtx); + ZSTD_memcpy(dstDCtx, srcDCtx, toCopy); /* no need to copy workspace */ +} + +/* Given a dctx with a digested frame params, re-selects the correct ZSTD_DDict based on + * the requested dict ID from the frame. If there exists a reference to the correct ZSTD_DDict, then + * accordingly sets the ddict to be used to decompress the frame. + * + * If no DDict is found, then no action is taken, and the ZSTD_DCtx::ddict remains as-is. + * + * ZSTD_d_refMultipleDDicts must be enabled for this function to be called. + */ +static void ZSTD_DCtx_selectFrameDDict(ZSTD_DCtx* dctx) { + assert(dctx->refMultipleDDicts && dctx->ddictSet); + DEBUGLOG(4, "Adjusting DDict based on requested dict ID from frame"); + if (dctx->ddict) { + const ZSTD_DDict* frameDDict = ZSTD_DDictHashSet_getDDict(dctx->ddictSet, dctx->fParams.dictID); + if (frameDDict) { + DEBUGLOG(4, "DDict found!"); + ZSTD_clearDict(dctx); + dctx->dictID = dctx->fParams.dictID; + dctx->ddict = frameDDict; + dctx->dictUses = ZSTD_use_indefinitely; + } + } +} + + +/*-************************************************************* + * Frame header decoding + ***************************************************************/ + +/*! ZSTD_isFrame() : + * Tells if the content of `buffer` starts with a valid Frame Identifier. + * Note : Frame Identifier is 4 bytes. If `size < 4`, @return will always be 0. + * Note 2 : Legacy Frame Identifiers are considered valid only if Legacy Support is enabled. + * Note 3 : Skippable Frame Identifiers are considered valid. */ +unsigned ZSTD_isFrame(const void* buffer, size_t size) +{ + if (size < ZSTD_FRAMEIDSIZE) return 0; + { U32 const magic = MEM_readLE32(buffer); + if (magic == ZSTD_MAGICNUMBER) return 1; + if ((magic & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) return 1; + } +#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1) + if (ZSTD_isLegacy(buffer, size)) return 1; +#endif + return 0; +} + +/*! ZSTD_isSkippableFrame() : + * Tells if the content of `buffer` starts with a valid Frame Identifier for a skippable frame. + * Note : Frame Identifier is 4 bytes. If `size < 4`, @return will always be 0. + */ +unsigned ZSTD_isSkippableFrame(const void* buffer, size_t size) +{ + if (size < ZSTD_FRAMEIDSIZE) return 0; + { U32 const magic = MEM_readLE32(buffer); + if ((magic & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) return 1; + } + return 0; +} + +/** ZSTD_frameHeaderSize_internal() : + * srcSize must be large enough to reach header size fields. + * note : only works for formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless. + * @return : size of the Frame Header + * or an error code, which can be tested with ZSTD_isError() */ +static size_t ZSTD_frameHeaderSize_internal(const void* src, size_t srcSize, ZSTD_format_e format) +{ + size_t const minInputSize = ZSTD_startingInputLength(format); + RETURN_ERROR_IF(srcSize < minInputSize, srcSize_wrong, ""); + + { BYTE const fhd = ((const BYTE*)src)[minInputSize-1]; + U32 const dictID= fhd & 3; + U32 const singleSegment = (fhd >> 5) & 1; + U32 const fcsId = fhd >> 6; + return minInputSize + !singleSegment + + ZSTD_did_fieldSize[dictID] + ZSTD_fcs_fieldSize[fcsId] + + (singleSegment && !fcsId); + } +} + +/** ZSTD_frameHeaderSize() : + * srcSize must be >= ZSTD_frameHeaderSize_prefix. + * @return : size of the Frame Header, + * or an error code (if srcSize is too small) */ +size_t ZSTD_frameHeaderSize(const void* src, size_t srcSize) +{ + return ZSTD_frameHeaderSize_internal(src, srcSize, ZSTD_f_zstd1); +} + + +/** ZSTD_getFrameHeader_advanced() : + * decode Frame Header, or require larger `srcSize`. + * note : only works for formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless + * @return : 0, `zfhPtr` is correctly filled, + * >0, `srcSize` is too small, value is wanted `srcSize` amount, +** or an error code, which can be tested using ZSTD_isError() */ +size_t ZSTD_getFrameHeader_advanced(ZSTD_FrameHeader* zfhPtr, const void* src, size_t srcSize, ZSTD_format_e format) +{ + const BYTE* ip = (const BYTE*)src; + size_t const minInputSize = ZSTD_startingInputLength(format); + + DEBUGLOG(5, "ZSTD_getFrameHeader_advanced: minInputSize = %zu, srcSize = %zu", minInputSize, srcSize); + + if (srcSize > 0) { + /* note : technically could be considered an assert(), since it's an invalid entry */ + RETURN_ERROR_IF(src==NULL, GENERIC, "invalid parameter : src==NULL, but srcSize>0"); + } + if (srcSize < minInputSize) { + if (srcSize > 0 && format != ZSTD_f_zstd1_magicless) { + /* when receiving less than @minInputSize bytes, + * control these bytes at least correspond to a supported magic number + * in order to error out early if they don't. + **/ + size_t const toCopy = MIN(4, srcSize); + unsigned char hbuf[4]; MEM_writeLE32(hbuf, ZSTD_MAGICNUMBER); + assert(src != NULL); + ZSTD_memcpy(hbuf, src, toCopy); + if ( MEM_readLE32(hbuf) != ZSTD_MAGICNUMBER ) { + /* not a zstd frame : let's check if it's a skippable frame */ + MEM_writeLE32(hbuf, ZSTD_MAGIC_SKIPPABLE_START); + ZSTD_memcpy(hbuf, src, toCopy); + if ((MEM_readLE32(hbuf) & ZSTD_MAGIC_SKIPPABLE_MASK) != ZSTD_MAGIC_SKIPPABLE_START) { + RETURN_ERROR(prefix_unknown, + "first bytes don't correspond to any supported magic number"); + } } } + return minInputSize; + } + + ZSTD_memset(zfhPtr, 0, sizeof(*zfhPtr)); /* not strictly necessary, but static analyzers may not understand that zfhPtr will be read only if return value is zero, since they are 2 different signals */ + if ( (format != ZSTD_f_zstd1_magicless) + && (MEM_readLE32(src) != ZSTD_MAGICNUMBER) ) { + if ((MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { + /* skippable frame */ + if (srcSize < ZSTD_SKIPPABLEHEADERSIZE) + return ZSTD_SKIPPABLEHEADERSIZE; /* magic number + frame length */ + ZSTD_memset(zfhPtr, 0, sizeof(*zfhPtr)); + zfhPtr->frameType = ZSTD_skippableFrame; + zfhPtr->dictID = MEM_readLE32(src) - ZSTD_MAGIC_SKIPPABLE_START; + zfhPtr->headerSize = ZSTD_SKIPPABLEHEADERSIZE; + zfhPtr->frameContentSize = MEM_readLE32((const char *)src + ZSTD_FRAMEIDSIZE); + return 0; + } + RETURN_ERROR(prefix_unknown, ""); + } + + /* ensure there is enough `srcSize` to fully read/decode frame header */ + { size_t const fhsize = ZSTD_frameHeaderSize_internal(src, srcSize, format); + if (srcSize < fhsize) return fhsize; + zfhPtr->headerSize = (U32)fhsize; + } + + { BYTE const fhdByte = ip[minInputSize-1]; + size_t pos = minInputSize; + U32 const dictIDSizeCode = fhdByte&3; + U32 const checksumFlag = (fhdByte>>2)&1; + U32 const singleSegment = (fhdByte>>5)&1; + U32 const fcsID = fhdByte>>6; + U64 windowSize = 0; + U32 dictID = 0; + U64 frameContentSize = ZSTD_CONTENTSIZE_UNKNOWN; + RETURN_ERROR_IF((fhdByte & 0x08) != 0, frameParameter_unsupported, + "reserved bits, must be zero"); + + if (!singleSegment) { + BYTE const wlByte = ip[pos++]; + U32 const windowLog = (wlByte >> 3) + ZSTD_WINDOWLOG_ABSOLUTEMIN; + RETURN_ERROR_IF(windowLog > ZSTD_WINDOWLOG_MAX, frameParameter_windowTooLarge, ""); + windowSize = (1ULL << windowLog); + windowSize += (windowSize >> 3) * (wlByte&7); + } + switch(dictIDSizeCode) + { + default: + assert(0); /* impossible */ + ZSTD_FALLTHROUGH; + case 0 : break; + case 1 : dictID = ip[pos]; pos++; break; + case 2 : dictID = MEM_readLE16(ip+pos); pos+=2; break; + case 3 : dictID = MEM_readLE32(ip+pos); pos+=4; break; + } + switch(fcsID) + { + default: + assert(0); /* impossible */ + ZSTD_FALLTHROUGH; + case 0 : if (singleSegment) frameContentSize = ip[pos]; break; + case 1 : frameContentSize = MEM_readLE16(ip+pos)+256; break; + case 2 : frameContentSize = MEM_readLE32(ip+pos); break; + case 3 : frameContentSize = MEM_readLE64(ip+pos); break; + } + if (singleSegment) windowSize = frameContentSize; + + zfhPtr->frameType = ZSTD_frame; + zfhPtr->frameContentSize = frameContentSize; + zfhPtr->windowSize = windowSize; + zfhPtr->blockSizeMax = (unsigned) MIN(windowSize, ZSTD_BLOCKSIZE_MAX); + zfhPtr->dictID = dictID; + zfhPtr->checksumFlag = checksumFlag; + } + return 0; +} + +/** ZSTD_getFrameHeader() : + * decode Frame Header, or require larger `srcSize`. + * note : this function does not consume input, it only reads it. + * @return : 0, `zfhPtr` is correctly filled, + * >0, `srcSize` is too small, value is wanted `srcSize` amount, + * or an error code, which can be tested using ZSTD_isError() */ +size_t ZSTD_getFrameHeader(ZSTD_FrameHeader* zfhPtr, const void* src, size_t srcSize) +{ + return ZSTD_getFrameHeader_advanced(zfhPtr, src, srcSize, ZSTD_f_zstd1); +} + +/** ZSTD_getFrameContentSize() : + * compatible with legacy mode + * @return : decompressed size of the single frame pointed to be `src` if known, otherwise + * - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined + * - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small) */ +unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize) +{ +#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1) + if (ZSTD_isLegacy(src, srcSize)) { + unsigned long long const ret = ZSTD_getDecompressedSize_legacy(src, srcSize); + return ret == 0 ? ZSTD_CONTENTSIZE_UNKNOWN : ret; + } +#endif + { ZSTD_FrameHeader zfh; + if (ZSTD_getFrameHeader(&zfh, src, srcSize) != 0) + return ZSTD_CONTENTSIZE_ERROR; + if (zfh.frameType == ZSTD_skippableFrame) { + return 0; + } else { + return zfh.frameContentSize; + } } +} + +static size_t readSkippableFrameSize(void const* src, size_t srcSize) +{ + size_t const skippableHeaderSize = ZSTD_SKIPPABLEHEADERSIZE; + U32 sizeU32; + + RETURN_ERROR_IF(srcSize < ZSTD_SKIPPABLEHEADERSIZE, srcSize_wrong, ""); + + sizeU32 = MEM_readLE32((BYTE const*)src + ZSTD_FRAMEIDSIZE); + RETURN_ERROR_IF((U32)(sizeU32 + ZSTD_SKIPPABLEHEADERSIZE) < sizeU32, + frameParameter_unsupported, ""); + { size_t const skippableSize = skippableHeaderSize + sizeU32; + RETURN_ERROR_IF(skippableSize > srcSize, srcSize_wrong, ""); + return skippableSize; + } +} + +/*! ZSTD_readSkippableFrame() : + * Retrieves content of a skippable frame, and writes it to dst buffer. + * + * The parameter magicVariant will receive the magicVariant that was supplied when the frame was written, + * i.e. magicNumber - ZSTD_MAGIC_SKIPPABLE_START. This can be NULL if the caller is not interested + * in the magicVariant. + * + * Returns an error if destination buffer is not large enough, or if this is not a valid skippable frame. + * + * @return : number of bytes written or a ZSTD error. + */ +size_t ZSTD_readSkippableFrame(void* dst, size_t dstCapacity, + unsigned* magicVariant, /* optional, can be NULL */ + const void* src, size_t srcSize) +{ + RETURN_ERROR_IF(srcSize < ZSTD_SKIPPABLEHEADERSIZE, srcSize_wrong, ""); + + { U32 const magicNumber = MEM_readLE32(src); + size_t skippableFrameSize = readSkippableFrameSize(src, srcSize); + size_t skippableContentSize = skippableFrameSize - ZSTD_SKIPPABLEHEADERSIZE; + + /* check input validity */ + RETURN_ERROR_IF(!ZSTD_isSkippableFrame(src, srcSize), frameParameter_unsupported, ""); + RETURN_ERROR_IF(skippableFrameSize < ZSTD_SKIPPABLEHEADERSIZE || skippableFrameSize > srcSize, srcSize_wrong, ""); + RETURN_ERROR_IF(skippableContentSize > dstCapacity, dstSize_tooSmall, ""); + + /* deliver payload */ + if (skippableContentSize > 0 && dst != NULL) + ZSTD_memcpy(dst, (const BYTE *)src + ZSTD_SKIPPABLEHEADERSIZE, skippableContentSize); + if (magicVariant != NULL) + *magicVariant = magicNumber - ZSTD_MAGIC_SKIPPABLE_START; + return skippableContentSize; + } +} + +/** ZSTD_findDecompressedSize() : + * `srcSize` must be the exact length of some number of ZSTD compressed and/or + * skippable frames + * note: compatible with legacy mode + * @return : decompressed size of the frames contained */ +unsigned long long ZSTD_findDecompressedSize(const void* src, size_t srcSize) +{ + unsigned long long totalDstSize = 0; + + while (srcSize >= ZSTD_startingInputLength(ZSTD_f_zstd1)) { + U32 const magicNumber = MEM_readLE32(src); + + if ((magicNumber & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { + size_t const skippableSize = readSkippableFrameSize(src, srcSize); + if (ZSTD_isError(skippableSize)) return ZSTD_CONTENTSIZE_ERROR; + assert(skippableSize <= srcSize); + + src = (const BYTE *)src + skippableSize; + srcSize -= skippableSize; + continue; + } + + { unsigned long long const fcs = ZSTD_getFrameContentSize(src, srcSize); + if (fcs >= ZSTD_CONTENTSIZE_ERROR) return fcs; + + if (totalDstSize + fcs < totalDstSize) + return ZSTD_CONTENTSIZE_ERROR; /* check for overflow */ + totalDstSize += fcs; + } + /* skip to next frame */ + { size_t const frameSrcSize = ZSTD_findFrameCompressedSize(src, srcSize); + if (ZSTD_isError(frameSrcSize)) return ZSTD_CONTENTSIZE_ERROR; + assert(frameSrcSize <= srcSize); + + src = (const BYTE *)src + frameSrcSize; + srcSize -= frameSrcSize; + } + } /* while (srcSize >= ZSTD_frameHeaderSize_prefix) */ + + if (srcSize) return ZSTD_CONTENTSIZE_ERROR; + + return totalDstSize; +} + +/** ZSTD_getDecompressedSize() : + * compatible with legacy mode + * @return : decompressed size if known, 0 otherwise + note : 0 can mean any of the following : + - frame content is empty + - decompressed size field is not present in frame header + - frame header unknown / not supported + - frame header not complete (`srcSize` too small) */ +unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize) +{ + unsigned long long const ret = ZSTD_getFrameContentSize(src, srcSize); + ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_ERROR < ZSTD_CONTENTSIZE_UNKNOWN); + return (ret >= ZSTD_CONTENTSIZE_ERROR) ? 0 : ret; +} + + +/** ZSTD_decodeFrameHeader() : + * `headerSize` must be the size provided by ZSTD_frameHeaderSize(). + * If multiple DDict references are enabled, also will choose the correct DDict to use. + * @return : 0 if success, or an error code, which can be tested using ZSTD_isError() */ +static size_t ZSTD_decodeFrameHeader(ZSTD_DCtx* dctx, const void* src, size_t headerSize) +{ + size_t const result = ZSTD_getFrameHeader_advanced(&(dctx->fParams), src, headerSize, dctx->format); + if (ZSTD_isError(result)) return result; /* invalid header */ + RETURN_ERROR_IF(result>0, srcSize_wrong, "headerSize too small"); + + /* Reference DDict requested by frame if dctx references multiple ddicts */ + if (dctx->refMultipleDDicts == ZSTD_rmd_refMultipleDDicts && dctx->ddictSet) { + ZSTD_DCtx_selectFrameDDict(dctx); + } + +#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION + /* Skip the dictID check in fuzzing mode, because it makes the search + * harder. + */ + RETURN_ERROR_IF(dctx->fParams.dictID && (dctx->dictID != dctx->fParams.dictID), + dictionary_wrong, ""); +#endif + dctx->validateChecksum = (dctx->fParams.checksumFlag && !dctx->forceIgnoreChecksum) ? 1 : 0; + if (dctx->validateChecksum) XXH64_reset(&dctx->xxhState, 0); + dctx->processedCSize += headerSize; + return 0; +} + +static ZSTD_frameSizeInfo ZSTD_errorFrameSizeInfo(size_t ret) +{ + ZSTD_frameSizeInfo frameSizeInfo; + frameSizeInfo.compressedSize = ret; + frameSizeInfo.decompressedBound = ZSTD_CONTENTSIZE_ERROR; + return frameSizeInfo; +} + +static ZSTD_frameSizeInfo ZSTD_findFrameSizeInfo(const void* src, size_t srcSize, ZSTD_format_e format) +{ + ZSTD_frameSizeInfo frameSizeInfo; + ZSTD_memset(&frameSizeInfo, 0, sizeof(ZSTD_frameSizeInfo)); + +#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1) + if (format == ZSTD_f_zstd1 && ZSTD_isLegacy(src, srcSize)) + return ZSTD_findFrameSizeInfoLegacy(src, srcSize); +#endif + + if (format == ZSTD_f_zstd1 && (srcSize >= ZSTD_SKIPPABLEHEADERSIZE) + && (MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { + frameSizeInfo.compressedSize = readSkippableFrameSize(src, srcSize); + assert(ZSTD_isError(frameSizeInfo.compressedSize) || + frameSizeInfo.compressedSize <= srcSize); + return frameSizeInfo; + } else { + const BYTE* ip = (const BYTE*)src; + const BYTE* const ipstart = ip; + size_t remainingSize = srcSize; + size_t nbBlocks = 0; + ZSTD_FrameHeader zfh; + + /* Extract Frame Header */ + { size_t const ret = ZSTD_getFrameHeader_advanced(&zfh, src, srcSize, format); + if (ZSTD_isError(ret)) + return ZSTD_errorFrameSizeInfo(ret); + if (ret > 0) + return ZSTD_errorFrameSizeInfo(ERROR(srcSize_wrong)); + } + + ip += zfh.headerSize; + remainingSize -= zfh.headerSize; + + /* Iterate over each block */ + while (1) { + blockProperties_t blockProperties; + size_t const cBlockSize = ZSTD_getcBlockSize(ip, remainingSize, &blockProperties); + if (ZSTD_isError(cBlockSize)) + return ZSTD_errorFrameSizeInfo(cBlockSize); + + if (ZSTD_blockHeaderSize + cBlockSize > remainingSize) + return ZSTD_errorFrameSizeInfo(ERROR(srcSize_wrong)); + + ip += ZSTD_blockHeaderSize + cBlockSize; + remainingSize -= ZSTD_blockHeaderSize + cBlockSize; + nbBlocks++; + + if (blockProperties.lastBlock) break; + } + + /* Final frame content checksum */ + if (zfh.checksumFlag) { + if (remainingSize < 4) + return ZSTD_errorFrameSizeInfo(ERROR(srcSize_wrong)); + ip += 4; + } + + frameSizeInfo.nbBlocks = nbBlocks; + frameSizeInfo.compressedSize = (size_t)(ip - ipstart); + frameSizeInfo.decompressedBound = (zfh.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN) + ? zfh.frameContentSize + : (unsigned long long)nbBlocks * zfh.blockSizeMax; + return frameSizeInfo; + } +} + +static size_t ZSTD_findFrameCompressedSize_advanced(const void *src, size_t srcSize, ZSTD_format_e format) { + ZSTD_frameSizeInfo const frameSizeInfo = ZSTD_findFrameSizeInfo(src, srcSize, format); + return frameSizeInfo.compressedSize; +} + +/** ZSTD_findFrameCompressedSize() : + * See docs in zstd.h + * Note: compatible with legacy mode */ +size_t ZSTD_findFrameCompressedSize(const void *src, size_t srcSize) +{ + return ZSTD_findFrameCompressedSize_advanced(src, srcSize, ZSTD_f_zstd1); +} + +/** ZSTD_decompressBound() : + * compatible with legacy mode + * `src` must point to the start of a ZSTD frame or a skippable frame + * `srcSize` must be at least as large as the frame contained + * @return : the maximum decompressed size of the compressed source + */ +unsigned long long ZSTD_decompressBound(const void* src, size_t srcSize) +{ + unsigned long long bound = 0; + /* Iterate over each frame */ + while (srcSize > 0) { + ZSTD_frameSizeInfo const frameSizeInfo = ZSTD_findFrameSizeInfo(src, srcSize, ZSTD_f_zstd1); + size_t const compressedSize = frameSizeInfo.compressedSize; + unsigned long long const decompressedBound = frameSizeInfo.decompressedBound; + if (ZSTD_isError(compressedSize) || decompressedBound == ZSTD_CONTENTSIZE_ERROR) + return ZSTD_CONTENTSIZE_ERROR; + assert(srcSize >= compressedSize); + src = (const BYTE*)src + compressedSize; + srcSize -= compressedSize; + bound += decompressedBound; + } + return bound; +} + +size_t ZSTD_decompressionMargin(void const* src, size_t srcSize) +{ + size_t margin = 0; + unsigned maxBlockSize = 0; + + /* Iterate over each frame */ + while (srcSize > 0) { + ZSTD_frameSizeInfo const frameSizeInfo = ZSTD_findFrameSizeInfo(src, srcSize, ZSTD_f_zstd1); + size_t const compressedSize = frameSizeInfo.compressedSize; + unsigned long long const decompressedBound = frameSizeInfo.decompressedBound; + ZSTD_FrameHeader zfh; + + FORWARD_IF_ERROR(ZSTD_getFrameHeader(&zfh, src, srcSize), ""); + if (ZSTD_isError(compressedSize) || decompressedBound == ZSTD_CONTENTSIZE_ERROR) + return ERROR(corruption_detected); + + if (zfh.frameType == ZSTD_frame) { + /* Add the frame header to our margin */ + margin += zfh.headerSize; + /* Add the checksum to our margin */ + margin += zfh.checksumFlag ? 4 : 0; + /* Add 3 bytes per block */ + margin += 3 * frameSizeInfo.nbBlocks; + + /* Compute the max block size */ + maxBlockSize = MAX(maxBlockSize, zfh.blockSizeMax); + } else { + assert(zfh.frameType == ZSTD_skippableFrame); + /* Add the entire skippable frame size to our margin. */ + margin += compressedSize; + } + + assert(srcSize >= compressedSize); + src = (const BYTE*)src + compressedSize; + srcSize -= compressedSize; + } + + /* Add the max block size back to the margin. */ + margin += maxBlockSize; + + return margin; +} + +/*-************************************************************* + * Frame decoding + ***************************************************************/ + +/** ZSTD_insertBlock() : + * insert `src` block into `dctx` history. Useful to track uncompressed blocks. */ +size_t ZSTD_insertBlock(ZSTD_DCtx* dctx, const void* blockStart, size_t blockSize) +{ + DEBUGLOG(5, "ZSTD_insertBlock: %u bytes", (unsigned)blockSize); + ZSTD_checkContinuity(dctx, blockStart, blockSize); + dctx->previousDstEnd = (const char*)blockStart + blockSize; + return blockSize; +} + + +static size_t ZSTD_copyRawBlock(void* dst, size_t dstCapacity, + const void* src, size_t srcSize) +{ + DEBUGLOG(5, "ZSTD_copyRawBlock"); + RETURN_ERROR_IF(srcSize > dstCapacity, dstSize_tooSmall, ""); + if (dst == NULL) { + if (srcSize == 0) return 0; + RETURN_ERROR(dstBuffer_null, ""); + } + ZSTD_memmove(dst, src, srcSize); + return srcSize; +} + +static size_t ZSTD_setRleBlock(void* dst, size_t dstCapacity, + BYTE b, + size_t regenSize) +{ + RETURN_ERROR_IF(regenSize > dstCapacity, dstSize_tooSmall, ""); + if (dst == NULL) { + if (regenSize == 0) return 0; + RETURN_ERROR(dstBuffer_null, ""); + } + ZSTD_memset(dst, b, regenSize); + return regenSize; +} + +static void ZSTD_DCtx_trace_end(ZSTD_DCtx const* dctx, U64 uncompressedSize, U64 compressedSize, int streaming) +{ +#if ZSTD_TRACE + if (dctx->traceCtx && ZSTD_trace_decompress_end != NULL) { + ZSTD_Trace trace; + ZSTD_memset(&trace, 0, sizeof(trace)); + trace.version = ZSTD_VERSION_NUMBER; + trace.streaming = streaming; + if (dctx->ddict) { + trace.dictionaryID = ZSTD_getDictID_fromDDict(dctx->ddict); + trace.dictionarySize = ZSTD_DDict_dictSize(dctx->ddict); + trace.dictionaryIsCold = dctx->ddictIsCold; + } + trace.uncompressedSize = (size_t)uncompressedSize; + trace.compressedSize = (size_t)compressedSize; + trace.dctx = dctx; + ZSTD_trace_decompress_end(dctx->traceCtx, &trace); + } +#else + (void)dctx; + (void)uncompressedSize; + (void)compressedSize; + (void)streaming; +#endif +} + + +/*! ZSTD_decompressFrame() : + * @dctx must be properly initialized + * will update *srcPtr and *srcSizePtr, + * to make *srcPtr progress by one frame. */ +static size_t ZSTD_decompressFrame(ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, + const void** srcPtr, size_t *srcSizePtr) +{ + const BYTE* const istart = (const BYTE*)(*srcPtr); + const BYTE* ip = istart; + BYTE* const ostart = (BYTE*)dst; + BYTE* const oend = dstCapacity != 0 ? ostart + dstCapacity : ostart; + BYTE* op = ostart; + size_t remainingSrcSize = *srcSizePtr; + + DEBUGLOG(4, "ZSTD_decompressFrame (srcSize:%i)", (int)*srcSizePtr); + + /* check */ + RETURN_ERROR_IF( + remainingSrcSize < ZSTD_FRAMEHEADERSIZE_MIN(dctx->format)+ZSTD_blockHeaderSize, + srcSize_wrong, ""); + + /* Frame Header */ + { size_t const frameHeaderSize = ZSTD_frameHeaderSize_internal( + ip, ZSTD_FRAMEHEADERSIZE_PREFIX(dctx->format), dctx->format); + if (ZSTD_isError(frameHeaderSize)) return frameHeaderSize; + RETURN_ERROR_IF(remainingSrcSize < frameHeaderSize+ZSTD_blockHeaderSize, + srcSize_wrong, ""); + FORWARD_IF_ERROR( ZSTD_decodeFrameHeader(dctx, ip, frameHeaderSize) , ""); + ip += frameHeaderSize; remainingSrcSize -= frameHeaderSize; + } + + /* Shrink the blockSizeMax if enabled */ + if (dctx->maxBlockSizeParam != 0) + dctx->fParams.blockSizeMax = MIN(dctx->fParams.blockSizeMax, (unsigned)dctx->maxBlockSizeParam); + + /* Loop on each block */ + while (1) { + BYTE* oBlockEnd = oend; + size_t decodedSize; + blockProperties_t blockProperties; + size_t const cBlockSize = ZSTD_getcBlockSize(ip, remainingSrcSize, &blockProperties); + if (ZSTD_isError(cBlockSize)) return cBlockSize; + + ip += ZSTD_blockHeaderSize; + remainingSrcSize -= ZSTD_blockHeaderSize; + RETURN_ERROR_IF(cBlockSize > remainingSrcSize, srcSize_wrong, ""); + + if (ip >= op && ip < oBlockEnd) { + /* We are decompressing in-place. Limit the output pointer so that we + * don't overwrite the block that we are currently reading. This will + * fail decompression if the input & output pointers aren't spaced + * far enough apart. + * + * This is important to set, even when the pointers are far enough + * apart, because ZSTD_decompressBlock_internal() can decide to store + * literals in the output buffer, after the block it is decompressing. + * Since we don't want anything to overwrite our input, we have to tell + * ZSTD_decompressBlock_internal to never write past ip. + * + * See ZSTD_allocateLiteralsBuffer() for reference. + */ + oBlockEnd = op + (ip - op); + } + + switch(blockProperties.blockType) + { + case bt_compressed: + assert(dctx->isFrameDecompression == 1); + decodedSize = ZSTD_decompressBlock_internal(dctx, op, (size_t)(oBlockEnd-op), ip, cBlockSize, not_streaming); + break; + case bt_raw : + /* Use oend instead of oBlockEnd because this function is safe to overlap. It uses memmove. */ + decodedSize = ZSTD_copyRawBlock(op, (size_t)(oend-op), ip, cBlockSize); + break; + case bt_rle : + decodedSize = ZSTD_setRleBlock(op, (size_t)(oBlockEnd-op), *ip, blockProperties.origSize); + break; + case bt_reserved : + default: + RETURN_ERROR(corruption_detected, "invalid block type"); + } + FORWARD_IF_ERROR(decodedSize, "Block decompression failure"); + DEBUGLOG(5, "Decompressed block of dSize = %u", (unsigned)decodedSize); + if (dctx->validateChecksum) { + XXH64_update(&dctx->xxhState, op, decodedSize); + } + if (decodedSize) /* support dst = NULL,0 */ { + op += decodedSize; + } + assert(ip != NULL); + ip += cBlockSize; + remainingSrcSize -= cBlockSize; + if (blockProperties.lastBlock) break; + } + + if (dctx->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN) { + RETURN_ERROR_IF((U64)(op-ostart) != dctx->fParams.frameContentSize, + corruption_detected, ""); + } + if (dctx->fParams.checksumFlag) { /* Frame content checksum verification */ + RETURN_ERROR_IF(remainingSrcSize<4, checksum_wrong, ""); + if (!dctx->forceIgnoreChecksum) { + U32 const checkCalc = (U32)XXH64_digest(&dctx->xxhState); + U32 checkRead; + checkRead = MEM_readLE32(ip); + RETURN_ERROR_IF(checkRead != checkCalc, checksum_wrong, ""); + } + ip += 4; + remainingSrcSize -= 4; + } + ZSTD_DCtx_trace_end(dctx, (U64)(op-ostart), (U64)(ip-istart), /* streaming */ 0); + /* Allow caller to get size read */ + DEBUGLOG(4, "ZSTD_decompressFrame: decompressed frame of size %i, consuming %i bytes of input", (int)(op-ostart), (int)(ip - (const BYTE*)*srcPtr)); + *srcPtr = ip; + *srcSizePtr = remainingSrcSize; + return (size_t)(op-ostart); +} + +static +ZSTD_ALLOW_POINTER_OVERFLOW_ATTR +size_t ZSTD_decompressMultiFrame(ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const void* dict, size_t dictSize, + const ZSTD_DDict* ddict) +{ + void* const dststart = dst; + int moreThan1Frame = 0; + + DEBUGLOG(5, "ZSTD_decompressMultiFrame"); + assert(dict==NULL || ddict==NULL); /* either dict or ddict set, not both */ + + if (ddict) { + dict = ZSTD_DDict_dictContent(ddict); + dictSize = ZSTD_DDict_dictSize(ddict); + } + + while (srcSize >= ZSTD_startingInputLength(dctx->format)) { + +#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1) + if (dctx->format == ZSTD_f_zstd1 && ZSTD_isLegacy(src, srcSize)) { + size_t decodedSize; + size_t const frameSize = ZSTD_findFrameCompressedSizeLegacy(src, srcSize); + if (ZSTD_isError(frameSize)) return frameSize; + RETURN_ERROR_IF(dctx->staticSize, memory_allocation, + "legacy support is not compatible with static dctx"); + + decodedSize = ZSTD_decompressLegacy(dst, dstCapacity, src, frameSize, dict, dictSize); + if (ZSTD_isError(decodedSize)) return decodedSize; + + { + unsigned long long const expectedSize = ZSTD_getFrameContentSize(src, srcSize); + RETURN_ERROR_IF(expectedSize == ZSTD_CONTENTSIZE_ERROR, corruption_detected, "Corrupted frame header!"); + if (expectedSize != ZSTD_CONTENTSIZE_UNKNOWN) { + RETURN_ERROR_IF(expectedSize != decodedSize, corruption_detected, + "Frame header size does not match decoded size!"); + } + } + + assert(decodedSize <= dstCapacity); + dst = (BYTE*)dst + decodedSize; + dstCapacity -= decodedSize; + + src = (const BYTE*)src + frameSize; + srcSize -= frameSize; + + continue; + } +#endif + + if (dctx->format == ZSTD_f_zstd1 && srcSize >= 4) { + U32 const magicNumber = MEM_readLE32(src); + DEBUGLOG(5, "reading magic number %08X", (unsigned)magicNumber); + if ((magicNumber & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { + /* skippable frame detected : skip it */ + size_t const skippableSize = readSkippableFrameSize(src, srcSize); + FORWARD_IF_ERROR(skippableSize, "invalid skippable frame"); + assert(skippableSize <= srcSize); + + src = (const BYTE *)src + skippableSize; + srcSize -= skippableSize; + continue; /* check next frame */ + } } + + if (ddict) { + /* we were called from ZSTD_decompress_usingDDict */ + FORWARD_IF_ERROR(ZSTD_decompressBegin_usingDDict(dctx, ddict), ""); + } else { + /* this will initialize correctly with no dict if dict == NULL, so + * use this in all cases but ddict */ + FORWARD_IF_ERROR(ZSTD_decompressBegin_usingDict(dctx, dict, dictSize), ""); + } + ZSTD_checkContinuity(dctx, dst, dstCapacity); + + { const size_t res = ZSTD_decompressFrame(dctx, dst, dstCapacity, + &src, &srcSize); + RETURN_ERROR_IF( + (ZSTD_getErrorCode(res) == ZSTD_error_prefix_unknown) + && (moreThan1Frame==1), + srcSize_wrong, + "At least one frame successfully completed, " + "but following bytes are garbage: " + "it's more likely to be a srcSize error, " + "specifying more input bytes than size of frame(s). " + "Note: one could be unlucky, it might be a corruption error instead, " + "happening right at the place where we expect zstd magic bytes. " + "But this is _much_ less likely than a srcSize field error."); + if (ZSTD_isError(res)) return res; + assert(res <= dstCapacity); + if (res != 0) + dst = (BYTE*)dst + res; + dstCapacity -= res; + } + moreThan1Frame = 1; + } /* while (srcSize >= ZSTD_frameHeaderSize_prefix) */ + + RETURN_ERROR_IF(srcSize, srcSize_wrong, "input not entirely consumed"); + + return (size_t)((BYTE*)dst - (BYTE*)dststart); +} + +size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const void* dict, size_t dictSize) +{ + return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize, dict, dictSize, NULL); +} + + +static ZSTD_DDict const* ZSTD_getDDict(ZSTD_DCtx* dctx) +{ + switch (dctx->dictUses) { + default: + assert(0 /* Impossible */); + ZSTD_FALLTHROUGH; + case ZSTD_dont_use: + ZSTD_clearDict(dctx); + return NULL; + case ZSTD_use_indefinitely: + return dctx->ddict; + case ZSTD_use_once: + dctx->dictUses = ZSTD_dont_use; + return dctx->ddict; + } +} + +size_t ZSTD_decompressDCtx(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize) +{ + return ZSTD_decompress_usingDDict(dctx, dst, dstCapacity, src, srcSize, ZSTD_getDDict(dctx)); +} + + +size_t ZSTD_decompress(void* dst, size_t dstCapacity, const void* src, size_t srcSize) +{ +#if defined(ZSTD_HEAPMODE) && (ZSTD_HEAPMODE>=1) + size_t regenSize; + ZSTD_DCtx* const dctx = ZSTD_createDCtx_internal(ZSTD_defaultCMem); + RETURN_ERROR_IF(dctx==NULL, memory_allocation, "NULL pointer!"); + regenSize = ZSTD_decompressDCtx(dctx, dst, dstCapacity, src, srcSize); + ZSTD_freeDCtx(dctx); + return regenSize; +#else /* stack mode */ + ZSTD_DCtx dctx; + ZSTD_initDCtx_internal(&dctx); + return ZSTD_decompressDCtx(&dctx, dst, dstCapacity, src, srcSize); +#endif +} + + +/*-************************************** +* Advanced Streaming Decompression API +* Bufferless and synchronous +****************************************/ +size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx) { return dctx->expected; } + +/** + * Similar to ZSTD_nextSrcSizeToDecompress(), but when a block input can be streamed, we + * allow taking a partial block as the input. Currently only raw uncompressed blocks can + * be streamed. + * + * For blocks that can be streamed, this allows us to reduce the latency until we produce + * output, and avoid copying the input. + * + * @param inputSize - The total amount of input that the caller currently has. + */ +static size_t ZSTD_nextSrcSizeToDecompressWithInputSize(ZSTD_DCtx* dctx, size_t inputSize) { + if (!(dctx->stage == ZSTDds_decompressBlock || dctx->stage == ZSTDds_decompressLastBlock)) + return dctx->expected; + if (dctx->bType != bt_raw) + return dctx->expected; + return BOUNDED(1, inputSize, dctx->expected); +} + +ZSTD_nextInputType_e ZSTD_nextInputType(ZSTD_DCtx* dctx) { + switch(dctx->stage) + { + default: /* should not happen */ + assert(0); + ZSTD_FALLTHROUGH; + case ZSTDds_getFrameHeaderSize: + ZSTD_FALLTHROUGH; + case ZSTDds_decodeFrameHeader: + return ZSTDnit_frameHeader; + case ZSTDds_decodeBlockHeader: + return ZSTDnit_blockHeader; + case ZSTDds_decompressBlock: + return ZSTDnit_block; + case ZSTDds_decompressLastBlock: + return ZSTDnit_lastBlock; + case ZSTDds_checkChecksum: + return ZSTDnit_checksum; + case ZSTDds_decodeSkippableHeader: + ZSTD_FALLTHROUGH; + case ZSTDds_skipFrame: + return ZSTDnit_skippableFrame; + } +} + +static int ZSTD_isSkipFrame(ZSTD_DCtx* dctx) { return dctx->stage == ZSTDds_skipFrame; } + +/** ZSTD_decompressContinue() : + * srcSize : must be the exact nb of bytes expected (see ZSTD_nextSrcSizeToDecompress()) + * @return : nb of bytes generated into `dst` (necessarily <= `dstCapacity) + * or an error code, which can be tested using ZSTD_isError() */ +size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize) +{ + DEBUGLOG(5, "ZSTD_decompressContinue (srcSize:%u)", (unsigned)srcSize); + /* Sanity check */ + RETURN_ERROR_IF(srcSize != ZSTD_nextSrcSizeToDecompressWithInputSize(dctx, srcSize), srcSize_wrong, "not allowed"); + ZSTD_checkContinuity(dctx, dst, dstCapacity); + + dctx->processedCSize += srcSize; + + switch (dctx->stage) + { + case ZSTDds_getFrameHeaderSize : + assert(src != NULL); + if (dctx->format == ZSTD_f_zstd1) { /* allows header */ + assert(srcSize >= ZSTD_FRAMEIDSIZE); /* to read skippable magic number */ + if ((MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { /* skippable frame */ + ZSTD_memcpy(dctx->headerBuffer, src, srcSize); + dctx->expected = ZSTD_SKIPPABLEHEADERSIZE - srcSize; /* remaining to load to get full skippable frame header */ + dctx->stage = ZSTDds_decodeSkippableHeader; + return 0; + } } + dctx->headerSize = ZSTD_frameHeaderSize_internal(src, srcSize, dctx->format); + if (ZSTD_isError(dctx->headerSize)) return dctx->headerSize; + ZSTD_memcpy(dctx->headerBuffer, src, srcSize); + dctx->expected = dctx->headerSize - srcSize; + dctx->stage = ZSTDds_decodeFrameHeader; + return 0; + + case ZSTDds_decodeFrameHeader: + assert(src != NULL); + ZSTD_memcpy(dctx->headerBuffer + (dctx->headerSize - srcSize), src, srcSize); + FORWARD_IF_ERROR(ZSTD_decodeFrameHeader(dctx, dctx->headerBuffer, dctx->headerSize), ""); + dctx->expected = ZSTD_blockHeaderSize; + dctx->stage = ZSTDds_decodeBlockHeader; + return 0; + + case ZSTDds_decodeBlockHeader: + { blockProperties_t bp; + size_t const cBlockSize = ZSTD_getcBlockSize(src, ZSTD_blockHeaderSize, &bp); + if (ZSTD_isError(cBlockSize)) return cBlockSize; + RETURN_ERROR_IF(cBlockSize > dctx->fParams.blockSizeMax, corruption_detected, "Block Size Exceeds Maximum"); + dctx->expected = cBlockSize; + dctx->bType = bp.blockType; + dctx->rleSize = bp.origSize; + if (cBlockSize) { + dctx->stage = bp.lastBlock ? ZSTDds_decompressLastBlock : ZSTDds_decompressBlock; + return 0; + } + /* empty block */ + if (bp.lastBlock) { + if (dctx->fParams.checksumFlag) { + dctx->expected = 4; + dctx->stage = ZSTDds_checkChecksum; + } else { + dctx->expected = 0; /* end of frame */ + dctx->stage = ZSTDds_getFrameHeaderSize; + } + } else { + dctx->expected = ZSTD_blockHeaderSize; /* jump to next header */ + dctx->stage = ZSTDds_decodeBlockHeader; + } + return 0; + } + + case ZSTDds_decompressLastBlock: + case ZSTDds_decompressBlock: + DEBUGLOG(5, "ZSTD_decompressContinue: case ZSTDds_decompressBlock"); + { size_t rSize; + switch(dctx->bType) + { + case bt_compressed: + DEBUGLOG(5, "ZSTD_decompressContinue: case bt_compressed"); + assert(dctx->isFrameDecompression == 1); + rSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, is_streaming); + dctx->expected = 0; /* Streaming not supported */ + break; + case bt_raw : + assert(srcSize <= dctx->expected); + rSize = ZSTD_copyRawBlock(dst, dstCapacity, src, srcSize); + FORWARD_IF_ERROR(rSize, "ZSTD_copyRawBlock failed"); + assert(rSize == srcSize); + dctx->expected -= rSize; + break; + case bt_rle : + rSize = ZSTD_setRleBlock(dst, dstCapacity, *(const BYTE*)src, dctx->rleSize); + dctx->expected = 0; /* Streaming not supported */ + break; + case bt_reserved : /* should never happen */ + default: + RETURN_ERROR(corruption_detected, "invalid block type"); + } + FORWARD_IF_ERROR(rSize, ""); + RETURN_ERROR_IF(rSize > dctx->fParams.blockSizeMax, corruption_detected, "Decompressed Block Size Exceeds Maximum"); + DEBUGLOG(5, "ZSTD_decompressContinue: decoded size from block : %u", (unsigned)rSize); + dctx->decodedSize += rSize; + if (dctx->validateChecksum) XXH64_update(&dctx->xxhState, dst, rSize); + dctx->previousDstEnd = (char*)dst + rSize; + + /* Stay on the same stage until we are finished streaming the block. */ + if (dctx->expected > 0) { + return rSize; + } + + if (dctx->stage == ZSTDds_decompressLastBlock) { /* end of frame */ + DEBUGLOG(4, "ZSTD_decompressContinue: decoded size from frame : %u", (unsigned)dctx->decodedSize); + RETURN_ERROR_IF( + dctx->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN + && dctx->decodedSize != dctx->fParams.frameContentSize, + corruption_detected, ""); + if (dctx->fParams.checksumFlag) { /* another round for frame checksum */ + dctx->expected = 4; + dctx->stage = ZSTDds_checkChecksum; + } else { + ZSTD_DCtx_trace_end(dctx, dctx->decodedSize, dctx->processedCSize, /* streaming */ 1); + dctx->expected = 0; /* ends here */ + dctx->stage = ZSTDds_getFrameHeaderSize; + } + } else { + dctx->stage = ZSTDds_decodeBlockHeader; + dctx->expected = ZSTD_blockHeaderSize; + } + return rSize; + } + + case ZSTDds_checkChecksum: + assert(srcSize == 4); /* guaranteed by dctx->expected */ + { + if (dctx->validateChecksum) { + U32 const h32 = (U32)XXH64_digest(&dctx->xxhState); + U32 const check32 = MEM_readLE32(src); + DEBUGLOG(4, "ZSTD_decompressContinue: checksum : calculated %08X :: %08X read", (unsigned)h32, (unsigned)check32); + RETURN_ERROR_IF(check32 != h32, checksum_wrong, ""); + } + ZSTD_DCtx_trace_end(dctx, dctx->decodedSize, dctx->processedCSize, /* streaming */ 1); + dctx->expected = 0; + dctx->stage = ZSTDds_getFrameHeaderSize; + return 0; + } + + case ZSTDds_decodeSkippableHeader: + assert(src != NULL); + assert(srcSize <= ZSTD_SKIPPABLEHEADERSIZE); + assert(dctx->format != ZSTD_f_zstd1_magicless); + ZSTD_memcpy(dctx->headerBuffer + (ZSTD_SKIPPABLEHEADERSIZE - srcSize), src, srcSize); /* complete skippable header */ + dctx->expected = MEM_readLE32(dctx->headerBuffer + ZSTD_FRAMEIDSIZE); /* note : dctx->expected can grow seriously large, beyond local buffer size */ + dctx->stage = ZSTDds_skipFrame; + return 0; + + case ZSTDds_skipFrame: + dctx->expected = 0; + dctx->stage = ZSTDds_getFrameHeaderSize; + return 0; + + default: + assert(0); /* impossible */ + RETURN_ERROR(GENERIC, "impossible to reach"); /* some compilers require default to do something */ + } +} + + +static size_t ZSTD_refDictContent(ZSTD_DCtx* dctx, const void* dict, size_t dictSize) +{ + dctx->dictEnd = dctx->previousDstEnd; + dctx->virtualStart = (const char*)dict - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->prefixStart)); + dctx->prefixStart = dict; + dctx->previousDstEnd = (const char*)dict + dictSize; +#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION + dctx->dictContentBeginForFuzzing = dctx->prefixStart; + dctx->dictContentEndForFuzzing = dctx->previousDstEnd; +#endif + return 0; +} + +/*! ZSTD_loadDEntropy() : + * dict : must point at beginning of a valid zstd dictionary. + * @return : size of entropy tables read */ +size_t +ZSTD_loadDEntropy(ZSTD_entropyDTables_t* entropy, + const void* const dict, size_t const dictSize) +{ + const BYTE* dictPtr = (const BYTE*)dict; + const BYTE* const dictEnd = dictPtr + dictSize; + + RETURN_ERROR_IF(dictSize <= 8, dictionary_corrupted, "dict is too small"); + assert(MEM_readLE32(dict) == ZSTD_MAGIC_DICTIONARY); /* dict must be valid */ + dictPtr += 8; /* skip header = magic + dictID */ + + ZSTD_STATIC_ASSERT(offsetof(ZSTD_entropyDTables_t, OFTable) == offsetof(ZSTD_entropyDTables_t, LLTable) + sizeof(entropy->LLTable)); + ZSTD_STATIC_ASSERT(offsetof(ZSTD_entropyDTables_t, MLTable) == offsetof(ZSTD_entropyDTables_t, OFTable) + sizeof(entropy->OFTable)); + ZSTD_STATIC_ASSERT(sizeof(entropy->LLTable) + sizeof(entropy->OFTable) + sizeof(entropy->MLTable) >= HUF_DECOMPRESS_WORKSPACE_SIZE); + { void* const workspace = &entropy->LLTable; /* use fse tables as temporary workspace; implies fse tables are grouped together */ + size_t const workspaceSize = sizeof(entropy->LLTable) + sizeof(entropy->OFTable) + sizeof(entropy->MLTable); +#ifdef HUF_FORCE_DECOMPRESS_X1 + /* in minimal huffman, we always use X1 variants */ + size_t const hSize = HUF_readDTableX1_wksp(entropy->hufTable, + dictPtr, dictEnd - dictPtr, + workspace, workspaceSize, /* flags */ 0); +#else + size_t const hSize = HUF_readDTableX2_wksp(entropy->hufTable, + dictPtr, (size_t)(dictEnd - dictPtr), + workspace, workspaceSize, /* flags */ 0); +#endif + RETURN_ERROR_IF(HUF_isError(hSize), dictionary_corrupted, ""); + dictPtr += hSize; + } + + { short offcodeNCount[MaxOff+1]; + unsigned offcodeMaxValue = MaxOff, offcodeLog; + size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, (size_t)(dictEnd-dictPtr)); + RETURN_ERROR_IF(FSE_isError(offcodeHeaderSize), dictionary_corrupted, ""); + RETURN_ERROR_IF(offcodeMaxValue > MaxOff, dictionary_corrupted, ""); + RETURN_ERROR_IF(offcodeLog > OffFSELog, dictionary_corrupted, ""); + ZSTD_buildFSETable( entropy->OFTable, + offcodeNCount, offcodeMaxValue, + OF_base, OF_bits, + offcodeLog, + entropy->workspace, sizeof(entropy->workspace), + /* bmi2 */0); + dictPtr += offcodeHeaderSize; + } + + { short matchlengthNCount[MaxML+1]; + unsigned matchlengthMaxValue = MaxML, matchlengthLog; + size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, (size_t)(dictEnd-dictPtr)); + RETURN_ERROR_IF(FSE_isError(matchlengthHeaderSize), dictionary_corrupted, ""); + RETURN_ERROR_IF(matchlengthMaxValue > MaxML, dictionary_corrupted, ""); + RETURN_ERROR_IF(matchlengthLog > MLFSELog, dictionary_corrupted, ""); + ZSTD_buildFSETable( entropy->MLTable, + matchlengthNCount, matchlengthMaxValue, + ML_base, ML_bits, + matchlengthLog, + entropy->workspace, sizeof(entropy->workspace), + /* bmi2 */ 0); + dictPtr += matchlengthHeaderSize; + } + + { short litlengthNCount[MaxLL+1]; + unsigned litlengthMaxValue = MaxLL, litlengthLog; + size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, (size_t)(dictEnd-dictPtr)); + RETURN_ERROR_IF(FSE_isError(litlengthHeaderSize), dictionary_corrupted, ""); + RETURN_ERROR_IF(litlengthMaxValue > MaxLL, dictionary_corrupted, ""); + RETURN_ERROR_IF(litlengthLog > LLFSELog, dictionary_corrupted, ""); + ZSTD_buildFSETable( entropy->LLTable, + litlengthNCount, litlengthMaxValue, + LL_base, LL_bits, + litlengthLog, + entropy->workspace, sizeof(entropy->workspace), + /* bmi2 */ 0); + dictPtr += litlengthHeaderSize; + } + + RETURN_ERROR_IF(dictPtr+12 > dictEnd, dictionary_corrupted, ""); + { int i; + size_t const dictContentSize = (size_t)(dictEnd - (dictPtr+12)); + for (i=0; i<3; i++) { + U32 const rep = MEM_readLE32(dictPtr); dictPtr += 4; + RETURN_ERROR_IF(rep==0 || rep > dictContentSize, + dictionary_corrupted, ""); + entropy->rep[i] = rep; + } } + + return (size_t)(dictPtr - (const BYTE*)dict); +} + +static size_t ZSTD_decompress_insertDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize) +{ + if (dictSize < 8) return ZSTD_refDictContent(dctx, dict, dictSize); + { U32 const magic = MEM_readLE32(dict); + if (magic != ZSTD_MAGIC_DICTIONARY) { + return ZSTD_refDictContent(dctx, dict, dictSize); /* pure content mode */ + } } + dctx->dictID = MEM_readLE32((const char*)dict + ZSTD_FRAMEIDSIZE); + + /* load entropy tables */ + { size_t const eSize = ZSTD_loadDEntropy(&dctx->entropy, dict, dictSize); + RETURN_ERROR_IF(ZSTD_isError(eSize), dictionary_corrupted, ""); + dict = (const char*)dict + eSize; + dictSize -= eSize; + } + dctx->litEntropy = dctx->fseEntropy = 1; + + /* reference dictionary content */ + return ZSTD_refDictContent(dctx, dict, dictSize); +} + +size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx) +{ + assert(dctx != NULL); +#if ZSTD_TRACE + dctx->traceCtx = (ZSTD_trace_decompress_begin != NULL) ? ZSTD_trace_decompress_begin(dctx) : 0; +#endif + dctx->expected = ZSTD_startingInputLength(dctx->format); /* dctx->format must be properly set */ + dctx->stage = ZSTDds_getFrameHeaderSize; + dctx->processedCSize = 0; + dctx->decodedSize = 0; + dctx->previousDstEnd = NULL; + dctx->prefixStart = NULL; + dctx->virtualStart = NULL; + dctx->dictEnd = NULL; + dctx->entropy.hufTable[0] = (HUF_DTable)((ZSTD_HUFFDTABLE_CAPACITY_LOG)*0x1000001); /* cover both little and big endian */ + dctx->litEntropy = dctx->fseEntropy = 0; + dctx->dictID = 0; + dctx->bType = bt_reserved; + dctx->isFrameDecompression = 1; + ZSTD_STATIC_ASSERT(sizeof(dctx->entropy.rep) == sizeof(repStartValue)); + ZSTD_memcpy(dctx->entropy.rep, repStartValue, sizeof(repStartValue)); /* initial repcodes */ + dctx->LLTptr = dctx->entropy.LLTable; + dctx->MLTptr = dctx->entropy.MLTable; + dctx->OFTptr = dctx->entropy.OFTable; + dctx->HUFptr = dctx->entropy.hufTable; + return 0; +} + +size_t ZSTD_decompressBegin_usingDict(ZSTD_DCtx* dctx, const void* dict, size_t dictSize) +{ + FORWARD_IF_ERROR( ZSTD_decompressBegin(dctx) , ""); + if (dict && dictSize) + RETURN_ERROR_IF( + ZSTD_isError(ZSTD_decompress_insertDictionary(dctx, dict, dictSize)), + dictionary_corrupted, ""); + return 0; +} + + +/* ====== ZSTD_DDict ====== */ + +size_t ZSTD_decompressBegin_usingDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict) +{ + DEBUGLOG(4, "ZSTD_decompressBegin_usingDDict"); + assert(dctx != NULL); + if (ddict) { + const char* const dictStart = (const char*)ZSTD_DDict_dictContent(ddict); + size_t const dictSize = ZSTD_DDict_dictSize(ddict); + const void* const dictEnd = dictStart + dictSize; + dctx->ddictIsCold = (dctx->dictEnd != dictEnd); + DEBUGLOG(4, "DDict is %s", + dctx->ddictIsCold ? "~cold~" : "hot!"); + } + FORWARD_IF_ERROR( ZSTD_decompressBegin(dctx) , ""); + if (ddict) { /* NULL ddict is equivalent to no dictionary */ + ZSTD_copyDDictParameters(dctx, ddict); + } + return 0; +} + +/*! ZSTD_getDictID_fromDict() : + * Provides the dictID stored within dictionary. + * if @return == 0, the dictionary is not conformant with Zstandard specification. + * It can still be loaded, but as a content-only dictionary. */ +unsigned ZSTD_getDictID_fromDict(const void* dict, size_t dictSize) +{ + if (dictSize < 8) return 0; + if (MEM_readLE32(dict) != ZSTD_MAGIC_DICTIONARY) return 0; + return MEM_readLE32((const char*)dict + ZSTD_FRAMEIDSIZE); +} + +/*! ZSTD_getDictID_fromFrame() : + * Provides the dictID required to decompress frame stored within `src`. + * If @return == 0, the dictID could not be decoded. + * This could for one of the following reasons : + * - The frame does not require a dictionary (most common case). + * - The frame was built with dictID intentionally removed. + * Needed dictionary is a hidden piece of information. + * Note : this use case also happens when using a non-conformant dictionary. + * - `srcSize` is too small, and as a result, frame header could not be decoded. + * Note : possible if `srcSize < ZSTD_FRAMEHEADERSIZE_MAX`. + * - This is not a Zstandard frame. + * When identifying the exact failure cause, it's possible to use + * ZSTD_getFrameHeader(), which will provide a more precise error code. */ +unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize) +{ + ZSTD_FrameHeader zfp = { 0, 0, 0, ZSTD_frame, 0, 0, 0, 0, 0 }; + size_t const hError = ZSTD_getFrameHeader(&zfp, src, srcSize); + if (ZSTD_isError(hError)) return 0; + return zfp.dictID; +} + + +/*! ZSTD_decompress_usingDDict() : +* Decompression using a pre-digested Dictionary +* Use dictionary without significant overhead. */ +size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const ZSTD_DDict* ddict) +{ + /* pass content and size in case legacy frames are encountered */ + return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize, + NULL, 0, + ddict); +} + + +/*===================================== +* Streaming decompression +*====================================*/ + +ZSTD_DStream* ZSTD_createDStream(void) +{ + DEBUGLOG(3, "ZSTD_createDStream"); + return ZSTD_createDCtx_internal(ZSTD_defaultCMem); +} + +ZSTD_DStream* ZSTD_initStaticDStream(void *workspace, size_t workspaceSize) +{ + return ZSTD_initStaticDCtx(workspace, workspaceSize); +} + +ZSTD_DStream* ZSTD_createDStream_advanced(ZSTD_customMem customMem) +{ + return ZSTD_createDCtx_internal(customMem); +} + +size_t ZSTD_freeDStream(ZSTD_DStream* zds) +{ + return ZSTD_freeDCtx(zds); +} + + +/* *** Initialization *** */ + +size_t ZSTD_DStreamInSize(void) { return ZSTD_BLOCKSIZE_MAX + ZSTD_blockHeaderSize; } +size_t ZSTD_DStreamOutSize(void) { return ZSTD_BLOCKSIZE_MAX; } + +size_t ZSTD_DCtx_loadDictionary_advanced(ZSTD_DCtx* dctx, + const void* dict, size_t dictSize, + ZSTD_dictLoadMethod_e dictLoadMethod, + ZSTD_dictContentType_e dictContentType) +{ + RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, ""); + ZSTD_clearDict(dctx); + if (dict && dictSize != 0) { + dctx->ddictLocal = ZSTD_createDDict_advanced(dict, dictSize, dictLoadMethod, dictContentType, dctx->customMem); + RETURN_ERROR_IF(dctx->ddictLocal == NULL, memory_allocation, "NULL pointer!"); + dctx->ddict = dctx->ddictLocal; + dctx->dictUses = ZSTD_use_indefinitely; + } + return 0; +} + +size_t ZSTD_DCtx_loadDictionary_byReference(ZSTD_DCtx* dctx, const void* dict, size_t dictSize) +{ + return ZSTD_DCtx_loadDictionary_advanced(dctx, dict, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto); +} + +size_t ZSTD_DCtx_loadDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize) +{ + return ZSTD_DCtx_loadDictionary_advanced(dctx, dict, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto); +} + +size_t ZSTD_DCtx_refPrefix_advanced(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType) +{ + FORWARD_IF_ERROR(ZSTD_DCtx_loadDictionary_advanced(dctx, prefix, prefixSize, ZSTD_dlm_byRef, dictContentType), ""); + dctx->dictUses = ZSTD_use_once; + return 0; +} + +size_t ZSTD_DCtx_refPrefix(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize) +{ + return ZSTD_DCtx_refPrefix_advanced(dctx, prefix, prefixSize, ZSTD_dct_rawContent); +} + + +/* ZSTD_initDStream_usingDict() : + * return : expected size, aka ZSTD_startingInputLength(). + * this function cannot fail */ +size_t ZSTD_initDStream_usingDict(ZSTD_DStream* zds, const void* dict, size_t dictSize) +{ + DEBUGLOG(4, "ZSTD_initDStream_usingDict"); + FORWARD_IF_ERROR( ZSTD_DCtx_reset(zds, ZSTD_reset_session_only) , ""); + FORWARD_IF_ERROR( ZSTD_DCtx_loadDictionary(zds, dict, dictSize) , ""); + return ZSTD_startingInputLength(zds->format); +} + +/* note : this variant can't fail */ +size_t ZSTD_initDStream(ZSTD_DStream* zds) +{ + DEBUGLOG(4, "ZSTD_initDStream"); + FORWARD_IF_ERROR(ZSTD_DCtx_reset(zds, ZSTD_reset_session_only), ""); + FORWARD_IF_ERROR(ZSTD_DCtx_refDDict(zds, NULL), ""); + return ZSTD_startingInputLength(zds->format); +} + +/* ZSTD_initDStream_usingDDict() : + * ddict will just be referenced, and must outlive decompression session + * this function cannot fail */ +size_t ZSTD_initDStream_usingDDict(ZSTD_DStream* dctx, const ZSTD_DDict* ddict) +{ + DEBUGLOG(4, "ZSTD_initDStream_usingDDict"); + FORWARD_IF_ERROR( ZSTD_DCtx_reset(dctx, ZSTD_reset_session_only) , ""); + FORWARD_IF_ERROR( ZSTD_DCtx_refDDict(dctx, ddict) , ""); + return ZSTD_startingInputLength(dctx->format); +} + +/* ZSTD_resetDStream() : + * return : expected size, aka ZSTD_startingInputLength(). + * this function cannot fail */ +size_t ZSTD_resetDStream(ZSTD_DStream* dctx) +{ + DEBUGLOG(4, "ZSTD_resetDStream"); + FORWARD_IF_ERROR(ZSTD_DCtx_reset(dctx, ZSTD_reset_session_only), ""); + return ZSTD_startingInputLength(dctx->format); +} + + +size_t ZSTD_DCtx_refDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict) +{ + RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, ""); + ZSTD_clearDict(dctx); + if (ddict) { + dctx->ddict = ddict; + dctx->dictUses = ZSTD_use_indefinitely; + if (dctx->refMultipleDDicts == ZSTD_rmd_refMultipleDDicts) { + if (dctx->ddictSet == NULL) { + dctx->ddictSet = ZSTD_createDDictHashSet(dctx->customMem); + if (!dctx->ddictSet) { + RETURN_ERROR(memory_allocation, "Failed to allocate memory for hash set!"); + } + } + assert(!dctx->staticSize); /* Impossible: ddictSet cannot have been allocated if static dctx */ + FORWARD_IF_ERROR(ZSTD_DDictHashSet_addDDict(dctx->ddictSet, ddict, dctx->customMem), ""); + } + } + return 0; +} + +/* ZSTD_DCtx_setMaxWindowSize() : + * note : no direct equivalence in ZSTD_DCtx_setParameter, + * since this version sets windowSize, and the other sets windowLog */ +size_t ZSTD_DCtx_setMaxWindowSize(ZSTD_DCtx* dctx, size_t maxWindowSize) +{ + ZSTD_bounds const bounds = ZSTD_dParam_getBounds(ZSTD_d_windowLogMax); + size_t const min = (size_t)1 << bounds.lowerBound; + size_t const max = (size_t)1 << bounds.upperBound; + RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, ""); + RETURN_ERROR_IF(maxWindowSize < min, parameter_outOfBound, ""); + RETURN_ERROR_IF(maxWindowSize > max, parameter_outOfBound, ""); + dctx->maxWindowSize = maxWindowSize; + return 0; +} + +size_t ZSTD_DCtx_setFormat(ZSTD_DCtx* dctx, ZSTD_format_e format) +{ + return ZSTD_DCtx_setParameter(dctx, ZSTD_d_format, (int)format); +} + +ZSTD_bounds ZSTD_dParam_getBounds(ZSTD_dParameter dParam) +{ + ZSTD_bounds bounds = { 0, 0, 0 }; + switch(dParam) { + case ZSTD_d_windowLogMax: + bounds.lowerBound = ZSTD_WINDOWLOG_ABSOLUTEMIN; + bounds.upperBound = ZSTD_WINDOWLOG_MAX; + return bounds; + case ZSTD_d_format: + bounds.lowerBound = (int)ZSTD_f_zstd1; + bounds.upperBound = (int)ZSTD_f_zstd1_magicless; + ZSTD_STATIC_ASSERT(ZSTD_f_zstd1 < ZSTD_f_zstd1_magicless); + return bounds; + case ZSTD_d_stableOutBuffer: + bounds.lowerBound = (int)ZSTD_bm_buffered; + bounds.upperBound = (int)ZSTD_bm_stable; + return bounds; + case ZSTD_d_forceIgnoreChecksum: + bounds.lowerBound = (int)ZSTD_d_validateChecksum; + bounds.upperBound = (int)ZSTD_d_ignoreChecksum; + return bounds; + case ZSTD_d_refMultipleDDicts: + bounds.lowerBound = (int)ZSTD_rmd_refSingleDDict; + bounds.upperBound = (int)ZSTD_rmd_refMultipleDDicts; + return bounds; + case ZSTD_d_disableHuffmanAssembly: + bounds.lowerBound = 0; + bounds.upperBound = 1; + return bounds; + case ZSTD_d_maxBlockSize: + bounds.lowerBound = ZSTD_BLOCKSIZE_MAX_MIN; + bounds.upperBound = ZSTD_BLOCKSIZE_MAX; + return bounds; + + default:; + } + bounds.error = ERROR(parameter_unsupported); + return bounds; +} + +/* ZSTD_dParam_withinBounds: + * @return 1 if value is within dParam bounds, + * 0 otherwise */ +static int ZSTD_dParam_withinBounds(ZSTD_dParameter dParam, int value) +{ + ZSTD_bounds const bounds = ZSTD_dParam_getBounds(dParam); + if (ZSTD_isError(bounds.error)) return 0; + if (value < bounds.lowerBound) return 0; + if (value > bounds.upperBound) return 0; + return 1; +} + +#define CHECK_DBOUNDS(p,v) { \ + RETURN_ERROR_IF(!ZSTD_dParam_withinBounds(p, v), parameter_outOfBound, ""); \ +} + +size_t ZSTD_DCtx_getParameter(ZSTD_DCtx* dctx, ZSTD_dParameter param, int* value) +{ + switch (param) { + case ZSTD_d_windowLogMax: + *value = (int)ZSTD_highbit32((U32)dctx->maxWindowSize); + return 0; + case ZSTD_d_format: + *value = (int)dctx->format; + return 0; + case ZSTD_d_stableOutBuffer: + *value = (int)dctx->outBufferMode; + return 0; + case ZSTD_d_forceIgnoreChecksum: + *value = (int)dctx->forceIgnoreChecksum; + return 0; + case ZSTD_d_refMultipleDDicts: + *value = (int)dctx->refMultipleDDicts; + return 0; + case ZSTD_d_disableHuffmanAssembly: + *value = (int)dctx->disableHufAsm; + return 0; + case ZSTD_d_maxBlockSize: + *value = dctx->maxBlockSizeParam; + return 0; + default:; + } + RETURN_ERROR(parameter_unsupported, ""); +} + +size_t ZSTD_DCtx_setParameter(ZSTD_DCtx* dctx, ZSTD_dParameter dParam, int value) +{ + RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, ""); + switch(dParam) { + case ZSTD_d_windowLogMax: + if (value == 0) value = ZSTD_WINDOWLOG_LIMIT_DEFAULT; + CHECK_DBOUNDS(ZSTD_d_windowLogMax, value); + dctx->maxWindowSize = ((size_t)1) << value; + return 0; + case ZSTD_d_format: + CHECK_DBOUNDS(ZSTD_d_format, value); + dctx->format = (ZSTD_format_e)value; + return 0; + case ZSTD_d_stableOutBuffer: + CHECK_DBOUNDS(ZSTD_d_stableOutBuffer, value); + dctx->outBufferMode = (ZSTD_bufferMode_e)value; + return 0; + case ZSTD_d_forceIgnoreChecksum: + CHECK_DBOUNDS(ZSTD_d_forceIgnoreChecksum, value); + dctx->forceIgnoreChecksum = (ZSTD_forceIgnoreChecksum_e)value; + return 0; + case ZSTD_d_refMultipleDDicts: + CHECK_DBOUNDS(ZSTD_d_refMultipleDDicts, value); + if (dctx->staticSize != 0) { + RETURN_ERROR(parameter_unsupported, "Static dctx does not support multiple DDicts!"); + } + dctx->refMultipleDDicts = (ZSTD_refMultipleDDicts_e)value; + return 0; + case ZSTD_d_disableHuffmanAssembly: + CHECK_DBOUNDS(ZSTD_d_disableHuffmanAssembly, value); + dctx->disableHufAsm = value != 0; + return 0; + case ZSTD_d_maxBlockSize: + if (value != 0) CHECK_DBOUNDS(ZSTD_d_maxBlockSize, value); + dctx->maxBlockSizeParam = value; + return 0; + default:; + } + RETURN_ERROR(parameter_unsupported, ""); +} + +size_t ZSTD_DCtx_reset(ZSTD_DCtx* dctx, ZSTD_ResetDirective reset) +{ + if ( (reset == ZSTD_reset_session_only) + || (reset == ZSTD_reset_session_and_parameters) ) { + dctx->streamStage = zdss_init; + dctx->noForwardProgress = 0; + dctx->isFrameDecompression = 1; + } + if ( (reset == ZSTD_reset_parameters) + || (reset == ZSTD_reset_session_and_parameters) ) { + RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, ""); + ZSTD_clearDict(dctx); + ZSTD_DCtx_resetParameters(dctx); + } + return 0; +} + + +size_t ZSTD_sizeof_DStream(const ZSTD_DStream* dctx) +{ + return ZSTD_sizeof_DCtx(dctx); +} + +static size_t ZSTD_decodingBufferSize_internal(unsigned long long windowSize, unsigned long long frameContentSize, size_t blockSizeMax) +{ + size_t const blockSize = MIN((size_t)MIN(windowSize, ZSTD_BLOCKSIZE_MAX), blockSizeMax); + /* We need blockSize + WILDCOPY_OVERLENGTH worth of buffer so that if a block + * ends at windowSize + WILDCOPY_OVERLENGTH + 1 bytes, we can start writing + * the block at the beginning of the output buffer, and maintain a full window. + * + * We need another blockSize worth of buffer so that we can store split + * literals at the end of the block without overwriting the extDict window. + */ + unsigned long long const neededRBSize = windowSize + (blockSize * 2) + (WILDCOPY_OVERLENGTH * 2); + unsigned long long const neededSize = MIN(frameContentSize, neededRBSize); + size_t const minRBSize = (size_t) neededSize; + RETURN_ERROR_IF((unsigned long long)minRBSize != neededSize, + frameParameter_windowTooLarge, ""); + return minRBSize; +} + +size_t ZSTD_decodingBufferSize_min(unsigned long long windowSize, unsigned long long frameContentSize) +{ + return ZSTD_decodingBufferSize_internal(windowSize, frameContentSize, ZSTD_BLOCKSIZE_MAX); +} + +size_t ZSTD_estimateDStreamSize(size_t windowSize) +{ + size_t const blockSize = MIN(windowSize, ZSTD_BLOCKSIZE_MAX); + size_t const inBuffSize = blockSize; /* no block can be larger */ + size_t const outBuffSize = ZSTD_decodingBufferSize_min(windowSize, ZSTD_CONTENTSIZE_UNKNOWN); + return ZSTD_estimateDCtxSize() + inBuffSize + outBuffSize; +} + +size_t ZSTD_estimateDStreamSize_fromFrame(const void* src, size_t srcSize) +{ + U32 const windowSizeMax = 1U << ZSTD_WINDOWLOG_MAX; /* note : should be user-selectable, but requires an additional parameter (or a dctx) */ + ZSTD_FrameHeader zfh; + size_t const err = ZSTD_getFrameHeader(&zfh, src, srcSize); + if (ZSTD_isError(err)) return err; + RETURN_ERROR_IF(err>0, srcSize_wrong, ""); + RETURN_ERROR_IF(zfh.windowSize > windowSizeMax, + frameParameter_windowTooLarge, ""); + return ZSTD_estimateDStreamSize((size_t)zfh.windowSize); +} + + +/* ***** Decompression ***** */ + +static int ZSTD_DCtx_isOverflow(ZSTD_DStream* zds, size_t const neededInBuffSize, size_t const neededOutBuffSize) +{ + return (zds->inBuffSize + zds->outBuffSize) >= (neededInBuffSize + neededOutBuffSize) * ZSTD_WORKSPACETOOLARGE_FACTOR; +} + +static void ZSTD_DCtx_updateOversizedDuration(ZSTD_DStream* zds, size_t const neededInBuffSize, size_t const neededOutBuffSize) +{ + if (ZSTD_DCtx_isOverflow(zds, neededInBuffSize, neededOutBuffSize)) + zds->oversizedDuration++; + else + zds->oversizedDuration = 0; +} + +static int ZSTD_DCtx_isOversizedTooLong(ZSTD_DStream* zds) +{ + return zds->oversizedDuration >= ZSTD_WORKSPACETOOLARGE_MAXDURATION; +} + +/* Checks that the output buffer hasn't changed if ZSTD_obm_stable is used. */ +static size_t ZSTD_checkOutBuffer(ZSTD_DStream const* zds, ZSTD_outBuffer const* output) +{ + ZSTD_outBuffer const expect = zds->expectedOutBuffer; + /* No requirement when ZSTD_obm_stable is not enabled. */ + if (zds->outBufferMode != ZSTD_bm_stable) + return 0; + /* Any buffer is allowed in zdss_init, this must be the same for every other call until + * the context is reset. + */ + if (zds->streamStage == zdss_init) + return 0; + /* The buffer must match our expectation exactly. */ + if (expect.dst == output->dst && expect.pos == output->pos && expect.size == output->size) + return 0; + RETURN_ERROR(dstBuffer_wrong, "ZSTD_d_stableOutBuffer enabled but output differs!"); +} + +/* Calls ZSTD_decompressContinue() with the right parameters for ZSTD_decompressStream() + * and updates the stage and the output buffer state. This call is extracted so it can be + * used both when reading directly from the ZSTD_inBuffer, and in buffered input mode. + * NOTE: You must break after calling this function since the streamStage is modified. + */ +static size_t ZSTD_decompressContinueStream( + ZSTD_DStream* zds, char** op, char* oend, + void const* src, size_t srcSize) { + int const isSkipFrame = ZSTD_isSkipFrame(zds); + if (zds->outBufferMode == ZSTD_bm_buffered) { + size_t const dstSize = isSkipFrame ? 0 : zds->outBuffSize - zds->outStart; + size_t const decodedSize = ZSTD_decompressContinue(zds, + zds->outBuff + zds->outStart, dstSize, src, srcSize); + FORWARD_IF_ERROR(decodedSize, ""); + if (!decodedSize && !isSkipFrame) { + zds->streamStage = zdss_read; + } else { + zds->outEnd = zds->outStart + decodedSize; + zds->streamStage = zdss_flush; + } + } else { + /* Write directly into the output buffer */ + size_t const dstSize = isSkipFrame ? 0 : (size_t)(oend - *op); + size_t const decodedSize = ZSTD_decompressContinue(zds, *op, dstSize, src, srcSize); + FORWARD_IF_ERROR(decodedSize, ""); + *op += decodedSize; + /* Flushing is not needed. */ + zds->streamStage = zdss_read; + assert(*op <= oend); + assert(zds->outBufferMode == ZSTD_bm_stable); + } + return 0; +} + +size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input) +{ + const char* const src = (const char*)input->src; + const char* const istart = input->pos != 0 ? src + input->pos : src; + const char* const iend = input->size != 0 ? src + input->size : src; + const char* ip = istart; + char* const dst = (char*)output->dst; + char* const ostart = output->pos != 0 ? dst + output->pos : dst; + char* const oend = output->size != 0 ? dst + output->size : dst; + char* op = ostart; + U32 someMoreWork = 1; + + DEBUGLOG(5, "ZSTD_decompressStream"); + assert(zds != NULL); + RETURN_ERROR_IF( + input->pos > input->size, + srcSize_wrong, + "forbidden. in: pos: %u vs size: %u", + (U32)input->pos, (U32)input->size); + RETURN_ERROR_IF( + output->pos > output->size, + dstSize_tooSmall, + "forbidden. out: pos: %u vs size: %u", + (U32)output->pos, (U32)output->size); + DEBUGLOG(5, "input size : %u", (U32)(input->size - input->pos)); + FORWARD_IF_ERROR(ZSTD_checkOutBuffer(zds, output), ""); + + while (someMoreWork) { + switch(zds->streamStage) + { + case zdss_init : + DEBUGLOG(5, "stage zdss_init => transparent reset "); + zds->streamStage = zdss_loadHeader; + zds->lhSize = zds->inPos = zds->outStart = zds->outEnd = 0; +#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1) + zds->legacyVersion = 0; +#endif + zds->hostageByte = 0; + zds->expectedOutBuffer = *output; + ZSTD_FALLTHROUGH; + + case zdss_loadHeader : + DEBUGLOG(5, "stage zdss_loadHeader (srcSize : %u)", (U32)(iend - ip)); +#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1) + if (zds->legacyVersion) { + RETURN_ERROR_IF(zds->staticSize, memory_allocation, + "legacy support is incompatible with static dctx"); + { size_t const hint = ZSTD_decompressLegacyStream(zds->legacyContext, zds->legacyVersion, output, input); + if (hint==0) zds->streamStage = zdss_init; + return hint; + } } +#endif + { size_t const hSize = ZSTD_getFrameHeader_advanced(&zds->fParams, zds->headerBuffer, zds->lhSize, zds->format); + if (zds->refMultipleDDicts && zds->ddictSet) { + ZSTD_DCtx_selectFrameDDict(zds); + } + if (ZSTD_isError(hSize)) { +#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1) + U32 const legacyVersion = ZSTD_isLegacy(istart, iend-istart); + if (legacyVersion) { + ZSTD_DDict const* const ddict = ZSTD_getDDict(zds); + const void* const dict = ddict ? ZSTD_DDict_dictContent(ddict) : NULL; + size_t const dictSize = ddict ? ZSTD_DDict_dictSize(ddict) : 0; + DEBUGLOG(5, "ZSTD_decompressStream: detected legacy version v0.%u", legacyVersion); + RETURN_ERROR_IF(zds->staticSize, memory_allocation, + "legacy support is incompatible with static dctx"); + FORWARD_IF_ERROR(ZSTD_initLegacyStream(&zds->legacyContext, + zds->previousLegacyVersion, legacyVersion, + dict, dictSize), ""); + zds->legacyVersion = zds->previousLegacyVersion = legacyVersion; + { size_t const hint = ZSTD_decompressLegacyStream(zds->legacyContext, legacyVersion, output, input); + if (hint==0) zds->streamStage = zdss_init; /* or stay in stage zdss_loadHeader */ + return hint; + } } +#endif + return hSize; /* error */ + } + if (hSize != 0) { /* need more input */ + size_t const toLoad = hSize - zds->lhSize; /* if hSize!=0, hSize > zds->lhSize */ + size_t const remainingInput = (size_t)(iend-ip); + assert(iend >= ip); + if (toLoad > remainingInput) { /* not enough input to load full header */ + if (remainingInput > 0) { + ZSTD_memcpy(zds->headerBuffer + zds->lhSize, ip, remainingInput); + zds->lhSize += remainingInput; + } + input->pos = input->size; + /* check first few bytes */ + FORWARD_IF_ERROR( + ZSTD_getFrameHeader_advanced(&zds->fParams, zds->headerBuffer, zds->lhSize, zds->format), + "First few bytes detected incorrect" ); + /* return hint input size */ + return (MAX((size_t)ZSTD_FRAMEHEADERSIZE_MIN(zds->format), hSize) - zds->lhSize) + ZSTD_blockHeaderSize; /* remaining header bytes + next block header */ + } + assert(ip != NULL); + ZSTD_memcpy(zds->headerBuffer + zds->lhSize, ip, toLoad); zds->lhSize = hSize; ip += toLoad; + break; + } } + + /* check for single-pass mode opportunity */ + if (zds->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN + && zds->fParams.frameType != ZSTD_skippableFrame + && (U64)(size_t)(oend-op) >= zds->fParams.frameContentSize) { + size_t const cSize = ZSTD_findFrameCompressedSize_advanced(istart, (size_t)(iend-istart), zds->format); + if (cSize <= (size_t)(iend-istart)) { + /* shortcut : using single-pass mode */ + size_t const decompressedSize = ZSTD_decompress_usingDDict(zds, op, (size_t)(oend-op), istart, cSize, ZSTD_getDDict(zds)); + if (ZSTD_isError(decompressedSize)) return decompressedSize; + DEBUGLOG(4, "shortcut to single-pass ZSTD_decompress_usingDDict()"); + assert(istart != NULL); + ip = istart + cSize; + op = op ? op + decompressedSize : op; /* can occur if frameContentSize = 0 (empty frame) */ + zds->expected = 0; + zds->streamStage = zdss_init; + someMoreWork = 0; + break; + } } + + /* Check output buffer is large enough for ZSTD_odm_stable. */ + if (zds->outBufferMode == ZSTD_bm_stable + && zds->fParams.frameType != ZSTD_skippableFrame + && zds->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN + && (U64)(size_t)(oend-op) < zds->fParams.frameContentSize) { + RETURN_ERROR(dstSize_tooSmall, "ZSTD_obm_stable passed but ZSTD_outBuffer is too small"); + } + + /* Consume header (see ZSTDds_decodeFrameHeader) */ + DEBUGLOG(4, "Consume header"); + FORWARD_IF_ERROR(ZSTD_decompressBegin_usingDDict(zds, ZSTD_getDDict(zds)), ""); + + if (zds->format == ZSTD_f_zstd1 + && (MEM_readLE32(zds->headerBuffer) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { /* skippable frame */ + zds->expected = MEM_readLE32(zds->headerBuffer + ZSTD_FRAMEIDSIZE); + zds->stage = ZSTDds_skipFrame; + } else { + FORWARD_IF_ERROR(ZSTD_decodeFrameHeader(zds, zds->headerBuffer, zds->lhSize), ""); + zds->expected = ZSTD_blockHeaderSize; + zds->stage = ZSTDds_decodeBlockHeader; + } + + /* control buffer memory usage */ + DEBUGLOG(4, "Control max memory usage (%u KB <= max %u KB)", + (U32)(zds->fParams.windowSize >>10), + (U32)(zds->maxWindowSize >> 10) ); + zds->fParams.windowSize = MAX(zds->fParams.windowSize, 1U << ZSTD_WINDOWLOG_ABSOLUTEMIN); + RETURN_ERROR_IF(zds->fParams.windowSize > zds->maxWindowSize, + frameParameter_windowTooLarge, ""); + if (zds->maxBlockSizeParam != 0) + zds->fParams.blockSizeMax = MIN(zds->fParams.blockSizeMax, (unsigned)zds->maxBlockSizeParam); + + /* Adapt buffer sizes to frame header instructions */ + { size_t const neededInBuffSize = MAX(zds->fParams.blockSizeMax, 4 /* frame checksum */); + size_t const neededOutBuffSize = zds->outBufferMode == ZSTD_bm_buffered + ? ZSTD_decodingBufferSize_internal(zds->fParams.windowSize, zds->fParams.frameContentSize, zds->fParams.blockSizeMax) + : 0; + + ZSTD_DCtx_updateOversizedDuration(zds, neededInBuffSize, neededOutBuffSize); + + { int const tooSmall = (zds->inBuffSize < neededInBuffSize) || (zds->outBuffSize < neededOutBuffSize); + int const tooLarge = ZSTD_DCtx_isOversizedTooLong(zds); + + if (tooSmall || tooLarge) { + size_t const bufferSize = neededInBuffSize + neededOutBuffSize; + DEBUGLOG(4, "inBuff : from %u to %u", + (U32)zds->inBuffSize, (U32)neededInBuffSize); + DEBUGLOG(4, "outBuff : from %u to %u", + (U32)zds->outBuffSize, (U32)neededOutBuffSize); + if (zds->staticSize) { /* static DCtx */ + DEBUGLOG(4, "staticSize : %u", (U32)zds->staticSize); + assert(zds->staticSize >= sizeof(ZSTD_DCtx)); /* controlled at init */ + RETURN_ERROR_IF( + bufferSize > zds->staticSize - sizeof(ZSTD_DCtx), + memory_allocation, ""); + } else { + ZSTD_customFree(zds->inBuff, zds->customMem); + zds->inBuffSize = 0; + zds->outBuffSize = 0; + zds->inBuff = (char*)ZSTD_customMalloc(bufferSize, zds->customMem); + RETURN_ERROR_IF(zds->inBuff == NULL, memory_allocation, ""); + } + zds->inBuffSize = neededInBuffSize; + zds->outBuff = zds->inBuff + zds->inBuffSize; + zds->outBuffSize = neededOutBuffSize; + } } } + zds->streamStage = zdss_read; + ZSTD_FALLTHROUGH; + + case zdss_read: + DEBUGLOG(5, "stage zdss_read"); + { size_t const neededInSize = ZSTD_nextSrcSizeToDecompressWithInputSize(zds, (size_t)(iend - ip)); + DEBUGLOG(5, "neededInSize = %u", (U32)neededInSize); + if (neededInSize==0) { /* end of frame */ + zds->streamStage = zdss_init; + someMoreWork = 0; + break; + } + if ((size_t)(iend-ip) >= neededInSize) { /* decode directly from src */ + FORWARD_IF_ERROR(ZSTD_decompressContinueStream(zds, &op, oend, ip, neededInSize), ""); + assert(ip != NULL); + ip += neededInSize; + /* Function modifies the stage so we must break */ + break; + } } + if (ip==iend) { someMoreWork = 0; break; } /* no more input */ + zds->streamStage = zdss_load; + ZSTD_FALLTHROUGH; + + case zdss_load: + { size_t const neededInSize = ZSTD_nextSrcSizeToDecompress(zds); + size_t const toLoad = neededInSize - zds->inPos; + int const isSkipFrame = ZSTD_isSkipFrame(zds); + size_t loadedSize; + /* At this point we shouldn't be decompressing a block that we can stream. */ + assert(neededInSize == ZSTD_nextSrcSizeToDecompressWithInputSize(zds, (size_t)(iend - ip))); + if (isSkipFrame) { + loadedSize = MIN(toLoad, (size_t)(iend-ip)); + } else { + RETURN_ERROR_IF(toLoad > zds->inBuffSize - zds->inPos, + corruption_detected, + "should never happen"); + loadedSize = ZSTD_limitCopy(zds->inBuff + zds->inPos, toLoad, ip, (size_t)(iend-ip)); + } + if (loadedSize != 0) { + /* ip may be NULL */ + ip += loadedSize; + zds->inPos += loadedSize; + } + if (loadedSize < toLoad) { someMoreWork = 0; break; } /* not enough input, wait for more */ + + /* decode loaded input */ + zds->inPos = 0; /* input is consumed */ + FORWARD_IF_ERROR(ZSTD_decompressContinueStream(zds, &op, oend, zds->inBuff, neededInSize), ""); + /* Function modifies the stage so we must break */ + break; + } + case zdss_flush: + { + size_t const toFlushSize = zds->outEnd - zds->outStart; + size_t const flushedSize = ZSTD_limitCopy(op, (size_t)(oend-op), zds->outBuff + zds->outStart, toFlushSize); + + op = op ? op + flushedSize : op; + + zds->outStart += flushedSize; + if (flushedSize == toFlushSize) { /* flush completed */ + zds->streamStage = zdss_read; + if ( (zds->outBuffSize < zds->fParams.frameContentSize) + && (zds->outStart + zds->fParams.blockSizeMax > zds->outBuffSize) ) { + DEBUGLOG(5, "restart filling outBuff from beginning (left:%i, needed:%u)", + (int)(zds->outBuffSize - zds->outStart), + (U32)zds->fParams.blockSizeMax); + zds->outStart = zds->outEnd = 0; + } + break; + } } + /* cannot complete flush */ + someMoreWork = 0; + break; + + default: + assert(0); /* impossible */ + RETURN_ERROR(GENERIC, "impossible to reach"); /* some compilers require default to do something */ + } } + + /* result */ + input->pos = (size_t)(ip - (const char*)(input->src)); + output->pos = (size_t)(op - (char*)(output->dst)); + + /* Update the expected output buffer for ZSTD_obm_stable. */ + zds->expectedOutBuffer = *output; + + if ((ip==istart) && (op==ostart)) { /* no forward progress */ + zds->noForwardProgress ++; + if (zds->noForwardProgress >= ZSTD_NO_FORWARD_PROGRESS_MAX) { + RETURN_ERROR_IF(op==oend, noForwardProgress_destFull, ""); + RETURN_ERROR_IF(ip==iend, noForwardProgress_inputEmpty, ""); + assert(0); + } + } else { + zds->noForwardProgress = 0; + } + { size_t nextSrcSizeHint = ZSTD_nextSrcSizeToDecompress(zds); + if (!nextSrcSizeHint) { /* frame fully decoded */ + if (zds->outEnd == zds->outStart) { /* output fully flushed */ + if (zds->hostageByte) { + if (input->pos >= input->size) { + /* can't release hostage (not present) */ + zds->streamStage = zdss_read; + return 1; + } + input->pos++; /* release hostage */ + } /* zds->hostageByte */ + return 0; + } /* zds->outEnd == zds->outStart */ + if (!zds->hostageByte) { /* output not fully flushed; keep last byte as hostage; will be released when all output is flushed */ + input->pos--; /* note : pos > 0, otherwise, impossible to finish reading last block */ + zds->hostageByte=1; + } + return 1; + } /* nextSrcSizeHint==0 */ + nextSrcSizeHint += ZSTD_blockHeaderSize * (ZSTD_nextInputType(zds) == ZSTDnit_block); /* preload header of next block */ + assert(zds->inPos <= nextSrcSizeHint); + nextSrcSizeHint -= zds->inPos; /* part already loaded*/ + return nextSrcSizeHint; + } +} + +size_t ZSTD_decompressStream_simpleArgs ( + ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, size_t* dstPos, + const void* src, size_t srcSize, size_t* srcPos) +{ + ZSTD_outBuffer output; + ZSTD_inBuffer input; + output.dst = dst; + output.size = dstCapacity; + output.pos = *dstPos; + input.src = src; + input.size = srcSize; + input.pos = *srcPos; + { size_t const cErr = ZSTD_decompressStream(dctx, &output, &input); + *dstPos = output.pos; + *srcPos = input.pos; + return cErr; + } +} +/**** ended inlining decompress/zstd_decompress.c ****/ +/**** start inlining decompress/zstd_decompress_block.c ****/ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +/* zstd_decompress_block : + * this module takes care of decompressing _compressed_ block */ + +/*-******************************************************* +* Dependencies +*********************************************************/ +/**** skipping file: ../common/zstd_deps.h ****/ +/**** skipping file: ../common/compiler.h ****/ +/**** skipping file: ../common/cpu.h ****/ +/**** skipping file: ../common/mem.h ****/ +#define FSE_STATIC_LINKING_ONLY +/**** skipping file: ../common/fse.h ****/ +/**** skipping file: ../common/huf.h ****/ +/**** skipping file: ../common/zstd_internal.h ****/ +/**** skipping file: zstd_decompress_internal.h ****/ +/**** skipping file: zstd_ddict.h ****/ +/**** skipping file: zstd_decompress_block.h ****/ +/**** skipping file: ../common/bits.h ****/ + +/*_******************************************************* +* Macros +**********************************************************/ + +/* These two optional macros force the use one way or another of the two + * ZSTD_decompressSequences implementations. You can't force in both directions + * at the same time. + */ +#if defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \ + defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG) +#error "Cannot force the use of the short and the long ZSTD_decompressSequences variants!" +#endif + + +/*_******************************************************* +* Memory operations +**********************************************************/ +static void ZSTD_copy4(void* dst, const void* src) { ZSTD_memcpy(dst, src, 4); } + + +/*-************************************************************* + * Block decoding + ***************************************************************/ + +static size_t ZSTD_blockSizeMax(ZSTD_DCtx const* dctx) +{ + size_t const blockSizeMax = dctx->isFrameDecompression ? dctx->fParams.blockSizeMax : ZSTD_BLOCKSIZE_MAX; + assert(blockSizeMax <= ZSTD_BLOCKSIZE_MAX); + return blockSizeMax; +} + +/*! ZSTD_getcBlockSize() : + * Provides the size of compressed block from block header `src` */ +size_t ZSTD_getcBlockSize(const void* src, size_t srcSize, + blockProperties_t* bpPtr) +{ + RETURN_ERROR_IF(srcSize < ZSTD_blockHeaderSize, srcSize_wrong, ""); + + { U32 const cBlockHeader = MEM_readLE24(src); + U32 const cSize = cBlockHeader >> 3; + bpPtr->lastBlock = cBlockHeader & 1; + bpPtr->blockType = (blockType_e)((cBlockHeader >> 1) & 3); + bpPtr->origSize = cSize; /* only useful for RLE */ + if (bpPtr->blockType == bt_rle) return 1; + RETURN_ERROR_IF(bpPtr->blockType == bt_reserved, corruption_detected, ""); + return cSize; + } +} + +/* Allocate buffer for literals, either overlapping current dst, or split between dst and litExtraBuffer, or stored entirely within litExtraBuffer */ +static void ZSTD_allocateLiteralsBuffer(ZSTD_DCtx* dctx, void* const dst, const size_t dstCapacity, const size_t litSize, + const streaming_operation streaming, const size_t expectedWriteSize, const unsigned splitImmediately) +{ + size_t const blockSizeMax = ZSTD_blockSizeMax(dctx); + assert(litSize <= blockSizeMax); + assert(dctx->isFrameDecompression || streaming == not_streaming); + assert(expectedWriteSize <= blockSizeMax); + if (streaming == not_streaming && dstCapacity > blockSizeMax + WILDCOPY_OVERLENGTH + litSize + WILDCOPY_OVERLENGTH) { + /* If we aren't streaming, we can just put the literals after the output + * of the current block. We don't need to worry about overwriting the + * extDict of our window, because it doesn't exist. + * So if we have space after the end of the block, just put it there. + */ + dctx->litBuffer = (BYTE*)dst + blockSizeMax + WILDCOPY_OVERLENGTH; + dctx->litBufferEnd = dctx->litBuffer + litSize; + dctx->litBufferLocation = ZSTD_in_dst; + } else if (litSize <= ZSTD_LITBUFFEREXTRASIZE) { + /* Literals fit entirely within the extra buffer, put them there to avoid + * having to split the literals. + */ + dctx->litBuffer = dctx->litExtraBuffer; + dctx->litBufferEnd = dctx->litBuffer + litSize; + dctx->litBufferLocation = ZSTD_not_in_dst; + } else { + assert(blockSizeMax > ZSTD_LITBUFFEREXTRASIZE); + /* Literals must be split between the output block and the extra lit + * buffer. We fill the extra lit buffer with the tail of the literals, + * and put the rest of the literals at the end of the block, with + * WILDCOPY_OVERLENGTH of buffer room to allow for overreads. + * This MUST not write more than our maxBlockSize beyond dst, because in + * streaming mode, that could overwrite part of our extDict window. + */ + if (splitImmediately) { + /* won't fit in litExtraBuffer, so it will be split between end of dst and extra buffer */ + dctx->litBuffer = (BYTE*)dst + expectedWriteSize - litSize + ZSTD_LITBUFFEREXTRASIZE - WILDCOPY_OVERLENGTH; + dctx->litBufferEnd = dctx->litBuffer + litSize - ZSTD_LITBUFFEREXTRASIZE; + } else { + /* initially this will be stored entirely in dst during huffman decoding, it will partially be shifted to litExtraBuffer after */ + dctx->litBuffer = (BYTE*)dst + expectedWriteSize - litSize; + dctx->litBufferEnd = (BYTE*)dst + expectedWriteSize; + } + dctx->litBufferLocation = ZSTD_split; + assert(dctx->litBufferEnd <= (BYTE*)dst + expectedWriteSize); + } +} + +/*! ZSTD_decodeLiteralsBlock() : + * Where it is possible to do so without being stomped by the output during decompression, the literals block will be stored + * in the dstBuffer. If there is room to do so, it will be stored in full in the excess dst space after where the current + * block will be output. Otherwise it will be stored at the end of the current dst blockspace, with a small portion being + * stored in dctx->litExtraBuffer to help keep it "ahead" of the current output write. + * + * @return : nb of bytes read from src (< srcSize ) + * note : symbol not declared but exposed for fullbench */ +static size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx, + const void* src, size_t srcSize, /* note : srcSize < BLOCKSIZE */ + void* dst, size_t dstCapacity, const streaming_operation streaming) +{ + DEBUGLOG(5, "ZSTD_decodeLiteralsBlock"); + RETURN_ERROR_IF(srcSize < MIN_CBLOCK_SIZE, corruption_detected, ""); + + { const BYTE* const istart = (const BYTE*) src; + SymbolEncodingType_e const litEncType = (SymbolEncodingType_e)(istart[0] & 3); + size_t const blockSizeMax = ZSTD_blockSizeMax(dctx); + + switch(litEncType) + { + case set_repeat: + DEBUGLOG(5, "set_repeat flag : re-using stats from previous compressed literals block"); + RETURN_ERROR_IF(dctx->litEntropy==0, dictionary_corrupted, ""); + ZSTD_FALLTHROUGH; + + case set_compressed: + RETURN_ERROR_IF(srcSize < 5, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 2; here we need up to 5 for case 3"); + { size_t lhSize, litSize, litCSize; + U32 singleStream=0; + U32 const lhlCode = (istart[0] >> 2) & 3; + U32 const lhc = MEM_readLE32(istart); + size_t hufSuccess; + size_t expectedWriteSize = MIN(blockSizeMax, dstCapacity); + int const flags = 0 + | (ZSTD_DCtx_get_bmi2(dctx) ? HUF_flags_bmi2 : 0) + | (dctx->disableHufAsm ? HUF_flags_disableAsm : 0); + switch(lhlCode) + { + case 0: case 1: default: /* note : default is impossible, since lhlCode into [0..3] */ + /* 2 - 2 - 10 - 10 */ + singleStream = !lhlCode; + lhSize = 3; + litSize = (lhc >> 4) & 0x3FF; + litCSize = (lhc >> 14) & 0x3FF; + break; + case 2: + /* 2 - 2 - 14 - 14 */ + lhSize = 4; + litSize = (lhc >> 4) & 0x3FFF; + litCSize = lhc >> 18; + break; + case 3: + /* 2 - 2 - 18 - 18 */ + lhSize = 5; + litSize = (lhc >> 4) & 0x3FFFF; + litCSize = (lhc >> 22) + ((size_t)istart[4] << 10); + break; + } + RETURN_ERROR_IF(litSize > 0 && dst == NULL, dstSize_tooSmall, "NULL not handled"); + RETURN_ERROR_IF(litSize > blockSizeMax, corruption_detected, ""); + if (!singleStream) + RETURN_ERROR_IF(litSize < MIN_LITERALS_FOR_4_STREAMS, literals_headerWrong, + "Not enough literals (%zu) for the 4-streams mode (min %u)", + litSize, MIN_LITERALS_FOR_4_STREAMS); + RETURN_ERROR_IF(litCSize + lhSize > srcSize, corruption_detected, ""); + RETURN_ERROR_IF(expectedWriteSize < litSize , dstSize_tooSmall, ""); + ZSTD_allocateLiteralsBuffer(dctx, dst, dstCapacity, litSize, streaming, expectedWriteSize, 0); + + /* prefetch huffman table if cold */ + if (dctx->ddictIsCold && (litSize > 768 /* heuristic */)) { + PREFETCH_AREA(dctx->HUFptr, sizeof(dctx->entropy.hufTable)); + } + + if (litEncType==set_repeat) { + if (singleStream) { + hufSuccess = HUF_decompress1X_usingDTable( + dctx->litBuffer, litSize, istart+lhSize, litCSize, + dctx->HUFptr, flags); + } else { + assert(litSize >= MIN_LITERALS_FOR_4_STREAMS); + hufSuccess = HUF_decompress4X_usingDTable( + dctx->litBuffer, litSize, istart+lhSize, litCSize, + dctx->HUFptr, flags); + } + } else { + if (singleStream) { +#if defined(HUF_FORCE_DECOMPRESS_X2) + hufSuccess = HUF_decompress1X_DCtx_wksp( + dctx->entropy.hufTable, dctx->litBuffer, litSize, + istart+lhSize, litCSize, dctx->workspace, + sizeof(dctx->workspace), flags); +#else + hufSuccess = HUF_decompress1X1_DCtx_wksp( + dctx->entropy.hufTable, dctx->litBuffer, litSize, + istart+lhSize, litCSize, dctx->workspace, + sizeof(dctx->workspace), flags); +#endif + } else { + hufSuccess = HUF_decompress4X_hufOnly_wksp( + dctx->entropy.hufTable, dctx->litBuffer, litSize, + istart+lhSize, litCSize, dctx->workspace, + sizeof(dctx->workspace), flags); + } + } + if (dctx->litBufferLocation == ZSTD_split) + { + assert(litSize > ZSTD_LITBUFFEREXTRASIZE); + ZSTD_memcpy(dctx->litExtraBuffer, dctx->litBufferEnd - ZSTD_LITBUFFEREXTRASIZE, ZSTD_LITBUFFEREXTRASIZE); + ZSTD_memmove(dctx->litBuffer + ZSTD_LITBUFFEREXTRASIZE - WILDCOPY_OVERLENGTH, dctx->litBuffer, litSize - ZSTD_LITBUFFEREXTRASIZE); + dctx->litBuffer += ZSTD_LITBUFFEREXTRASIZE - WILDCOPY_OVERLENGTH; + dctx->litBufferEnd -= WILDCOPY_OVERLENGTH; + assert(dctx->litBufferEnd <= (BYTE*)dst + blockSizeMax); + } + + RETURN_ERROR_IF(HUF_isError(hufSuccess), corruption_detected, ""); + + dctx->litPtr = dctx->litBuffer; + dctx->litSize = litSize; + dctx->litEntropy = 1; + if (litEncType==set_compressed) dctx->HUFptr = dctx->entropy.hufTable; + return litCSize + lhSize; + } + + case set_basic: + { size_t litSize, lhSize; + U32 const lhlCode = ((istart[0]) >> 2) & 3; + size_t expectedWriteSize = MIN(blockSizeMax, dstCapacity); + switch(lhlCode) + { + case 0: case 2: default: /* note : default is impossible, since lhlCode into [0..3] */ + lhSize = 1; + litSize = istart[0] >> 3; + break; + case 1: + lhSize = 2; + litSize = MEM_readLE16(istart) >> 4; + break; + case 3: + lhSize = 3; + RETURN_ERROR_IF(srcSize<3, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 2; here we need lhSize = 3"); + litSize = MEM_readLE24(istart) >> 4; + break; + } + + RETURN_ERROR_IF(litSize > 0 && dst == NULL, dstSize_tooSmall, "NULL not handled"); + RETURN_ERROR_IF(litSize > blockSizeMax, corruption_detected, ""); + RETURN_ERROR_IF(expectedWriteSize < litSize, dstSize_tooSmall, ""); + ZSTD_allocateLiteralsBuffer(dctx, dst, dstCapacity, litSize, streaming, expectedWriteSize, 1); + if (lhSize+litSize+WILDCOPY_OVERLENGTH > srcSize) { /* risk reading beyond src buffer with wildcopy */ + RETURN_ERROR_IF(litSize+lhSize > srcSize, corruption_detected, ""); + if (dctx->litBufferLocation == ZSTD_split) + { + ZSTD_memcpy(dctx->litBuffer, istart + lhSize, litSize - ZSTD_LITBUFFEREXTRASIZE); + ZSTD_memcpy(dctx->litExtraBuffer, istart + lhSize + litSize - ZSTD_LITBUFFEREXTRASIZE, ZSTD_LITBUFFEREXTRASIZE); + } + else + { + ZSTD_memcpy(dctx->litBuffer, istart + lhSize, litSize); + } + dctx->litPtr = dctx->litBuffer; + dctx->litSize = litSize; + return lhSize+litSize; + } + /* direct reference into compressed stream */ + dctx->litPtr = istart+lhSize; + dctx->litSize = litSize; + dctx->litBufferEnd = dctx->litPtr + litSize; + dctx->litBufferLocation = ZSTD_not_in_dst; + return lhSize+litSize; + } + + case set_rle: + { U32 const lhlCode = ((istart[0]) >> 2) & 3; + size_t litSize, lhSize; + size_t expectedWriteSize = MIN(blockSizeMax, dstCapacity); + switch(lhlCode) + { + case 0: case 2: default: /* note : default is impossible, since lhlCode into [0..3] */ + lhSize = 1; + litSize = istart[0] >> 3; + break; + case 1: + lhSize = 2; + RETURN_ERROR_IF(srcSize<3, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 2; here we need lhSize+1 = 3"); + litSize = MEM_readLE16(istart) >> 4; + break; + case 3: + lhSize = 3; + RETURN_ERROR_IF(srcSize<4, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 2; here we need lhSize+1 = 4"); + litSize = MEM_readLE24(istart) >> 4; + break; + } + RETURN_ERROR_IF(litSize > 0 && dst == NULL, dstSize_tooSmall, "NULL not handled"); + RETURN_ERROR_IF(litSize > blockSizeMax, corruption_detected, ""); + RETURN_ERROR_IF(expectedWriteSize < litSize, dstSize_tooSmall, ""); + ZSTD_allocateLiteralsBuffer(dctx, dst, dstCapacity, litSize, streaming, expectedWriteSize, 1); + if (dctx->litBufferLocation == ZSTD_split) + { + ZSTD_memset(dctx->litBuffer, istart[lhSize], litSize - ZSTD_LITBUFFEREXTRASIZE); + ZSTD_memset(dctx->litExtraBuffer, istart[lhSize], ZSTD_LITBUFFEREXTRASIZE); + } + else + { + ZSTD_memset(dctx->litBuffer, istart[lhSize], litSize); + } + dctx->litPtr = dctx->litBuffer; + dctx->litSize = litSize; + return lhSize+1; + } + default: + RETURN_ERROR(corruption_detected, "impossible"); + } + } +} + +/* Hidden declaration for fullbench */ +size_t ZSTD_decodeLiteralsBlock_wrapper(ZSTD_DCtx* dctx, + const void* src, size_t srcSize, + void* dst, size_t dstCapacity); +size_t ZSTD_decodeLiteralsBlock_wrapper(ZSTD_DCtx* dctx, + const void* src, size_t srcSize, + void* dst, size_t dstCapacity) +{ + dctx->isFrameDecompression = 0; + return ZSTD_decodeLiteralsBlock(dctx, src, srcSize, dst, dstCapacity, not_streaming); +} + +/* Default FSE distribution tables. + * These are pre-calculated FSE decoding tables using default distributions as defined in specification : + * https://github.com/facebook/zstd/blob/release/doc/zstd_compression_format.md#default-distributions + * They were generated programmatically with following method : + * - start from default distributions, present in /lib/common/zstd_internal.h + * - generate tables normally, using ZSTD_buildFSETable() + * - printout the content of tables + * - prettify output, report below, test with fuzzer to ensure it's correct */ + +/* Default FSE distribution table for Literal Lengths */ +static const ZSTD_seqSymbol LL_defaultDTable[(1<tableLog = 0; + DTableH->fastMode = 0; + + cell->nbBits = 0; + cell->nextState = 0; + assert(nbAddBits < 255); + cell->nbAdditionalBits = nbAddBits; + cell->baseValue = baseValue; +} + + +/* ZSTD_buildFSETable() : + * generate FSE decoding table for one symbol (ll, ml or off) + * cannot fail if input is valid => + * all inputs are presumed validated at this stage */ +FORCE_INLINE_TEMPLATE +void ZSTD_buildFSETable_body(ZSTD_seqSymbol* dt, + const short* normalizedCounter, unsigned maxSymbolValue, + const U32* baseValue, const U8* nbAdditionalBits, + unsigned tableLog, void* wksp, size_t wkspSize) +{ + ZSTD_seqSymbol* const tableDecode = dt+1; + U32 const maxSV1 = maxSymbolValue + 1; + U32 const tableSize = 1 << tableLog; + + U16* symbolNext = (U16*)wksp; + BYTE* spread = (BYTE*)(symbolNext + MaxSeq + 1); + U32 highThreshold = tableSize - 1; + + + /* Sanity Checks */ + assert(maxSymbolValue <= MaxSeq); + assert(tableLog <= MaxFSELog); + assert(wkspSize >= ZSTD_BUILD_FSE_TABLE_WKSP_SIZE); + (void)wkspSize; + /* Init, lay down lowprob symbols */ + { ZSTD_seqSymbol_header DTableH; + DTableH.tableLog = tableLog; + DTableH.fastMode = 1; + { S16 const largeLimit= (S16)(1 << (tableLog-1)); + U32 s; + for (s=0; s= largeLimit) DTableH.fastMode=0; + assert(normalizedCounter[s]>=0); + symbolNext[s] = (U16)normalizedCounter[s]; + } } } + ZSTD_memcpy(dt, &DTableH, sizeof(DTableH)); + } + + /* Spread symbols */ + assert(tableSize <= 512); + /* Specialized symbol spreading for the case when there are + * no low probability (-1 count) symbols. When compressing + * small blocks we avoid low probability symbols to hit this + * case, since header decoding speed matters more. + */ + if (highThreshold == tableSize - 1) { + size_t const tableMask = tableSize-1; + size_t const step = FSE_TABLESTEP(tableSize); + /* First lay down the symbols in order. + * We use a uint64_t to lay down 8 bytes at a time. This reduces branch + * misses since small blocks generally have small table logs, so nearly + * all symbols have counts <= 8. We ensure we have 8 bytes at the end of + * our buffer to handle the over-write. + */ + { + U64 const add = 0x0101010101010101ull; + size_t pos = 0; + U64 sv = 0; + U32 s; + for (s=0; s=0); + pos += (size_t)n; + } + } + /* Now we spread those positions across the table. + * The benefit of doing it in two stages is that we avoid the + * variable size inner loop, which caused lots of branch misses. + * Now we can run through all the positions without any branch misses. + * We unroll the loop twice, since that is what empirically worked best. + */ + { + size_t position = 0; + size_t s; + size_t const unroll = 2; + assert(tableSize % unroll == 0); /* FSE_MIN_TABLELOG is 5 */ + for (s = 0; s < (size_t)tableSize; s += unroll) { + size_t u; + for (u = 0; u < unroll; ++u) { + size_t const uPosition = (position + (u * step)) & tableMask; + tableDecode[uPosition].baseValue = spread[s + u]; + } + position = (position + (unroll * step)) & tableMask; + } + assert(position == 0); + } + } else { + U32 const tableMask = tableSize-1; + U32 const step = FSE_TABLESTEP(tableSize); + U32 s, position = 0; + for (s=0; s highThreshold)) position = (position + step) & tableMask; /* lowprob area */ + } } + assert(position == 0); /* position must reach all cells once, otherwise normalizedCounter is incorrect */ + } + + /* Build Decoding table */ + { + U32 u; + for (u=0; u max, corruption_detected, ""); + { U32 const symbol = *(const BYTE*)src; + U32 const baseline = baseValue[symbol]; + U8 const nbBits = nbAdditionalBits[symbol]; + ZSTD_buildSeqTable_rle(DTableSpace, baseline, nbBits); + } + *DTablePtr = DTableSpace; + return 1; + case set_basic : + *DTablePtr = defaultTable; + return 0; + case set_repeat: + RETURN_ERROR_IF(!flagRepeatTable, corruption_detected, ""); + /* prefetch FSE table if used */ + if (ddictIsCold && (nbSeq > 24 /* heuristic */)) { + const void* const pStart = *DTablePtr; + size_t const pSize = sizeof(ZSTD_seqSymbol) * (SEQSYMBOL_TABLE_SIZE(maxLog)); + PREFETCH_AREA(pStart, pSize); + } + return 0; + case set_compressed : + { unsigned tableLog; + S16 norm[MaxSeq+1]; + size_t const headerSize = FSE_readNCount(norm, &max, &tableLog, src, srcSize); + RETURN_ERROR_IF(FSE_isError(headerSize), corruption_detected, ""); + RETURN_ERROR_IF(tableLog > maxLog, corruption_detected, ""); + ZSTD_buildFSETable(DTableSpace, norm, max, baseValue, nbAdditionalBits, tableLog, wksp, wkspSize, bmi2); + *DTablePtr = DTableSpace; + return headerSize; + } + default : + assert(0); + RETURN_ERROR(GENERIC, "impossible"); + } +} + +size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr, + const void* src, size_t srcSize) +{ + const BYTE* const istart = (const BYTE*)src; + const BYTE* const iend = istart + srcSize; + const BYTE* ip = istart; + int nbSeq; + DEBUGLOG(5, "ZSTD_decodeSeqHeaders"); + + /* check */ + RETURN_ERROR_IF(srcSize < MIN_SEQUENCES_SIZE, srcSize_wrong, ""); + + /* SeqHead */ + nbSeq = *ip++; + if (nbSeq > 0x7F) { + if (nbSeq == 0xFF) { + RETURN_ERROR_IF(ip+2 > iend, srcSize_wrong, ""); + nbSeq = MEM_readLE16(ip) + LONGNBSEQ; + ip+=2; + } else { + RETURN_ERROR_IF(ip >= iend, srcSize_wrong, ""); + nbSeq = ((nbSeq-0x80)<<8) + *ip++; + } + } + *nbSeqPtr = nbSeq; + + if (nbSeq == 0) { + /* No sequence : section ends immediately */ + RETURN_ERROR_IF(ip != iend, corruption_detected, + "extraneous data present in the Sequences section"); + return (size_t)(ip - istart); + } + + /* FSE table descriptors */ + RETURN_ERROR_IF(ip+1 > iend, srcSize_wrong, ""); /* minimum possible size: 1 byte for symbol encoding types */ + RETURN_ERROR_IF(*ip & 3, corruption_detected, ""); /* The last field, Reserved, must be all-zeroes. */ + { SymbolEncodingType_e const LLtype = (SymbolEncodingType_e)(*ip >> 6); + SymbolEncodingType_e const OFtype = (SymbolEncodingType_e)((*ip >> 4) & 3); + SymbolEncodingType_e const MLtype = (SymbolEncodingType_e)((*ip >> 2) & 3); + ip++; + + /* Build DTables */ + { size_t const llhSize = ZSTD_buildSeqTable(dctx->entropy.LLTable, &dctx->LLTptr, + LLtype, MaxLL, LLFSELog, + ip, iend-ip, + LL_base, LL_bits, + LL_defaultDTable, dctx->fseEntropy, + dctx->ddictIsCold, nbSeq, + dctx->workspace, sizeof(dctx->workspace), + ZSTD_DCtx_get_bmi2(dctx)); + RETURN_ERROR_IF(ZSTD_isError(llhSize), corruption_detected, "ZSTD_buildSeqTable failed"); + ip += llhSize; + } + + { size_t const ofhSize = ZSTD_buildSeqTable(dctx->entropy.OFTable, &dctx->OFTptr, + OFtype, MaxOff, OffFSELog, + ip, iend-ip, + OF_base, OF_bits, + OF_defaultDTable, dctx->fseEntropy, + dctx->ddictIsCold, nbSeq, + dctx->workspace, sizeof(dctx->workspace), + ZSTD_DCtx_get_bmi2(dctx)); + RETURN_ERROR_IF(ZSTD_isError(ofhSize), corruption_detected, "ZSTD_buildSeqTable failed"); + ip += ofhSize; + } + + { size_t const mlhSize = ZSTD_buildSeqTable(dctx->entropy.MLTable, &dctx->MLTptr, + MLtype, MaxML, MLFSELog, + ip, iend-ip, + ML_base, ML_bits, + ML_defaultDTable, dctx->fseEntropy, + dctx->ddictIsCold, nbSeq, + dctx->workspace, sizeof(dctx->workspace), + ZSTD_DCtx_get_bmi2(dctx)); + RETURN_ERROR_IF(ZSTD_isError(mlhSize), corruption_detected, "ZSTD_buildSeqTable failed"); + ip += mlhSize; + } + } + + return ip-istart; +} + + +typedef struct { + size_t litLength; + size_t matchLength; + size_t offset; +} seq_t; + +typedef struct { + size_t state; + const ZSTD_seqSymbol* table; +} ZSTD_fseState; + +typedef struct { + BIT_DStream_t DStream; + ZSTD_fseState stateLL; + ZSTD_fseState stateOffb; + ZSTD_fseState stateML; + size_t prevOffset[ZSTD_REP_NUM]; +} seqState_t; + +/*! ZSTD_overlapCopy8() : + * Copies 8 bytes from ip to op and updates op and ip where ip <= op. + * If the offset is < 8 then the offset is spread to at least 8 bytes. + * + * Precondition: *ip <= *op + * Postcondition: *op - *op >= 8 + */ +HINT_INLINE void ZSTD_overlapCopy8(BYTE** op, BYTE const** ip, size_t offset) { + assert(*ip <= *op); + if (offset < 8) { + /* close range match, overlap */ + static const U32 dec32table[] = { 0, 1, 2, 1, 4, 4, 4, 4 }; /* added */ + static const int dec64table[] = { 8, 8, 8, 7, 8, 9,10,11 }; /* subtracted */ + int const sub2 = dec64table[offset]; + (*op)[0] = (*ip)[0]; + (*op)[1] = (*ip)[1]; + (*op)[2] = (*ip)[2]; + (*op)[3] = (*ip)[3]; + *ip += dec32table[offset]; + ZSTD_copy4(*op+4, *ip); + *ip -= sub2; + } else { + ZSTD_copy8(*op, *ip); + } + *ip += 8; + *op += 8; + assert(*op - *ip >= 8); +} + +/*! ZSTD_safecopy() : + * Specialized version of memcpy() that is allowed to READ up to WILDCOPY_OVERLENGTH past the input buffer + * and write up to 16 bytes past oend_w (op >= oend_w is allowed). + * This function is only called in the uncommon case where the sequence is near the end of the block. It + * should be fast for a single long sequence, but can be slow for several short sequences. + * + * @param ovtype controls the overlap detection + * - ZSTD_no_overlap: The source and destination are guaranteed to be at least WILDCOPY_VECLEN bytes apart. + * - ZSTD_overlap_src_before_dst: The src and dst may overlap and may be any distance apart. + * The src buffer must be before the dst buffer. + */ +static void ZSTD_safecopy(BYTE* op, const BYTE* const oend_w, BYTE const* ip, ptrdiff_t length, ZSTD_overlap_e ovtype) { + ptrdiff_t const diff = op - ip; + BYTE* const oend = op + length; + + assert((ovtype == ZSTD_no_overlap && (diff <= -8 || diff >= 8 || op >= oend_w)) || + (ovtype == ZSTD_overlap_src_before_dst && diff >= 0)); + + if (length < 8) { + /* Handle short lengths. */ + while (op < oend) *op++ = *ip++; + return; + } + if (ovtype == ZSTD_overlap_src_before_dst) { + /* Copy 8 bytes and ensure the offset >= 8 when there can be overlap. */ + assert(length >= 8); + ZSTD_overlapCopy8(&op, &ip, diff); + length -= 8; + assert(op - ip >= 8); + assert(op <= oend); + } + + if (oend <= oend_w) { + /* No risk of overwrite. */ + ZSTD_wildcopy(op, ip, length, ovtype); + return; + } + if (op <= oend_w) { + /* Wildcopy until we get close to the end. */ + assert(oend > oend_w); + ZSTD_wildcopy(op, ip, oend_w - op, ovtype); + ip += oend_w - op; + op += oend_w - op; + } + /* Handle the leftovers. */ + while (op < oend) *op++ = *ip++; +} + +/* ZSTD_safecopyDstBeforeSrc(): + * This version allows overlap with dst before src, or handles the non-overlap case with dst after src + * Kept separate from more common ZSTD_safecopy case to avoid performance impact to the safecopy common case */ +static void ZSTD_safecopyDstBeforeSrc(BYTE* op, const BYTE* ip, ptrdiff_t length) { + ptrdiff_t const diff = op - ip; + BYTE* const oend = op + length; + + if (length < 8 || diff > -8) { + /* Handle short lengths, close overlaps, and dst not before src. */ + while (op < oend) *op++ = *ip++; + return; + } + + if (op <= oend - WILDCOPY_OVERLENGTH && diff < -WILDCOPY_VECLEN) { + ZSTD_wildcopy(op, ip, oend - WILDCOPY_OVERLENGTH - op, ZSTD_no_overlap); + ip += oend - WILDCOPY_OVERLENGTH - op; + op += oend - WILDCOPY_OVERLENGTH - op; + } + + /* Handle the leftovers. */ + while (op < oend) *op++ = *ip++; +} + +/* ZSTD_execSequenceEnd(): + * This version handles cases that are near the end of the output buffer. It requires + * more careful checks to make sure there is no overflow. By separating out these hard + * and unlikely cases, we can speed up the common cases. + * + * NOTE: This function needs to be fast for a single long sequence, but doesn't need + * to be optimized for many small sequences, since those fall into ZSTD_execSequence(). + */ +FORCE_NOINLINE +ZSTD_ALLOW_POINTER_OVERFLOW_ATTR +size_t ZSTD_execSequenceEnd(BYTE* op, + BYTE* const oend, seq_t sequence, + const BYTE** litPtr, const BYTE* const litLimit, + const BYTE* const prefixStart, const BYTE* const virtualStart, const BYTE* const dictEnd) +{ + BYTE* const oLitEnd = op + sequence.litLength; + size_t const sequenceLength = sequence.litLength + sequence.matchLength; + const BYTE* const iLitEnd = *litPtr + sequence.litLength; + const BYTE* match = oLitEnd - sequence.offset; + BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH; + + /* bounds checks : careful of address space overflow in 32-bit mode */ + RETURN_ERROR_IF(sequenceLength > (size_t)(oend - op), dstSize_tooSmall, "last match must fit within dstBuffer"); + RETURN_ERROR_IF(sequence.litLength > (size_t)(litLimit - *litPtr), corruption_detected, "try to read beyond literal buffer"); + assert(op < op + sequenceLength); + assert(oLitEnd < op + sequenceLength); + + /* copy literals */ + ZSTD_safecopy(op, oend_w, *litPtr, sequence.litLength, ZSTD_no_overlap); + op = oLitEnd; + *litPtr = iLitEnd; + + /* copy Match */ + if (sequence.offset > (size_t)(oLitEnd - prefixStart)) { + /* offset beyond prefix */ + RETURN_ERROR_IF(sequence.offset > (size_t)(oLitEnd - virtualStart), corruption_detected, ""); + match = dictEnd - (prefixStart - match); + if (match + sequence.matchLength <= dictEnd) { + ZSTD_memmove(oLitEnd, match, sequence.matchLength); + return sequenceLength; + } + /* span extDict & currentPrefixSegment */ + { size_t const length1 = dictEnd - match; + ZSTD_memmove(oLitEnd, match, length1); + op = oLitEnd + length1; + sequence.matchLength -= length1; + match = prefixStart; + } + } + ZSTD_safecopy(op, oend_w, match, sequence.matchLength, ZSTD_overlap_src_before_dst); + return sequenceLength; +} + +/* ZSTD_execSequenceEndSplitLitBuffer(): + * This version is intended to be used during instances where the litBuffer is still split. It is kept separate to avoid performance impact for the good case. + */ +FORCE_NOINLINE +ZSTD_ALLOW_POINTER_OVERFLOW_ATTR +size_t ZSTD_execSequenceEndSplitLitBuffer(BYTE* op, + BYTE* const oend, const BYTE* const oend_w, seq_t sequence, + const BYTE** litPtr, const BYTE* const litLimit, + const BYTE* const prefixStart, const BYTE* const virtualStart, const BYTE* const dictEnd) +{ + BYTE* const oLitEnd = op + sequence.litLength; + size_t const sequenceLength = sequence.litLength + sequence.matchLength; + const BYTE* const iLitEnd = *litPtr + sequence.litLength; + const BYTE* match = oLitEnd - sequence.offset; + + + /* bounds checks : careful of address space overflow in 32-bit mode */ + RETURN_ERROR_IF(sequenceLength > (size_t)(oend - op), dstSize_tooSmall, "last match must fit within dstBuffer"); + RETURN_ERROR_IF(sequence.litLength > (size_t)(litLimit - *litPtr), corruption_detected, "try to read beyond literal buffer"); + assert(op < op + sequenceLength); + assert(oLitEnd < op + sequenceLength); + + /* copy literals */ + RETURN_ERROR_IF(op > *litPtr && op < *litPtr + sequence.litLength, dstSize_tooSmall, "output should not catch up to and overwrite literal buffer"); + ZSTD_safecopyDstBeforeSrc(op, *litPtr, sequence.litLength); + op = oLitEnd; + *litPtr = iLitEnd; + + /* copy Match */ + if (sequence.offset > (size_t)(oLitEnd - prefixStart)) { + /* offset beyond prefix */ + RETURN_ERROR_IF(sequence.offset > (size_t)(oLitEnd - virtualStart), corruption_detected, ""); + match = dictEnd - (prefixStart - match); + if (match + sequence.matchLength <= dictEnd) { + ZSTD_memmove(oLitEnd, match, sequence.matchLength); + return sequenceLength; + } + /* span extDict & currentPrefixSegment */ + { size_t const length1 = dictEnd - match; + ZSTD_memmove(oLitEnd, match, length1); + op = oLitEnd + length1; + sequence.matchLength -= length1; + match = prefixStart; + } + } + ZSTD_safecopy(op, oend_w, match, sequence.matchLength, ZSTD_overlap_src_before_dst); + return sequenceLength; +} + +HINT_INLINE +ZSTD_ALLOW_POINTER_OVERFLOW_ATTR +size_t ZSTD_execSequence(BYTE* op, + BYTE* const oend, seq_t sequence, + const BYTE** litPtr, const BYTE* const litLimit, + const BYTE* const prefixStart, const BYTE* const virtualStart, const BYTE* const dictEnd) +{ + BYTE* const oLitEnd = op + sequence.litLength; + size_t const sequenceLength = sequence.litLength + sequence.matchLength; + BYTE* const oMatchEnd = op + sequenceLength; /* risk : address space overflow (32-bits) */ + BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH; /* risk : address space underflow on oend=NULL */ + const BYTE* const iLitEnd = *litPtr + sequence.litLength; + const BYTE* match = oLitEnd - sequence.offset; + + assert(op != NULL /* Precondition */); + assert(oend_w < oend /* No underflow */); + +#if defined(__aarch64__) + /* prefetch sequence starting from match that will be used for copy later */ + PREFETCH_L1(match); +#endif + /* Handle edge cases in a slow path: + * - Read beyond end of literals + * - Match end is within WILDCOPY_OVERLIMIT of oend + * - 32-bit mode and the match length overflows + */ + if (UNLIKELY( + iLitEnd > litLimit || + oMatchEnd > oend_w || + (MEM_32bits() && (size_t)(oend - op) < sequenceLength + WILDCOPY_OVERLENGTH))) + return ZSTD_execSequenceEnd(op, oend, sequence, litPtr, litLimit, prefixStart, virtualStart, dictEnd); + + /* Assumptions (everything else goes into ZSTD_execSequenceEnd()) */ + assert(op <= oLitEnd /* No overflow */); + assert(oLitEnd < oMatchEnd /* Non-zero match & no overflow */); + assert(oMatchEnd <= oend /* No underflow */); + assert(iLitEnd <= litLimit /* Literal length is in bounds */); + assert(oLitEnd <= oend_w /* Can wildcopy literals */); + assert(oMatchEnd <= oend_w /* Can wildcopy matches */); + + /* Copy Literals: + * Split out litLength <= 16 since it is nearly always true. +1.6% on gcc-9. + * We likely don't need the full 32-byte wildcopy. + */ + assert(WILDCOPY_OVERLENGTH >= 16); + ZSTD_copy16(op, (*litPtr)); + if (UNLIKELY(sequence.litLength > 16)) { + ZSTD_wildcopy(op + 16, (*litPtr) + 16, sequence.litLength - 16, ZSTD_no_overlap); + } + op = oLitEnd; + *litPtr = iLitEnd; /* update for next sequence */ + + /* Copy Match */ + if (sequence.offset > (size_t)(oLitEnd - prefixStart)) { + /* offset beyond prefix -> go into extDict */ + RETURN_ERROR_IF(UNLIKELY(sequence.offset > (size_t)(oLitEnd - virtualStart)), corruption_detected, ""); + match = dictEnd + (match - prefixStart); + if (match + sequence.matchLength <= dictEnd) { + ZSTD_memmove(oLitEnd, match, sequence.matchLength); + return sequenceLength; + } + /* span extDict & currentPrefixSegment */ + { size_t const length1 = dictEnd - match; + ZSTD_memmove(oLitEnd, match, length1); + op = oLitEnd + length1; + sequence.matchLength -= length1; + match = prefixStart; + } + } + /* Match within prefix of 1 or more bytes */ + assert(op <= oMatchEnd); + assert(oMatchEnd <= oend_w); + assert(match >= prefixStart); + assert(sequence.matchLength >= 1); + + /* Nearly all offsets are >= WILDCOPY_VECLEN bytes, which means we can use wildcopy + * without overlap checking. + */ + if (LIKELY(sequence.offset >= WILDCOPY_VECLEN)) { + /* We bet on a full wildcopy for matches, since we expect matches to be + * longer than literals (in general). In silesia, ~10% of matches are longer + * than 16 bytes. + */ + ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength, ZSTD_no_overlap); + return sequenceLength; + } + assert(sequence.offset < WILDCOPY_VECLEN); + + /* Copy 8 bytes and spread the offset to be >= 8. */ + ZSTD_overlapCopy8(&op, &match, sequence.offset); + + /* If the match length is > 8 bytes, then continue with the wildcopy. */ + if (sequence.matchLength > 8) { + assert(op < oMatchEnd); + ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength - 8, ZSTD_overlap_src_before_dst); + } + return sequenceLength; +} + +HINT_INLINE +ZSTD_ALLOW_POINTER_OVERFLOW_ATTR +size_t ZSTD_execSequenceSplitLitBuffer(BYTE* op, + BYTE* const oend, const BYTE* const oend_w, seq_t sequence, + const BYTE** litPtr, const BYTE* const litLimit, + const BYTE* const prefixStart, const BYTE* const virtualStart, const BYTE* const dictEnd) +{ + BYTE* const oLitEnd = op + sequence.litLength; + size_t const sequenceLength = sequence.litLength + sequence.matchLength; + BYTE* const oMatchEnd = op + sequenceLength; /* risk : address space overflow (32-bits) */ + const BYTE* const iLitEnd = *litPtr + sequence.litLength; + const BYTE* match = oLitEnd - sequence.offset; + + assert(op != NULL /* Precondition */); + assert(oend_w < oend /* No underflow */); + /* Handle edge cases in a slow path: + * - Read beyond end of literals + * - Match end is within WILDCOPY_OVERLIMIT of oend + * - 32-bit mode and the match length overflows + */ + if (UNLIKELY( + iLitEnd > litLimit || + oMatchEnd > oend_w || + (MEM_32bits() && (size_t)(oend - op) < sequenceLength + WILDCOPY_OVERLENGTH))) + return ZSTD_execSequenceEndSplitLitBuffer(op, oend, oend_w, sequence, litPtr, litLimit, prefixStart, virtualStart, dictEnd); + + /* Assumptions (everything else goes into ZSTD_execSequenceEnd()) */ + assert(op <= oLitEnd /* No overflow */); + assert(oLitEnd < oMatchEnd /* Non-zero match & no overflow */); + assert(oMatchEnd <= oend /* No underflow */); + assert(iLitEnd <= litLimit /* Literal length is in bounds */); + assert(oLitEnd <= oend_w /* Can wildcopy literals */); + assert(oMatchEnd <= oend_w /* Can wildcopy matches */); + + /* Copy Literals: + * Split out litLength <= 16 since it is nearly always true. +1.6% on gcc-9. + * We likely don't need the full 32-byte wildcopy. + */ + assert(WILDCOPY_OVERLENGTH >= 16); + ZSTD_copy16(op, (*litPtr)); + if (UNLIKELY(sequence.litLength > 16)) { + ZSTD_wildcopy(op+16, (*litPtr)+16, sequence.litLength-16, ZSTD_no_overlap); + } + op = oLitEnd; + *litPtr = iLitEnd; /* update for next sequence */ + + /* Copy Match */ + if (sequence.offset > (size_t)(oLitEnd - prefixStart)) { + /* offset beyond prefix -> go into extDict */ + RETURN_ERROR_IF(UNLIKELY(sequence.offset > (size_t)(oLitEnd - virtualStart)), corruption_detected, ""); + match = dictEnd + (match - prefixStart); + if (match + sequence.matchLength <= dictEnd) { + ZSTD_memmove(oLitEnd, match, sequence.matchLength); + return sequenceLength; + } + /* span extDict & currentPrefixSegment */ + { size_t const length1 = dictEnd - match; + ZSTD_memmove(oLitEnd, match, length1); + op = oLitEnd + length1; + sequence.matchLength -= length1; + match = prefixStart; + } } + /* Match within prefix of 1 or more bytes */ + assert(op <= oMatchEnd); + assert(oMatchEnd <= oend_w); + assert(match >= prefixStart); + assert(sequence.matchLength >= 1); + + /* Nearly all offsets are >= WILDCOPY_VECLEN bytes, which means we can use wildcopy + * without overlap checking. + */ + if (LIKELY(sequence.offset >= WILDCOPY_VECLEN)) { + /* We bet on a full wildcopy for matches, since we expect matches to be + * longer than literals (in general). In silesia, ~10% of matches are longer + * than 16 bytes. + */ + ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength, ZSTD_no_overlap); + return sequenceLength; + } + assert(sequence.offset < WILDCOPY_VECLEN); + + /* Copy 8 bytes and spread the offset to be >= 8. */ + ZSTD_overlapCopy8(&op, &match, sequence.offset); + + /* If the match length is > 8 bytes, then continue with the wildcopy. */ + if (sequence.matchLength > 8) { + assert(op < oMatchEnd); + ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength-8, ZSTD_overlap_src_before_dst); + } + return sequenceLength; +} + + +static void +ZSTD_initFseState(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD, const ZSTD_seqSymbol* dt) +{ + const void* ptr = dt; + const ZSTD_seqSymbol_header* const DTableH = (const ZSTD_seqSymbol_header*)ptr; + DStatePtr->state = BIT_readBits(bitD, DTableH->tableLog); + DEBUGLOG(6, "ZSTD_initFseState : val=%u using %u bits", + (U32)DStatePtr->state, DTableH->tableLog); + BIT_reloadDStream(bitD); + DStatePtr->table = dt + 1; +} + +FORCE_INLINE_TEMPLATE void +ZSTD_updateFseStateWithDInfo(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD, U16 nextState, U32 nbBits) +{ + size_t const lowBits = BIT_readBits(bitD, nbBits); + DStatePtr->state = nextState + lowBits; +} + +/* We need to add at most (ZSTD_WINDOWLOG_MAX_32 - 1) bits to read the maximum + * offset bits. But we can only read at most STREAM_ACCUMULATOR_MIN_32 + * bits before reloading. This value is the maximum number of bytes we read + * after reloading when we are decoding long offsets. + */ +#define LONG_OFFSETS_MAX_EXTRA_BITS_32 \ + (ZSTD_WINDOWLOG_MAX_32 > STREAM_ACCUMULATOR_MIN_32 \ + ? ZSTD_WINDOWLOG_MAX_32 - STREAM_ACCUMULATOR_MIN_32 \ + : 0) + +typedef enum { ZSTD_lo_isRegularOffset, ZSTD_lo_isLongOffset=1 } ZSTD_longOffset_e; + +/** + * ZSTD_decodeSequence(): + * @p longOffsets : tells the decoder to reload more bit while decoding large offsets + * only used in 32-bit mode + * @return : Sequence (litL + matchL + offset) + */ +FORCE_INLINE_TEMPLATE seq_t +ZSTD_decodeSequence(seqState_t* seqState, const ZSTD_longOffset_e longOffsets, const int isLastSeq) +{ + seq_t seq; + /* + * ZSTD_seqSymbol is a 64 bits wide structure. + * It can be loaded in one operation + * and its fields extracted by simply shifting or bit-extracting on aarch64. + * GCC doesn't recognize this and generates more unnecessary ldr/ldrb/ldrh + * operations that cause performance drop. This can be avoided by using this + * ZSTD_memcpy hack. + */ +#if defined(__aarch64__) && (defined(__GNUC__) && !defined(__clang__)) + ZSTD_seqSymbol llDInfoS, mlDInfoS, ofDInfoS; + ZSTD_seqSymbol* const llDInfo = &llDInfoS; + ZSTD_seqSymbol* const mlDInfo = &mlDInfoS; + ZSTD_seqSymbol* const ofDInfo = &ofDInfoS; + ZSTD_memcpy(llDInfo, seqState->stateLL.table + seqState->stateLL.state, sizeof(ZSTD_seqSymbol)); + ZSTD_memcpy(mlDInfo, seqState->stateML.table + seqState->stateML.state, sizeof(ZSTD_seqSymbol)); + ZSTD_memcpy(ofDInfo, seqState->stateOffb.table + seqState->stateOffb.state, sizeof(ZSTD_seqSymbol)); +#else + const ZSTD_seqSymbol* const llDInfo = seqState->stateLL.table + seqState->stateLL.state; + const ZSTD_seqSymbol* const mlDInfo = seqState->stateML.table + seqState->stateML.state; + const ZSTD_seqSymbol* const ofDInfo = seqState->stateOffb.table + seqState->stateOffb.state; +#endif + seq.matchLength = mlDInfo->baseValue; + seq.litLength = llDInfo->baseValue; + { U32 const ofBase = ofDInfo->baseValue; + BYTE const llBits = llDInfo->nbAdditionalBits; + BYTE const mlBits = mlDInfo->nbAdditionalBits; + BYTE const ofBits = ofDInfo->nbAdditionalBits; + BYTE const totalBits = llBits+mlBits+ofBits; + + U16 const llNext = llDInfo->nextState; + U16 const mlNext = mlDInfo->nextState; + U16 const ofNext = ofDInfo->nextState; + U32 const llnbBits = llDInfo->nbBits; + U32 const mlnbBits = mlDInfo->nbBits; + U32 const ofnbBits = ofDInfo->nbBits; + + assert(llBits <= MaxLLBits); + assert(mlBits <= MaxMLBits); + assert(ofBits <= MaxOff); + /* + * As gcc has better branch and block analyzers, sometimes it is only + * valuable to mark likeliness for clang, it gives around 3-4% of + * performance. + */ + + /* sequence */ + { size_t offset; + if (ofBits > 1) { + ZSTD_STATIC_ASSERT(ZSTD_lo_isLongOffset == 1); + ZSTD_STATIC_ASSERT(LONG_OFFSETS_MAX_EXTRA_BITS_32 == 5); + ZSTD_STATIC_ASSERT(STREAM_ACCUMULATOR_MIN_32 > LONG_OFFSETS_MAX_EXTRA_BITS_32); + ZSTD_STATIC_ASSERT(STREAM_ACCUMULATOR_MIN_32 - LONG_OFFSETS_MAX_EXTRA_BITS_32 >= MaxMLBits); + if (MEM_32bits() && longOffsets && (ofBits >= STREAM_ACCUMULATOR_MIN_32)) { + /* Always read extra bits, this keeps the logic simple, + * avoids branches, and avoids accidentally reading 0 bits. + */ + U32 const extraBits = LONG_OFFSETS_MAX_EXTRA_BITS_32; + offset = ofBase + (BIT_readBitsFast(&seqState->DStream, ofBits - extraBits) << extraBits); + BIT_reloadDStream(&seqState->DStream); + offset += BIT_readBitsFast(&seqState->DStream, extraBits); + } else { + offset = ofBase + BIT_readBitsFast(&seqState->DStream, ofBits/*>0*/); /* <= (ZSTD_WINDOWLOG_MAX-1) bits */ + if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); + } + seqState->prevOffset[2] = seqState->prevOffset[1]; + seqState->prevOffset[1] = seqState->prevOffset[0]; + seqState->prevOffset[0] = offset; + } else { + U32 const ll0 = (llDInfo->baseValue == 0); + if (LIKELY((ofBits == 0))) { + offset = seqState->prevOffset[ll0]; + seqState->prevOffset[1] = seqState->prevOffset[!ll0]; + seqState->prevOffset[0] = offset; + } else { + offset = ofBase + ll0 + BIT_readBitsFast(&seqState->DStream, 1); + { size_t temp = (offset==3) ? seqState->prevOffset[0] - 1 : seqState->prevOffset[offset]; + temp -= !temp; /* 0 is not valid: input corrupted => force offset to -1 => corruption detected at execSequence */ + if (offset != 1) seqState->prevOffset[2] = seqState->prevOffset[1]; + seqState->prevOffset[1] = seqState->prevOffset[0]; + seqState->prevOffset[0] = offset = temp; + } } } + seq.offset = offset; + } + + if (mlBits > 0) + seq.matchLength += BIT_readBitsFast(&seqState->DStream, mlBits/*>0*/); + + if (MEM_32bits() && (mlBits+llBits >= STREAM_ACCUMULATOR_MIN_32-LONG_OFFSETS_MAX_EXTRA_BITS_32)) + BIT_reloadDStream(&seqState->DStream); + if (MEM_64bits() && UNLIKELY(totalBits >= STREAM_ACCUMULATOR_MIN_64-(LLFSELog+MLFSELog+OffFSELog))) + BIT_reloadDStream(&seqState->DStream); + /* Ensure there are enough bits to read the rest of data in 64-bit mode. */ + ZSTD_STATIC_ASSERT(16+LLFSELog+MLFSELog+OffFSELog < STREAM_ACCUMULATOR_MIN_64); + + if (llBits > 0) + seq.litLength += BIT_readBitsFast(&seqState->DStream, llBits/*>0*/); + + if (MEM_32bits()) + BIT_reloadDStream(&seqState->DStream); + + DEBUGLOG(6, "seq: litL=%u, matchL=%u, offset=%u", + (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset); + + if (!isLastSeq) { + /* don't update FSE state for last Sequence */ + ZSTD_updateFseStateWithDInfo(&seqState->stateLL, &seqState->DStream, llNext, llnbBits); /* <= 9 bits */ + ZSTD_updateFseStateWithDInfo(&seqState->stateML, &seqState->DStream, mlNext, mlnbBits); /* <= 9 bits */ + if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); /* <= 18 bits */ + ZSTD_updateFseStateWithDInfo(&seqState->stateOffb, &seqState->DStream, ofNext, ofnbBits); /* <= 8 bits */ + BIT_reloadDStream(&seqState->DStream); + } + } + + return seq; +} + +#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) +#if DEBUGLEVEL >= 1 +static int ZSTD_dictionaryIsActive(ZSTD_DCtx const* dctx, BYTE const* prefixStart, BYTE const* oLitEnd) +{ + size_t const windowSize = dctx->fParams.windowSize; + /* No dictionary used. */ + if (dctx->dictContentEndForFuzzing == NULL) return 0; + /* Dictionary is our prefix. */ + if (prefixStart == dctx->dictContentBeginForFuzzing) return 1; + /* Dictionary is not our ext-dict. */ + if (dctx->dictEnd != dctx->dictContentEndForFuzzing) return 0; + /* Dictionary is not within our window size. */ + if ((size_t)(oLitEnd - prefixStart) >= windowSize) return 0; + /* Dictionary is active. */ + return 1; +} +#endif + +static void ZSTD_assertValidSequence( + ZSTD_DCtx const* dctx, + BYTE const* op, BYTE const* oend, + seq_t const seq, + BYTE const* prefixStart, BYTE const* virtualStart) +{ +#if DEBUGLEVEL >= 1 + if (dctx->isFrameDecompression) { + size_t const windowSize = dctx->fParams.windowSize; + size_t const sequenceSize = seq.litLength + seq.matchLength; + BYTE const* const oLitEnd = op + seq.litLength; + DEBUGLOG(6, "Checking sequence: litL=%u matchL=%u offset=%u", + (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset); + assert(op <= oend); + assert((size_t)(oend - op) >= sequenceSize); + assert(sequenceSize <= ZSTD_blockSizeMax(dctx)); + if (ZSTD_dictionaryIsActive(dctx, prefixStart, oLitEnd)) { + size_t const dictSize = (size_t)((char const*)dctx->dictContentEndForFuzzing - (char const*)dctx->dictContentBeginForFuzzing); + /* Offset must be within the dictionary. */ + assert(seq.offset <= (size_t)(oLitEnd - virtualStart)); + assert(seq.offset <= windowSize + dictSize); + } else { + /* Offset must be within our window. */ + assert(seq.offset <= windowSize); + } + } +#else + (void)dctx, (void)op, (void)oend, (void)seq, (void)prefixStart, (void)virtualStart; +#endif +} +#endif + +#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG + + +FORCE_INLINE_TEMPLATE size_t +DONT_VECTORIZE +ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx, + void* dst, size_t maxDstSize, + const void* seqStart, size_t seqSize, int nbSeq, + const ZSTD_longOffset_e isLongOffset) +{ + const BYTE* ip = (const BYTE*)seqStart; + const BYTE* const iend = ip + seqSize; + BYTE* const ostart = (BYTE*)dst; + BYTE* const oend = ZSTD_maybeNullPtrAdd(ostart, maxDstSize); + BYTE* op = ostart; + const BYTE* litPtr = dctx->litPtr; + const BYTE* litBufferEnd = dctx->litBufferEnd; + const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart); + const BYTE* const vBase = (const BYTE*) (dctx->virtualStart); + const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd); + DEBUGLOG(5, "ZSTD_decompressSequences_bodySplitLitBuffer (%i seqs)", nbSeq); + + /* Literals are split between internal buffer & output buffer */ + if (nbSeq) { + seqState_t seqState; + dctx->fseEntropy = 1; + { U32 i; for (i=0; ientropy.rep[i]; } + RETURN_ERROR_IF( + ERR_isError(BIT_initDStream(&seqState.DStream, ip, iend-ip)), + corruption_detected, ""); + ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr); + ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr); + ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr); + assert(dst != NULL); + + ZSTD_STATIC_ASSERT( + BIT_DStream_unfinished < BIT_DStream_completed && + BIT_DStream_endOfBuffer < BIT_DStream_completed && + BIT_DStream_completed < BIT_DStream_overflow); + + /* decompress without overrunning litPtr begins */ + { seq_t sequence = {0,0,0}; /* some static analyzer believe that @sequence is not initialized (it necessarily is, since for(;;) loop as at least one iteration) */ + /* Align the decompression loop to 32 + 16 bytes. + * + * zstd compiled with gcc-9 on an Intel i9-9900k shows 10% decompression + * speed swings based on the alignment of the decompression loop. This + * performance swing is caused by parts of the decompression loop falling + * out of the DSB. The entire decompression loop should fit in the DSB, + * when it can't we get much worse performance. You can measure if you've + * hit the good case or the bad case with this perf command for some + * compressed file test.zst: + * + * perf stat -e cycles -e instructions -e idq.all_dsb_cycles_any_uops \ + * -e idq.all_mite_cycles_any_uops -- ./zstd -tq test.zst + * + * If you see most cycles served out of the MITE you've hit the bad case. + * If you see most cycles served out of the DSB you've hit the good case. + * If it is pretty even then you may be in an okay case. + * + * This issue has been reproduced on the following CPUs: + * - Kabylake: Macbook Pro (15-inch, 2019) 2.4 GHz Intel Core i9 + * Use Instruments->Counters to get DSB/MITE cycles. + * I never got performance swings, but I was able to + * go from the good case of mostly DSB to half of the + * cycles served from MITE. + * - Coffeelake: Intel i9-9900k + * - Coffeelake: Intel i7-9700k + * + * I haven't been able to reproduce the instability or DSB misses on any + * of the following CPUS: + * - Haswell + * - Broadwell: Intel(R) Xeon(R) CPU E5-2680 v4 @ 2.40GH + * - Skylake + * + * Alignment is done for each of the three major decompression loops: + * - ZSTD_decompressSequences_bodySplitLitBuffer - presplit section of the literal buffer + * - ZSTD_decompressSequences_bodySplitLitBuffer - postsplit section of the literal buffer + * - ZSTD_decompressSequences_body + * Alignment choices are made to minimize large swings on bad cases and influence on performance + * from changes external to this code, rather than to overoptimize on the current commit. + * + * If you are seeing performance stability this script can help test. + * It tests on 4 commits in zstd where I saw performance change. + * + * https://gist.github.com/terrelln/9889fc06a423fd5ca6e99351564473f4 + */ +#if defined(__GNUC__) && defined(__x86_64__) + __asm__(".p2align 6"); +# if __GNUC__ >= 7 + /* good for gcc-7, gcc-9, and gcc-11 */ + __asm__("nop"); + __asm__(".p2align 5"); + __asm__("nop"); + __asm__(".p2align 4"); +# if __GNUC__ == 8 || __GNUC__ == 10 + /* good for gcc-8 and gcc-10 */ + __asm__("nop"); + __asm__(".p2align 3"); +# endif +# endif +#endif + + /* Handle the initial state where litBuffer is currently split between dst and litExtraBuffer */ + for ( ; nbSeq; nbSeq--) { + sequence = ZSTD_decodeSequence(&seqState, isLongOffset, nbSeq==1); + if (litPtr + sequence.litLength > dctx->litBufferEnd) break; + { size_t const oneSeqSize = ZSTD_execSequenceSplitLitBuffer(op, oend, litPtr + sequence.litLength - WILDCOPY_OVERLENGTH, sequence, &litPtr, litBufferEnd, prefixStart, vBase, dictEnd); +#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) + assert(!ZSTD_isError(oneSeqSize)); + ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase); +#endif + if (UNLIKELY(ZSTD_isError(oneSeqSize))) + return oneSeqSize; + DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize); + op += oneSeqSize; + } } + DEBUGLOG(6, "reached: (litPtr + sequence.litLength > dctx->litBufferEnd)"); + + /* If there are more sequences, they will need to read literals from litExtraBuffer; copy over the remainder from dst and update litPtr and litEnd */ + if (nbSeq > 0) { + const size_t leftoverLit = dctx->litBufferEnd - litPtr; + DEBUGLOG(6, "There are %i sequences left, and %zu/%zu literals left in buffer", nbSeq, leftoverLit, sequence.litLength); + if (leftoverLit) { + RETURN_ERROR_IF(leftoverLit > (size_t)(oend - op), dstSize_tooSmall, "remaining lit must fit within dstBuffer"); + ZSTD_safecopyDstBeforeSrc(op, litPtr, leftoverLit); + sequence.litLength -= leftoverLit; + op += leftoverLit; + } + litPtr = dctx->litExtraBuffer; + litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE; + dctx->litBufferLocation = ZSTD_not_in_dst; + { size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litBufferEnd, prefixStart, vBase, dictEnd); +#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) + assert(!ZSTD_isError(oneSeqSize)); + ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase); +#endif + if (UNLIKELY(ZSTD_isError(oneSeqSize))) + return oneSeqSize; + DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize); + op += oneSeqSize; + } + nbSeq--; + } + } + + if (nbSeq > 0) { + /* there is remaining lit from extra buffer */ + +#if defined(__GNUC__) && defined(__x86_64__) + __asm__(".p2align 6"); + __asm__("nop"); +# if __GNUC__ != 7 + /* worse for gcc-7 better for gcc-8, gcc-9, and gcc-10 and clang */ + __asm__(".p2align 4"); + __asm__("nop"); + __asm__(".p2align 3"); +# elif __GNUC__ >= 11 + __asm__(".p2align 3"); +# else + __asm__(".p2align 5"); + __asm__("nop"); + __asm__(".p2align 3"); +# endif +#endif + + for ( ; nbSeq ; nbSeq--) { + seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset, nbSeq==1); + size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litBufferEnd, prefixStart, vBase, dictEnd); +#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) + assert(!ZSTD_isError(oneSeqSize)); + ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase); +#endif + if (UNLIKELY(ZSTD_isError(oneSeqSize))) + return oneSeqSize; + DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize); + op += oneSeqSize; + } + } + + /* check if reached exact end */ + DEBUGLOG(5, "ZSTD_decompressSequences_bodySplitLitBuffer: after decode loop, remaining nbSeq : %i", nbSeq); + RETURN_ERROR_IF(nbSeq, corruption_detected, ""); + DEBUGLOG(5, "bitStream : start=%p, ptr=%p, bitsConsumed=%u", seqState.DStream.start, seqState.DStream.ptr, seqState.DStream.bitsConsumed); + RETURN_ERROR_IF(!BIT_endOfDStream(&seqState.DStream), corruption_detected, ""); + /* save reps for next block */ + { U32 i; for (i=0; ientropy.rep[i] = (U32)(seqState.prevOffset[i]); } + } + + /* last literal segment */ + if (dctx->litBufferLocation == ZSTD_split) { + /* split hasn't been reached yet, first get dst then copy litExtraBuffer */ + size_t const lastLLSize = (size_t)(litBufferEnd - litPtr); + DEBUGLOG(6, "copy last literals from segment : %u", (U32)lastLLSize); + RETURN_ERROR_IF(lastLLSize > (size_t)(oend - op), dstSize_tooSmall, ""); + if (op != NULL) { + ZSTD_memmove(op, litPtr, lastLLSize); + op += lastLLSize; + } + litPtr = dctx->litExtraBuffer; + litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE; + dctx->litBufferLocation = ZSTD_not_in_dst; + } + /* copy last literals from internal buffer */ + { size_t const lastLLSize = (size_t)(litBufferEnd - litPtr); + DEBUGLOG(6, "copy last literals from internal buffer : %u", (U32)lastLLSize); + RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, ""); + if (op != NULL) { + ZSTD_memcpy(op, litPtr, lastLLSize); + op += lastLLSize; + } } + + DEBUGLOG(6, "decoded block of size %u bytes", (U32)(op - ostart)); + return (size_t)(op - ostart); +} + +FORCE_INLINE_TEMPLATE size_t +DONT_VECTORIZE +ZSTD_decompressSequences_body(ZSTD_DCtx* dctx, + void* dst, size_t maxDstSize, + const void* seqStart, size_t seqSize, int nbSeq, + const ZSTD_longOffset_e isLongOffset) +{ + const BYTE* ip = (const BYTE*)seqStart; + const BYTE* const iend = ip + seqSize; + BYTE* const ostart = (BYTE*)dst; + BYTE* const oend = dctx->litBufferLocation == ZSTD_not_in_dst ? ZSTD_maybeNullPtrAdd(ostart, maxDstSize) : dctx->litBuffer; + BYTE* op = ostart; + const BYTE* litPtr = dctx->litPtr; + const BYTE* const litEnd = litPtr + dctx->litSize; + const BYTE* const prefixStart = (const BYTE*)(dctx->prefixStart); + const BYTE* const vBase = (const BYTE*)(dctx->virtualStart); + const BYTE* const dictEnd = (const BYTE*)(dctx->dictEnd); + DEBUGLOG(5, "ZSTD_decompressSequences_body: nbSeq = %d", nbSeq); + + /* Regen sequences */ + if (nbSeq) { + seqState_t seqState; + dctx->fseEntropy = 1; + { U32 i; for (i = 0; i < ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; } + RETURN_ERROR_IF( + ERR_isError(BIT_initDStream(&seqState.DStream, ip, iend - ip)), + corruption_detected, ""); + ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr); + ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr); + ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr); + assert(dst != NULL); + +#if defined(__GNUC__) && defined(__x86_64__) + __asm__(".p2align 6"); + __asm__("nop"); +# if __GNUC__ >= 7 + __asm__(".p2align 5"); + __asm__("nop"); + __asm__(".p2align 3"); +# else + __asm__(".p2align 4"); + __asm__("nop"); + __asm__(".p2align 3"); +# endif +#endif + + for ( ; nbSeq ; nbSeq--) { + seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset, nbSeq==1); + size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litEnd, prefixStart, vBase, dictEnd); +#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) + assert(!ZSTD_isError(oneSeqSize)); + ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase); +#endif + if (UNLIKELY(ZSTD_isError(oneSeqSize))) + return oneSeqSize; + DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize); + op += oneSeqSize; + } + + /* check if reached exact end */ + assert(nbSeq == 0); + RETURN_ERROR_IF(!BIT_endOfDStream(&seqState.DStream), corruption_detected, ""); + /* save reps for next block */ + { U32 i; for (i=0; ientropy.rep[i] = (U32)(seqState.prevOffset[i]); } + } + + /* last literal segment */ + { size_t const lastLLSize = (size_t)(litEnd - litPtr); + DEBUGLOG(6, "copy last literals : %u", (U32)lastLLSize); + RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, ""); + if (op != NULL) { + ZSTD_memcpy(op, litPtr, lastLLSize); + op += lastLLSize; + } } + + DEBUGLOG(6, "decoded block of size %u bytes", (U32)(op - ostart)); + return (size_t)(op - ostart); +} + +static size_t +ZSTD_decompressSequences_default(ZSTD_DCtx* dctx, + void* dst, size_t maxDstSize, + const void* seqStart, size_t seqSize, int nbSeq, + const ZSTD_longOffset_e isLongOffset) +{ + return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); +} + +static size_t +ZSTD_decompressSequencesSplitLitBuffer_default(ZSTD_DCtx* dctx, + void* dst, size_t maxDstSize, + const void* seqStart, size_t seqSize, int nbSeq, + const ZSTD_longOffset_e isLongOffset) +{ + return ZSTD_decompressSequences_bodySplitLitBuffer(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); +} +#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */ + +#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT + +FORCE_INLINE_TEMPLATE + +size_t ZSTD_prefetchMatch(size_t prefetchPos, seq_t const sequence, + const BYTE* const prefixStart, const BYTE* const dictEnd) +{ + prefetchPos += sequence.litLength; + { const BYTE* const matchBase = (sequence.offset > prefetchPos) ? dictEnd : prefixStart; + /* note : this operation can overflow when seq.offset is really too large, which can only happen when input is corrupted. + * No consequence though : memory address is only used for prefetching, not for dereferencing */ + const BYTE* const match = ZSTD_wrappedPtrSub(ZSTD_wrappedPtrAdd(matchBase, prefetchPos), sequence.offset); + PREFETCH_L1(match); PREFETCH_L1(match+CACHELINE_SIZE); /* note : it's safe to invoke PREFETCH() on any memory address, including invalid ones */ + } + return prefetchPos + sequence.matchLength; +} + +/* This decoding function employs prefetching + * to reduce latency impact of cache misses. + * It's generally employed when block contains a significant portion of long-distance matches + * or when coupled with a "cold" dictionary */ +FORCE_INLINE_TEMPLATE size_t +ZSTD_decompressSequencesLong_body( + ZSTD_DCtx* dctx, + void* dst, size_t maxDstSize, + const void* seqStart, size_t seqSize, int nbSeq, + const ZSTD_longOffset_e isLongOffset) +{ + const BYTE* ip = (const BYTE*)seqStart; + const BYTE* const iend = ip + seqSize; + BYTE* const ostart = (BYTE*)dst; + BYTE* const oend = dctx->litBufferLocation == ZSTD_in_dst ? dctx->litBuffer : ZSTD_maybeNullPtrAdd(ostart, maxDstSize); + BYTE* op = ostart; + const BYTE* litPtr = dctx->litPtr; + const BYTE* litBufferEnd = dctx->litBufferEnd; + const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart); + const BYTE* const dictStart = (const BYTE*) (dctx->virtualStart); + const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd); + + /* Regen sequences */ + if (nbSeq) { +#define STORED_SEQS 8 +#define STORED_SEQS_MASK (STORED_SEQS-1) +#define ADVANCED_SEQS STORED_SEQS + seq_t sequences[STORED_SEQS]; + int const seqAdvance = MIN(nbSeq, ADVANCED_SEQS); + seqState_t seqState; + int seqNb; + size_t prefetchPos = (size_t)(op-prefixStart); /* track position relative to prefixStart */ + + dctx->fseEntropy = 1; + { int i; for (i=0; ientropy.rep[i]; } + assert(dst != NULL); + assert(iend >= ip); + RETURN_ERROR_IF( + ERR_isError(BIT_initDStream(&seqState.DStream, ip, iend-ip)), + corruption_detected, ""); + ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr); + ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr); + ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr); + + /* prepare in advance */ + for (seqNb=0; seqNblitBufferLocation == ZSTD_split && litPtr + sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK].litLength > dctx->litBufferEnd) { + /* lit buffer is reaching split point, empty out the first buffer and transition to litExtraBuffer */ + const size_t leftoverLit = dctx->litBufferEnd - litPtr; + if (leftoverLit) + { + RETURN_ERROR_IF(leftoverLit > (size_t)(oend - op), dstSize_tooSmall, "remaining lit must fit within dstBuffer"); + ZSTD_safecopyDstBeforeSrc(op, litPtr, leftoverLit); + sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK].litLength -= leftoverLit; + op += leftoverLit; + } + litPtr = dctx->litExtraBuffer; + litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE; + dctx->litBufferLocation = ZSTD_not_in_dst; + { size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd); +#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) + assert(!ZSTD_isError(oneSeqSize)); + ZSTD_assertValidSequence(dctx, op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], prefixStart, dictStart); +#endif + if (ZSTD_isError(oneSeqSize)) return oneSeqSize; + + prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd); + sequences[seqNb & STORED_SEQS_MASK] = sequence; + op += oneSeqSize; + } } + else + { + /* lit buffer is either wholly contained in first or second split, or not split at all*/ + size_t const oneSeqSize = dctx->litBufferLocation == ZSTD_split ? + ZSTD_execSequenceSplitLitBuffer(op, oend, litPtr + sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK].litLength - WILDCOPY_OVERLENGTH, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd) : + ZSTD_execSequence(op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd); +#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) + assert(!ZSTD_isError(oneSeqSize)); + ZSTD_assertValidSequence(dctx, op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], prefixStart, dictStart); +#endif + if (ZSTD_isError(oneSeqSize)) return oneSeqSize; + + prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd); + sequences[seqNb & STORED_SEQS_MASK] = sequence; + op += oneSeqSize; + } + } + RETURN_ERROR_IF(!BIT_endOfDStream(&seqState.DStream), corruption_detected, ""); + + /* finish queue */ + seqNb -= seqAdvance; + for ( ; seqNblitBufferLocation == ZSTD_split && litPtr + sequence->litLength > dctx->litBufferEnd) { + const size_t leftoverLit = dctx->litBufferEnd - litPtr; + if (leftoverLit) { + RETURN_ERROR_IF(leftoverLit > (size_t)(oend - op), dstSize_tooSmall, "remaining lit must fit within dstBuffer"); + ZSTD_safecopyDstBeforeSrc(op, litPtr, leftoverLit); + sequence->litLength -= leftoverLit; + op += leftoverLit; + } + litPtr = dctx->litExtraBuffer; + litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE; + dctx->litBufferLocation = ZSTD_not_in_dst; + { size_t const oneSeqSize = ZSTD_execSequence(op, oend, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd); +#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) + assert(!ZSTD_isError(oneSeqSize)); + ZSTD_assertValidSequence(dctx, op, oend, sequences[seqNb&STORED_SEQS_MASK], prefixStart, dictStart); +#endif + if (ZSTD_isError(oneSeqSize)) return oneSeqSize; + op += oneSeqSize; + } + } + else + { + size_t const oneSeqSize = dctx->litBufferLocation == ZSTD_split ? + ZSTD_execSequenceSplitLitBuffer(op, oend, litPtr + sequence->litLength - WILDCOPY_OVERLENGTH, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd) : + ZSTD_execSequence(op, oend, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd); +#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) + assert(!ZSTD_isError(oneSeqSize)); + ZSTD_assertValidSequence(dctx, op, oend, sequences[seqNb&STORED_SEQS_MASK], prefixStart, dictStart); +#endif + if (ZSTD_isError(oneSeqSize)) return oneSeqSize; + op += oneSeqSize; + } + } + + /* save reps for next block */ + { U32 i; for (i=0; ientropy.rep[i] = (U32)(seqState.prevOffset[i]); } + } + + /* last literal segment */ + if (dctx->litBufferLocation == ZSTD_split) { /* first deplete literal buffer in dst, then copy litExtraBuffer */ + size_t const lastLLSize = litBufferEnd - litPtr; + RETURN_ERROR_IF(lastLLSize > (size_t)(oend - op), dstSize_tooSmall, ""); + if (op != NULL) { + ZSTD_memmove(op, litPtr, lastLLSize); + op += lastLLSize; + } + litPtr = dctx->litExtraBuffer; + litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE; + } + { size_t const lastLLSize = litBufferEnd - litPtr; + RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, ""); + if (op != NULL) { + ZSTD_memmove(op, litPtr, lastLLSize); + op += lastLLSize; + } + } + + return (size_t)(op - ostart); +} + +static size_t +ZSTD_decompressSequencesLong_default(ZSTD_DCtx* dctx, + void* dst, size_t maxDstSize, + const void* seqStart, size_t seqSize, int nbSeq, + const ZSTD_longOffset_e isLongOffset) +{ + return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); +} +#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */ + + + +#if DYNAMIC_BMI2 + +#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG +static BMI2_TARGET_ATTRIBUTE size_t +DONT_VECTORIZE +ZSTD_decompressSequences_bmi2(ZSTD_DCtx* dctx, + void* dst, size_t maxDstSize, + const void* seqStart, size_t seqSize, int nbSeq, + const ZSTD_longOffset_e isLongOffset) +{ + return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); +} +static BMI2_TARGET_ATTRIBUTE size_t +DONT_VECTORIZE +ZSTD_decompressSequencesSplitLitBuffer_bmi2(ZSTD_DCtx* dctx, + void* dst, size_t maxDstSize, + const void* seqStart, size_t seqSize, int nbSeq, + const ZSTD_longOffset_e isLongOffset) +{ + return ZSTD_decompressSequences_bodySplitLitBuffer(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); +} +#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */ + +#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT +static BMI2_TARGET_ATTRIBUTE size_t +ZSTD_decompressSequencesLong_bmi2(ZSTD_DCtx* dctx, + void* dst, size_t maxDstSize, + const void* seqStart, size_t seqSize, int nbSeq, + const ZSTD_longOffset_e isLongOffset) +{ + return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); +} +#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */ + +#endif /* DYNAMIC_BMI2 */ + +#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG +static size_t +ZSTD_decompressSequences(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize, + const void* seqStart, size_t seqSize, int nbSeq, + const ZSTD_longOffset_e isLongOffset) +{ + DEBUGLOG(5, "ZSTD_decompressSequences"); +#if DYNAMIC_BMI2 + if (ZSTD_DCtx_get_bmi2(dctx)) { + return ZSTD_decompressSequences_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); + } +#endif + return ZSTD_decompressSequences_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); +} +static size_t +ZSTD_decompressSequencesSplitLitBuffer(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize, + const void* seqStart, size_t seqSize, int nbSeq, + const ZSTD_longOffset_e isLongOffset) +{ + DEBUGLOG(5, "ZSTD_decompressSequencesSplitLitBuffer"); +#if DYNAMIC_BMI2 + if (ZSTD_DCtx_get_bmi2(dctx)) { + return ZSTD_decompressSequencesSplitLitBuffer_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); + } +#endif + return ZSTD_decompressSequencesSplitLitBuffer_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); +} +#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */ + + +#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT +/* ZSTD_decompressSequencesLong() : + * decompression function triggered when a minimum share of offsets is considered "long", + * aka out of cache. + * note : "long" definition seems overloaded here, sometimes meaning "wider than bitstream register", and sometimes meaning "farther than memory cache distance". + * This function will try to mitigate main memory latency through the use of prefetching */ +static size_t +ZSTD_decompressSequencesLong(ZSTD_DCtx* dctx, + void* dst, size_t maxDstSize, + const void* seqStart, size_t seqSize, int nbSeq, + const ZSTD_longOffset_e isLongOffset) +{ + DEBUGLOG(5, "ZSTD_decompressSequencesLong"); +#if DYNAMIC_BMI2 + if (ZSTD_DCtx_get_bmi2(dctx)) { + return ZSTD_decompressSequencesLong_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); + } +#endif + return ZSTD_decompressSequencesLong_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); +} +#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */ + + +/** + * @returns The total size of the history referenceable by zstd, including + * both the prefix and the extDict. At @p op any offset larger than this + * is invalid. + */ +static size_t ZSTD_totalHistorySize(BYTE* op, BYTE const* virtualStart) +{ + return (size_t)(op - virtualStart); +} + +typedef struct { + unsigned longOffsetShare; + unsigned maxNbAdditionalBits; +} ZSTD_OffsetInfo; + +/* ZSTD_getOffsetInfo() : + * condition : offTable must be valid + * @return : "share" of long offsets (arbitrarily defined as > (1<<23)) + * compared to maximum possible of (1< 22) info.longOffsetShare += 1; + } + + assert(tableLog <= OffFSELog); + info.longOffsetShare <<= (OffFSELog - tableLog); /* scale to OffFSELog */ + } + + return info; +} + +/** + * @returns The maximum offset we can decode in one read of our bitstream, without + * reloading more bits in the middle of the offset bits read. Any offsets larger + * than this must use the long offset decoder. + */ +static size_t ZSTD_maxShortOffset(void) +{ + if (MEM_64bits()) { + /* We can decode any offset without reloading bits. + * This might change if the max window size grows. + */ + ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX <= 31); + return (size_t)-1; + } else { + /* The maximum offBase is (1 << (STREAM_ACCUMULATOR_MIN + 1)) - 1. + * This offBase would require STREAM_ACCUMULATOR_MIN extra bits. + * Then we have to subtract ZSTD_REP_NUM to get the maximum possible offset. + */ + size_t const maxOffbase = ((size_t)1 << (STREAM_ACCUMULATOR_MIN + 1)) - 1; + size_t const maxOffset = maxOffbase - ZSTD_REP_NUM; + assert(ZSTD_highbit32((U32)maxOffbase) == STREAM_ACCUMULATOR_MIN); + return maxOffset; + } +} + +size_t +ZSTD_decompressBlock_internal(ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, const streaming_operation streaming) +{ /* blockType == blockCompressed */ + const BYTE* ip = (const BYTE*)src; + DEBUGLOG(5, "ZSTD_decompressBlock_internal (cSize : %u)", (unsigned)srcSize); + + /* Note : the wording of the specification + * allows compressed block to be sized exactly ZSTD_blockSizeMax(dctx). + * This generally does not happen, as it makes little sense, + * since an uncompressed block would feature same size and have no decompression cost. + * Also, note that decoder from reference libzstd before < v1.5.4 + * would consider this edge case as an error. + * As a consequence, avoid generating compressed blocks of size ZSTD_blockSizeMax(dctx) + * for broader compatibility with the deployed ecosystem of zstd decoders */ + RETURN_ERROR_IF(srcSize > ZSTD_blockSizeMax(dctx), srcSize_wrong, ""); + + /* Decode literals section */ + { size_t const litCSize = ZSTD_decodeLiteralsBlock(dctx, src, srcSize, dst, dstCapacity, streaming); + DEBUGLOG(5, "ZSTD_decodeLiteralsBlock : cSize=%u, nbLiterals=%zu", (U32)litCSize, dctx->litSize); + if (ZSTD_isError(litCSize)) return litCSize; + ip += litCSize; + srcSize -= litCSize; + } + + /* Build Decoding Tables */ + { + /* Compute the maximum block size, which must also work when !frame and fParams are unset. + * Additionally, take the min with dstCapacity to ensure that the totalHistorySize fits in a size_t. + */ + size_t const blockSizeMax = MIN(dstCapacity, ZSTD_blockSizeMax(dctx)); + size_t const totalHistorySize = ZSTD_totalHistorySize(ZSTD_maybeNullPtrAdd((BYTE*)dst, blockSizeMax), (BYTE const*)dctx->virtualStart); + /* isLongOffset must be true if there are long offsets. + * Offsets are long if they are larger than ZSTD_maxShortOffset(). + * We don't expect that to be the case in 64-bit mode. + * + * We check here to see if our history is large enough to allow long offsets. + * If it isn't, then we can't possible have (valid) long offsets. If the offset + * is invalid, then it is okay to read it incorrectly. + * + * If isLongOffsets is true, then we will later check our decoding table to see + * if it is even possible to generate long offsets. + */ + ZSTD_longOffset_e isLongOffset = (ZSTD_longOffset_e)(MEM_32bits() && (totalHistorySize > ZSTD_maxShortOffset())); + /* These macros control at build-time which decompressor implementation + * we use. If neither is defined, we do some inspection and dispatch at + * runtime. + */ +#if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \ + !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG) + int usePrefetchDecoder = dctx->ddictIsCold; +#else + /* Set to 1 to avoid computing offset info if we don't need to. + * Otherwise this value is ignored. + */ + int usePrefetchDecoder = 1; +#endif + int nbSeq; + size_t const seqHSize = ZSTD_decodeSeqHeaders(dctx, &nbSeq, ip, srcSize); + if (ZSTD_isError(seqHSize)) return seqHSize; + ip += seqHSize; + srcSize -= seqHSize; + + RETURN_ERROR_IF((dst == NULL || dstCapacity == 0) && nbSeq > 0, dstSize_tooSmall, "NULL not handled"); + RETURN_ERROR_IF(MEM_64bits() && sizeof(size_t) == sizeof(void*) && (size_t)(-1) - (size_t)dst < (size_t)(1 << 20), dstSize_tooSmall, + "invalid dst"); + + /* If we could potentially have long offsets, or we might want to use the prefetch decoder, + * compute information about the share of long offsets, and the maximum nbAdditionalBits. + * NOTE: could probably use a larger nbSeq limit + */ + if (isLongOffset || (!usePrefetchDecoder && (totalHistorySize > (1u << 24)) && (nbSeq > 8))) { + ZSTD_OffsetInfo const info = ZSTD_getOffsetInfo(dctx->OFTptr, nbSeq); + if (isLongOffset && info.maxNbAdditionalBits <= STREAM_ACCUMULATOR_MIN) { + /* If isLongOffset, but the maximum number of additional bits that we see in our table is small + * enough, then we know it is impossible to have too long an offset in this block, so we can + * use the regular offset decoder. + */ + isLongOffset = ZSTD_lo_isRegularOffset; + } + if (!usePrefetchDecoder) { + U32 const minShare = MEM_64bits() ? 7 : 20; /* heuristic values, correspond to 2.73% and 7.81% */ + usePrefetchDecoder = (info.longOffsetShare >= minShare); + } + } + + dctx->ddictIsCold = 0; + +#if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \ + !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG) + if (usePrefetchDecoder) { +#else + (void)usePrefetchDecoder; + { +#endif +#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT + return ZSTD_decompressSequencesLong(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset); +#endif + } + +#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG + /* else */ + if (dctx->litBufferLocation == ZSTD_split) + return ZSTD_decompressSequencesSplitLitBuffer(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset); + else + return ZSTD_decompressSequences(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset); +#endif + } +} + + +ZSTD_ALLOW_POINTER_OVERFLOW_ATTR +void ZSTD_checkContinuity(ZSTD_DCtx* dctx, const void* dst, size_t dstSize) +{ + if (dst != dctx->previousDstEnd && dstSize > 0) { /* not contiguous */ + dctx->dictEnd = dctx->previousDstEnd; + dctx->virtualStart = (const char*)dst - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->prefixStart)); + dctx->prefixStart = dst; + dctx->previousDstEnd = dst; + } +} + + +size_t ZSTD_decompressBlock_deprecated(ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize) +{ + size_t dSize; + dctx->isFrameDecompression = 0; + ZSTD_checkContinuity(dctx, dst, dstCapacity); + dSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, not_streaming); + FORWARD_IF_ERROR(dSize, ""); + dctx->previousDstEnd = (char*)dst + dSize; + return dSize; +} + + +/* NOTE: Must just wrap ZSTD_decompressBlock_deprecated() */ +size_t ZSTD_decompressBlock(ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize) +{ + return ZSTD_decompressBlock_deprecated(dctx, dst, dstCapacity, src, srcSize); +} +/**** ended inlining decompress/zstd_decompress_block.c ****/ diff --git a/libretrodroid/src/main/cpp/libchdr/include/dr_libs/dr_flac.h b/libretrodroid/src/main/cpp/libchdr/include/dr_libs/dr_flac.h new file mode 100644 index 000000000..8ed53bc9c --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/include/dr_libs/dr_flac.h @@ -0,0 +1,11793 @@ +/* +FLAC audio decoder. Choice of public domain or MIT-0. See license statements at the end of this file. +dr_flac - v0.13.3 - 2026-01-17 + +David Reid - mackron@gmail.com + +GitHub: https://github.com/mackron/dr_libs +*/ + +/* +Introduction +============ +dr_flac is a single file library. To use it, do something like the following in one .c file. + + ```c + #define DR_FLAC_IMPLEMENTATION + #include "dr_flac.h" + ``` + +You can then #include this file in other parts of the program as you would with any other header file. To decode audio data, do something like the following: + + ```c + drflac* pFlac = drflac_open_file("MySong.flac", NULL); + if (pFlac == NULL) { + // Failed to open FLAC file + } + + drflac_int32* pSamples = malloc(pFlac->totalPCMFrameCount * pFlac->channels * sizeof(drflac_int32)); + drflac_uint64 numberOfInterleavedSamplesActuallyRead = drflac_read_pcm_frames_s32(pFlac, pFlac->totalPCMFrameCount, pSamples); + ``` + +The drflac object represents the decoder. It is a transparent type so all the information you need, such as the number of channels and the bits per sample, +should be directly accessible - just make sure you don't change their values. Samples are always output as interleaved signed 32-bit PCM. In the example above +a native FLAC stream was opened, however dr_flac has seamless support for Ogg encapsulated FLAC streams as well. + +You do not need to decode the entire stream in one go - you just specify how many samples you'd like at any given time and the decoder will give you as many +samples as it can, up to the amount requested. Later on when you need the next batch of samples, just call it again. Example: + + ```c + while (drflac_read_pcm_frames_s32(pFlac, chunkSizeInPCMFrames, pChunkSamples) > 0) { + do_something(); + } + ``` + +You can seek to a specific PCM frame with `drflac_seek_to_pcm_frame()`. + +If you just want to quickly decode an entire FLAC file in one go you can do something like this: + + ```c + unsigned int channels; + unsigned int sampleRate; + drflac_uint64 totalPCMFrameCount; + drflac_int32* pSampleData = drflac_open_file_and_read_pcm_frames_s32("MySong.flac", &channels, &sampleRate, &totalPCMFrameCount, NULL); + if (pSampleData == NULL) { + // Failed to open and decode FLAC file. + } + + ... + + drflac_free(pSampleData, NULL); + ``` + +You can read samples as signed 16-bit integer and 32-bit floating-point PCM with the *_s16() and *_f32() family of APIs respectively, but note that these +should be considered lossy. + + +If you need access to metadata (album art, etc.), use `drflac_open_with_metadata()`, `drflac_open_file_with_metdata()` or `drflac_open_memory_with_metadata()`. +The rationale for keeping these APIs separate is that they're slightly slower than the normal versions and also just a little bit harder to use. dr_flac +reports metadata to the application through the use of a callback, and every metadata block is reported before `drflac_open_with_metdata()` returns. + +The main opening APIs (`drflac_open()`, etc.) will fail if the header is not present. The presents a problem in certain scenarios such as broadcast style +streams or internet radio where the header may not be present because the user has started playback mid-stream. To handle this, use the relaxed APIs: + + `drflac_open_relaxed()` + `drflac_open_with_metadata_relaxed()` + +It is not recommended to use these APIs for file based streams because a missing header would usually indicate a corrupt or perverse file. In addition, these +APIs can take a long time to initialize because they may need to spend a lot of time finding the first frame. + + + +Build Options +============= +#define these options before including this file. + +#define DR_FLAC_NO_OGG + Disables support for Ogg/FLAC streams. + +#define DR_FLAC_BUFFER_SIZE + Defines the size of the internal buffer to store data from onRead(). This buffer is used to reduce the number of calls back to the client for more data. + Larger values means more memory, but better performance. My tests show diminishing returns after about 4KB (which is the default). Consider reducing this if + you have a very efficient implementation of onRead(), or increase it if it's very inefficient. Must be a multiple of 8. + +#define DR_FLAC_NO_CRC + Disables CRC checks. This will offer a performance boost when CRC is unnecessary. This will disable binary search seeking. When seeking, the seek table will + be used if available. Otherwise the seek will be performed using brute force. + +#define DR_FLAC_NO_SIMD + Disables SIMD optimizations (SSE on x86/x64 architectures, NEON on ARM architectures). Use this if you are having compatibility issues with your compiler. + +#define DR_FLAC_NO_WCHAR + Disables all functions ending with `_w`. Use this if your compiler does not provide wchar.h. + + + +Notes +===== +- dr_flac does not support changing the sample rate nor channel count mid stream. +- dr_flac is not thread-safe, but its APIs can be called from any thread so long as you do your own synchronization. +- When using Ogg encapsulation, a corrupted metadata block will result in `drflac_open_with_metadata()` and `drflac_open()` returning inconsistent samples due + to differences in corrupted stream recorvery logic between the two APIs. +*/ + +#ifndef dr_flac_h +#define dr_flac_h + +#ifdef __cplusplus +extern "C" { +#endif + +#define DRFLAC_STRINGIFY(x) #x +#define DRFLAC_XSTRINGIFY(x) DRFLAC_STRINGIFY(x) + +#define DRFLAC_VERSION_MAJOR 0 +#define DRFLAC_VERSION_MINOR 13 +#define DRFLAC_VERSION_REVISION 3 +#define DRFLAC_VERSION_STRING DRFLAC_XSTRINGIFY(DRFLAC_VERSION_MAJOR) "." DRFLAC_XSTRINGIFY(DRFLAC_VERSION_MINOR) "." DRFLAC_XSTRINGIFY(DRFLAC_VERSION_REVISION) + +#include /* For size_t. */ + +/* Sized Types */ +typedef signed char drflac_int8; +typedef unsigned char drflac_uint8; +typedef signed short drflac_int16; +typedef unsigned short drflac_uint16; +typedef signed int drflac_int32; +typedef unsigned int drflac_uint32; +#if defined(_MSC_VER) && !defined(__clang__) + typedef signed __int64 drflac_int64; + typedef unsigned __int64 drflac_uint64; +#else + #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wlong-long" + #if defined(__clang__) + #pragma GCC diagnostic ignored "-Wc++11-long-long" + #endif + #endif + typedef signed long long drflac_int64; + typedef unsigned long long drflac_uint64; + #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))) + #pragma GCC diagnostic pop + #endif +#endif +#if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__)) || defined(_M_X64) || defined(__ia64) || defined(_M_IA64) || defined(__aarch64__) || defined(_M_ARM64) || defined(__powerpc64__) + typedef drflac_uint64 drflac_uintptr; +#else + typedef drflac_uint32 drflac_uintptr; +#endif +typedef drflac_uint8 drflac_bool8; +typedef drflac_uint32 drflac_bool32; +#define DRFLAC_TRUE 1 +#define DRFLAC_FALSE 0 +/* End Sized Types */ + +/* Decorations */ +#if !defined(DRFLAC_API) + #if defined(DRFLAC_DLL) + #if defined(_WIN32) + #define DRFLAC_DLL_IMPORT __declspec(dllimport) + #define DRFLAC_DLL_EXPORT __declspec(dllexport) + #define DRFLAC_DLL_PRIVATE static + #else + #if defined(__GNUC__) && __GNUC__ >= 4 + #define DRFLAC_DLL_IMPORT __attribute__((visibility("default"))) + #define DRFLAC_DLL_EXPORT __attribute__((visibility("default"))) + #define DRFLAC_DLL_PRIVATE __attribute__((visibility("hidden"))) + #else + #define DRFLAC_DLL_IMPORT + #define DRFLAC_DLL_EXPORT + #define DRFLAC_DLL_PRIVATE static + #endif + #endif + + #if defined(DR_FLAC_IMPLEMENTATION) || defined(DRFLAC_IMPLEMENTATION) + #define DRFLAC_API DRFLAC_DLL_EXPORT + #else + #define DRFLAC_API DRFLAC_DLL_IMPORT + #endif + #define DRFLAC_PRIVATE DRFLAC_DLL_PRIVATE + #else + #define DRFLAC_API extern + #define DRFLAC_PRIVATE static + #endif +#endif +/* End Decorations */ + +#if defined(_MSC_VER) && _MSC_VER >= 1700 /* Visual Studio 2012 */ + #define DRFLAC_DEPRECATED __declspec(deprecated) +#elif (defined(__GNUC__) && __GNUC__ >= 4) /* GCC 4 */ + #define DRFLAC_DEPRECATED __attribute__((deprecated)) +#elif defined(__has_feature) /* Clang */ + #if __has_feature(attribute_deprecated) + #define DRFLAC_DEPRECATED __attribute__((deprecated)) + #else + #define DRFLAC_DEPRECATED + #endif +#else + #define DRFLAC_DEPRECATED +#endif + +DRFLAC_API void drflac_version(drflac_uint32* pMajor, drflac_uint32* pMinor, drflac_uint32* pRevision); +DRFLAC_API const char* drflac_version_string(void); + +/* Allocation Callbacks */ +typedef struct +{ + void* pUserData; + void* (* onMalloc)(size_t sz, void* pUserData); + void* (* onRealloc)(void* p, size_t sz, void* pUserData); + void (* onFree)(void* p, void* pUserData); +} drflac_allocation_callbacks; +/* End Allocation Callbacks */ + +/* +As data is read from the client it is placed into an internal buffer for fast access. This controls the size of that buffer. Larger values means more speed, +but also more memory. In my testing there is diminishing returns after about 4KB, but you can fiddle with this to suit your own needs. Must be a multiple of 8. +*/ +#ifndef DR_FLAC_BUFFER_SIZE +#define DR_FLAC_BUFFER_SIZE 4096 +#endif + + +/* Architecture Detection */ +#if defined(_WIN64) || defined(_LP64) || defined(__LP64__) +#define DRFLAC_64BIT +#endif + +#if defined(__x86_64__) || (defined(_M_X64) && !defined(_M_ARM64EC)) + #define DRFLAC_X64 +#elif defined(__i386) || defined(_M_IX86) + #define DRFLAC_X86 +#elif defined(__arm__) || defined(_M_ARM) || defined(__arm64) || defined(__arm64__) || defined(__aarch64__) || defined(_M_ARM64) || defined(_M_ARM64EC) + #define DRFLAC_ARM +#endif +/* End Architecture Detection */ + + +#ifdef DRFLAC_64BIT +typedef drflac_uint64 drflac_cache_t; +#else +typedef drflac_uint32 drflac_cache_t; +#endif + +/* The various metadata block types. */ +#define DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO 0 +#define DRFLAC_METADATA_BLOCK_TYPE_PADDING 1 +#define DRFLAC_METADATA_BLOCK_TYPE_APPLICATION 2 +#define DRFLAC_METADATA_BLOCK_TYPE_SEEKTABLE 3 +#define DRFLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT 4 +#define DRFLAC_METADATA_BLOCK_TYPE_CUESHEET 5 +#define DRFLAC_METADATA_BLOCK_TYPE_PICTURE 6 +#define DRFLAC_METADATA_BLOCK_TYPE_INVALID 127 + +/* The various picture types specified in the PICTURE block. */ +#define DRFLAC_PICTURE_TYPE_OTHER 0 +#define DRFLAC_PICTURE_TYPE_FILE_ICON 1 +#define DRFLAC_PICTURE_TYPE_OTHER_FILE_ICON 2 +#define DRFLAC_PICTURE_TYPE_COVER_FRONT 3 +#define DRFLAC_PICTURE_TYPE_COVER_BACK 4 +#define DRFLAC_PICTURE_TYPE_LEAFLET_PAGE 5 +#define DRFLAC_PICTURE_TYPE_MEDIA 6 +#define DRFLAC_PICTURE_TYPE_LEAD_ARTIST 7 +#define DRFLAC_PICTURE_TYPE_ARTIST 8 +#define DRFLAC_PICTURE_TYPE_CONDUCTOR 9 +#define DRFLAC_PICTURE_TYPE_BAND 10 +#define DRFLAC_PICTURE_TYPE_COMPOSER 11 +#define DRFLAC_PICTURE_TYPE_LYRICIST 12 +#define DRFLAC_PICTURE_TYPE_RECORDING_LOCATION 13 +#define DRFLAC_PICTURE_TYPE_DURING_RECORDING 14 +#define DRFLAC_PICTURE_TYPE_DURING_PERFORMANCE 15 +#define DRFLAC_PICTURE_TYPE_SCREEN_CAPTURE 16 +#define DRFLAC_PICTURE_TYPE_BRIGHT_COLORED_FISH 17 +#define DRFLAC_PICTURE_TYPE_ILLUSTRATION 18 +#define DRFLAC_PICTURE_TYPE_BAND_LOGOTYPE 19 +#define DRFLAC_PICTURE_TYPE_PUBLISHER_LOGOTYPE 20 + +typedef enum +{ + drflac_container_native, + drflac_container_ogg, + drflac_container_unknown +} drflac_container; + +typedef enum +{ + DRFLAC_SEEK_SET, + DRFLAC_SEEK_CUR, + DRFLAC_SEEK_END +} drflac_seek_origin; + +/* The order of members in this structure is important because we map this directly to the raw data within the SEEKTABLE metadata block. */ +typedef struct +{ + drflac_uint64 firstPCMFrame; + drflac_uint64 flacFrameOffset; /* The offset from the first byte of the header of the first frame. */ + drflac_uint16 pcmFrameCount; +} drflac_seekpoint; + +typedef struct +{ + drflac_uint16 minBlockSizeInPCMFrames; + drflac_uint16 maxBlockSizeInPCMFrames; + drflac_uint32 minFrameSizeInPCMFrames; + drflac_uint32 maxFrameSizeInPCMFrames; + drflac_uint32 sampleRate; + drflac_uint8 channels; + drflac_uint8 bitsPerSample; + drflac_uint64 totalPCMFrameCount; + drflac_uint8 md5[16]; +} drflac_streaminfo; + +typedef struct +{ + /* + The metadata type. Use this to know how to interpret the data below. Will be set to one of the + DRFLAC_METADATA_BLOCK_TYPE_* tokens. + */ + drflac_uint32 type; + + /* The size in bytes of the block and the buffer pointed to by pRawData if it's non-NULL. */ + drflac_uint32 rawDataSize; + + /* The offset in the stream of the raw data. */ + drflac_uint64 rawDataOffset; + + /* + A pointer to the raw data. This points to a temporary buffer so don't hold on to it. It's best to + not modify the contents of this buffer. Use the structures below for more meaningful and structured + information about the metadata. It's possible for this to be null. + */ + const void* pRawData; + + union + { + drflac_streaminfo streaminfo; + + struct + { + int unused; + } padding; + + struct + { + drflac_uint32 id; + const void* pData; + drflac_uint32 dataSize; + } application; + + struct + { + drflac_uint32 seekpointCount; + const drflac_seekpoint* pSeekpoints; + } seektable; + + struct + { + drflac_uint32 vendorLength; + const char* vendor; + drflac_uint32 commentCount; + const void* pComments; + } vorbis_comment; + + struct + { + char catalog[128]; + drflac_uint64 leadInSampleCount; + drflac_bool32 isCD; + drflac_uint8 trackCount; + const void* pTrackData; + } cuesheet; + + struct + { + drflac_uint32 type; + drflac_uint32 mimeLength; + const char* mime; + drflac_uint32 descriptionLength; + const char* description; + drflac_uint32 width; + drflac_uint32 height; + drflac_uint32 colorDepth; + drflac_uint32 indexColorCount; + drflac_uint32 pictureDataSize; + drflac_uint64 pictureDataOffset; /* Offset from the start of the stream. */ + const drflac_uint8* pPictureData; + } picture; + } data; +} drflac_metadata; + + +/* +Callback for when data needs to be read from the client. + + +Parameters +---------- +pUserData (in) + The user data that was passed to drflac_open() and family. + +pBufferOut (out) + The output buffer. + +bytesToRead (in) + The number of bytes to read. + + +Return Value +------------ +The number of bytes actually read. + + +Remarks +------- +A return value of less than bytesToRead indicates the end of the stream. Do _not_ return from this callback until either the entire bytesToRead is filled or +you have reached the end of the stream. +*/ +typedef size_t (* drflac_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead); + +/* +Callback for when data needs to be seeked. + + +Parameters +---------- +pUserData (in) + The user data that was passed to drflac_open() and family. + +offset (in) + The number of bytes to move, relative to the origin. Will never be negative. + +origin (in) + The origin of the seek - the current position, the start of the stream, or the end of the stream. + + +Return Value +------------ +Whether or not the seek was successful. + + +Remarks +------- +Seeking relative to the start and the current position must always be supported. If seeking from the end of the stream is not supported, return DRFLAC_FALSE. + +When seeking to a PCM frame using drflac_seek_to_pcm_frame(), dr_flac may call this with an offset beyond the end of the FLAC stream. This needs to be detected +and handled by returning DRFLAC_FALSE. +*/ +typedef drflac_bool32 (* drflac_seek_proc)(void* pUserData, int offset, drflac_seek_origin origin); + +/* +Callback for when the current position in the stream needs to be retrieved. + + +Parameters +---------- +pUserData (in) + The user data that was passed to drflac_open() and family. + +pCursor (out) + A pointer to a variable to receive the current position in the stream. + + +Return Value +------------ +Whether or not the operation was successful. +*/ +typedef drflac_bool32 (* drflac_tell_proc)(void* pUserData, drflac_int64* pCursor); + +/* +Callback for when a metadata block is read. + + +Parameters +---------- +pUserData (in) + The user data that was passed to drflac_open() and family. + +pMetadata (in) + A pointer to a structure containing the data of the metadata block. + + +Remarks +------- +Use pMetadata->type to determine which metadata block is being handled and how to read the data. This +will be set to one of the DRFLAC_METADATA_BLOCK_TYPE_* tokens. +*/ +typedef void (* drflac_meta_proc)(void* pUserData, drflac_metadata* pMetadata); + + +/* Structure for internal use. Only used for decoders opened with drflac_open_memory. */ +typedef struct +{ + const drflac_uint8* data; + size_t dataSize; + size_t currentReadPos; +} drflac__memory_stream; + +/* Structure for internal use. Used for bit streaming. */ +typedef struct +{ + /* The function to call when more data needs to be read. */ + drflac_read_proc onRead; + + /* The function to call when the current read position needs to be moved. */ + drflac_seek_proc onSeek; + + /* The function to call when the current read position needs to be retrieved. */ + drflac_tell_proc onTell; + + /* The user data to pass around to onRead and onSeek. */ + void* pUserData; + + + /* + The number of unaligned bytes in the L2 cache. This will always be 0 until the end of the stream is hit. At the end of the + stream there will be a number of bytes that don't cleanly fit in an L1 cache line, so we use this variable to know whether + or not the bistreamer needs to run on a slower path to read those last bytes. This will never be more than sizeof(drflac_cache_t). + */ + size_t unalignedByteCount; + + /* The content of the unaligned bytes. */ + drflac_cache_t unalignedCache; + + /* The index of the next valid cache line in the "L2" cache. */ + drflac_uint32 nextL2Line; + + /* The number of bits that have been consumed by the cache. This is used to determine how many valid bits are remaining. */ + drflac_uint32 consumedBits; + + /* + The cached data which was most recently read from the client. There are two levels of cache. Data flows as such: + Client -> L2 -> L1. The L2 -> L1 movement is aligned and runs on a fast path in just a few instructions. + */ + drflac_cache_t cacheL2[DR_FLAC_BUFFER_SIZE/sizeof(drflac_cache_t)]; + drflac_cache_t cache; + + /* + CRC-16. This is updated whenever bits are read from the bit stream. Manually set this to 0 to reset the CRC. For FLAC, this + is reset to 0 at the beginning of each frame. + */ + drflac_uint16 crc16; + drflac_cache_t crc16Cache; /* A cache for optimizing CRC calculations. This is filled when when the L1 cache is reloaded. */ + drflac_uint32 crc16CacheIgnoredBytes; /* The number of bytes to ignore when updating the CRC-16 from the CRC-16 cache. */ +} drflac_bs; + +typedef struct +{ + /* The type of the subframe: SUBFRAME_CONSTANT, SUBFRAME_VERBATIM, SUBFRAME_FIXED or SUBFRAME_LPC. */ + drflac_uint8 subframeType; + + /* The number of wasted bits per sample as specified by the sub-frame header. */ + drflac_uint8 wastedBitsPerSample; + + /* The order to use for the prediction stage for SUBFRAME_FIXED and SUBFRAME_LPC. */ + drflac_uint8 lpcOrder; + + /* A pointer to the buffer containing the decoded samples in the subframe. This pointer is an offset from drflac::pExtraData. */ + drflac_int32* pSamplesS32; +} drflac_subframe; + +typedef struct +{ + /* + If the stream uses variable block sizes, this will be set to the index of the first PCM frame. If fixed block sizes are used, this will + always be set to 0. This is 64-bit because the decoded PCM frame number will be 36 bits. + */ + drflac_uint64 pcmFrameNumber; + + /* + If the stream uses fixed block sizes, this will be set to the frame number. If variable block sizes are used, this will always be 0. This + is 32-bit because in fixed block sizes, the maximum frame number will be 31 bits. + */ + drflac_uint32 flacFrameNumber; + + /* The sample rate of this frame. */ + drflac_uint32 sampleRate; + + /* The number of PCM frames in each sub-frame within this frame. */ + drflac_uint16 blockSizeInPCMFrames; + + /* + The channel assignment of this frame. This is not always set to the channel count. If interchannel decorrelation is being used this + will be set to DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE, DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE or DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE. + */ + drflac_uint8 channelAssignment; + + /* The number of bits per sample within this frame. */ + drflac_uint8 bitsPerSample; + + /* The frame's CRC. */ + drflac_uint8 crc8; +} drflac_frame_header; + +typedef struct +{ + /* The header. */ + drflac_frame_header header; + + /* + The number of PCM frames left to be read in this FLAC frame. This is initially set to the block size. As PCM frames are read, + this will be decremented. When it reaches 0, the decoder will see this frame as fully consumed and load the next frame. + */ + drflac_uint32 pcmFramesRemaining; + + /* The list of sub-frames within the frame. There is one sub-frame for each channel, and there's a maximum of 8 channels. */ + drflac_subframe subframes[8]; +} drflac_frame; + +typedef struct +{ + /* The function to call when a metadata block is read. */ + drflac_meta_proc onMeta; + + /* The user data posted to the metadata callback function. */ + void* pUserDataMD; + + /* Memory allocation callbacks. */ + drflac_allocation_callbacks allocationCallbacks; + + + /* The sample rate. Will be set to something like 44100. */ + drflac_uint32 sampleRate; + + /* + The number of channels. This will be set to 1 for monaural streams, 2 for stereo, etc. Maximum 8. This is set based on the + value specified in the STREAMINFO block. + */ + drflac_uint8 channels; + + /* The bits per sample. Will be set to something like 16, 24, etc. */ + drflac_uint8 bitsPerSample; + + /* The maximum block size, in samples. This number represents the number of samples in each channel (not combined). */ + drflac_uint16 maxBlockSizeInPCMFrames; + + /* + The total number of PCM Frames making up the stream. Can be 0 in which case it's still a valid stream, but just means + the total PCM frame count is unknown. Likely the case with streams like internet radio. + */ + drflac_uint64 totalPCMFrameCount; + + + /* The container type. This is set based on whether or not the decoder was opened from a native or Ogg stream. */ + drflac_container container; + + /* The number of seekpoints in the seektable. */ + drflac_uint32 seekpointCount; + + + /* Information about the frame the decoder is currently sitting on. */ + drflac_frame currentFLACFrame; + + + /* The index of the PCM frame the decoder is currently sitting on. This is only used for seeking. */ + drflac_uint64 currentPCMFrame; + + /* The position of the first FLAC frame in the stream. This is only ever used for seeking. */ + drflac_uint64 firstFLACFramePosInBytes; + + + /* A hack to avoid a malloc() when opening a decoder with drflac_open_memory(). */ + drflac__memory_stream memoryStream; + + + /* A pointer to the decoded sample data. This is an offset of pExtraData. */ + drflac_int32* pDecodedSamples; + + /* A pointer to the seek table. This is an offset of pExtraData, or NULL if there is no seek table. */ + drflac_seekpoint* pSeekpoints; + + /* Internal use only. Only used with Ogg containers. Points to a drflac_oggbs object. This is an offset of pExtraData. */ + void* _oggbs; + + /* Internal use only. Used for profiling and testing different seeking modes. */ + drflac_bool32 _noSeekTableSeek : 1; + drflac_bool32 _noBinarySearchSeek : 1; + drflac_bool32 _noBruteForceSeek : 1; + + /* The bit streamer. The raw FLAC data is fed through this object. */ + drflac_bs bs; + + /* Variable length extra data. We attach this to the end of the object so we can avoid unnecessary mallocs. */ + drflac_uint8 pExtraData[1]; +} drflac; + + +/* +Opens a FLAC decoder. + + +Parameters +---------- +onRead (in) + The function to call when data needs to be read from the client. + +onSeek (in) + The function to call when the read position of the client data needs to move. + +pUserData (in, optional) + A pointer to application defined data that will be passed to onRead and onSeek. + +pAllocationCallbacks (in, optional) + A pointer to application defined callbacks for managing memory allocations. + + +Return Value +------------ +Returns a pointer to an object representing the decoder. + + +Remarks +------- +Close the decoder with `drflac_close()`. + +`pAllocationCallbacks` can be NULL in which case it will use `DRFLAC_MALLOC`, `DRFLAC_REALLOC` and `DRFLAC_FREE`. + +This function will automatically detect whether or not you are attempting to open a native or Ogg encapsulated FLAC, both of which should work seamlessly +without any manual intervention. Ogg encapsulation also works with multiplexed streams which basically means it can play FLAC encoded audio tracks in videos. + +This is the lowest level function for opening a FLAC stream. You can also use `drflac_open_file()` and `drflac_open_memory()` to open the stream from a file or +from a block of memory respectively. + +The STREAMINFO block must be present for this to succeed. Use `drflac_open_relaxed()` to open a FLAC stream where the header may not be present. + +Use `drflac_open_with_metadata()` if you need access to metadata. + + +Seek Also +--------- +drflac_open_file() +drflac_open_memory() +drflac_open_with_metadata() +drflac_close() +*/ +DRFLAC_API drflac* drflac_open(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks); + +/* +Opens a FLAC stream with relaxed validation of the header block. + + +Parameters +---------- +onRead (in) + The function to call when data needs to be read from the client. + +onSeek (in) + The function to call when the read position of the client data needs to move. + +container (in) + Whether or not the FLAC stream is encapsulated using standard FLAC encapsulation or Ogg encapsulation. + +pUserData (in, optional) + A pointer to application defined data that will be passed to onRead and onSeek. + +pAllocationCallbacks (in, optional) + A pointer to application defined callbacks for managing memory allocations. + + +Return Value +------------ +A pointer to an object representing the decoder. + + +Remarks +------- +The same as drflac_open(), except attempts to open the stream even when a header block is not present. + +Because the header is not necessarily available, the caller must explicitly define the container (Native or Ogg). Do not set this to `drflac_container_unknown` +as that is for internal use only. + +Opening in relaxed mode will continue reading data from onRead until it finds a valid frame. If a frame is never found it will continue forever. To abort, +force your `onRead` callback to return 0, which dr_flac will use as an indicator that the end of the stream was found. + +Use `drflac_open_with_metadata_relaxed()` if you need access to metadata. +*/ +DRFLAC_API drflac* drflac_open_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks); + +/* +Opens a FLAC decoder and notifies the caller of the metadata chunks (album art, etc.). + + +Parameters +---------- +onRead (in) + The function to call when data needs to be read from the client. + +onSeek (in) + The function to call when the read position of the client data needs to move. + +onMeta (in) + The function to call for every metadata block. + +pUserData (in, optional) + A pointer to application defined data that will be passed to onRead, onSeek and onMeta. + +pAllocationCallbacks (in, optional) + A pointer to application defined callbacks for managing memory allocations. + + +Return Value +------------ +A pointer to an object representing the decoder. + + +Remarks +------- +Close the decoder with `drflac_close()`. + +`pAllocationCallbacks` can be NULL in which case it will use `DRFLAC_MALLOC`, `DRFLAC_REALLOC` and `DRFLAC_FREE`. + +This is slower than `drflac_open()`, so avoid this one if you don't need metadata. Internally, this will allocate and free memory on the heap for every +metadata block except for STREAMINFO and PADDING blocks. + +The caller is notified of the metadata via the `onMeta` callback. All metadata blocks will be handled before the function returns. This callback takes a +pointer to a `drflac_metadata` object which is a union containing the data of all relevant metadata blocks. Use the `type` member to discriminate against +the different metadata types. + +The STREAMINFO block must be present for this to succeed. Use `drflac_open_with_metadata_relaxed()` to open a FLAC stream where the header may not be present. + +Note that this will behave inconsistently with `drflac_open()` if the stream is an Ogg encapsulated stream and a metadata block is corrupted. This is due to +the way the Ogg stream recovers from corrupted pages. When `drflac_open_with_metadata()` is being used, the open routine will try to read the contents of the +metadata block, whereas `drflac_open()` will simply seek past it (for the sake of efficiency). This inconsistency can result in different samples being +returned depending on whether or not the stream is being opened with metadata. + + +Seek Also +--------- +drflac_open_file_with_metadata() +drflac_open_memory_with_metadata() +drflac_open() +drflac_close() +*/ +DRFLAC_API drflac* drflac_open_with_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks); + +/* +The same as drflac_open_with_metadata(), except attempts to open the stream even when a header block is not present. + +See Also +-------- +drflac_open_with_metadata() +drflac_open_relaxed() +*/ +DRFLAC_API drflac* drflac_open_with_metadata_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, drflac_meta_proc onMeta, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks); + +/* +Closes the given FLAC decoder. + + +Parameters +---------- +pFlac (in) + The decoder to close. + + +Remarks +------- +This will destroy the decoder object. + + +See Also +-------- +drflac_open() +drflac_open_with_metadata() +drflac_open_file() +drflac_open_file_w() +drflac_open_file_with_metadata() +drflac_open_file_with_metadata_w() +drflac_open_memory() +drflac_open_memory_with_metadata() +*/ +DRFLAC_API void drflac_close(drflac* pFlac); + + +/* +Reads sample data from the given FLAC decoder, output as interleaved signed 32-bit PCM. + + +Parameters +---------- +pFlac (in) + The decoder. + +framesToRead (in) + The number of PCM frames to read. + +pBufferOut (out, optional) + A pointer to the buffer that will receive the decoded samples. + + +Return Value +------------ +Returns the number of PCM frames actually read. If the return value is less than `framesToRead` it has reached the end. + + +Remarks +------- +pBufferOut can be null, in which case the call will act as a seek, and the return value will be the number of frames seeked. +*/ +DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s32(drflac* pFlac, drflac_uint64 framesToRead, drflac_int32* pBufferOut); + + +/* +Reads sample data from the given FLAC decoder, output as interleaved signed 16-bit PCM. + + +Parameters +---------- +pFlac (in) + The decoder. + +framesToRead (in) + The number of PCM frames to read. + +pBufferOut (out, optional) + A pointer to the buffer that will receive the decoded samples. + + +Return Value +------------ +Returns the number of PCM frames actually read. If the return value is less than `framesToRead` it has reached the end. + + +Remarks +------- +pBufferOut can be null, in which case the call will act as a seek, and the return value will be the number of frames seeked. + +Note that this is lossy for streams where the bits per sample is larger than 16. +*/ +DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s16(drflac* pFlac, drflac_uint64 framesToRead, drflac_int16* pBufferOut); + +/* +Reads sample data from the given FLAC decoder, output as interleaved 32-bit floating point PCM. + + +Parameters +---------- +pFlac (in) + The decoder. + +framesToRead (in) + The number of PCM frames to read. + +pBufferOut (out, optional) + A pointer to the buffer that will receive the decoded samples. + + +Return Value +------------ +Returns the number of PCM frames actually read. If the return value is less than `framesToRead` it has reached the end. + + +Remarks +------- +pBufferOut can be null, in which case the call will act as a seek, and the return value will be the number of frames seeked. + +Note that this should be considered lossy due to the nature of floating point numbers not being able to exactly represent every possible number. +*/ +DRFLAC_API drflac_uint64 drflac_read_pcm_frames_f32(drflac* pFlac, drflac_uint64 framesToRead, float* pBufferOut); + +/* +Seeks to the PCM frame at the given index. + + +Parameters +---------- +pFlac (in) + The decoder. + +pcmFrameIndex (in) + The index of the PCM frame to seek to. See notes below. + + +Return Value +------------- +`DRFLAC_TRUE` if successful; `DRFLAC_FALSE` otherwise. +*/ +DRFLAC_API drflac_bool32 drflac_seek_to_pcm_frame(drflac* pFlac, drflac_uint64 pcmFrameIndex); + + + + +/* +Opens a FLAC decoder from a pre-allocated block of memory + + +Parameters +---------- +pData (in) + A pointer to the raw encoded FLAC data. + +dataSize (in) + The size in bytes of `data`. + +pAllocationCallbacks (in) + A pointer to application defined callbacks for managing memory allocations. + + +Return Value +------------ +A pointer to an object representing the decoder. + + +Remarks +------- +This does not create a copy of the data. It is up to the application to ensure the buffer remains valid for the lifetime of the decoder. + + +See Also +-------- +drflac_open() +drflac_close() +*/ +DRFLAC_API drflac* drflac_open_memory(const void* pData, size_t dataSize, const drflac_allocation_callbacks* pAllocationCallbacks); + +/* +Opens a FLAC decoder from a pre-allocated block of memory and notifies the caller of the metadata chunks (album art, etc.) + + +Parameters +---------- +pData (in) + A pointer to the raw encoded FLAC data. + +dataSize (in) + The size in bytes of `data`. + +onMeta (in) + The callback to fire for each metadata block. + +pUserData (in) + A pointer to the user data to pass to the metadata callback. + +pAllocationCallbacks (in) + A pointer to application defined callbacks for managing memory allocations. + + +Remarks +------- +Look at the documentation for drflac_open_with_metadata() for more information on how metadata is handled. + + +See Also +------- +drflac_open_with_metadata() +drflac_open() +drflac_close() +*/ +DRFLAC_API drflac* drflac_open_memory_with_metadata(const void* pData, size_t dataSize, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks); + + + +/* High Level APIs */ + +/* +Opens a FLAC stream from the given callbacks and fully decodes it in a single operation. The return value is a +pointer to the sample data as interleaved signed 32-bit PCM. The returned data must be freed with drflac_free(). + +You can pass in custom memory allocation callbacks via the pAllocationCallbacks parameter. This can be NULL in which +case it will use DRFLAC_MALLOC, DRFLAC_REALLOC and DRFLAC_FREE. + +Sometimes a FLAC file won't keep track of the total sample count. In this situation the function will continuously +read samples into a dynamically sized buffer on the heap until no samples are left. + +Do not call this function on a broadcast type of stream (like internet radio streams and whatnot). +*/ +DRFLAC_API drflac_int32* drflac_open_and_read_pcm_frames_s32(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks); + +/* Same as drflac_open_and_read_pcm_frames_s32(), except returns signed 16-bit integer samples. */ +DRFLAC_API drflac_int16* drflac_open_and_read_pcm_frames_s16(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks); + +/* Same as drflac_open_and_read_pcm_frames_s32(), except returns 32-bit floating-point samples. */ +DRFLAC_API float* drflac_open_and_read_pcm_frames_f32(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks); + + +/* Same as drflac_open_and_read_pcm_frames_s32() except opens the decoder from a block of memory. */ +DRFLAC_API drflac_int32* drflac_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks); + +/* Same as drflac_open_memory_and_read_pcm_frames_s32(), except returns signed 16-bit integer samples. */ +DRFLAC_API drflac_int16* drflac_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks); + +/* Same as drflac_open_memory_and_read_pcm_frames_s32(), except returns 32-bit floating-point samples. */ +DRFLAC_API float* drflac_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks); + +/* +Frees memory that was allocated internally by dr_flac. + +Set pAllocationCallbacks to the same object that was passed to drflac_open_*_and_read_pcm_frames_*(). If you originally passed in NULL, pass in NULL for this. +*/ +DRFLAC_API void drflac_free(void* p, const drflac_allocation_callbacks* pAllocationCallbacks); + + +/* Structure representing an iterator for vorbis comments in a VORBIS_COMMENT metadata block. */ +typedef struct +{ + drflac_uint32 countRemaining; + const char* pRunningData; +} drflac_vorbis_comment_iterator; + +/* +Initializes a vorbis comment iterator. This can be used for iterating over the vorbis comments in a VORBIS_COMMENT +metadata block. +*/ +DRFLAC_API void drflac_init_vorbis_comment_iterator(drflac_vorbis_comment_iterator* pIter, drflac_uint32 commentCount, const void* pComments); + +/* +Goes to the next vorbis comment in the given iterator. If null is returned it means there are no more comments. The +returned string is NOT null terminated. +*/ +DRFLAC_API const char* drflac_next_vorbis_comment(drflac_vorbis_comment_iterator* pIter, drflac_uint32* pCommentLengthOut); + + +/* Structure representing an iterator for cuesheet tracks in a CUESHEET metadata block. */ +typedef struct +{ + drflac_uint32 countRemaining; + const char* pRunningData; +} drflac_cuesheet_track_iterator; + +/* The order of members here is important because we map this directly to the raw data within the CUESHEET metadata block. */ +typedef struct +{ + drflac_uint64 offset; + drflac_uint8 index; + drflac_uint8 reserved[3]; +} drflac_cuesheet_track_index; + +typedef struct +{ + drflac_uint64 offset; + drflac_uint8 trackNumber; + char ISRC[12]; + drflac_bool8 isAudio; + drflac_bool8 preEmphasis; + drflac_uint8 indexCount; + const drflac_cuesheet_track_index* pIndexPoints; +} drflac_cuesheet_track; + +/* +Initializes a cuesheet track iterator. This can be used for iterating over the cuesheet tracks in a CUESHEET metadata +block. +*/ +DRFLAC_API void drflac_init_cuesheet_track_iterator(drflac_cuesheet_track_iterator* pIter, drflac_uint32 trackCount, const void* pTrackData); + +/* Goes to the next cuesheet track in the given iterator. If DRFLAC_FALSE is returned it means there are no more comments. */ +DRFLAC_API drflac_bool32 drflac_next_cuesheet_track(drflac_cuesheet_track_iterator* pIter, drflac_cuesheet_track* pCuesheetTrack); + + +#ifdef __cplusplus +} +#endif +#endif /* dr_flac_h */ + + +/************************************************************************************************************************************************************ + ************************************************************************************************************************************************************ + + IMPLEMENTATION + + ************************************************************************************************************************************************************ + ************************************************************************************************************************************************************/ +#if defined(DR_FLAC_IMPLEMENTATION) || defined(DRFLAC_IMPLEMENTATION) +#ifndef dr_flac_c +#define dr_flac_c + +/* Disable some annoying warnings. */ +#if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))) + #pragma GCC diagnostic push + #if __GNUC__ >= 7 + #pragma GCC diagnostic ignored "-Wimplicit-fallthrough" + #endif +#endif + +#ifdef __linux__ + #ifndef _BSD_SOURCE + #define _BSD_SOURCE + #endif + #ifndef _DEFAULT_SOURCE + #define _DEFAULT_SOURCE + #endif + #ifndef __USE_BSD + #define __USE_BSD + #endif + #include +#endif + +#include +#include + +/* Inline */ +#ifdef _MSC_VER + #define DRFLAC_INLINE __forceinline +#elif defined(__GNUC__) + /* + I've had a bug report where GCC is emitting warnings about functions possibly not being inlineable. This warning happens when + the __attribute__((always_inline)) attribute is defined without an "inline" statement. I think therefore there must be some + case where "__inline__" is not always defined, thus the compiler emitting these warnings. When using -std=c89 or -ansi on the + command line, we cannot use the "inline" keyword and instead need to use "__inline__". In an attempt to work around this issue + I am using "__inline__" only when we're compiling in strict ANSI mode. + */ + #if defined(__STRICT_ANSI__) + #define DRFLAC_GNUC_INLINE_HINT __inline__ + #else + #define DRFLAC_GNUC_INLINE_HINT inline + #endif + + #if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 2)) || defined(__clang__) + #define DRFLAC_INLINE DRFLAC_GNUC_INLINE_HINT __attribute__((always_inline)) + #else + #define DRFLAC_INLINE DRFLAC_GNUC_INLINE_HINT + #endif +#elif defined(__WATCOMC__) + #define DRFLAC_INLINE __inline +#else + #define DRFLAC_INLINE +#endif +/* End Inline */ + +/* +Intrinsics Support + +There's a bug in GCC 4.2.x which results in an incorrect compilation error when using _mm_slli_epi32() where it complains with + + "error: shift must be an immediate" + +Unfortuantely dr_flac depends on this for a few things so we're just going to disable SSE on GCC 4.2 and below. +*/ +#if !defined(DR_FLAC_NO_SIMD) + #if defined(DRFLAC_X64) || defined(DRFLAC_X86) + #if defined(_MSC_VER) && !defined(__clang__) + /* MSVC. */ + #if _MSC_VER >= 1400 && !defined(DRFLAC_NO_SSE2) /* 2005 */ + #define DRFLAC_SUPPORT_SSE2 + #endif + #if _MSC_VER >= 1600 && !defined(DRFLAC_NO_SSE41) /* 2010 */ + #define DRFLAC_SUPPORT_SSE41 + #endif + #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))) + /* Assume GNUC-style. */ + #if defined(__SSE2__) && !defined(DRFLAC_NO_SSE2) + #define DRFLAC_SUPPORT_SSE2 + #endif + #if defined(__SSE4_1__) && !defined(DRFLAC_NO_SSE41) + #define DRFLAC_SUPPORT_SSE41 + #endif + #endif + + /* If at this point we still haven't determined compiler support for the intrinsics just fall back to __has_include. */ + #if !defined(__GNUC__) && !defined(__clang__) && defined(__has_include) + #if !defined(DRFLAC_SUPPORT_SSE2) && !defined(DRFLAC_NO_SSE2) && __has_include() + #define DRFLAC_SUPPORT_SSE2 + #endif + #if !defined(DRFLAC_SUPPORT_SSE41) && !defined(DRFLAC_NO_SSE41) && __has_include() + #define DRFLAC_SUPPORT_SSE41 + #endif + #endif + + #if defined(DRFLAC_SUPPORT_SSE41) + #include + #elif defined(DRFLAC_SUPPORT_SSE2) + #include + #endif + #endif + + #if defined(DRFLAC_ARM) + #if !defined(DRFLAC_NO_NEON) && (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64)) + #define DRFLAC_SUPPORT_NEON + #include + #endif + #endif +#endif + +/* Compile-time CPU feature support. */ +#if !defined(DR_FLAC_NO_SIMD) && (defined(DRFLAC_X86) || defined(DRFLAC_X64)) + #if defined(_MSC_VER) && !defined(__clang__) + #if _MSC_VER >= 1400 + #include + static void drflac__cpuid(int info[4], int fid) + { + __cpuid(info, fid); + } + #else + #define DRFLAC_NO_CPUID + #endif + #else + #if defined(__GNUC__) || defined(__clang__) + static void drflac__cpuid(int info[4], int fid) + { + /* + It looks like the -fPIC option uses the ebx register which GCC complains about. We can work around this by just using a different register, the + specific register of which I'm letting the compiler decide on. The "k" prefix is used to specify a 32-bit register. The {...} syntax is for + supporting different assembly dialects. + + What's basically happening is that we're saving and restoring the ebx register manually. + */ + #if defined(DRFLAC_X86) && defined(__PIC__) + __asm__ __volatile__ ( + "xchg{l} {%%}ebx, %k1;" + "cpuid;" + "xchg{l} {%%}ebx, %k1;" + : "=a"(info[0]), "=&r"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0) + ); + #else + __asm__ __volatile__ ( + "cpuid" : "=a"(info[0]), "=b"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0) + ); + #endif + } + #else + #define DRFLAC_NO_CPUID + #endif + #endif +#else + #define DRFLAC_NO_CPUID +#endif + +static DRFLAC_INLINE drflac_bool32 drflac_has_sse2(void) +{ +#if defined(DRFLAC_SUPPORT_SSE2) + #if (defined(DRFLAC_X64) || defined(DRFLAC_X86)) && !defined(DRFLAC_NO_SSE2) + #if defined(DRFLAC_X64) + return DRFLAC_TRUE; /* 64-bit targets always support SSE2. */ + #elif (defined(_M_IX86_FP) && _M_IX86_FP == 2) || defined(__SSE2__) + return DRFLAC_TRUE; /* If the compiler is allowed to freely generate SSE2 code we can assume support. */ + #else + #if defined(DRFLAC_NO_CPUID) + return DRFLAC_FALSE; + #else + int info[4]; + drflac__cpuid(info, 1); + return (info[3] & (1 << 26)) != 0; + #endif + #endif + #else + return DRFLAC_FALSE; /* SSE2 is only supported on x86 and x64 architectures. */ + #endif +#else + return DRFLAC_FALSE; /* No compiler support. */ +#endif +} + +static DRFLAC_INLINE drflac_bool32 drflac_has_sse41(void) +{ +#if defined(DRFLAC_SUPPORT_SSE41) + #if (defined(DRFLAC_X64) || defined(DRFLAC_X86)) && !defined(DRFLAC_NO_SSE41) + #if defined(__SSE4_1__) || defined(__AVX__) + return DRFLAC_TRUE; /* If the compiler is allowed to freely generate SSE41 code we can assume support. */ + #else + #if defined(DRFLAC_NO_CPUID) + return DRFLAC_FALSE; + #else + int info[4]; + drflac__cpuid(info, 1); + return (info[2] & (1 << 19)) != 0; + #endif + #endif + #else + return DRFLAC_FALSE; /* SSE41 is only supported on x86 and x64 architectures. */ + #endif +#else + return DRFLAC_FALSE; /* No compiler support. */ +#endif +} + + +#if defined(_MSC_VER) && _MSC_VER >= 1500 && (defined(DRFLAC_X86) || defined(DRFLAC_X64)) && !defined(__clang__) + #define DRFLAC_HAS_LZCNT_INTRINSIC +#elif (defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7))) + #define DRFLAC_HAS_LZCNT_INTRINSIC +#elif defined(__clang__) + #if defined(__has_builtin) + #if __has_builtin(__builtin_clzll) || __has_builtin(__builtin_clzl) + #define DRFLAC_HAS_LZCNT_INTRINSIC + #endif + #endif +#endif + +#if defined(_MSC_VER) && _MSC_VER >= 1400 && !defined(__clang__) + #define DRFLAC_HAS_BYTESWAP16_INTRINSIC + #define DRFLAC_HAS_BYTESWAP32_INTRINSIC + #define DRFLAC_HAS_BYTESWAP64_INTRINSIC +#elif defined(__clang__) + #if defined(__has_builtin) + #if __has_builtin(__builtin_bswap16) + #define DRFLAC_HAS_BYTESWAP16_INTRINSIC + #endif + #if __has_builtin(__builtin_bswap32) + #define DRFLAC_HAS_BYTESWAP32_INTRINSIC + #endif + #if __has_builtin(__builtin_bswap64) + #define DRFLAC_HAS_BYTESWAP64_INTRINSIC + #endif + #endif +#elif defined(__GNUC__) + #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) + #define DRFLAC_HAS_BYTESWAP32_INTRINSIC + #define DRFLAC_HAS_BYTESWAP64_INTRINSIC + #endif + #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)) + #define DRFLAC_HAS_BYTESWAP16_INTRINSIC + #endif +#elif defined(__WATCOMC__) && defined(__386__) + #define DRFLAC_HAS_BYTESWAP16_INTRINSIC + #define DRFLAC_HAS_BYTESWAP32_INTRINSIC + #define DRFLAC_HAS_BYTESWAP64_INTRINSIC + extern __inline drflac_uint16 _watcom_bswap16(drflac_uint16); + extern __inline drflac_uint32 _watcom_bswap32(drflac_uint32); + extern __inline drflac_uint64 _watcom_bswap64(drflac_uint64); +#pragma aux _watcom_bswap16 = \ + "xchg al, ah" \ + parm [ax] \ + value [ax] \ + modify nomemory; +#pragma aux _watcom_bswap32 = \ + "bswap eax" \ + parm [eax] \ + value [eax] \ + modify nomemory; +#pragma aux _watcom_bswap64 = \ + "bswap eax" \ + "bswap edx" \ + "xchg eax,edx" \ + parm [eax edx] \ + value [eax edx] \ + modify nomemory; +#endif + + +/* Standard library stuff. */ +#ifndef DRFLAC_ASSERT +#include +#define DRFLAC_ASSERT(expression) assert(expression) +#endif +#ifndef DRFLAC_MALLOC +#define DRFLAC_MALLOC(sz) malloc((sz)) +#endif +#ifndef DRFLAC_REALLOC +#define DRFLAC_REALLOC(p, sz) realloc((p), (sz)) +#endif +#ifndef DRFLAC_FREE +#define DRFLAC_FREE(p) free((p)) +#endif +#ifndef DRFLAC_COPY_MEMORY +#define DRFLAC_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz)) +#endif +#ifndef DRFLAC_ZERO_MEMORY +#define DRFLAC_ZERO_MEMORY(p, sz) memset((p), 0, (sz)) +#endif +#ifndef DRFLAC_ZERO_OBJECT +#define DRFLAC_ZERO_OBJECT(p) DRFLAC_ZERO_MEMORY((p), sizeof(*(p))) +#endif + +#define DRFLAC_MAX_SIMD_VECTOR_SIZE 64 /* 64 for AVX-512 in the future. */ + +/* Result Codes */ +typedef drflac_int32 drflac_result; +#define DRFLAC_SUCCESS 0 +#define DRFLAC_ERROR -1 /* A generic error. */ +#define DRFLAC_INVALID_ARGS -2 +#define DRFLAC_INVALID_OPERATION -3 +#define DRFLAC_OUT_OF_MEMORY -4 +#define DRFLAC_OUT_OF_RANGE -5 +#define DRFLAC_ACCESS_DENIED -6 +#define DRFLAC_DOES_NOT_EXIST -7 +#define DRFLAC_ALREADY_EXISTS -8 +#define DRFLAC_TOO_MANY_OPEN_FILES -9 +#define DRFLAC_INVALID_FILE -10 +#define DRFLAC_TOO_BIG -11 +#define DRFLAC_PATH_TOO_LONG -12 +#define DRFLAC_NAME_TOO_LONG -13 +#define DRFLAC_NOT_DIRECTORY -14 +#define DRFLAC_IS_DIRECTORY -15 +#define DRFLAC_DIRECTORY_NOT_EMPTY -16 +#define DRFLAC_END_OF_FILE -17 +#define DRFLAC_NO_SPACE -18 +#define DRFLAC_BUSY -19 +#define DRFLAC_IO_ERROR -20 +#define DRFLAC_INTERRUPT -21 +#define DRFLAC_UNAVAILABLE -22 +#define DRFLAC_ALREADY_IN_USE -23 +#define DRFLAC_BAD_ADDRESS -24 +#define DRFLAC_BAD_SEEK -25 +#define DRFLAC_BAD_PIPE -26 +#define DRFLAC_DEADLOCK -27 +#define DRFLAC_TOO_MANY_LINKS -28 +#define DRFLAC_NOT_IMPLEMENTED -29 +#define DRFLAC_NO_MESSAGE -30 +#define DRFLAC_BAD_MESSAGE -31 +#define DRFLAC_NO_DATA_AVAILABLE -32 +#define DRFLAC_INVALID_DATA -33 +#define DRFLAC_TIMEOUT -34 +#define DRFLAC_NO_NETWORK -35 +#define DRFLAC_NOT_UNIQUE -36 +#define DRFLAC_NOT_SOCKET -37 +#define DRFLAC_NO_ADDRESS -38 +#define DRFLAC_BAD_PROTOCOL -39 +#define DRFLAC_PROTOCOL_UNAVAILABLE -40 +#define DRFLAC_PROTOCOL_NOT_SUPPORTED -41 +#define DRFLAC_PROTOCOL_FAMILY_NOT_SUPPORTED -42 +#define DRFLAC_ADDRESS_FAMILY_NOT_SUPPORTED -43 +#define DRFLAC_SOCKET_NOT_SUPPORTED -44 +#define DRFLAC_CONNECTION_RESET -45 +#define DRFLAC_ALREADY_CONNECTED -46 +#define DRFLAC_NOT_CONNECTED -47 +#define DRFLAC_CONNECTION_REFUSED -48 +#define DRFLAC_NO_HOST -49 +#define DRFLAC_IN_PROGRESS -50 +#define DRFLAC_CANCELLED -51 +#define DRFLAC_MEMORY_ALREADY_MAPPED -52 +#define DRFLAC_AT_END -53 + +#define DRFLAC_CRC_MISMATCH -100 +/* End Result Codes */ + + +#define DRFLAC_SUBFRAME_CONSTANT 0 +#define DRFLAC_SUBFRAME_VERBATIM 1 +#define DRFLAC_SUBFRAME_FIXED 8 +#define DRFLAC_SUBFRAME_LPC 32 +#define DRFLAC_SUBFRAME_RESERVED 255 + +#define DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE 0 +#define DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2 1 + +#define DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT 0 +#define DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE 8 +#define DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE 9 +#define DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE 10 + +#define DRFLAC_SEEKPOINT_SIZE_IN_BYTES 18 +#define DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES 36 +#define DRFLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES 12 + +#define drflac_align(x, a) ((((x) + (a) - 1) / (a)) * (a)) + + +DRFLAC_API void drflac_version(drflac_uint32* pMajor, drflac_uint32* pMinor, drflac_uint32* pRevision) +{ + if (pMajor) { + *pMajor = DRFLAC_VERSION_MAJOR; + } + + if (pMinor) { + *pMinor = DRFLAC_VERSION_MINOR; + } + + if (pRevision) { + *pRevision = DRFLAC_VERSION_REVISION; + } +} + +DRFLAC_API const char* drflac_version_string(void) +{ + return DRFLAC_VERSION_STRING; +} + + +/* CPU caps. */ +#if defined(__has_feature) + #if __has_feature(thread_sanitizer) + #define DRFLAC_NO_THREAD_SANITIZE __attribute__((no_sanitize("thread"))) + #else + #define DRFLAC_NO_THREAD_SANITIZE + #endif +#else + #define DRFLAC_NO_THREAD_SANITIZE +#endif + +#if defined(DRFLAC_HAS_LZCNT_INTRINSIC) +static drflac_bool32 drflac__gIsLZCNTSupported = DRFLAC_FALSE; +#endif + +#ifndef DRFLAC_NO_CPUID +static drflac_bool32 drflac__gIsSSE2Supported = DRFLAC_FALSE; +static drflac_bool32 drflac__gIsSSE41Supported = DRFLAC_FALSE; + +/* +I've had a bug report that Clang's ThreadSanitizer presents a warning in this function. Having reviewed this, this does +actually make sense. However, since CPU caps should never differ for a running process, I don't think the trade off of +complicating internal API's by passing around CPU caps versus just disabling the warnings is worthwhile. I'm therefore +just going to disable these warnings. This is disabled via the DRFLAC_NO_THREAD_SANITIZE attribute. +*/ +DRFLAC_NO_THREAD_SANITIZE static void drflac__init_cpu_caps(void) +{ + static drflac_bool32 isCPUCapsInitialized = DRFLAC_FALSE; + + if (!isCPUCapsInitialized) { + /* LZCNT */ +#if defined(DRFLAC_HAS_LZCNT_INTRINSIC) + int info[4] = {0}; + drflac__cpuid(info, 0x80000001); + drflac__gIsLZCNTSupported = (info[2] & (1 << 5)) != 0; +#endif + + /* SSE2 */ + drflac__gIsSSE2Supported = drflac_has_sse2(); + + /* SSE4.1 */ + drflac__gIsSSE41Supported = drflac_has_sse41(); + + /* Initialized. */ + isCPUCapsInitialized = DRFLAC_TRUE; + } +} +#else +static drflac_bool32 drflac__gIsNEONSupported = DRFLAC_FALSE; + +static DRFLAC_INLINE drflac_bool32 drflac__has_neon(void) +{ +#if defined(DRFLAC_SUPPORT_NEON) + #if defined(DRFLAC_ARM) && !defined(DRFLAC_NO_NEON) + #if (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64)) + return DRFLAC_TRUE; /* If the compiler is allowed to freely generate NEON code we can assume support. */ + #else + /* TODO: Runtime check. */ + return DRFLAC_FALSE; + #endif + #else + return DRFLAC_FALSE; /* NEON is only supported on ARM architectures. */ + #endif +#else + return DRFLAC_FALSE; /* No compiler support. */ +#endif +} + +DRFLAC_NO_THREAD_SANITIZE static void drflac__init_cpu_caps(void) +{ + drflac__gIsNEONSupported = drflac__has_neon(); + +#if defined(DRFLAC_HAS_LZCNT_INTRINSIC) && defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 5) + drflac__gIsLZCNTSupported = DRFLAC_TRUE; +#endif +} +#endif + + +/* Endian Management */ +static DRFLAC_INLINE drflac_bool32 drflac__is_little_endian(void) +{ +#if defined(DRFLAC_X86) || defined(DRFLAC_X64) + return DRFLAC_TRUE; +#elif defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && __BYTE_ORDER == __LITTLE_ENDIAN + return DRFLAC_TRUE; +#else + int n = 1; + return (*(char*)&n) == 1; +#endif +} + +static DRFLAC_INLINE drflac_uint16 drflac__swap_endian_uint16(drflac_uint16 n) +{ +#ifdef DRFLAC_HAS_BYTESWAP16_INTRINSIC + #if defined(_MSC_VER) && !defined(__clang__) + return _byteswap_ushort(n); + #elif defined(__GNUC__) || defined(__clang__) + return __builtin_bswap16(n); + #elif defined(__WATCOMC__) && defined(__386__) + return _watcom_bswap16(n); + #else + #error "This compiler does not support the byte swap intrinsic." + #endif +#else + return ((n & 0xFF00) >> 8) | + ((n & 0x00FF) << 8); +#endif +} + +static DRFLAC_INLINE drflac_uint32 drflac__swap_endian_uint32(drflac_uint32 n) +{ +#ifdef DRFLAC_HAS_BYTESWAP32_INTRINSIC + #if defined(_MSC_VER) && !defined(__clang__) + return _byteswap_ulong(n); + #elif defined(__GNUC__) || defined(__clang__) + #if defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 6) && !defined(__ARM_ARCH_6M__) && !defined(DRFLAC_64BIT) /* <-- 64-bit inline assembly has not been tested, so disabling for now. */ + /* Inline assembly optimized implementation for ARM. In my testing, GCC does not generate optimized code with __builtin_bswap32(). */ + drflac_uint32 r; + __asm__ __volatile__ ( + #if defined(DRFLAC_64BIT) + "rev %w[out], %w[in]" : [out]"=r"(r) : [in]"r"(n) /* <-- This is untested. If someone in the community could test this, that would be appreciated! */ + #else + "rev %[out], %[in]" : [out]"=r"(r) : [in]"r"(n) + #endif + ); + return r; + #else + return __builtin_bswap32(n); + #endif + #elif defined(__WATCOMC__) && defined(__386__) + return _watcom_bswap32(n); + #else + #error "This compiler does not support the byte swap intrinsic." + #endif +#else + return ((n & 0xFF000000) >> 24) | + ((n & 0x00FF0000) >> 8) | + ((n & 0x0000FF00) << 8) | + ((n & 0x000000FF) << 24); +#endif +} + +static DRFLAC_INLINE drflac_uint64 drflac__swap_endian_uint64(drflac_uint64 n) +{ +#ifdef DRFLAC_HAS_BYTESWAP64_INTRINSIC + #if defined(_MSC_VER) && !defined(__clang__) + return _byteswap_uint64(n); + #elif defined(__GNUC__) || defined(__clang__) + return __builtin_bswap64(n); + #elif defined(__WATCOMC__) && defined(__386__) + return _watcom_bswap64(n); + #else + #error "This compiler does not support the byte swap intrinsic." + #endif +#else + /* Weird "<< 32" bitshift is required for C89 because it doesn't support 64-bit constants. Should be optimized out by a good compiler. */ + return ((n & ((drflac_uint64)0xFF000000 << 32)) >> 56) | + ((n & ((drflac_uint64)0x00FF0000 << 32)) >> 40) | + ((n & ((drflac_uint64)0x0000FF00 << 32)) >> 24) | + ((n & ((drflac_uint64)0x000000FF << 32)) >> 8) | + ((n & ((drflac_uint64)0xFF000000 )) << 8) | + ((n & ((drflac_uint64)0x00FF0000 )) << 24) | + ((n & ((drflac_uint64)0x0000FF00 )) << 40) | + ((n & ((drflac_uint64)0x000000FF )) << 56); +#endif +} + + +static DRFLAC_INLINE drflac_uint16 drflac__be2host_16(drflac_uint16 n) +{ + if (drflac__is_little_endian()) { + return drflac__swap_endian_uint16(n); + } + + return n; +} + +static DRFLAC_INLINE drflac_uint32 drflac__be2host_32(drflac_uint32 n) +{ + if (drflac__is_little_endian()) { + return drflac__swap_endian_uint32(n); + } + + return n; +} + +static DRFLAC_INLINE drflac_uint32 drflac__be2host_32_ptr_unaligned(const void* pData) +{ + const drflac_uint8* pNum = (drflac_uint8*)pData; + return *(pNum) << 24 | *(pNum+1) << 16 | *(pNum+2) << 8 | *(pNum+3); +} + +static DRFLAC_INLINE drflac_uint64 drflac__be2host_64(drflac_uint64 n) +{ + if (drflac__is_little_endian()) { + return drflac__swap_endian_uint64(n); + } + + return n; +} + + +static DRFLAC_INLINE drflac_uint32 drflac__le2host_32(drflac_uint32 n) +{ + if (!drflac__is_little_endian()) { + return drflac__swap_endian_uint32(n); + } + + return n; +} + +static DRFLAC_INLINE drflac_uint32 drflac__le2host_32_ptr_unaligned(const void* pData) +{ + const drflac_uint8* pNum = (drflac_uint8*)pData; + return *pNum | *(pNum+1) << 8 | *(pNum+2) << 16 | *(pNum+3) << 24; +} + + +static DRFLAC_INLINE drflac_uint32 drflac__unsynchsafe_32(drflac_uint32 n) +{ + drflac_uint32 result = 0; + result |= (n & 0x7F000000) >> 3; + result |= (n & 0x007F0000) >> 2; + result |= (n & 0x00007F00) >> 1; + result |= (n & 0x0000007F) >> 0; + + return result; +} + + + +/* The CRC code below is based on this document: http://zlib.net/crc_v3.txt */ +static drflac_uint8 drflac__crc8_table[] = { + 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15, 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D, + 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65, 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D, + 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5, 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD, + 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85, 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD, + 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2, 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA, + 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2, 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A, + 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32, 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A, + 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42, 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A, + 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C, 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4, + 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC, 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4, + 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C, 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44, + 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C, 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34, + 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B, 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63, + 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B, 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13, + 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB, 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83, + 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB, 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3 +}; + +static drflac_uint16 drflac__crc16_table[] = { + 0x0000, 0x8005, 0x800F, 0x000A, 0x801B, 0x001E, 0x0014, 0x8011, + 0x8033, 0x0036, 0x003C, 0x8039, 0x0028, 0x802D, 0x8027, 0x0022, + 0x8063, 0x0066, 0x006C, 0x8069, 0x0078, 0x807D, 0x8077, 0x0072, + 0x0050, 0x8055, 0x805F, 0x005A, 0x804B, 0x004E, 0x0044, 0x8041, + 0x80C3, 0x00C6, 0x00CC, 0x80C9, 0x00D8, 0x80DD, 0x80D7, 0x00D2, + 0x00F0, 0x80F5, 0x80FF, 0x00FA, 0x80EB, 0x00EE, 0x00E4, 0x80E1, + 0x00A0, 0x80A5, 0x80AF, 0x00AA, 0x80BB, 0x00BE, 0x00B4, 0x80B1, + 0x8093, 0x0096, 0x009C, 0x8099, 0x0088, 0x808D, 0x8087, 0x0082, + 0x8183, 0x0186, 0x018C, 0x8189, 0x0198, 0x819D, 0x8197, 0x0192, + 0x01B0, 0x81B5, 0x81BF, 0x01BA, 0x81AB, 0x01AE, 0x01A4, 0x81A1, + 0x01E0, 0x81E5, 0x81EF, 0x01EA, 0x81FB, 0x01FE, 0x01F4, 0x81F1, + 0x81D3, 0x01D6, 0x01DC, 0x81D9, 0x01C8, 0x81CD, 0x81C7, 0x01C2, + 0x0140, 0x8145, 0x814F, 0x014A, 0x815B, 0x015E, 0x0154, 0x8151, + 0x8173, 0x0176, 0x017C, 0x8179, 0x0168, 0x816D, 0x8167, 0x0162, + 0x8123, 0x0126, 0x012C, 0x8129, 0x0138, 0x813D, 0x8137, 0x0132, + 0x0110, 0x8115, 0x811F, 0x011A, 0x810B, 0x010E, 0x0104, 0x8101, + 0x8303, 0x0306, 0x030C, 0x8309, 0x0318, 0x831D, 0x8317, 0x0312, + 0x0330, 0x8335, 0x833F, 0x033A, 0x832B, 0x032E, 0x0324, 0x8321, + 0x0360, 0x8365, 0x836F, 0x036A, 0x837B, 0x037E, 0x0374, 0x8371, + 0x8353, 0x0356, 0x035C, 0x8359, 0x0348, 0x834D, 0x8347, 0x0342, + 0x03C0, 0x83C5, 0x83CF, 0x03CA, 0x83DB, 0x03DE, 0x03D4, 0x83D1, + 0x83F3, 0x03F6, 0x03FC, 0x83F9, 0x03E8, 0x83ED, 0x83E7, 0x03E2, + 0x83A3, 0x03A6, 0x03AC, 0x83A9, 0x03B8, 0x83BD, 0x83B7, 0x03B2, + 0x0390, 0x8395, 0x839F, 0x039A, 0x838B, 0x038E, 0x0384, 0x8381, + 0x0280, 0x8285, 0x828F, 0x028A, 0x829B, 0x029E, 0x0294, 0x8291, + 0x82B3, 0x02B6, 0x02BC, 0x82B9, 0x02A8, 0x82AD, 0x82A7, 0x02A2, + 0x82E3, 0x02E6, 0x02EC, 0x82E9, 0x02F8, 0x82FD, 0x82F7, 0x02F2, + 0x02D0, 0x82D5, 0x82DF, 0x02DA, 0x82CB, 0x02CE, 0x02C4, 0x82C1, + 0x8243, 0x0246, 0x024C, 0x8249, 0x0258, 0x825D, 0x8257, 0x0252, + 0x0270, 0x8275, 0x827F, 0x027A, 0x826B, 0x026E, 0x0264, 0x8261, + 0x0220, 0x8225, 0x822F, 0x022A, 0x823B, 0x023E, 0x0234, 0x8231, + 0x8213, 0x0216, 0x021C, 0x8219, 0x0208, 0x820D, 0x8207, 0x0202 +}; + +static DRFLAC_INLINE drflac_uint8 drflac_crc8_byte(drflac_uint8 crc, drflac_uint8 data) +{ + return drflac__crc8_table[crc ^ data]; +} + +static DRFLAC_INLINE drflac_uint8 drflac_crc8(drflac_uint8 crc, drflac_uint32 data, drflac_uint32 count) +{ +#ifdef DR_FLAC_NO_CRC + (void)crc; + (void)data; + (void)count; + return 0; +#else +#if 0 + /* REFERENCE (use of this implementation requires an explicit flush by doing "drflac_crc8(crc, 0, 8);") */ + drflac_uint8 p = 0x07; + for (int i = count-1; i >= 0; --i) { + drflac_uint8 bit = (data & (1 << i)) >> i; + if (crc & 0x80) { + crc = ((crc << 1) | bit) ^ p; + } else { + crc = ((crc << 1) | bit); + } + } + return crc; +#else + drflac_uint32 wholeBytes; + drflac_uint32 leftoverBits; + drflac_uint64 leftoverDataMask; + + static drflac_uint64 leftoverDataMaskTable[8] = { + 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F + }; + + DRFLAC_ASSERT(count <= 32); + + wholeBytes = count >> 3; + leftoverBits = count - (wholeBytes*8); + leftoverDataMask = leftoverDataMaskTable[leftoverBits]; + + switch (wholeBytes) { + case 4: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0xFF000000UL << leftoverBits)) >> (24 + leftoverBits))); + case 3: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0x00FF0000UL << leftoverBits)) >> (16 + leftoverBits))); + case 2: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0x0000FF00UL << leftoverBits)) >> ( 8 + leftoverBits))); + case 1: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0x000000FFUL << leftoverBits)) >> ( 0 + leftoverBits))); + case 0: if (leftoverBits > 0) crc = (drflac_uint8)((crc << leftoverBits) ^ drflac__crc8_table[(crc >> (8 - leftoverBits)) ^ (data & leftoverDataMask)]); + } + return crc; +#endif +#endif +} + +static DRFLAC_INLINE drflac_uint16 drflac_crc16_byte(drflac_uint16 crc, drflac_uint8 data) +{ + return (crc << 8) ^ drflac__crc16_table[(drflac_uint8)(crc >> 8) ^ data]; +} + +static DRFLAC_INLINE drflac_uint16 drflac_crc16_cache(drflac_uint16 crc, drflac_cache_t data) +{ +#ifdef DRFLAC_64BIT + crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 56) & 0xFF)); + crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 48) & 0xFF)); + crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 40) & 0xFF)); + crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 32) & 0xFF)); +#endif + crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 24) & 0xFF)); + crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 16) & 0xFF)); + crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 8) & 0xFF)); + crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 0) & 0xFF)); + + return crc; +} + +static DRFLAC_INLINE drflac_uint16 drflac_crc16_bytes(drflac_uint16 crc, drflac_cache_t data, drflac_uint32 byteCount) +{ + switch (byteCount) + { +#ifdef DRFLAC_64BIT + case 8: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 56) & 0xFF)); + case 7: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 48) & 0xFF)); + case 6: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 40) & 0xFF)); + case 5: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 32) & 0xFF)); +#endif + case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 24) & 0xFF)); + case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 16) & 0xFF)); + case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 8) & 0xFF)); + case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 0) & 0xFF)); + } + + return crc; +} + +#if 0 +static DRFLAC_INLINE drflac_uint16 drflac_crc16__32bit(drflac_uint16 crc, drflac_uint32 data, drflac_uint32 count) +{ +#ifdef DR_FLAC_NO_CRC + (void)crc; + (void)data; + (void)count; + return 0; +#else +#if 0 + /* REFERENCE (use of this implementation requires an explicit flush by doing "drflac_crc16(crc, 0, 16);") */ + drflac_uint16 p = 0x8005; + for (int i = count-1; i >= 0; --i) { + drflac_uint16 bit = (data & (1ULL << i)) >> i; + if (r & 0x8000) { + r = ((r << 1) | bit) ^ p; + } else { + r = ((r << 1) | bit); + } + } + + return crc; +#else + drflac_uint32 wholeBytes; + drflac_uint32 leftoverBits; + drflac_uint64 leftoverDataMask; + + static drflac_uint64 leftoverDataMaskTable[8] = { + 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F + }; + + DRFLAC_ASSERT(count <= 64); + + wholeBytes = count >> 3; + leftoverBits = count & 7; + leftoverDataMask = leftoverDataMaskTable[leftoverBits]; + + switch (wholeBytes) { + default: + case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0xFF000000UL << leftoverBits)) >> (24 + leftoverBits))); + case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0x00FF0000UL << leftoverBits)) >> (16 + leftoverBits))); + case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0x0000FF00UL << leftoverBits)) >> ( 8 + leftoverBits))); + case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0x000000FFUL << leftoverBits)) >> ( 0 + leftoverBits))); + case 0: if (leftoverBits > 0) crc = (crc << leftoverBits) ^ drflac__crc16_table[(crc >> (16 - leftoverBits)) ^ (data & leftoverDataMask)]; + } + return crc; +#endif +#endif +} + +static DRFLAC_INLINE drflac_uint16 drflac_crc16__64bit(drflac_uint16 crc, drflac_uint64 data, drflac_uint32 count) +{ +#ifdef DR_FLAC_NO_CRC + (void)crc; + (void)data; + (void)count; + return 0; +#else + drflac_uint32 wholeBytes; + drflac_uint32 leftoverBits; + drflac_uint64 leftoverDataMask; + + static drflac_uint64 leftoverDataMaskTable[8] = { + 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F + }; + + DRFLAC_ASSERT(count <= 64); + + wholeBytes = count >> 3; + leftoverBits = count & 7; + leftoverDataMask = leftoverDataMaskTable[leftoverBits]; + + switch (wholeBytes) { + default: + case 8: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0xFF000000 << 32) << leftoverBits)) >> (56 + leftoverBits))); /* Weird "<< 32" bitshift is required for C89 because it doesn't support 64-bit constants. Should be optimized out by a good compiler. */ + case 7: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x00FF0000 << 32) << leftoverBits)) >> (48 + leftoverBits))); + case 6: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x0000FF00 << 32) << leftoverBits)) >> (40 + leftoverBits))); + case 5: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x000000FF << 32) << leftoverBits)) >> (32 + leftoverBits))); + case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0xFF000000 ) << leftoverBits)) >> (24 + leftoverBits))); + case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x00FF0000 ) << leftoverBits)) >> (16 + leftoverBits))); + case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x0000FF00 ) << leftoverBits)) >> ( 8 + leftoverBits))); + case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x000000FF ) << leftoverBits)) >> ( 0 + leftoverBits))); + case 0: if (leftoverBits > 0) crc = (crc << leftoverBits) ^ drflac__crc16_table[(crc >> (16 - leftoverBits)) ^ (data & leftoverDataMask)]; + } + return crc; +#endif +} + + +static DRFLAC_INLINE drflac_uint16 drflac_crc16(drflac_uint16 crc, drflac_cache_t data, drflac_uint32 count) +{ +#ifdef DRFLAC_64BIT + return drflac_crc16__64bit(crc, data, count); +#else + return drflac_crc16__32bit(crc, data, count); +#endif +} +#endif + + +#ifdef DRFLAC_64BIT +#define drflac__be2host__cache_line drflac__be2host_64 +#else +#define drflac__be2host__cache_line drflac__be2host_32 +#endif + +/* +BIT READING ATTEMPT #2 + +This uses a 32- or 64-bit bit-shifted cache - as bits are read, the cache is shifted such that the first valid bit is sitting +on the most significant bit. It uses the notion of an L1 and L2 cache (borrowed from CPU architecture), where the L1 cache +is a 32- or 64-bit unsigned integer (depending on whether or not a 32- or 64-bit build is being compiled) and the L2 is an +array of "cache lines", with each cache line being the same size as the L1. The L2 is a buffer of about 4KB and is where data +from onRead() is read into. +*/ +#define DRFLAC_CACHE_L1_SIZE_BYTES(bs) (sizeof((bs)->cache)) +#define DRFLAC_CACHE_L1_SIZE_BITS(bs) (sizeof((bs)->cache)*8) +#define DRFLAC_CACHE_L1_BITS_REMAINING(bs) (DRFLAC_CACHE_L1_SIZE_BITS(bs) - (bs)->consumedBits) +#define DRFLAC_CACHE_L1_SELECTION_MASK(_bitCount) (~((~(drflac_cache_t)0) >> (_bitCount))) +#define DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, _bitCount) (DRFLAC_CACHE_L1_SIZE_BITS(bs) - (_bitCount)) +#define DRFLAC_CACHE_L1_SELECT(bs, _bitCount) (((bs)->cache) & DRFLAC_CACHE_L1_SELECTION_MASK(_bitCount)) +#define DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, _bitCount) (DRFLAC_CACHE_L1_SELECT((bs), (_bitCount)) >> DRFLAC_CACHE_L1_SELECTION_SHIFT((bs), (_bitCount))) +#define DRFLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE(bs, _bitCount)(DRFLAC_CACHE_L1_SELECT((bs), (_bitCount)) >> (DRFLAC_CACHE_L1_SELECTION_SHIFT((bs), (_bitCount)) & (DRFLAC_CACHE_L1_SIZE_BITS(bs)-1))) +#define DRFLAC_CACHE_L2_SIZE_BYTES(bs) (sizeof((bs)->cacheL2)) +#define DRFLAC_CACHE_L2_LINE_COUNT(bs) (DRFLAC_CACHE_L2_SIZE_BYTES(bs) / sizeof((bs)->cacheL2[0])) +#define DRFLAC_CACHE_L2_LINES_REMAINING(bs) (DRFLAC_CACHE_L2_LINE_COUNT(bs) - (bs)->nextL2Line) + + +#ifndef DR_FLAC_NO_CRC +static DRFLAC_INLINE void drflac__reset_crc16(drflac_bs* bs) +{ + bs->crc16 = 0; + bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3; +} + +static DRFLAC_INLINE void drflac__update_crc16(drflac_bs* bs) +{ + if (bs->crc16CacheIgnoredBytes == 0) { + bs->crc16 = drflac_crc16_cache(bs->crc16, bs->crc16Cache); + } else { + bs->crc16 = drflac_crc16_bytes(bs->crc16, bs->crc16Cache, DRFLAC_CACHE_L1_SIZE_BYTES(bs) - bs->crc16CacheIgnoredBytes); + bs->crc16CacheIgnoredBytes = 0; + } +} + +static DRFLAC_INLINE drflac_uint16 drflac__flush_crc16(drflac_bs* bs) +{ + /* We should never be flushing in a situation where we are not aligned on a byte boundary. */ + DRFLAC_ASSERT((DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7) == 0); + + /* + The bits that were read from the L1 cache need to be accumulated. The number of bytes needing to be accumulated is determined + by the number of bits that have been consumed. + */ + if (DRFLAC_CACHE_L1_BITS_REMAINING(bs) == 0) { + drflac__update_crc16(bs); + } else { + /* We only accumulate the consumed bits. */ + bs->crc16 = drflac_crc16_bytes(bs->crc16, bs->crc16Cache >> DRFLAC_CACHE_L1_BITS_REMAINING(bs), (bs->consumedBits >> 3) - bs->crc16CacheIgnoredBytes); + + /* + The bits that we just accumulated should never be accumulated again. We need to keep track of how many bytes were accumulated + so we can handle that later. + */ + bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3; + } + + return bs->crc16; +} +#endif + +static DRFLAC_INLINE drflac_bool32 drflac__reload_l1_cache_from_l2(drflac_bs* bs) +{ + size_t bytesRead; + size_t alignedL1LineCount; + + /* Fast path. Try loading straight from L2. */ + if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) { + bs->cache = bs->cacheL2[bs->nextL2Line++]; + return DRFLAC_TRUE; + } + + /* + If we get here it means we've run out of data in the L2 cache. We'll need to fetch more from the client, if there's + any left. + */ + if (bs->unalignedByteCount > 0) { + return DRFLAC_FALSE; /* If we have any unaligned bytes it means there's no more aligned bytes left in the client. */ + } + + bytesRead = bs->onRead(bs->pUserData, bs->cacheL2, DRFLAC_CACHE_L2_SIZE_BYTES(bs)); + + bs->nextL2Line = 0; + if (bytesRead == DRFLAC_CACHE_L2_SIZE_BYTES(bs)) { + bs->cache = bs->cacheL2[bs->nextL2Line++]; + return DRFLAC_TRUE; + } + + + /* + If we get here it means we were unable to retrieve enough data to fill the entire L2 cache. It probably + means we've just reached the end of the file. We need to move the valid data down to the end of the buffer + and adjust the index of the next line accordingly. Also keep in mind that the L2 cache must be aligned to + the size of the L1 so we'll need to seek backwards by any misaligned bytes. + */ + alignedL1LineCount = bytesRead / DRFLAC_CACHE_L1_SIZE_BYTES(bs); + + /* We need to keep track of any unaligned bytes for later use. */ + bs->unalignedByteCount = bytesRead - (alignedL1LineCount * DRFLAC_CACHE_L1_SIZE_BYTES(bs)); + if (bs->unalignedByteCount > 0) { + bs->unalignedCache = bs->cacheL2[alignedL1LineCount]; + } + + if (alignedL1LineCount > 0) { + size_t offset = DRFLAC_CACHE_L2_LINE_COUNT(bs) - alignedL1LineCount; + size_t i; + for (i = alignedL1LineCount; i > 0; --i) { + bs->cacheL2[i-1 + offset] = bs->cacheL2[i-1]; + } + + bs->nextL2Line = (drflac_uint32)offset; + bs->cache = bs->cacheL2[bs->nextL2Line++]; + return DRFLAC_TRUE; + } else { + /* If we get into this branch it means we weren't able to load any L1-aligned data. */ + bs->nextL2Line = DRFLAC_CACHE_L2_LINE_COUNT(bs); + return DRFLAC_FALSE; + } +} + +static drflac_bool32 drflac__reload_cache(drflac_bs* bs) +{ + size_t bytesRead; + +#ifndef DR_FLAC_NO_CRC + drflac__update_crc16(bs); +#endif + + /* Fast path. Try just moving the next value in the L2 cache to the L1 cache. */ + if (drflac__reload_l1_cache_from_l2(bs)) { + bs->cache = drflac__be2host__cache_line(bs->cache); + bs->consumedBits = 0; +#ifndef DR_FLAC_NO_CRC + bs->crc16Cache = bs->cache; +#endif + return DRFLAC_TRUE; + } + + /* Slow path. */ + + /* + If we get here it means we have failed to load the L1 cache from the L2. Likely we've just reached the end of the stream and the last + few bytes did not meet the alignment requirements for the L2 cache. In this case we need to fall back to a slower path and read the + data from the unaligned cache. + */ + bytesRead = bs->unalignedByteCount; + if (bytesRead == 0) { + bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs); /* <-- The stream has been exhausted, so marked the bits as consumed. */ + return DRFLAC_FALSE; + } + + DRFLAC_ASSERT(bytesRead < DRFLAC_CACHE_L1_SIZE_BYTES(bs)); + bs->consumedBits = (drflac_uint32)(DRFLAC_CACHE_L1_SIZE_BYTES(bs) - bytesRead) * 8; + + bs->cache = drflac__be2host__cache_line(bs->unalignedCache); + bs->cache &= DRFLAC_CACHE_L1_SELECTION_MASK(DRFLAC_CACHE_L1_BITS_REMAINING(bs)); /* <-- Make sure the consumed bits are always set to zero. Other parts of the library depend on this property. */ + bs->unalignedByteCount = 0; /* <-- At this point the unaligned bytes have been moved into the cache and we thus have no more unaligned bytes. */ + +#ifndef DR_FLAC_NO_CRC + bs->crc16Cache = bs->cache >> bs->consumedBits; + bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3; +#endif + return DRFLAC_TRUE; +} + +static void drflac__reset_cache(drflac_bs* bs) +{ + bs->nextL2Line = DRFLAC_CACHE_L2_LINE_COUNT(bs); /* <-- This clears the L2 cache. */ + bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs); /* <-- This clears the L1 cache. */ + bs->cache = 0; + bs->unalignedByteCount = 0; /* <-- This clears the trailing unaligned bytes. */ + bs->unalignedCache = 0; + +#ifndef DR_FLAC_NO_CRC + bs->crc16Cache = 0; + bs->crc16CacheIgnoredBytes = 0; +#endif +} + + +static DRFLAC_INLINE drflac_bool32 drflac__read_uint32(drflac_bs* bs, unsigned int bitCount, drflac_uint32* pResultOut) +{ + DRFLAC_ASSERT(bs != NULL); + DRFLAC_ASSERT(pResultOut != NULL); + DRFLAC_ASSERT(bitCount > 0); + DRFLAC_ASSERT(bitCount <= 32); + + if (bs->consumedBits == DRFLAC_CACHE_L1_SIZE_BITS(bs)) { + if (!drflac__reload_cache(bs)) { + return DRFLAC_FALSE; + } + } + + if (bitCount <= DRFLAC_CACHE_L1_BITS_REMAINING(bs)) { + /* + If we want to load all 32-bits from a 32-bit cache we need to do it slightly differently because we can't do + a 32-bit shift on a 32-bit integer. This will never be the case on 64-bit caches, so we can have a slightly + more optimal solution for this. + */ +#ifdef DRFLAC_64BIT + *pResultOut = (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCount); + bs->consumedBits += bitCount; + bs->cache <<= bitCount; +#else + if (bitCount < DRFLAC_CACHE_L1_SIZE_BITS(bs)) { + *pResultOut = (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCount); + bs->consumedBits += bitCount; + bs->cache <<= bitCount; + } else { + /* Cannot shift by 32-bits, so need to do it differently. */ + *pResultOut = (drflac_uint32)bs->cache; + bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs); + bs->cache = 0; + } +#endif + + return DRFLAC_TRUE; + } else { + /* It straddles the cached data. It will never cover more than the next chunk. We just read the number in two parts and combine them. */ + drflac_uint32 bitCountHi = DRFLAC_CACHE_L1_BITS_REMAINING(bs); + drflac_uint32 bitCountLo = bitCount - bitCountHi; + drflac_uint32 resultHi; + + DRFLAC_ASSERT(bitCountHi > 0); + DRFLAC_ASSERT(bitCountHi < 32); + resultHi = (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCountHi); + + if (!drflac__reload_cache(bs)) { + return DRFLAC_FALSE; + } + if (bitCountLo > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) { + /* This happens when we get to end of stream */ + return DRFLAC_FALSE; + } + + *pResultOut = (resultHi << bitCountLo) | (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCountLo); + bs->consumedBits += bitCountLo; + bs->cache <<= bitCountLo; + return DRFLAC_TRUE; + } +} + +static drflac_bool32 drflac__read_int32(drflac_bs* bs, unsigned int bitCount, drflac_int32* pResult) +{ + drflac_uint32 result; + + DRFLAC_ASSERT(bs != NULL); + DRFLAC_ASSERT(pResult != NULL); + DRFLAC_ASSERT(bitCount > 0); + DRFLAC_ASSERT(bitCount <= 32); + + if (!drflac__read_uint32(bs, bitCount, &result)) { + return DRFLAC_FALSE; + } + + /* Do not attempt to shift by 32 as it's undefined. */ + if (bitCount < 32) { + drflac_uint32 signbit; + signbit = ((result >> (bitCount-1)) & 0x01); + result |= (~signbit + 1) << bitCount; + } + + *pResult = (drflac_int32)result; + return DRFLAC_TRUE; +} + +#ifdef DRFLAC_64BIT +static drflac_bool32 drflac__read_uint64(drflac_bs* bs, unsigned int bitCount, drflac_uint64* pResultOut) +{ + drflac_uint32 resultHi; + drflac_uint32 resultLo; + + DRFLAC_ASSERT(bitCount <= 64); + DRFLAC_ASSERT(bitCount > 32); + + if (!drflac__read_uint32(bs, bitCount - 32, &resultHi)) { + return DRFLAC_FALSE; + } + + if (!drflac__read_uint32(bs, 32, &resultLo)) { + return DRFLAC_FALSE; + } + + *pResultOut = (((drflac_uint64)resultHi) << 32) | ((drflac_uint64)resultLo); + return DRFLAC_TRUE; +} +#endif + +/* Function below is unused, but leaving it here in case I need to quickly add it again. */ +#if 0 +static drflac_bool32 drflac__read_int64(drflac_bs* bs, unsigned int bitCount, drflac_int64* pResultOut) +{ + drflac_uint64 result; + drflac_uint64 signbit; + + DRFLAC_ASSERT(bitCount <= 64); + + if (!drflac__read_uint64(bs, bitCount, &result)) { + return DRFLAC_FALSE; + } + + signbit = ((result >> (bitCount-1)) & 0x01); + result |= (~signbit + 1) << bitCount; + + *pResultOut = (drflac_int64)result; + return DRFLAC_TRUE; +} +#endif + +static drflac_bool32 drflac__read_uint16(drflac_bs* bs, unsigned int bitCount, drflac_uint16* pResult) +{ + drflac_uint32 result; + + DRFLAC_ASSERT(bs != NULL); + DRFLAC_ASSERT(pResult != NULL); + DRFLAC_ASSERT(bitCount > 0); + DRFLAC_ASSERT(bitCount <= 16); + + if (!drflac__read_uint32(bs, bitCount, &result)) { + return DRFLAC_FALSE; + } + + *pResult = (drflac_uint16)result; + return DRFLAC_TRUE; +} + +#if 0 +static drflac_bool32 drflac__read_int16(drflac_bs* bs, unsigned int bitCount, drflac_int16* pResult) +{ + drflac_int32 result; + + DRFLAC_ASSERT(bs != NULL); + DRFLAC_ASSERT(pResult != NULL); + DRFLAC_ASSERT(bitCount > 0); + DRFLAC_ASSERT(bitCount <= 16); + + if (!drflac__read_int32(bs, bitCount, &result)) { + return DRFLAC_FALSE; + } + + *pResult = (drflac_int16)result; + return DRFLAC_TRUE; +} +#endif + +static drflac_bool32 drflac__read_uint8(drflac_bs* bs, unsigned int bitCount, drflac_uint8* pResult) +{ + drflac_uint32 result; + + DRFLAC_ASSERT(bs != NULL); + DRFLAC_ASSERT(pResult != NULL); + DRFLAC_ASSERT(bitCount > 0); + DRFLAC_ASSERT(bitCount <= 8); + + if (!drflac__read_uint32(bs, bitCount, &result)) { + return DRFLAC_FALSE; + } + + *pResult = (drflac_uint8)result; + return DRFLAC_TRUE; +} + +static drflac_bool32 drflac__read_int8(drflac_bs* bs, unsigned int bitCount, drflac_int8* pResult) +{ + drflac_int32 result; + + DRFLAC_ASSERT(bs != NULL); + DRFLAC_ASSERT(pResult != NULL); + DRFLAC_ASSERT(bitCount > 0); + DRFLAC_ASSERT(bitCount <= 8); + + if (!drflac__read_int32(bs, bitCount, &result)) { + return DRFLAC_FALSE; + } + + *pResult = (drflac_int8)result; + return DRFLAC_TRUE; +} + + +static drflac_bool32 drflac__seek_bits(drflac_bs* bs, size_t bitsToSeek) +{ + if (bitsToSeek <= DRFLAC_CACHE_L1_BITS_REMAINING(bs)) { + bs->consumedBits += (drflac_uint32)bitsToSeek; + bs->cache <<= bitsToSeek; + return DRFLAC_TRUE; + } else { + /* It straddles the cached data. This function isn't called too frequently so I'm favouring simplicity here. */ + bitsToSeek -= DRFLAC_CACHE_L1_BITS_REMAINING(bs); + bs->consumedBits += DRFLAC_CACHE_L1_BITS_REMAINING(bs); + bs->cache = 0; + + /* Simple case. Seek in groups of the same number as bits that fit within a cache line. */ +#ifdef DRFLAC_64BIT + while (bitsToSeek >= DRFLAC_CACHE_L1_SIZE_BITS(bs)) { + drflac_uint64 bin; + if (!drflac__read_uint64(bs, DRFLAC_CACHE_L1_SIZE_BITS(bs), &bin)) { + return DRFLAC_FALSE; + } + bitsToSeek -= DRFLAC_CACHE_L1_SIZE_BITS(bs); + } +#else + while (bitsToSeek >= DRFLAC_CACHE_L1_SIZE_BITS(bs)) { + drflac_uint32 bin; + if (!drflac__read_uint32(bs, DRFLAC_CACHE_L1_SIZE_BITS(bs), &bin)) { + return DRFLAC_FALSE; + } + bitsToSeek -= DRFLAC_CACHE_L1_SIZE_BITS(bs); + } +#endif + + /* Whole leftover bytes. */ + while (bitsToSeek >= 8) { + drflac_uint8 bin; + if (!drflac__read_uint8(bs, 8, &bin)) { + return DRFLAC_FALSE; + } + bitsToSeek -= 8; + } + + /* Leftover bits. */ + if (bitsToSeek > 0) { + drflac_uint8 bin; + if (!drflac__read_uint8(bs, (drflac_uint32)bitsToSeek, &bin)) { + return DRFLAC_FALSE; + } + bitsToSeek = 0; /* <-- Necessary for the assert below. */ + } + + DRFLAC_ASSERT(bitsToSeek == 0); + return DRFLAC_TRUE; + } +} + + +/* This function moves the bit streamer to the first bit after the sync code (bit 15 of the of the frame header). It will also update the CRC-16. */ +static drflac_bool32 drflac__find_and_seek_to_next_sync_code(drflac_bs* bs) +{ + DRFLAC_ASSERT(bs != NULL); + + /* + The sync code is always aligned to 8 bits. This is convenient for us because it means we can do byte-aligned movements. The first + thing to do is align to the next byte. + */ + if (!drflac__seek_bits(bs, DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7)) { + return DRFLAC_FALSE; + } + + for (;;) { + drflac_uint8 hi; + +#ifndef DR_FLAC_NO_CRC + drflac__reset_crc16(bs); +#endif + + if (!drflac__read_uint8(bs, 8, &hi)) { + return DRFLAC_FALSE; + } + + if (hi == 0xFF) { + drflac_uint8 lo; + if (!drflac__read_uint8(bs, 6, &lo)) { + return DRFLAC_FALSE; + } + + if (lo == 0x3E) { + return DRFLAC_TRUE; + } else { + if (!drflac__seek_bits(bs, DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7)) { + return DRFLAC_FALSE; + } + } + } + } + + /* Should never get here. */ + /*return DRFLAC_FALSE;*/ +} + + +#if defined(DRFLAC_HAS_LZCNT_INTRINSIC) +#define DRFLAC_IMPLEMENT_CLZ_LZCNT +#endif +#if defined(_MSC_VER) && _MSC_VER >= 1400 && (defined(DRFLAC_X64) || defined(DRFLAC_X86)) && !defined(__clang__) +#define DRFLAC_IMPLEMENT_CLZ_MSVC +#endif +#if defined(__WATCOMC__) && defined(__386__) +#define DRFLAC_IMPLEMENT_CLZ_WATCOM +#endif +#ifdef __MRC__ +#include +#define DRFLAC_IMPLEMENT_CLZ_MRC +#endif + +static DRFLAC_INLINE drflac_uint32 drflac__clz_software(drflac_cache_t x) +{ + drflac_uint32 n; + static drflac_uint32 clz_table_4[] = { + 0, + 4, + 3, 3, + 2, 2, 2, 2, + 1, 1, 1, 1, 1, 1, 1, 1 + }; + + if (x == 0) { + return sizeof(x)*8; + } + + n = clz_table_4[x >> (sizeof(x)*8 - 4)]; + if (n == 0) { +#ifdef DRFLAC_64BIT + if ((x & ((drflac_uint64)0xFFFFFFFF << 32)) == 0) { n = 32; x <<= 32; } + if ((x & ((drflac_uint64)0xFFFF0000 << 32)) == 0) { n += 16; x <<= 16; } + if ((x & ((drflac_uint64)0xFF000000 << 32)) == 0) { n += 8; x <<= 8; } + if ((x & ((drflac_uint64)0xF0000000 << 32)) == 0) { n += 4; x <<= 4; } +#else + if ((x & 0xFFFF0000) == 0) { n = 16; x <<= 16; } + if ((x & 0xFF000000) == 0) { n += 8; x <<= 8; } + if ((x & 0xF0000000) == 0) { n += 4; x <<= 4; } +#endif + n += clz_table_4[x >> (sizeof(x)*8 - 4)]; + } + + return n - 1; +} + +#ifdef DRFLAC_IMPLEMENT_CLZ_LZCNT +static DRFLAC_INLINE drflac_bool32 drflac__is_lzcnt_supported(void) +{ + /* Fast compile time check for ARM. */ +#if defined(DRFLAC_HAS_LZCNT_INTRINSIC) && defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 5) + return DRFLAC_TRUE; +#elif defined(__MRC__) + return DRFLAC_TRUE; +#else + /* If the compiler itself does not support the intrinsic then we'll need to return false. */ + #ifdef DRFLAC_HAS_LZCNT_INTRINSIC + return drflac__gIsLZCNTSupported; + #else + return DRFLAC_FALSE; + #endif +#endif +} + +static DRFLAC_INLINE drflac_uint32 drflac__clz_lzcnt(drflac_cache_t x) +{ + /* + It's critical for competitive decoding performance that this function be highly optimal. With MSVC we can use the __lzcnt64() and __lzcnt() intrinsics + to achieve good performance, however on GCC and Clang it's a little bit more annoying. The __builtin_clzl() and __builtin_clzll() intrinsics leave + it undefined as to the return value when `x` is 0. We need this to be well defined as returning 32 or 64, depending on whether or not it's a 32- or + 64-bit build. To work around this we would need to add a conditional to check for the x = 0 case, but this creates unnecessary inefficiency. To work + around this problem I have written some inline assembly to emit the LZCNT (x86) or CLZ (ARM) instruction directly which removes the need to include + the conditional. This has worked well in the past, but for some reason Clang's MSVC compatible driver, clang-cl, does not seem to be handling this + in the same way as the normal Clang driver. It seems that `clang-cl` is just outputting the wrong results sometimes, maybe due to some register + getting clobbered? + + I'm not sure if this is a bug with dr_flac's inlined assembly (most likely), a bug in `clang-cl` or just a misunderstanding on my part with inline + assembly rules for `clang-cl`. If somebody can identify an error in dr_flac's inlined assembly I'm happy to get that fixed. + + Fortunately there is an easy workaround for this. Clang implements MSVC-specific intrinsics for compatibility. It also defines _MSC_VER for extra + compatibility. We can therefore just check for _MSC_VER and use the MSVC intrinsic which, fortunately for us, Clang supports. It would still be nice + to know how to fix the inlined assembly for correctness sake, however. + */ + +#if defined(_MSC_VER) /*&& !defined(__clang__)*/ /* <-- Intentionally wanting Clang to use the MSVC __lzcnt64/__lzcnt intrinsics due to above ^. */ + #ifdef DRFLAC_64BIT + return (drflac_uint32)__lzcnt64(x); + #else + return (drflac_uint32)__lzcnt(x); + #endif +#else + #if defined(__GNUC__) || defined(__clang__) + #if defined(DRFLAC_X64) + { + /* + A note on lzcnt. + + We check for the presence of the lzcnt instruction at runtime before calling this function, but we still generate this code. I have had + a report where the assembler does not recognize the lzcnt instruction. To work around this we are going to use `rep; bsr` instead which + has an identical byte encoding as lzcnt, and should hopefully improve compatibility with older assemblers. + */ + drflac_uint64 r; + __asm__ __volatile__ ( + "rep; bsr{q %1, %0| %0, %1}" : "=r"(r) : "r"(x) : "cc" + /*"lzcnt{ %1, %0| %0, %1}" : "=r"(r) : "r"(x) : "cc"*/ + ); + + return (drflac_uint32)r; + } + #elif defined(DRFLAC_X86) + { + drflac_uint32 r; + __asm__ __volatile__ ( + "rep; bsr{l %1, %0| %0, %1}" : "=r"(r) : "r"(x) : "cc" + /*"lzcnt{l %1, %0| %0, %1}" : "=r"(r) : "r"(x) : "cc"*/ + ); + + return r; + } + #elif defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 5) && !defined(__ARM_ARCH_6M__) && !(defined(__thumb__) && !defined(__thumb2__)) && !defined(DRFLAC_64BIT) /* <-- I haven't tested 64-bit inline assembly, so only enabling this for the 32-bit build for now. */ + { + unsigned int r; + __asm__ __volatile__ ( + #if defined(DRFLAC_64BIT) + "clz %w[out], %w[in]" : [out]"=r"(r) : [in]"r"(x) /* <-- This is untested. If someone in the community could test this, that would be appreciated! */ + #else + "clz %[out], %[in]" : [out]"=r"(r) : [in]"r"(x) + #endif + ); + + return r; + } + #else + if (x == 0) { + return sizeof(x)*8; + } + #ifdef DRFLAC_64BIT + return (drflac_uint32)__builtin_clzll((drflac_uint64)x); + #else + return (drflac_uint32)__builtin_clzl((drflac_uint32)x); + #endif + #endif + #else + /* Unsupported compiler. */ + #error "This compiler does not support the lzcnt intrinsic." + #endif +#endif +} +#endif + +#ifdef DRFLAC_IMPLEMENT_CLZ_MSVC +#include /* For BitScanReverse(). */ + +static DRFLAC_INLINE drflac_uint32 drflac__clz_msvc(drflac_cache_t x) +{ + drflac_uint32 n; + + if (x == 0) { + return sizeof(x)*8; + } + +#ifdef DRFLAC_64BIT + _BitScanReverse64((unsigned long*)&n, x); +#else + _BitScanReverse((unsigned long*)&n, x); +#endif + return sizeof(x)*8 - n - 1; +} +#endif + +#ifdef DRFLAC_IMPLEMENT_CLZ_WATCOM +static __inline drflac_uint32 drflac__clz_watcom (drflac_uint32); +#ifdef DRFLAC_IMPLEMENT_CLZ_WATCOM_LZCNT +/* Use the LZCNT instruction (only available on some processors since the 2010s). */ +#pragma aux drflac__clz_watcom_lzcnt = \ + "db 0F3h, 0Fh, 0BDh, 0C0h" /* lzcnt eax, eax */ \ + parm [eax] \ + value [eax] \ + modify nomemory; +#else +/* Use the 386+-compatible implementation. */ +#pragma aux drflac__clz_watcom = \ + "bsr eax, eax" \ + "xor eax, 31" \ + parm [eax] nomemory \ + value [eax] \ + modify exact [eax] nomemory; +#endif +#endif + +static DRFLAC_INLINE drflac_uint32 drflac__clz(drflac_cache_t x) +{ +#ifdef DRFLAC_IMPLEMENT_CLZ_LZCNT + if (drflac__is_lzcnt_supported()) { + return drflac__clz_lzcnt(x); + } else +#endif + { +#ifdef DRFLAC_IMPLEMENT_CLZ_MSVC + return drflac__clz_msvc(x); +#elif defined(DRFLAC_IMPLEMENT_CLZ_WATCOM_LZCNT) + return drflac__clz_watcom_lzcnt(x); +#elif defined(DRFLAC_IMPLEMENT_CLZ_WATCOM) + return (x == 0) ? sizeof(x)*8 : drflac__clz_watcom(x); +#elif defined(__MRC__) + return __cntlzw(x); +#else + return drflac__clz_software(x); +#endif + } +} + + +static DRFLAC_INLINE drflac_bool32 drflac__seek_past_next_set_bit(drflac_bs* bs, unsigned int* pOffsetOut) +{ + drflac_uint32 zeroCounter = 0; + drflac_uint32 setBitOffsetPlus1; + + while (bs->cache == 0) { + zeroCounter += (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs); + if (!drflac__reload_cache(bs)) { + return DRFLAC_FALSE; + } + } + + if (bs->cache == 1) { + /* Not catching this would lead to undefined behaviour: a shift of a 32-bit number by 32 or more is undefined */ + *pOffsetOut = zeroCounter + (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs) - 1; + if (!drflac__reload_cache(bs)) { + return DRFLAC_FALSE; + } + + return DRFLAC_TRUE; + } + + setBitOffsetPlus1 = drflac__clz(bs->cache); + setBitOffsetPlus1 += 1; + + if (setBitOffsetPlus1 > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) { + /* This happens when we get to end of stream */ + return DRFLAC_FALSE; + } + + bs->consumedBits += setBitOffsetPlus1; + bs->cache <<= setBitOffsetPlus1; + + *pOffsetOut = zeroCounter + setBitOffsetPlus1 - 1; + return DRFLAC_TRUE; +} + + + +static drflac_bool32 drflac__seek_to_byte(drflac_bs* bs, drflac_uint64 offsetFromStart) +{ + DRFLAC_ASSERT(bs != NULL); + DRFLAC_ASSERT(offsetFromStart > 0); + + /* + Seeking from the start is not quite as trivial as it sounds because the onSeek callback takes a signed 32-bit integer (which + is intentional because it simplifies the implementation of the onSeek callbacks), however offsetFromStart is unsigned 64-bit. + To resolve we just need to do an initial seek from the start, and then a series of offset seeks to make up the remainder. + */ + if (offsetFromStart > 0x7FFFFFFF) { + drflac_uint64 bytesRemaining = offsetFromStart; + if (!bs->onSeek(bs->pUserData, 0x7FFFFFFF, DRFLAC_SEEK_SET)) { + return DRFLAC_FALSE; + } + bytesRemaining -= 0x7FFFFFFF; + + while (bytesRemaining > 0x7FFFFFFF) { + if (!bs->onSeek(bs->pUserData, 0x7FFFFFFF, DRFLAC_SEEK_CUR)) { + return DRFLAC_FALSE; + } + bytesRemaining -= 0x7FFFFFFF; + } + + if (bytesRemaining > 0) { + if (!bs->onSeek(bs->pUserData, (int)bytesRemaining, DRFLAC_SEEK_CUR)) { + return DRFLAC_FALSE; + } + } + } else { + if (!bs->onSeek(bs->pUserData, (int)offsetFromStart, DRFLAC_SEEK_SET)) { + return DRFLAC_FALSE; + } + } + + /* The cache should be reset to force a reload of fresh data from the client. */ + drflac__reset_cache(bs); + return DRFLAC_TRUE; +} + + +static drflac_result drflac__read_utf8_coded_number(drflac_bs* bs, drflac_uint64* pNumberOut, drflac_uint8* pCRCOut) +{ + drflac_uint8 crc; + drflac_uint64 result; + drflac_uint8 utf8[7] = {0}; + int byteCount; + int i; + + DRFLAC_ASSERT(bs != NULL); + DRFLAC_ASSERT(pNumberOut != NULL); + DRFLAC_ASSERT(pCRCOut != NULL); + + crc = *pCRCOut; + + if (!drflac__read_uint8(bs, 8, utf8)) { + *pNumberOut = 0; + return DRFLAC_AT_END; + } + crc = drflac_crc8(crc, utf8[0], 8); + + if ((utf8[0] & 0x80) == 0) { + *pNumberOut = utf8[0]; + *pCRCOut = crc; + return DRFLAC_SUCCESS; + } + + /*byteCount = 1;*/ + if ((utf8[0] & 0xE0) == 0xC0) { + byteCount = 2; + } else if ((utf8[0] & 0xF0) == 0xE0) { + byteCount = 3; + } else if ((utf8[0] & 0xF8) == 0xF0) { + byteCount = 4; + } else if ((utf8[0] & 0xFC) == 0xF8) { + byteCount = 5; + } else if ((utf8[0] & 0xFE) == 0xFC) { + byteCount = 6; + } else if ((utf8[0] & 0xFF) == 0xFE) { + byteCount = 7; + } else { + *pNumberOut = 0; + return DRFLAC_CRC_MISMATCH; /* Bad UTF-8 encoding. */ + } + + /* Read extra bytes. */ + DRFLAC_ASSERT(byteCount > 1); + + result = (drflac_uint64)(utf8[0] & (0xFF >> (byteCount + 1))); + for (i = 1; i < byteCount; ++i) { + if (!drflac__read_uint8(bs, 8, utf8 + i)) { + *pNumberOut = 0; + return DRFLAC_AT_END; + } + crc = drflac_crc8(crc, utf8[i], 8); + + result = (result << 6) | (utf8[i] & 0x3F); + } + + *pNumberOut = result; + *pCRCOut = crc; + return DRFLAC_SUCCESS; +} + + +static DRFLAC_INLINE drflac_uint32 drflac__ilog2_u32(drflac_uint32 x) +{ +#if 1 /* Needs optimizing. */ + drflac_uint32 result = 0; + while (x > 0) { + result += 1; + x >>= 1; + } + + return result; +#endif +} + +static DRFLAC_INLINE drflac_bool32 drflac__use_64_bit_prediction(drflac_uint32 bitsPerSample, drflac_uint32 order, drflac_uint32 precision) +{ + /* https://web.archive.org/web/20220205005724/https://github.com/ietf-wg-cellar/flac-specification/blob/37a49aa48ba4ba12e8757badfc59c0df35435fec/rfc_backmatter.md */ + return bitsPerSample + precision + drflac__ilog2_u32(order) > 32; +} + + +/* +The next two functions are responsible for calculating the prediction. + +When the bits per sample is >16 we need to use 64-bit integer arithmetic because otherwise we'll run out of precision. It's +safe to assume this will be slower on 32-bit platforms so we use a more optimal solution when the bits per sample is <=16. +*/ +#if defined(__clang__) +__attribute__((no_sanitize("signed-integer-overflow"))) +#endif +static DRFLAC_INLINE drflac_int32 drflac__calculate_prediction_32(drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pDecodedSamples) +{ + drflac_int32 prediction = 0; + + DRFLAC_ASSERT(order <= 32); + + /* 32-bit version. */ + + /* VC++ optimizes this to a single jmp. I've not yet verified this for other compilers. */ + switch (order) + { + case 32: prediction += coefficients[31] * pDecodedSamples[-32]; + case 31: prediction += coefficients[30] * pDecodedSamples[-31]; + case 30: prediction += coefficients[29] * pDecodedSamples[-30]; + case 29: prediction += coefficients[28] * pDecodedSamples[-29]; + case 28: prediction += coefficients[27] * pDecodedSamples[-28]; + case 27: prediction += coefficients[26] * pDecodedSamples[-27]; + case 26: prediction += coefficients[25] * pDecodedSamples[-26]; + case 25: prediction += coefficients[24] * pDecodedSamples[-25]; + case 24: prediction += coefficients[23] * pDecodedSamples[-24]; + case 23: prediction += coefficients[22] * pDecodedSamples[-23]; + case 22: prediction += coefficients[21] * pDecodedSamples[-22]; + case 21: prediction += coefficients[20] * pDecodedSamples[-21]; + case 20: prediction += coefficients[19] * pDecodedSamples[-20]; + case 19: prediction += coefficients[18] * pDecodedSamples[-19]; + case 18: prediction += coefficients[17] * pDecodedSamples[-18]; + case 17: prediction += coefficients[16] * pDecodedSamples[-17]; + case 16: prediction += coefficients[15] * pDecodedSamples[-16]; + case 15: prediction += coefficients[14] * pDecodedSamples[-15]; + case 14: prediction += coefficients[13] * pDecodedSamples[-14]; + case 13: prediction += coefficients[12] * pDecodedSamples[-13]; + case 12: prediction += coefficients[11] * pDecodedSamples[-12]; + case 11: prediction += coefficients[10] * pDecodedSamples[-11]; + case 10: prediction += coefficients[ 9] * pDecodedSamples[-10]; + case 9: prediction += coefficients[ 8] * pDecodedSamples[- 9]; + case 8: prediction += coefficients[ 7] * pDecodedSamples[- 8]; + case 7: prediction += coefficients[ 6] * pDecodedSamples[- 7]; + case 6: prediction += coefficients[ 5] * pDecodedSamples[- 6]; + case 5: prediction += coefficients[ 4] * pDecodedSamples[- 5]; + case 4: prediction += coefficients[ 3] * pDecodedSamples[- 4]; + case 3: prediction += coefficients[ 2] * pDecodedSamples[- 3]; + case 2: prediction += coefficients[ 1] * pDecodedSamples[- 2]; + case 1: prediction += coefficients[ 0] * pDecodedSamples[- 1]; + } + + return (drflac_int32)(prediction >> shift); +} + +static DRFLAC_INLINE drflac_int32 drflac__calculate_prediction_64(drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pDecodedSamples) +{ + drflac_int64 prediction; + + DRFLAC_ASSERT(order <= 32); + + /* 64-bit version. */ + + /* This method is faster on the 32-bit build when compiling with VC++. See note below. */ +#ifndef DRFLAC_64BIT + if (order == 8) + { + prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1]; + prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2]; + prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3]; + prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4]; + prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5]; + prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6]; + prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7]; + prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8]; + } + else if (order == 7) + { + prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1]; + prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2]; + prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3]; + prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4]; + prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5]; + prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6]; + prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7]; + } + else if (order == 3) + { + prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1]; + prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2]; + prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3]; + } + else if (order == 6) + { + prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1]; + prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2]; + prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3]; + prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4]; + prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5]; + prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6]; + } + else if (order == 5) + { + prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1]; + prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2]; + prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3]; + prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4]; + prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5]; + } + else if (order == 4) + { + prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1]; + prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2]; + prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3]; + prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4]; + } + else if (order == 12) + { + prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1]; + prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2]; + prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3]; + prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4]; + prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5]; + prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6]; + prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7]; + prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8]; + prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9]; + prediction += coefficients[9] * (drflac_int64)pDecodedSamples[-10]; + prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11]; + prediction += coefficients[11] * (drflac_int64)pDecodedSamples[-12]; + } + else if (order == 2) + { + prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1]; + prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2]; + } + else if (order == 1) + { + prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1]; + } + else if (order == 10) + { + prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1]; + prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2]; + prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3]; + prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4]; + prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5]; + prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6]; + prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7]; + prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8]; + prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9]; + prediction += coefficients[9] * (drflac_int64)pDecodedSamples[-10]; + } + else if (order == 9) + { + prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1]; + prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2]; + prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3]; + prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4]; + prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5]; + prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6]; + prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7]; + prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8]; + prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9]; + } + else if (order == 11) + { + prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1]; + prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2]; + prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3]; + prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4]; + prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5]; + prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6]; + prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7]; + prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8]; + prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9]; + prediction += coefficients[9] * (drflac_int64)pDecodedSamples[-10]; + prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11]; + } + else + { + int j; + + prediction = 0; + for (j = 0; j < (int)order; ++j) { + prediction += coefficients[j] * (drflac_int64)pDecodedSamples[-j-1]; + } + } +#endif + + /* + VC++ optimizes this to a single jmp instruction, but only the 64-bit build. The 32-bit build generates less efficient code for some + reason. The ugly version above is faster so we'll just switch between the two depending on the target platform. + */ +#ifdef DRFLAC_64BIT + prediction = 0; + switch (order) + { + case 32: prediction += coefficients[31] * (drflac_int64)pDecodedSamples[-32]; + case 31: prediction += coefficients[30] * (drflac_int64)pDecodedSamples[-31]; + case 30: prediction += coefficients[29] * (drflac_int64)pDecodedSamples[-30]; + case 29: prediction += coefficients[28] * (drflac_int64)pDecodedSamples[-29]; + case 28: prediction += coefficients[27] * (drflac_int64)pDecodedSamples[-28]; + case 27: prediction += coefficients[26] * (drflac_int64)pDecodedSamples[-27]; + case 26: prediction += coefficients[25] * (drflac_int64)pDecodedSamples[-26]; + case 25: prediction += coefficients[24] * (drflac_int64)pDecodedSamples[-25]; + case 24: prediction += coefficients[23] * (drflac_int64)pDecodedSamples[-24]; + case 23: prediction += coefficients[22] * (drflac_int64)pDecodedSamples[-23]; + case 22: prediction += coefficients[21] * (drflac_int64)pDecodedSamples[-22]; + case 21: prediction += coefficients[20] * (drflac_int64)pDecodedSamples[-21]; + case 20: prediction += coefficients[19] * (drflac_int64)pDecodedSamples[-20]; + case 19: prediction += coefficients[18] * (drflac_int64)pDecodedSamples[-19]; + case 18: prediction += coefficients[17] * (drflac_int64)pDecodedSamples[-18]; + case 17: prediction += coefficients[16] * (drflac_int64)pDecodedSamples[-17]; + case 16: prediction += coefficients[15] * (drflac_int64)pDecodedSamples[-16]; + case 15: prediction += coefficients[14] * (drflac_int64)pDecodedSamples[-15]; + case 14: prediction += coefficients[13] * (drflac_int64)pDecodedSamples[-14]; + case 13: prediction += coefficients[12] * (drflac_int64)pDecodedSamples[-13]; + case 12: prediction += coefficients[11] * (drflac_int64)pDecodedSamples[-12]; + case 11: prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11]; + case 10: prediction += coefficients[ 9] * (drflac_int64)pDecodedSamples[-10]; + case 9: prediction += coefficients[ 8] * (drflac_int64)pDecodedSamples[- 9]; + case 8: prediction += coefficients[ 7] * (drflac_int64)pDecodedSamples[- 8]; + case 7: prediction += coefficients[ 6] * (drflac_int64)pDecodedSamples[- 7]; + case 6: prediction += coefficients[ 5] * (drflac_int64)pDecodedSamples[- 6]; + case 5: prediction += coefficients[ 4] * (drflac_int64)pDecodedSamples[- 5]; + case 4: prediction += coefficients[ 3] * (drflac_int64)pDecodedSamples[- 4]; + case 3: prediction += coefficients[ 2] * (drflac_int64)pDecodedSamples[- 3]; + case 2: prediction += coefficients[ 1] * (drflac_int64)pDecodedSamples[- 2]; + case 1: prediction += coefficients[ 0] * (drflac_int64)pDecodedSamples[- 1]; + } +#endif + + return (drflac_int32)(prediction >> shift); +} + + +#if 0 +/* +Reference implementation for reading and decoding samples with residual. This is intentionally left unoptimized for the +sake of readability and should only be used as a reference. +*/ +static drflac_bool32 drflac__decode_samples_with_residual__rice__reference(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pSamplesOut) +{ + drflac_uint32 i; + + DRFLAC_ASSERT(bs != NULL); + DRFLAC_ASSERT(pSamplesOut != NULL); + + for (i = 0; i < count; ++i) { + drflac_uint32 zeroCounter = 0; + for (;;) { + drflac_uint8 bit; + if (!drflac__read_uint8(bs, 1, &bit)) { + return DRFLAC_FALSE; + } + + if (bit == 0) { + zeroCounter += 1; + } else { + break; + } + } + + drflac_uint32 decodedRice; + if (riceParam > 0) { + if (!drflac__read_uint32(bs, riceParam, &decodedRice)) { + return DRFLAC_FALSE; + } + } else { + decodedRice = 0; + } + + decodedRice |= (zeroCounter << riceParam); + if ((decodedRice & 0x01)) { + decodedRice = ~(decodedRice >> 1); + } else { + decodedRice = (decodedRice >> 1); + } + + + if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) { + pSamplesOut[i] = decodedRice + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + i); + } else { + pSamplesOut[i] = decodedRice + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + i); + } + } + + return DRFLAC_TRUE; +} +#endif + +#if 0 +static drflac_bool32 drflac__read_rice_parts__reference(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut) +{ + drflac_uint32 zeroCounter = 0; + drflac_uint32 decodedRice; + + for (;;) { + drflac_uint8 bit; + if (!drflac__read_uint8(bs, 1, &bit)) { + return DRFLAC_FALSE; + } + + if (bit == 0) { + zeroCounter += 1; + } else { + break; + } + } + + if (riceParam > 0) { + if (!drflac__read_uint32(bs, riceParam, &decodedRice)) { + return DRFLAC_FALSE; + } + } else { + decodedRice = 0; + } + + *pZeroCounterOut = zeroCounter; + *pRiceParamPartOut = decodedRice; + return DRFLAC_TRUE; +} +#endif + +#if 0 +static DRFLAC_INLINE drflac_bool32 drflac__read_rice_parts(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut) +{ + drflac_cache_t riceParamMask; + drflac_uint32 zeroCounter; + drflac_uint32 setBitOffsetPlus1; + drflac_uint32 riceParamPart; + drflac_uint32 riceLength; + + DRFLAC_ASSERT(riceParam > 0); /* <-- riceParam should never be 0. drflac__read_rice_parts__param_equals_zero() should be used instead for this case. */ + + riceParamMask = DRFLAC_CACHE_L1_SELECTION_MASK(riceParam); + + zeroCounter = 0; + while (bs->cache == 0) { + zeroCounter += (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs); + if (!drflac__reload_cache(bs)) { + return DRFLAC_FALSE; + } + } + + setBitOffsetPlus1 = drflac__clz(bs->cache); + zeroCounter += setBitOffsetPlus1; + setBitOffsetPlus1 += 1; + + riceLength = setBitOffsetPlus1 + riceParam; + if (riceLength < DRFLAC_CACHE_L1_BITS_REMAINING(bs)) { + riceParamPart = (drflac_uint32)((bs->cache & (riceParamMask >> setBitOffsetPlus1)) >> DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceLength)); + + bs->consumedBits += riceLength; + bs->cache <<= riceLength; + } else { + drflac_uint32 bitCountLo; + drflac_cache_t resultHi; + + bs->consumedBits += riceLength; + bs->cache <<= setBitOffsetPlus1 & (DRFLAC_CACHE_L1_SIZE_BITS(bs)-1); /* <-- Equivalent to "if (setBitOffsetPlus1 < DRFLAC_CACHE_L1_SIZE_BITS(bs)) { bs->cache <<= setBitOffsetPlus1; }" */ + + /* It straddles the cached data. It will never cover more than the next chunk. We just read the number in two parts and combine them. */ + bitCountLo = bs->consumedBits - DRFLAC_CACHE_L1_SIZE_BITS(bs); + resultHi = DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, riceParam); /* <-- Use DRFLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE() if ever this function allows riceParam=0. */ + + if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) { +#ifndef DR_FLAC_NO_CRC + drflac__update_crc16(bs); +#endif + bs->cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]); + bs->consumedBits = 0; +#ifndef DR_FLAC_NO_CRC + bs->crc16Cache = bs->cache; +#endif + } else { + /* Slow path. We need to fetch more data from the client. */ + if (!drflac__reload_cache(bs)) { + return DRFLAC_FALSE; + } + if (bitCountLo > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) { + /* This happens when we get to end of stream */ + return DRFLAC_FALSE; + } + } + + riceParamPart = (drflac_uint32)(resultHi | DRFLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE(bs, bitCountLo)); + + bs->consumedBits += bitCountLo; + bs->cache <<= bitCountLo; + } + + pZeroCounterOut[0] = zeroCounter; + pRiceParamPartOut[0] = riceParamPart; + + return DRFLAC_TRUE; +} +#endif + +static DRFLAC_INLINE drflac_bool32 drflac__read_rice_parts_x1(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut) +{ + drflac_uint32 riceParamPlus1 = riceParam + 1; + /*drflac_cache_t riceParamPlus1Mask = DRFLAC_CACHE_L1_SELECTION_MASK(riceParamPlus1);*/ + drflac_uint32 riceParamPlus1Shift = DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceParamPlus1); + drflac_uint32 riceParamPlus1MaxConsumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs) - riceParamPlus1; + + /* + The idea here is to use local variables for the cache in an attempt to encourage the compiler to store them in registers. I have + no idea how this will work in practice... + */ + drflac_cache_t bs_cache = bs->cache; + drflac_uint32 bs_consumedBits = bs->consumedBits; + + /* The first thing to do is find the first unset bit. Most likely a bit will be set in the current cache line. */ + drflac_uint32 lzcount = drflac__clz(bs_cache); + if (lzcount < sizeof(bs_cache)*8) { + pZeroCounterOut[0] = lzcount; + + /* + It is most likely that the riceParam part (which comes after the zero counter) is also on this cache line. When extracting + this, we include the set bit from the unary coded part because it simplifies cache management. This bit will be handled + outside of this function at a higher level. + */ + extract_rice_param_part: + bs_cache <<= lzcount; + bs_consumedBits += lzcount; + + if (bs_consumedBits <= riceParamPlus1MaxConsumedBits) { + /* Getting here means the rice parameter part is wholly contained within the current cache line. */ + pRiceParamPartOut[0] = (drflac_uint32)(bs_cache >> riceParamPlus1Shift); + bs_cache <<= riceParamPlus1; + bs_consumedBits += riceParamPlus1; + } else { + drflac_uint32 riceParamPartHi; + drflac_uint32 riceParamPartLo; + drflac_uint32 riceParamPartLoBitCount; + + /* + Getting here means the rice parameter part straddles the cache line. We need to read from the tail of the current cache + line, reload the cache, and then combine it with the head of the next cache line. + */ + + /* Grab the high part of the rice parameter part. */ + riceParamPartHi = (drflac_uint32)(bs_cache >> riceParamPlus1Shift); + + /* Before reloading the cache we need to grab the size in bits of the low part. */ + riceParamPartLoBitCount = bs_consumedBits - riceParamPlus1MaxConsumedBits; + DRFLAC_ASSERT(riceParamPartLoBitCount > 0 && riceParamPartLoBitCount < 32); + + /* Now reload the cache. */ + if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) { + #ifndef DR_FLAC_NO_CRC + drflac__update_crc16(bs); + #endif + bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]); + bs_consumedBits = riceParamPartLoBitCount; + #ifndef DR_FLAC_NO_CRC + bs->crc16Cache = bs_cache; + #endif + } else { + /* Slow path. We need to fetch more data from the client. */ + if (!drflac__reload_cache(bs)) { + return DRFLAC_FALSE; + } + if (riceParamPartLoBitCount > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) { + /* This happens when we get to end of stream */ + return DRFLAC_FALSE; + } + + bs_cache = bs->cache; + bs_consumedBits = bs->consumedBits + riceParamPartLoBitCount; + } + + /* We should now have enough information to construct the rice parameter part. */ + riceParamPartLo = (drflac_uint32)(bs_cache >> (DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceParamPartLoBitCount))); + pRiceParamPartOut[0] = riceParamPartHi | riceParamPartLo; + + bs_cache <<= riceParamPartLoBitCount; + } + } else { + /* + Getting here means there are no bits set on the cache line. This is a less optimal case because we just wasted a call + to drflac__clz() and we need to reload the cache. + */ + drflac_uint32 zeroCounter = (drflac_uint32)(DRFLAC_CACHE_L1_SIZE_BITS(bs) - bs_consumedBits); + for (;;) { + if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) { + #ifndef DR_FLAC_NO_CRC + drflac__update_crc16(bs); + #endif + bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]); + bs_consumedBits = 0; + #ifndef DR_FLAC_NO_CRC + bs->crc16Cache = bs_cache; + #endif + } else { + /* Slow path. We need to fetch more data from the client. */ + if (!drflac__reload_cache(bs)) { + return DRFLAC_FALSE; + } + + bs_cache = bs->cache; + bs_consumedBits = bs->consumedBits; + } + + lzcount = drflac__clz(bs_cache); + zeroCounter += lzcount; + + if (lzcount < sizeof(bs_cache)*8) { + break; + } + } + + pZeroCounterOut[0] = zeroCounter; + goto extract_rice_param_part; + } + + /* Make sure the cache is restored at the end of it all. */ + bs->cache = bs_cache; + bs->consumedBits = bs_consumedBits; + + return DRFLAC_TRUE; +} + +static DRFLAC_INLINE drflac_bool32 drflac__seek_rice_parts(drflac_bs* bs, drflac_uint8 riceParam) +{ + drflac_uint32 riceParamPlus1 = riceParam + 1; + drflac_uint32 riceParamPlus1MaxConsumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs) - riceParamPlus1; + + /* + The idea here is to use local variables for the cache in an attempt to encourage the compiler to store them in registers. I have + no idea how this will work in practice... + */ + drflac_cache_t bs_cache = bs->cache; + drflac_uint32 bs_consumedBits = bs->consumedBits; + + /* The first thing to do is find the first unset bit. Most likely a bit will be set in the current cache line. */ + drflac_uint32 lzcount = drflac__clz(bs_cache); + if (lzcount < sizeof(bs_cache)*8) { + /* + It is most likely that the riceParam part (which comes after the zero counter) is also on this cache line. When extracting + this, we include the set bit from the unary coded part because it simplifies cache management. This bit will be handled + outside of this function at a higher level. + */ + extract_rice_param_part: + bs_cache <<= lzcount; + bs_consumedBits += lzcount; + + if (bs_consumedBits <= riceParamPlus1MaxConsumedBits) { + /* Getting here means the rice parameter part is wholly contained within the current cache line. */ + bs_cache <<= riceParamPlus1; + bs_consumedBits += riceParamPlus1; + } else { + /* + Getting here means the rice parameter part straddles the cache line. We need to read from the tail of the current cache + line, reload the cache, and then combine it with the head of the next cache line. + */ + + /* Before reloading the cache we need to grab the size in bits of the low part. */ + drflac_uint32 riceParamPartLoBitCount = bs_consumedBits - riceParamPlus1MaxConsumedBits; + DRFLAC_ASSERT(riceParamPartLoBitCount > 0 && riceParamPartLoBitCount < 32); + + /* Now reload the cache. */ + if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) { + #ifndef DR_FLAC_NO_CRC + drflac__update_crc16(bs); + #endif + bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]); + bs_consumedBits = riceParamPartLoBitCount; + #ifndef DR_FLAC_NO_CRC + bs->crc16Cache = bs_cache; + #endif + } else { + /* Slow path. We need to fetch more data from the client. */ + if (!drflac__reload_cache(bs)) { + return DRFLAC_FALSE; + } + + if (riceParamPartLoBitCount > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) { + /* This happens when we get to end of stream */ + return DRFLAC_FALSE; + } + + bs_cache = bs->cache; + bs_consumedBits = bs->consumedBits + riceParamPartLoBitCount; + } + + bs_cache <<= riceParamPartLoBitCount; + } + } else { + /* + Getting here means there are no bits set on the cache line. This is a less optimal case because we just wasted a call + to drflac__clz() and we need to reload the cache. + */ + for (;;) { + if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) { + #ifndef DR_FLAC_NO_CRC + drflac__update_crc16(bs); + #endif + bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]); + bs_consumedBits = 0; + #ifndef DR_FLAC_NO_CRC + bs->crc16Cache = bs_cache; + #endif + } else { + /* Slow path. We need to fetch more data from the client. */ + if (!drflac__reload_cache(bs)) { + return DRFLAC_FALSE; + } + + bs_cache = bs->cache; + bs_consumedBits = bs->consumedBits; + } + + lzcount = drflac__clz(bs_cache); + if (lzcount < sizeof(bs_cache)*8) { + break; + } + } + + goto extract_rice_param_part; + } + + /* Make sure the cache is restored at the end of it all. */ + bs->cache = bs_cache; + bs->consumedBits = bs_consumedBits; + + return DRFLAC_TRUE; +} + + +static drflac_bool32 drflac__decode_samples_with_residual__rice__scalar_zeroorder(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut) +{ + drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF}; + drflac_uint32 zeroCountPart0; + drflac_uint32 riceParamPart0; + drflac_uint32 riceParamMask; + drflac_uint32 i; + + DRFLAC_ASSERT(bs != NULL); + DRFLAC_ASSERT(pSamplesOut != NULL); + + (void)bitsPerSample; + (void)order; + (void)shift; + (void)coefficients; + + riceParamMask = (drflac_uint32)~((~0UL) << riceParam); + + i = 0; + while (i < count) { + /* Rice extraction. */ + if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0)) { + return DRFLAC_FALSE; + } + + /* Rice reconstruction. */ + riceParamPart0 &= riceParamMask; + riceParamPart0 |= (zeroCountPart0 << riceParam); + riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01]; + + pSamplesOut[i] = riceParamPart0; + + i += 1; + } + + return DRFLAC_TRUE; +} + +static drflac_bool32 drflac__decode_samples_with_residual__rice__scalar(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pSamplesOut) +{ + drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF}; + drflac_uint32 zeroCountPart0 = 0; + drflac_uint32 zeroCountPart1 = 0; + drflac_uint32 zeroCountPart2 = 0; + drflac_uint32 zeroCountPart3 = 0; + drflac_uint32 riceParamPart0 = 0; + drflac_uint32 riceParamPart1 = 0; + drflac_uint32 riceParamPart2 = 0; + drflac_uint32 riceParamPart3 = 0; + drflac_uint32 riceParamMask; + const drflac_int32* pSamplesOutEnd; + drflac_uint32 i; + + DRFLAC_ASSERT(bs != NULL); + DRFLAC_ASSERT(pSamplesOut != NULL); + + if (lpcOrder == 0) { + return drflac__decode_samples_with_residual__rice__scalar_zeroorder(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut); + } + + riceParamMask = (drflac_uint32)~((~0UL) << riceParam); + pSamplesOutEnd = pSamplesOut + (count & ~3); + + if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) { + while (pSamplesOut < pSamplesOutEnd) { + /* + Rice extraction. It's faster to do this one at a time against local variables than it is to use the x4 version + against an array. Not sure why, but perhaps it's making more efficient use of registers? + */ + if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart1, &riceParamPart1) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart2, &riceParamPart2) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart3, &riceParamPart3)) { + return DRFLAC_FALSE; + } + + riceParamPart0 &= riceParamMask; + riceParamPart1 &= riceParamMask; + riceParamPart2 &= riceParamMask; + riceParamPart3 &= riceParamMask; + + riceParamPart0 |= (zeroCountPart0 << riceParam); + riceParamPart1 |= (zeroCountPart1 << riceParam); + riceParamPart2 |= (zeroCountPart2 << riceParam); + riceParamPart3 |= (zeroCountPart3 << riceParam); + + riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01]; + riceParamPart1 = (riceParamPart1 >> 1) ^ t[riceParamPart1 & 0x01]; + riceParamPart2 = (riceParamPart2 >> 1) ^ t[riceParamPart2 & 0x01]; + riceParamPart3 = (riceParamPart3 >> 1) ^ t[riceParamPart3 & 0x01]; + + pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 0); + pSamplesOut[1] = riceParamPart1 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 1); + pSamplesOut[2] = riceParamPart2 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 2); + pSamplesOut[3] = riceParamPart3 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 3); + + pSamplesOut += 4; + } + } else { + while (pSamplesOut < pSamplesOutEnd) { + if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart1, &riceParamPart1) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart2, &riceParamPart2) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart3, &riceParamPart3)) { + return DRFLAC_FALSE; + } + + riceParamPart0 &= riceParamMask; + riceParamPart1 &= riceParamMask; + riceParamPart2 &= riceParamMask; + riceParamPart3 &= riceParamMask; + + riceParamPart0 |= (zeroCountPart0 << riceParam); + riceParamPart1 |= (zeroCountPart1 << riceParam); + riceParamPart2 |= (zeroCountPart2 << riceParam); + riceParamPart3 |= (zeroCountPart3 << riceParam); + + riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01]; + riceParamPart1 = (riceParamPart1 >> 1) ^ t[riceParamPart1 & 0x01]; + riceParamPart2 = (riceParamPart2 >> 1) ^ t[riceParamPart2 & 0x01]; + riceParamPart3 = (riceParamPart3 >> 1) ^ t[riceParamPart3 & 0x01]; + + pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 0); + pSamplesOut[1] = riceParamPart1 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 1); + pSamplesOut[2] = riceParamPart2 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 2); + pSamplesOut[3] = riceParamPart3 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 3); + + pSamplesOut += 4; + } + } + + i = (count & ~3); + while (i < count) { + /* Rice extraction. */ + if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0)) { + return DRFLAC_FALSE; + } + + /* Rice reconstruction. */ + riceParamPart0 &= riceParamMask; + riceParamPart0 |= (zeroCountPart0 << riceParam); + riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01]; + /*riceParamPart0 = (riceParamPart0 >> 1) ^ (~(riceParamPart0 & 0x01) + 1);*/ + + /* Sample reconstruction. */ + if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) { + pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 0); + } else { + pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 0); + } + + i += 1; + pSamplesOut += 1; + } + + return DRFLAC_TRUE; +} + +#if defined(DRFLAC_SUPPORT_SSE2) +static DRFLAC_INLINE __m128i drflac__mm_packs_interleaved_epi32(__m128i a, __m128i b) +{ + __m128i r; + + /* Pack. */ + r = _mm_packs_epi32(a, b); + + /* a3a2 a1a0 b3b2 b1b0 -> a3a2 b3b2 a1a0 b1b0 */ + r = _mm_shuffle_epi32(r, _MM_SHUFFLE(3, 1, 2, 0)); + + /* a3a2 b3b2 a1a0 b1b0 -> a3b3 a2b2 a1b1 a0b0 */ + r = _mm_shufflehi_epi16(r, _MM_SHUFFLE(3, 1, 2, 0)); + r = _mm_shufflelo_epi16(r, _MM_SHUFFLE(3, 1, 2, 0)); + + return r; +} +#endif + +#if defined(DRFLAC_SUPPORT_SSE41) +static DRFLAC_INLINE __m128i drflac__mm_not_si128(__m128i a) +{ + return _mm_xor_si128(a, _mm_cmpeq_epi32(_mm_setzero_si128(), _mm_setzero_si128())); +} + +static DRFLAC_INLINE __m128i drflac__mm_hadd_epi32(__m128i x) +{ + __m128i x64 = _mm_add_epi32(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(1, 0, 3, 2))); + __m128i x32 = _mm_shufflelo_epi16(x64, _MM_SHUFFLE(1, 0, 3, 2)); + return _mm_add_epi32(x64, x32); +} + +static DRFLAC_INLINE __m128i drflac__mm_hadd_epi64(__m128i x) +{ + return _mm_add_epi64(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(1, 0, 3, 2))); +} + +static DRFLAC_INLINE __m128i drflac__mm_srai_epi64(__m128i x, int count) +{ + /* + To simplify this we are assuming count < 32. This restriction allows us to work on a low side and a high side. The low side + is shifted with zero bits, whereas the right side is shifted with sign bits. + */ + __m128i lo = _mm_srli_epi64(x, count); + __m128i hi = _mm_srai_epi32(x, count); + + hi = _mm_and_si128(hi, _mm_set_epi32(0xFFFFFFFF, 0, 0xFFFFFFFF, 0)); /* The high part needs to have the low part cleared. */ + + return _mm_or_si128(lo, hi); +} + +static drflac_bool32 drflac__decode_samples_with_residual__rice__sse41_32(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut) +{ + int i; + drflac_uint32 riceParamMask; + drflac_int32* pDecodedSamples = pSamplesOut; + drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3); + drflac_uint32 zeroCountParts0 = 0; + drflac_uint32 zeroCountParts1 = 0; + drflac_uint32 zeroCountParts2 = 0; + drflac_uint32 zeroCountParts3 = 0; + drflac_uint32 riceParamParts0 = 0; + drflac_uint32 riceParamParts1 = 0; + drflac_uint32 riceParamParts2 = 0; + drflac_uint32 riceParamParts3 = 0; + __m128i coefficients128_0; + __m128i coefficients128_4; + __m128i coefficients128_8; + __m128i samples128_0; + __m128i samples128_4; + __m128i samples128_8; + __m128i riceParamMask128; + + const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF}; + + riceParamMask = (drflac_uint32)~((~0UL) << riceParam); + riceParamMask128 = _mm_set1_epi32(riceParamMask); + + /* Pre-load. */ + coefficients128_0 = _mm_setzero_si128(); + coefficients128_4 = _mm_setzero_si128(); + coefficients128_8 = _mm_setzero_si128(); + + samples128_0 = _mm_setzero_si128(); + samples128_4 = _mm_setzero_si128(); + samples128_8 = _mm_setzero_si128(); + + /* + Pre-loading the coefficients and prior samples is annoying because we need to ensure we don't try reading more than + what's available in the input buffers. It would be convenient to use a fall-through switch to do this, but this results + in strict aliasing warnings with GCC. To work around this I'm just doing something hacky. This feels a bit convoluted + so I think there's opportunity for this to be simplified. + */ +#if 1 + { + int runningOrder = order; + + /* 0 - 3. */ + if (runningOrder >= 4) { + coefficients128_0 = _mm_loadu_si128((const __m128i*)(coefficients + 0)); + samples128_0 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 4)); + runningOrder -= 4; + } else { + switch (runningOrder) { + case 3: coefficients128_0 = _mm_set_epi32(0, coefficients[2], coefficients[1], coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], pSamplesOut[-2], pSamplesOut[-3], 0); break; + case 2: coefficients128_0 = _mm_set_epi32(0, 0, coefficients[1], coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], pSamplesOut[-2], 0, 0); break; + case 1: coefficients128_0 = _mm_set_epi32(0, 0, 0, coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], 0, 0, 0); break; + } + runningOrder = 0; + } + + /* 4 - 7 */ + if (runningOrder >= 4) { + coefficients128_4 = _mm_loadu_si128((const __m128i*)(coefficients + 4)); + samples128_4 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 8)); + runningOrder -= 4; + } else { + switch (runningOrder) { + case 3: coefficients128_4 = _mm_set_epi32(0, coefficients[6], coefficients[5], coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], pSamplesOut[-6], pSamplesOut[-7], 0); break; + case 2: coefficients128_4 = _mm_set_epi32(0, 0, coefficients[5], coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], pSamplesOut[-6], 0, 0); break; + case 1: coefficients128_4 = _mm_set_epi32(0, 0, 0, coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], 0, 0, 0); break; + } + runningOrder = 0; + } + + /* 8 - 11 */ + if (runningOrder == 4) { + coefficients128_8 = _mm_loadu_si128((const __m128i*)(coefficients + 8)); + samples128_8 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 12)); + runningOrder -= 4; + } else { + switch (runningOrder) { + case 3: coefficients128_8 = _mm_set_epi32(0, coefficients[10], coefficients[9], coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], pSamplesOut[-10], pSamplesOut[-11], 0); break; + case 2: coefficients128_8 = _mm_set_epi32(0, 0, coefficients[9], coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], pSamplesOut[-10], 0, 0); break; + case 1: coefficients128_8 = _mm_set_epi32(0, 0, 0, coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], 0, 0, 0); break; + } + runningOrder = 0; + } + + /* Coefficients need to be shuffled for our streaming algorithm below to work. Samples are already in the correct order from the loading routine above. */ + coefficients128_0 = _mm_shuffle_epi32(coefficients128_0, _MM_SHUFFLE(0, 1, 2, 3)); + coefficients128_4 = _mm_shuffle_epi32(coefficients128_4, _MM_SHUFFLE(0, 1, 2, 3)); + coefficients128_8 = _mm_shuffle_epi32(coefficients128_8, _MM_SHUFFLE(0, 1, 2, 3)); + } +#else + /* This causes strict-aliasing warnings with GCC. */ + switch (order) + { + case 12: ((drflac_int32*)&coefficients128_8)[0] = coefficients[11]; ((drflac_int32*)&samples128_8)[0] = pDecodedSamples[-12]; + case 11: ((drflac_int32*)&coefficients128_8)[1] = coefficients[10]; ((drflac_int32*)&samples128_8)[1] = pDecodedSamples[-11]; + case 10: ((drflac_int32*)&coefficients128_8)[2] = coefficients[ 9]; ((drflac_int32*)&samples128_8)[2] = pDecodedSamples[-10]; + case 9: ((drflac_int32*)&coefficients128_8)[3] = coefficients[ 8]; ((drflac_int32*)&samples128_8)[3] = pDecodedSamples[- 9]; + case 8: ((drflac_int32*)&coefficients128_4)[0] = coefficients[ 7]; ((drflac_int32*)&samples128_4)[0] = pDecodedSamples[- 8]; + case 7: ((drflac_int32*)&coefficients128_4)[1] = coefficients[ 6]; ((drflac_int32*)&samples128_4)[1] = pDecodedSamples[- 7]; + case 6: ((drflac_int32*)&coefficients128_4)[2] = coefficients[ 5]; ((drflac_int32*)&samples128_4)[2] = pDecodedSamples[- 6]; + case 5: ((drflac_int32*)&coefficients128_4)[3] = coefficients[ 4]; ((drflac_int32*)&samples128_4)[3] = pDecodedSamples[- 5]; + case 4: ((drflac_int32*)&coefficients128_0)[0] = coefficients[ 3]; ((drflac_int32*)&samples128_0)[0] = pDecodedSamples[- 4]; + case 3: ((drflac_int32*)&coefficients128_0)[1] = coefficients[ 2]; ((drflac_int32*)&samples128_0)[1] = pDecodedSamples[- 3]; + case 2: ((drflac_int32*)&coefficients128_0)[2] = coefficients[ 1]; ((drflac_int32*)&samples128_0)[2] = pDecodedSamples[- 2]; + case 1: ((drflac_int32*)&coefficients128_0)[3] = coefficients[ 0]; ((drflac_int32*)&samples128_0)[3] = pDecodedSamples[- 1]; + } +#endif + + /* For this version we are doing one sample at a time. */ + while (pDecodedSamples < pDecodedSamplesEnd) { + __m128i prediction128; + __m128i zeroCountPart128; + __m128i riceParamPart128; + + if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts1, &riceParamParts1) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts2, &riceParamParts2) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts3, &riceParamParts3)) { + return DRFLAC_FALSE; + } + + zeroCountPart128 = _mm_set_epi32(zeroCountParts3, zeroCountParts2, zeroCountParts1, zeroCountParts0); + riceParamPart128 = _mm_set_epi32(riceParamParts3, riceParamParts2, riceParamParts1, riceParamParts0); + + riceParamPart128 = _mm_and_si128(riceParamPart128, riceParamMask128); + riceParamPart128 = _mm_or_si128(riceParamPart128, _mm_slli_epi32(zeroCountPart128, riceParam)); + riceParamPart128 = _mm_xor_si128(_mm_srli_epi32(riceParamPart128, 1), _mm_add_epi32(drflac__mm_not_si128(_mm_and_si128(riceParamPart128, _mm_set1_epi32(0x01))), _mm_set1_epi32(0x01))); /* <-- SSE2 compatible */ + /*riceParamPart128 = _mm_xor_si128(_mm_srli_epi32(riceParamPart128, 1), _mm_mullo_epi32(_mm_and_si128(riceParamPart128, _mm_set1_epi32(0x01)), _mm_set1_epi32(0xFFFFFFFF)));*/ /* <-- Only supported from SSE4.1 and is slower in my testing... */ + + if (order <= 4) { + for (i = 0; i < 4; i += 1) { + prediction128 = _mm_mullo_epi32(coefficients128_0, samples128_0); + + /* Horizontal add and shift. */ + prediction128 = drflac__mm_hadd_epi32(prediction128); + prediction128 = _mm_srai_epi32(prediction128, shift); + prediction128 = _mm_add_epi32(riceParamPart128, prediction128); + + samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4); + riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4); + } + } else if (order <= 8) { + for (i = 0; i < 4; i += 1) { + prediction128 = _mm_mullo_epi32(coefficients128_4, samples128_4); + prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_0, samples128_0)); + + /* Horizontal add and shift. */ + prediction128 = drflac__mm_hadd_epi32(prediction128); + prediction128 = _mm_srai_epi32(prediction128, shift); + prediction128 = _mm_add_epi32(riceParamPart128, prediction128); + + samples128_4 = _mm_alignr_epi8(samples128_0, samples128_4, 4); + samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4); + riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4); + } + } else { + for (i = 0; i < 4; i += 1) { + prediction128 = _mm_mullo_epi32(coefficients128_8, samples128_8); + prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_4, samples128_4)); + prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_0, samples128_0)); + + /* Horizontal add and shift. */ + prediction128 = drflac__mm_hadd_epi32(prediction128); + prediction128 = _mm_srai_epi32(prediction128, shift); + prediction128 = _mm_add_epi32(riceParamPart128, prediction128); + + samples128_8 = _mm_alignr_epi8(samples128_4, samples128_8, 4); + samples128_4 = _mm_alignr_epi8(samples128_0, samples128_4, 4); + samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4); + riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4); + } + } + + /* We store samples in groups of 4. */ + _mm_storeu_si128((__m128i*)pDecodedSamples, samples128_0); + pDecodedSamples += 4; + } + + /* Make sure we process the last few samples. */ + i = (count & ~3); + while (i < (int)count) { + /* Rice extraction. */ + if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0)) { + return DRFLAC_FALSE; + } + + /* Rice reconstruction. */ + riceParamParts0 &= riceParamMask; + riceParamParts0 |= (zeroCountParts0 << riceParam); + riceParamParts0 = (riceParamParts0 >> 1) ^ t[riceParamParts0 & 0x01]; + + /* Sample reconstruction. */ + pDecodedSamples[0] = riceParamParts0 + drflac__calculate_prediction_32(order, shift, coefficients, pDecodedSamples); + + i += 1; + pDecodedSamples += 1; + } + + return DRFLAC_TRUE; +} + +static drflac_bool32 drflac__decode_samples_with_residual__rice__sse41_64(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut) +{ + int i; + drflac_uint32 riceParamMask; + drflac_int32* pDecodedSamples = pSamplesOut; + drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3); + drflac_uint32 zeroCountParts0 = 0; + drflac_uint32 zeroCountParts1 = 0; + drflac_uint32 zeroCountParts2 = 0; + drflac_uint32 zeroCountParts3 = 0; + drflac_uint32 riceParamParts0 = 0; + drflac_uint32 riceParamParts1 = 0; + drflac_uint32 riceParamParts2 = 0; + drflac_uint32 riceParamParts3 = 0; + __m128i coefficients128_0; + __m128i coefficients128_4; + __m128i coefficients128_8; + __m128i samples128_0; + __m128i samples128_4; + __m128i samples128_8; + __m128i prediction128; + __m128i riceParamMask128; + + const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF}; + + DRFLAC_ASSERT(order <= 12); + + riceParamMask = (drflac_uint32)~((~0UL) << riceParam); + riceParamMask128 = _mm_set1_epi32(riceParamMask); + + prediction128 = _mm_setzero_si128(); + + /* Pre-load. */ + coefficients128_0 = _mm_setzero_si128(); + coefficients128_4 = _mm_setzero_si128(); + coefficients128_8 = _mm_setzero_si128(); + + samples128_0 = _mm_setzero_si128(); + samples128_4 = _mm_setzero_si128(); + samples128_8 = _mm_setzero_si128(); + +#if 1 + { + int runningOrder = order; + + /* 0 - 3. */ + if (runningOrder >= 4) { + coefficients128_0 = _mm_loadu_si128((const __m128i*)(coefficients + 0)); + samples128_0 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 4)); + runningOrder -= 4; + } else { + switch (runningOrder) { + case 3: coefficients128_0 = _mm_set_epi32(0, coefficients[2], coefficients[1], coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], pSamplesOut[-2], pSamplesOut[-3], 0); break; + case 2: coefficients128_0 = _mm_set_epi32(0, 0, coefficients[1], coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], pSamplesOut[-2], 0, 0); break; + case 1: coefficients128_0 = _mm_set_epi32(0, 0, 0, coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], 0, 0, 0); break; + } + runningOrder = 0; + } + + /* 4 - 7 */ + if (runningOrder >= 4) { + coefficients128_4 = _mm_loadu_si128((const __m128i*)(coefficients + 4)); + samples128_4 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 8)); + runningOrder -= 4; + } else { + switch (runningOrder) { + case 3: coefficients128_4 = _mm_set_epi32(0, coefficients[6], coefficients[5], coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], pSamplesOut[-6], pSamplesOut[-7], 0); break; + case 2: coefficients128_4 = _mm_set_epi32(0, 0, coefficients[5], coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], pSamplesOut[-6], 0, 0); break; + case 1: coefficients128_4 = _mm_set_epi32(0, 0, 0, coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], 0, 0, 0); break; + } + runningOrder = 0; + } + + /* 8 - 11 */ + if (runningOrder == 4) { + coefficients128_8 = _mm_loadu_si128((const __m128i*)(coefficients + 8)); + samples128_8 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 12)); + runningOrder -= 4; + } else { + switch (runningOrder) { + case 3: coefficients128_8 = _mm_set_epi32(0, coefficients[10], coefficients[9], coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], pSamplesOut[-10], pSamplesOut[-11], 0); break; + case 2: coefficients128_8 = _mm_set_epi32(0, 0, coefficients[9], coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], pSamplesOut[-10], 0, 0); break; + case 1: coefficients128_8 = _mm_set_epi32(0, 0, 0, coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], 0, 0, 0); break; + } + runningOrder = 0; + } + + /* Coefficients need to be shuffled for our streaming algorithm below to work. Samples are already in the correct order from the loading routine above. */ + coefficients128_0 = _mm_shuffle_epi32(coefficients128_0, _MM_SHUFFLE(0, 1, 2, 3)); + coefficients128_4 = _mm_shuffle_epi32(coefficients128_4, _MM_SHUFFLE(0, 1, 2, 3)); + coefficients128_8 = _mm_shuffle_epi32(coefficients128_8, _MM_SHUFFLE(0, 1, 2, 3)); + } +#else + switch (order) + { + case 12: ((drflac_int32*)&coefficients128_8)[0] = coefficients[11]; ((drflac_int32*)&samples128_8)[0] = pDecodedSamples[-12]; + case 11: ((drflac_int32*)&coefficients128_8)[1] = coefficients[10]; ((drflac_int32*)&samples128_8)[1] = pDecodedSamples[-11]; + case 10: ((drflac_int32*)&coefficients128_8)[2] = coefficients[ 9]; ((drflac_int32*)&samples128_8)[2] = pDecodedSamples[-10]; + case 9: ((drflac_int32*)&coefficients128_8)[3] = coefficients[ 8]; ((drflac_int32*)&samples128_8)[3] = pDecodedSamples[- 9]; + case 8: ((drflac_int32*)&coefficients128_4)[0] = coefficients[ 7]; ((drflac_int32*)&samples128_4)[0] = pDecodedSamples[- 8]; + case 7: ((drflac_int32*)&coefficients128_4)[1] = coefficients[ 6]; ((drflac_int32*)&samples128_4)[1] = pDecodedSamples[- 7]; + case 6: ((drflac_int32*)&coefficients128_4)[2] = coefficients[ 5]; ((drflac_int32*)&samples128_4)[2] = pDecodedSamples[- 6]; + case 5: ((drflac_int32*)&coefficients128_4)[3] = coefficients[ 4]; ((drflac_int32*)&samples128_4)[3] = pDecodedSamples[- 5]; + case 4: ((drflac_int32*)&coefficients128_0)[0] = coefficients[ 3]; ((drflac_int32*)&samples128_0)[0] = pDecodedSamples[- 4]; + case 3: ((drflac_int32*)&coefficients128_0)[1] = coefficients[ 2]; ((drflac_int32*)&samples128_0)[1] = pDecodedSamples[- 3]; + case 2: ((drflac_int32*)&coefficients128_0)[2] = coefficients[ 1]; ((drflac_int32*)&samples128_0)[2] = pDecodedSamples[- 2]; + case 1: ((drflac_int32*)&coefficients128_0)[3] = coefficients[ 0]; ((drflac_int32*)&samples128_0)[3] = pDecodedSamples[- 1]; + } +#endif + + /* For this version we are doing one sample at a time. */ + while (pDecodedSamples < pDecodedSamplesEnd) { + __m128i zeroCountPart128; + __m128i riceParamPart128; + + if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts1, &riceParamParts1) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts2, &riceParamParts2) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts3, &riceParamParts3)) { + return DRFLAC_FALSE; + } + + zeroCountPart128 = _mm_set_epi32(zeroCountParts3, zeroCountParts2, zeroCountParts1, zeroCountParts0); + riceParamPart128 = _mm_set_epi32(riceParamParts3, riceParamParts2, riceParamParts1, riceParamParts0); + + riceParamPart128 = _mm_and_si128(riceParamPart128, riceParamMask128); + riceParamPart128 = _mm_or_si128(riceParamPart128, _mm_slli_epi32(zeroCountPart128, riceParam)); + riceParamPart128 = _mm_xor_si128(_mm_srli_epi32(riceParamPart128, 1), _mm_add_epi32(drflac__mm_not_si128(_mm_and_si128(riceParamPart128, _mm_set1_epi32(1))), _mm_set1_epi32(1))); + + for (i = 0; i < 4; i += 1) { + prediction128 = _mm_xor_si128(prediction128, prediction128); /* Reset to 0. */ + + switch (order) + { + case 12: + case 11: prediction128 = _mm_add_epi64(prediction128, _mm_mul_epi32(_mm_shuffle_epi32(coefficients128_8, _MM_SHUFFLE(1, 1, 0, 0)), _mm_shuffle_epi32(samples128_8, _MM_SHUFFLE(1, 1, 0, 0)))); + case 10: + case 9: prediction128 = _mm_add_epi64(prediction128, _mm_mul_epi32(_mm_shuffle_epi32(coefficients128_8, _MM_SHUFFLE(3, 3, 2, 2)), _mm_shuffle_epi32(samples128_8, _MM_SHUFFLE(3, 3, 2, 2)))); + case 8: + case 7: prediction128 = _mm_add_epi64(prediction128, _mm_mul_epi32(_mm_shuffle_epi32(coefficients128_4, _MM_SHUFFLE(1, 1, 0, 0)), _mm_shuffle_epi32(samples128_4, _MM_SHUFFLE(1, 1, 0, 0)))); + case 6: + case 5: prediction128 = _mm_add_epi64(prediction128, _mm_mul_epi32(_mm_shuffle_epi32(coefficients128_4, _MM_SHUFFLE(3, 3, 2, 2)), _mm_shuffle_epi32(samples128_4, _MM_SHUFFLE(3, 3, 2, 2)))); + case 4: + case 3: prediction128 = _mm_add_epi64(prediction128, _mm_mul_epi32(_mm_shuffle_epi32(coefficients128_0, _MM_SHUFFLE(1, 1, 0, 0)), _mm_shuffle_epi32(samples128_0, _MM_SHUFFLE(1, 1, 0, 0)))); + case 2: + case 1: prediction128 = _mm_add_epi64(prediction128, _mm_mul_epi32(_mm_shuffle_epi32(coefficients128_0, _MM_SHUFFLE(3, 3, 2, 2)), _mm_shuffle_epi32(samples128_0, _MM_SHUFFLE(3, 3, 2, 2)))); + } + + /* Horizontal add and shift. */ + prediction128 = drflac__mm_hadd_epi64(prediction128); + prediction128 = drflac__mm_srai_epi64(prediction128, shift); + prediction128 = _mm_add_epi32(riceParamPart128, prediction128); + + /* Our value should be sitting in prediction128[0]. We need to combine this with our SSE samples. */ + samples128_8 = _mm_alignr_epi8(samples128_4, samples128_8, 4); + samples128_4 = _mm_alignr_epi8(samples128_0, samples128_4, 4); + samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4); + + /* Slide our rice parameter down so that the value in position 0 contains the next one to process. */ + riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4); + } + + /* We store samples in groups of 4. */ + _mm_storeu_si128((__m128i*)pDecodedSamples, samples128_0); + pDecodedSamples += 4; + } + + /* Make sure we process the last few samples. */ + i = (count & ~3); + while (i < (int)count) { + /* Rice extraction. */ + if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0)) { + return DRFLAC_FALSE; + } + + /* Rice reconstruction. */ + riceParamParts0 &= riceParamMask; + riceParamParts0 |= (zeroCountParts0 << riceParam); + riceParamParts0 = (riceParamParts0 >> 1) ^ t[riceParamParts0 & 0x01]; + + /* Sample reconstruction. */ + pDecodedSamples[0] = riceParamParts0 + drflac__calculate_prediction_64(order, shift, coefficients, pDecodedSamples); + + i += 1; + pDecodedSamples += 1; + } + + return DRFLAC_TRUE; +} + +static drflac_bool32 drflac__decode_samples_with_residual__rice__sse41(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pSamplesOut) +{ + DRFLAC_ASSERT(bs != NULL); + DRFLAC_ASSERT(pSamplesOut != NULL); + + /* In my testing the order is rarely > 12, so in this case I'm going to simplify the SSE implementation by only handling order <= 12. */ + if (lpcOrder > 0 && lpcOrder <= 12) { + if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) { + return drflac__decode_samples_with_residual__rice__sse41_64(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut); + } else { + return drflac__decode_samples_with_residual__rice__sse41_32(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut); + } + } else { + return drflac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut); + } +} +#endif + +#if defined(DRFLAC_SUPPORT_NEON) +static DRFLAC_INLINE void drflac__vst2q_s32(drflac_int32* p, int32x4x2_t x) +{ + vst1q_s32(p+0, x.val[0]); + vst1q_s32(p+4, x.val[1]); +} + +static DRFLAC_INLINE void drflac__vst2q_u32(drflac_uint32* p, uint32x4x2_t x) +{ + vst1q_u32(p+0, x.val[0]); + vst1q_u32(p+4, x.val[1]); +} + +static DRFLAC_INLINE void drflac__vst2q_f32(float* p, float32x4x2_t x) +{ + vst1q_f32(p+0, x.val[0]); + vst1q_f32(p+4, x.val[1]); +} + +static DRFLAC_INLINE void drflac__vst2q_s16(drflac_int16* p, int16x4x2_t x) +{ + vst1q_s16(p, vcombine_s16(x.val[0], x.val[1])); +} + +static DRFLAC_INLINE void drflac__vst2q_u16(drflac_uint16* p, uint16x4x2_t x) +{ + vst1q_u16(p, vcombine_u16(x.val[0], x.val[1])); +} + +static DRFLAC_INLINE int32x4_t drflac__vdupq_n_s32x4(drflac_int32 x3, drflac_int32 x2, drflac_int32 x1, drflac_int32 x0) +{ + drflac_int32 x[4]; + x[3] = x3; + x[2] = x2; + x[1] = x1; + x[0] = x0; + return vld1q_s32(x); +} + +static DRFLAC_INLINE int32x4_t drflac__valignrq_s32_1(int32x4_t a, int32x4_t b) +{ + /* Equivalent to SSE's _mm_alignr_epi8(a, b, 4) */ + + /* Reference */ + /*return drflac__vdupq_n_s32x4( + vgetq_lane_s32(a, 0), + vgetq_lane_s32(b, 3), + vgetq_lane_s32(b, 2), + vgetq_lane_s32(b, 1) + );*/ + + return vextq_s32(b, a, 1); +} + +static DRFLAC_INLINE uint32x4_t drflac__valignrq_u32_1(uint32x4_t a, uint32x4_t b) +{ + /* Equivalent to SSE's _mm_alignr_epi8(a, b, 4) */ + + /* Reference */ + /*return drflac__vdupq_n_s32x4( + vgetq_lane_s32(a, 0), + vgetq_lane_s32(b, 3), + vgetq_lane_s32(b, 2), + vgetq_lane_s32(b, 1) + );*/ + + return vextq_u32(b, a, 1); +} + +static DRFLAC_INLINE int32x2_t drflac__vhaddq_s32(int32x4_t x) +{ + /* The sum must end up in position 0. */ + + /* Reference */ + /*return vdupq_n_s32( + vgetq_lane_s32(x, 3) + + vgetq_lane_s32(x, 2) + + vgetq_lane_s32(x, 1) + + vgetq_lane_s32(x, 0) + );*/ + + int32x2_t r = vadd_s32(vget_high_s32(x), vget_low_s32(x)); + return vpadd_s32(r, r); +} + +static DRFLAC_INLINE int64x1_t drflac__vhaddq_s64(int64x2_t x) +{ + return vadd_s64(vget_high_s64(x), vget_low_s64(x)); +} + +static DRFLAC_INLINE int32x4_t drflac__vrevq_s32(int32x4_t x) +{ + /* Reference */ + /*return drflac__vdupq_n_s32x4( + vgetq_lane_s32(x, 0), + vgetq_lane_s32(x, 1), + vgetq_lane_s32(x, 2), + vgetq_lane_s32(x, 3) + );*/ + + return vrev64q_s32(vcombine_s32(vget_high_s32(x), vget_low_s32(x))); +} + +static DRFLAC_INLINE int32x4_t drflac__vnotq_s32(int32x4_t x) +{ + return veorq_s32(x, vdupq_n_s32(0xFFFFFFFF)); +} + +static DRFLAC_INLINE uint32x4_t drflac__vnotq_u32(uint32x4_t x) +{ + return veorq_u32(x, vdupq_n_u32(0xFFFFFFFF)); +} + +static drflac_bool32 drflac__decode_samples_with_residual__rice__neon_32(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut) +{ + int i; + drflac_uint32 riceParamMask; + drflac_int32* pDecodedSamples = pSamplesOut; + drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3); + drflac_uint32 zeroCountParts[4]; + drflac_uint32 riceParamParts[4]; + int32x4_t coefficients128_0; + int32x4_t coefficients128_4; + int32x4_t coefficients128_8; + int32x4_t samples128_0; + int32x4_t samples128_4; + int32x4_t samples128_8; + uint32x4_t riceParamMask128; + int32x4_t riceParam128; + int32x2_t shift64; + uint32x4_t one128; + + const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF}; + + riceParamMask = (drflac_uint32)~((~0UL) << riceParam); + riceParamMask128 = vdupq_n_u32(riceParamMask); + + riceParam128 = vdupq_n_s32(riceParam); + shift64 = vdup_n_s32(-shift); /* Negate the shift because we'll be doing a variable shift using vshlq_s32(). */ + one128 = vdupq_n_u32(1); + + /* + Pre-loading the coefficients and prior samples is annoying because we need to ensure we don't try reading more than + what's available in the input buffers. It would be conenient to use a fall-through switch to do this, but this results + in strict aliasing warnings with GCC. To work around this I'm just doing something hacky. This feels a bit convoluted + so I think there's opportunity for this to be simplified. + */ + { + int runningOrder = order; + drflac_int32 tempC[4] = {0, 0, 0, 0}; + drflac_int32 tempS[4] = {0, 0, 0, 0}; + + /* 0 - 3. */ + if (runningOrder >= 4) { + coefficients128_0 = vld1q_s32(coefficients + 0); + samples128_0 = vld1q_s32(pSamplesOut - 4); + runningOrder -= 4; + } else { + switch (runningOrder) { + case 3: tempC[2] = coefficients[2]; tempS[1] = pSamplesOut[-3]; /* fallthrough */ + case 2: tempC[1] = coefficients[1]; tempS[2] = pSamplesOut[-2]; /* fallthrough */ + case 1: tempC[0] = coefficients[0]; tempS[3] = pSamplesOut[-1]; /* fallthrough */ + } + + coefficients128_0 = vld1q_s32(tempC); + samples128_0 = vld1q_s32(tempS); + runningOrder = 0; + } + + /* 4 - 7 */ + if (runningOrder >= 4) { + coefficients128_4 = vld1q_s32(coefficients + 4); + samples128_4 = vld1q_s32(pSamplesOut - 8); + runningOrder -= 4; + } else { + switch (runningOrder) { + case 3: tempC[2] = coefficients[6]; tempS[1] = pSamplesOut[-7]; /* fallthrough */ + case 2: tempC[1] = coefficients[5]; tempS[2] = pSamplesOut[-6]; /* fallthrough */ + case 1: tempC[0] = coefficients[4]; tempS[3] = pSamplesOut[-5]; /* fallthrough */ + } + + coefficients128_4 = vld1q_s32(tempC); + samples128_4 = vld1q_s32(tempS); + runningOrder = 0; + } + + /* 8 - 11 */ + if (runningOrder == 4) { + coefficients128_8 = vld1q_s32(coefficients + 8); + samples128_8 = vld1q_s32(pSamplesOut - 12); + runningOrder -= 4; + } else { + switch (runningOrder) { + case 3: tempC[2] = coefficients[10]; tempS[1] = pSamplesOut[-11]; /* fallthrough */ + case 2: tempC[1] = coefficients[ 9]; tempS[2] = pSamplesOut[-10]; /* fallthrough */ + case 1: tempC[0] = coefficients[ 8]; tempS[3] = pSamplesOut[- 9]; /* fallthrough */ + } + + coefficients128_8 = vld1q_s32(tempC); + samples128_8 = vld1q_s32(tempS); + runningOrder = 0; + } + + /* Coefficients need to be shuffled for our streaming algorithm below to work. Samples are already in the correct order from the loading routine above. */ + coefficients128_0 = drflac__vrevq_s32(coefficients128_0); + coefficients128_4 = drflac__vrevq_s32(coefficients128_4); + coefficients128_8 = drflac__vrevq_s32(coefficients128_8); + } + + /* For this version we are doing one sample at a time. */ + while (pDecodedSamples < pDecodedSamplesEnd) { + int32x4_t prediction128; + int32x2_t prediction64; + uint32x4_t zeroCountPart128; + uint32x4_t riceParamPart128; + + if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0]) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[1], &riceParamParts[1]) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[2], &riceParamParts[2]) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[3], &riceParamParts[3])) { + return DRFLAC_FALSE; + } + + zeroCountPart128 = vld1q_u32(zeroCountParts); + riceParamPart128 = vld1q_u32(riceParamParts); + + riceParamPart128 = vandq_u32(riceParamPart128, riceParamMask128); + riceParamPart128 = vorrq_u32(riceParamPart128, vshlq_u32(zeroCountPart128, riceParam128)); + riceParamPart128 = veorq_u32(vshrq_n_u32(riceParamPart128, 1), vaddq_u32(drflac__vnotq_u32(vandq_u32(riceParamPart128, one128)), one128)); + + if (order <= 4) { + for (i = 0; i < 4; i += 1) { + prediction128 = vmulq_s32(coefficients128_0, samples128_0); + + /* Horizontal add and shift. */ + prediction64 = drflac__vhaddq_s32(prediction128); + prediction64 = vshl_s32(prediction64, shift64); + prediction64 = vadd_s32(prediction64, vget_low_s32(vreinterpretq_s32_u32(riceParamPart128))); + + samples128_0 = drflac__valignrq_s32_1(vcombine_s32(prediction64, vdup_n_s32(0)), samples128_0); + riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128); + } + } else if (order <= 8) { + for (i = 0; i < 4; i += 1) { + prediction128 = vmulq_s32(coefficients128_4, samples128_4); + prediction128 = vmlaq_s32(prediction128, coefficients128_0, samples128_0); + + /* Horizontal add and shift. */ + prediction64 = drflac__vhaddq_s32(prediction128); + prediction64 = vshl_s32(prediction64, shift64); + prediction64 = vadd_s32(prediction64, vget_low_s32(vreinterpretq_s32_u32(riceParamPart128))); + + samples128_4 = drflac__valignrq_s32_1(samples128_0, samples128_4); + samples128_0 = drflac__valignrq_s32_1(vcombine_s32(prediction64, vdup_n_s32(0)), samples128_0); + riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128); + } + } else { + for (i = 0; i < 4; i += 1) { + prediction128 = vmulq_s32(coefficients128_8, samples128_8); + prediction128 = vmlaq_s32(prediction128, coefficients128_4, samples128_4); + prediction128 = vmlaq_s32(prediction128, coefficients128_0, samples128_0); + + /* Horizontal add and shift. */ + prediction64 = drflac__vhaddq_s32(prediction128); + prediction64 = vshl_s32(prediction64, shift64); + prediction64 = vadd_s32(prediction64, vget_low_s32(vreinterpretq_s32_u32(riceParamPart128))); + + samples128_8 = drflac__valignrq_s32_1(samples128_4, samples128_8); + samples128_4 = drflac__valignrq_s32_1(samples128_0, samples128_4); + samples128_0 = drflac__valignrq_s32_1(vcombine_s32(prediction64, vdup_n_s32(0)), samples128_0); + riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128); + } + } + + /* We store samples in groups of 4. */ + vst1q_s32(pDecodedSamples, samples128_0); + pDecodedSamples += 4; + } + + /* Make sure we process the last few samples. */ + i = (count & ~3); + while (i < (int)count) { + /* Rice extraction. */ + if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0])) { + return DRFLAC_FALSE; + } + + /* Rice reconstruction. */ + riceParamParts[0] &= riceParamMask; + riceParamParts[0] |= (zeroCountParts[0] << riceParam); + riceParamParts[0] = (riceParamParts[0] >> 1) ^ t[riceParamParts[0] & 0x01]; + + /* Sample reconstruction. */ + pDecodedSamples[0] = riceParamParts[0] + drflac__calculate_prediction_32(order, shift, coefficients, pDecodedSamples); + + i += 1; + pDecodedSamples += 1; + } + + return DRFLAC_TRUE; +} + +static drflac_bool32 drflac__decode_samples_with_residual__rice__neon_64(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut) +{ + int i; + drflac_uint32 riceParamMask; + drflac_int32* pDecodedSamples = pSamplesOut; + drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3); + drflac_uint32 zeroCountParts[4]; + drflac_uint32 riceParamParts[4]; + int32x4_t coefficients128_0; + int32x4_t coefficients128_4; + int32x4_t coefficients128_8; + int32x4_t samples128_0; + int32x4_t samples128_4; + int32x4_t samples128_8; + uint32x4_t riceParamMask128; + int32x4_t riceParam128; + int64x1_t shift64; + uint32x4_t one128; + int64x2_t prediction128 = { 0 }; + uint32x4_t zeroCountPart128; + uint32x4_t riceParamPart128; + + const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF}; + + riceParamMask = (drflac_uint32)~((~0UL) << riceParam); + riceParamMask128 = vdupq_n_u32(riceParamMask); + + riceParam128 = vdupq_n_s32(riceParam); + shift64 = vdup_n_s64(-shift); /* Negate the shift because we'll be doing a variable shift using vshlq_s32(). */ + one128 = vdupq_n_u32(1); + + /* + Pre-loading the coefficients and prior samples is annoying because we need to ensure we don't try reading more than + what's available in the input buffers. It would be convenient to use a fall-through switch to do this, but this results + in strict aliasing warnings with GCC. To work around this I'm just doing something hacky. This feels a bit convoluted + so I think there's opportunity for this to be simplified. + */ + { + int runningOrder = order; + drflac_int32 tempC[4] = {0, 0, 0, 0}; + drflac_int32 tempS[4] = {0, 0, 0, 0}; + + /* 0 - 3. */ + if (runningOrder >= 4) { + coefficients128_0 = vld1q_s32(coefficients + 0); + samples128_0 = vld1q_s32(pSamplesOut - 4); + runningOrder -= 4; + } else { + switch (runningOrder) { + case 3: tempC[2] = coefficients[2]; tempS[1] = pSamplesOut[-3]; /* fallthrough */ + case 2: tempC[1] = coefficients[1]; tempS[2] = pSamplesOut[-2]; /* fallthrough */ + case 1: tempC[0] = coefficients[0]; tempS[3] = pSamplesOut[-1]; /* fallthrough */ + } + + coefficients128_0 = vld1q_s32(tempC); + samples128_0 = vld1q_s32(tempS); + runningOrder = 0; + } + + /* 4 - 7 */ + if (runningOrder >= 4) { + coefficients128_4 = vld1q_s32(coefficients + 4); + samples128_4 = vld1q_s32(pSamplesOut - 8); + runningOrder -= 4; + } else { + switch (runningOrder) { + case 3: tempC[2] = coefficients[6]; tempS[1] = pSamplesOut[-7]; /* fallthrough */ + case 2: tempC[1] = coefficients[5]; tempS[2] = pSamplesOut[-6]; /* fallthrough */ + case 1: tempC[0] = coefficients[4]; tempS[3] = pSamplesOut[-5]; /* fallthrough */ + } + + coefficients128_4 = vld1q_s32(tempC); + samples128_4 = vld1q_s32(tempS); + runningOrder = 0; + } + + /* 8 - 11 */ + if (runningOrder == 4) { + coefficients128_8 = vld1q_s32(coefficients + 8); + samples128_8 = vld1q_s32(pSamplesOut - 12); + runningOrder -= 4; + } else { + switch (runningOrder) { + case 3: tempC[2] = coefficients[10]; tempS[1] = pSamplesOut[-11]; /* fallthrough */ + case 2: tempC[1] = coefficients[ 9]; tempS[2] = pSamplesOut[-10]; /* fallthrough */ + case 1: tempC[0] = coefficients[ 8]; tempS[3] = pSamplesOut[- 9]; /* fallthrough */ + } + + coefficients128_8 = vld1q_s32(tempC); + samples128_8 = vld1q_s32(tempS); + runningOrder = 0; + } + + /* Coefficients need to be shuffled for our streaming algorithm below to work. Samples are already in the correct order from the loading routine above. */ + coefficients128_0 = drflac__vrevq_s32(coefficients128_0); + coefficients128_4 = drflac__vrevq_s32(coefficients128_4); + coefficients128_8 = drflac__vrevq_s32(coefficients128_8); + } + + /* For this version we are doing one sample at a time. */ + while (pDecodedSamples < pDecodedSamplesEnd) { + if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0]) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[1], &riceParamParts[1]) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[2], &riceParamParts[2]) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[3], &riceParamParts[3])) { + return DRFLAC_FALSE; + } + + zeroCountPart128 = vld1q_u32(zeroCountParts); + riceParamPart128 = vld1q_u32(riceParamParts); + + riceParamPart128 = vandq_u32(riceParamPart128, riceParamMask128); + riceParamPart128 = vorrq_u32(riceParamPart128, vshlq_u32(zeroCountPart128, riceParam128)); + riceParamPart128 = veorq_u32(vshrq_n_u32(riceParamPart128, 1), vaddq_u32(drflac__vnotq_u32(vandq_u32(riceParamPart128, one128)), one128)); + + for (i = 0; i < 4; i += 1) { + int64x1_t prediction64; + + prediction128 = veorq_s64(prediction128, prediction128); /* Reset to 0. */ + switch (order) + { + case 12: + case 11: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_low_s32(coefficients128_8), vget_low_s32(samples128_8))); + case 10: + case 9: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_high_s32(coefficients128_8), vget_high_s32(samples128_8))); + case 8: + case 7: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_low_s32(coefficients128_4), vget_low_s32(samples128_4))); + case 6: + case 5: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_high_s32(coefficients128_4), vget_high_s32(samples128_4))); + case 4: + case 3: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_low_s32(coefficients128_0), vget_low_s32(samples128_0))); + case 2: + case 1: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_high_s32(coefficients128_0), vget_high_s32(samples128_0))); + } + + /* Horizontal add and shift. */ + prediction64 = drflac__vhaddq_s64(prediction128); + prediction64 = vshl_s64(prediction64, shift64); + prediction64 = vadd_s64(prediction64, vdup_n_s64(vgetq_lane_u32(riceParamPart128, 0))); + + /* Our value should be sitting in prediction64[0]. We need to combine this with our SSE samples. */ + samples128_8 = drflac__valignrq_s32_1(samples128_4, samples128_8); + samples128_4 = drflac__valignrq_s32_1(samples128_0, samples128_4); + samples128_0 = drflac__valignrq_s32_1(vcombine_s32(vreinterpret_s32_s64(prediction64), vdup_n_s32(0)), samples128_0); + + /* Slide our rice parameter down so that the value in position 0 contains the next one to process. */ + riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128); + } + + /* We store samples in groups of 4. */ + vst1q_s32(pDecodedSamples, samples128_0); + pDecodedSamples += 4; + } + + /* Make sure we process the last few samples. */ + i = (count & ~3); + while (i < (int)count) { + /* Rice extraction. */ + if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0])) { + return DRFLAC_FALSE; + } + + /* Rice reconstruction. */ + riceParamParts[0] &= riceParamMask; + riceParamParts[0] |= (zeroCountParts[0] << riceParam); + riceParamParts[0] = (riceParamParts[0] >> 1) ^ t[riceParamParts[0] & 0x01]; + + /* Sample reconstruction. */ + pDecodedSamples[0] = riceParamParts[0] + drflac__calculate_prediction_64(order, shift, coefficients, pDecodedSamples); + + i += 1; + pDecodedSamples += 1; + } + + return DRFLAC_TRUE; +} + +static drflac_bool32 drflac__decode_samples_with_residual__rice__neon(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pSamplesOut) +{ + DRFLAC_ASSERT(bs != NULL); + DRFLAC_ASSERT(pSamplesOut != NULL); + + /* In my testing the order is rarely > 12, so in this case I'm going to simplify the NEON implementation by only handling order <= 12. */ + if (lpcOrder > 0 && lpcOrder <= 12) { + if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) { + return drflac__decode_samples_with_residual__rice__neon_64(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut); + } else { + return drflac__decode_samples_with_residual__rice__neon_32(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut); + } + } else { + return drflac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut); + } +} +#endif + +static drflac_bool32 drflac__decode_samples_with_residual__rice(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pSamplesOut) +{ +#if defined(DRFLAC_SUPPORT_SSE41) + if (drflac__gIsSSE41Supported) { + return drflac__decode_samples_with_residual__rice__sse41(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut); + } else +#elif defined(DRFLAC_SUPPORT_NEON) + if (drflac__gIsNEONSupported) { + return drflac__decode_samples_with_residual__rice__neon(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut); + } else +#endif + { + /* Scalar fallback. */ + #if 0 + return drflac__decode_samples_with_residual__rice__reference(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut); + #else + return drflac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut); + #endif + } +} + +/* Reads and seeks past a string of residual values as Rice codes. The decoder should be sitting on the first bit of the Rice codes. */ +static drflac_bool32 drflac__read_and_seek_residual__rice(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam) +{ + drflac_uint32 i; + + DRFLAC_ASSERT(bs != NULL); + + for (i = 0; i < count; ++i) { + if (!drflac__seek_rice_parts(bs, riceParam)) { + return DRFLAC_FALSE; + } + } + + return DRFLAC_TRUE; +} + +#if defined(__clang__) +__attribute__((no_sanitize("signed-integer-overflow"))) +#endif +static drflac_bool32 drflac__decode_samples_with_residual__unencoded(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 unencodedBitsPerSample, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pSamplesOut) +{ + drflac_uint32 i; + + DRFLAC_ASSERT(bs != NULL); + DRFLAC_ASSERT(unencodedBitsPerSample <= 31); /* <-- unencodedBitsPerSample is a 5 bit number, so cannot exceed 31. */ + DRFLAC_ASSERT(pSamplesOut != NULL); + + for (i = 0; i < count; ++i) { + if (unencodedBitsPerSample > 0) { + if (!drflac__read_int32(bs, unencodedBitsPerSample, pSamplesOut + i)) { + return DRFLAC_FALSE; + } + } else { + pSamplesOut[i] = 0; + } + + if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) { + pSamplesOut[i] += drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + i); + } else { + pSamplesOut[i] += drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + i); + } + } + + return DRFLAC_TRUE; +} + + +/* +Reads and decodes the residual for the sub-frame the decoder is currently sitting on. This function should be called +when the decoder is sitting at the very start of the RESIDUAL block. The first residuals will be ignored. The + and parameters are used to determine how many residual values need to be decoded. +*/ +static drflac_bool32 drflac__decode_samples_with_residual(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 blockSize, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pDecodedSamples) +{ + drflac_uint8 residualMethod; + drflac_uint8 partitionOrder; + drflac_uint32 samplesInPartition; + drflac_uint32 partitionsRemaining; + + DRFLAC_ASSERT(bs != NULL); + DRFLAC_ASSERT(blockSize != 0); + DRFLAC_ASSERT(pDecodedSamples != NULL); /* <-- Should we allow NULL, in which case we just seek past the residual rather than do a full decode? */ + + if (!drflac__read_uint8(bs, 2, &residualMethod)) { + return DRFLAC_FALSE; + } + + if (residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) { + return DRFLAC_FALSE; /* Unknown or unsupported residual coding method. */ + } + + /* Ignore the first values. */ + pDecodedSamples += lpcOrder; + + if (!drflac__read_uint8(bs, 4, &partitionOrder)) { + return DRFLAC_FALSE; + } + + /* + From the FLAC spec: + The Rice partition order in a Rice-coded residual section must be less than or equal to 8. + */ + if (partitionOrder > 8) { + return DRFLAC_FALSE; + } + + /* Validation check. */ + if ((blockSize / (1 << partitionOrder)) < lpcOrder) { + return DRFLAC_FALSE; + } + + samplesInPartition = (blockSize / (1 << partitionOrder)) - lpcOrder; + partitionsRemaining = (1 << partitionOrder); + for (;;) { + drflac_uint8 riceParam = 0; + if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE) { + if (!drflac__read_uint8(bs, 4, &riceParam)) { + return DRFLAC_FALSE; + } + if (riceParam == 15) { + riceParam = 0xFF; + } + } else if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) { + if (!drflac__read_uint8(bs, 5, &riceParam)) { + return DRFLAC_FALSE; + } + if (riceParam == 31) { + riceParam = 0xFF; + } + } + + if (riceParam != 0xFF) { + if (!drflac__decode_samples_with_residual__rice(bs, bitsPerSample, samplesInPartition, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pDecodedSamples)) { + return DRFLAC_FALSE; + } + } else { + drflac_uint8 unencodedBitsPerSample = 0; + if (!drflac__read_uint8(bs, 5, &unencodedBitsPerSample)) { + return DRFLAC_FALSE; + } + + if (!drflac__decode_samples_with_residual__unencoded(bs, bitsPerSample, samplesInPartition, unencodedBitsPerSample, lpcOrder, lpcShift, lpcPrecision, coefficients, pDecodedSamples)) { + return DRFLAC_FALSE; + } + } + + pDecodedSamples += samplesInPartition; + + if (partitionsRemaining == 1) { + break; + } + + partitionsRemaining -= 1; + + if (partitionOrder != 0) { + samplesInPartition = blockSize / (1 << partitionOrder); + } + } + + return DRFLAC_TRUE; +} + +/* +Reads and seeks past the residual for the sub-frame the decoder is currently sitting on. This function should be called +when the decoder is sitting at the very start of the RESIDUAL block. The first residuals will be set to 0. The + and parameters are used to determine how many residual values need to be decoded. +*/ +static drflac_bool32 drflac__read_and_seek_residual(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 order) +{ + drflac_uint8 residualMethod; + drflac_uint8 partitionOrder; + drflac_uint32 samplesInPartition; + drflac_uint32 partitionsRemaining; + + DRFLAC_ASSERT(bs != NULL); + DRFLAC_ASSERT(blockSize != 0); + + if (!drflac__read_uint8(bs, 2, &residualMethod)) { + return DRFLAC_FALSE; + } + + if (residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) { + return DRFLAC_FALSE; /* Unknown or unsupported residual coding method. */ + } + + if (!drflac__read_uint8(bs, 4, &partitionOrder)) { + return DRFLAC_FALSE; + } + + /* + From the FLAC spec: + The Rice partition order in a Rice-coded residual section must be less than or equal to 8. + */ + if (partitionOrder > 8) { + return DRFLAC_FALSE; + } + + /* Validation check. */ + if ((blockSize / (1 << partitionOrder)) <= order) { + return DRFLAC_FALSE; + } + + samplesInPartition = (blockSize / (1 << partitionOrder)) - order; + partitionsRemaining = (1 << partitionOrder); + for (;;) + { + drflac_uint8 riceParam = 0; + if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE) { + if (!drflac__read_uint8(bs, 4, &riceParam)) { + return DRFLAC_FALSE; + } + if (riceParam == 15) { + riceParam = 0xFF; + } + } else if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) { + if (!drflac__read_uint8(bs, 5, &riceParam)) { + return DRFLAC_FALSE; + } + if (riceParam == 31) { + riceParam = 0xFF; + } + } + + if (riceParam != 0xFF) { + if (!drflac__read_and_seek_residual__rice(bs, samplesInPartition, riceParam)) { + return DRFLAC_FALSE; + } + } else { + drflac_uint8 unencodedBitsPerSample = 0; + if (!drflac__read_uint8(bs, 5, &unencodedBitsPerSample)) { + return DRFLAC_FALSE; + } + + if (!drflac__seek_bits(bs, unencodedBitsPerSample * samplesInPartition)) { + return DRFLAC_FALSE; + } + } + + + if (partitionsRemaining == 1) { + break; + } + + partitionsRemaining -= 1; + samplesInPartition = blockSize / (1 << partitionOrder); + } + + return DRFLAC_TRUE; +} + + +static drflac_bool32 drflac__decode_samples__constant(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 subframeBitsPerSample, drflac_int32* pDecodedSamples) +{ + drflac_uint32 i; + + /* Only a single sample needs to be decoded here. */ + drflac_int32 sample; + if (!drflac__read_int32(bs, subframeBitsPerSample, &sample)) { + return DRFLAC_FALSE; + } + + /* + We don't really need to expand this, but it does simplify the process of reading samples. If this becomes a performance issue (unlikely) + we'll want to look at a more efficient way. + */ + for (i = 0; i < blockSize; ++i) { + pDecodedSamples[i] = sample; + } + + return DRFLAC_TRUE; +} + +static drflac_bool32 drflac__decode_samples__verbatim(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 subframeBitsPerSample, drflac_int32* pDecodedSamples) +{ + drflac_uint32 i; + + for (i = 0; i < blockSize; ++i) { + drflac_int32 sample; + if (!drflac__read_int32(bs, subframeBitsPerSample, &sample)) { + return DRFLAC_FALSE; + } + + pDecodedSamples[i] = sample; + } + + return DRFLAC_TRUE; +} + +static drflac_bool32 drflac__decode_samples__fixed(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 subframeBitsPerSample, drflac_uint8 lpcOrder, drflac_int32* pDecodedSamples) +{ + drflac_uint32 i; + + static drflac_int32 lpcCoefficientsTable[5][4] = { + {0, 0, 0, 0}, + {1, 0, 0, 0}, + {2, -1, 0, 0}, + {3, -3, 1, 0}, + {4, -6, 4, -1} + }; + + /* Warm up samples and coefficients. */ + for (i = 0; i < lpcOrder; ++i) { + drflac_int32 sample; + if (!drflac__read_int32(bs, subframeBitsPerSample, &sample)) { + return DRFLAC_FALSE; + } + + pDecodedSamples[i] = sample; + } + + if (!drflac__decode_samples_with_residual(bs, subframeBitsPerSample, blockSize, lpcOrder, 0, 4, lpcCoefficientsTable[lpcOrder], pDecodedSamples)) { + return DRFLAC_FALSE; + } + + return DRFLAC_TRUE; +} + +static drflac_bool32 drflac__decode_samples__lpc(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 bitsPerSample, drflac_uint8 lpcOrder, drflac_int32* pDecodedSamples) +{ + drflac_uint8 i; + drflac_uint8 lpcPrecision; + drflac_int8 lpcShift; + drflac_int32 coefficients[32]; + + /* Warm up samples. */ + for (i = 0; i < lpcOrder; ++i) { + drflac_int32 sample; + if (!drflac__read_int32(bs, bitsPerSample, &sample)) { + return DRFLAC_FALSE; + } + + pDecodedSamples[i] = sample; + } + + if (!drflac__read_uint8(bs, 4, &lpcPrecision)) { + return DRFLAC_FALSE; + } + if (lpcPrecision == 15) { + return DRFLAC_FALSE; /* Invalid. */ + } + lpcPrecision += 1; + + if (!drflac__read_int8(bs, 5, &lpcShift)) { + return DRFLAC_FALSE; + } + + /* + From the FLAC specification: + + Quantized linear predictor coefficient shift needed in bits (NOTE: this number is signed two's-complement) + + Emphasis on the "signed two's-complement". In practice there does not seem to be any encoders nor decoders supporting negative shifts. For now dr_flac is + not going to support negative shifts as I don't have any reference files. However, when a reference file comes through I will consider adding support. + */ + if (lpcShift < 0) { + return DRFLAC_FALSE; + } + + DRFLAC_ZERO_MEMORY(coefficients, sizeof(coefficients)); + for (i = 0; i < lpcOrder; ++i) { + if (!drflac__read_int32(bs, lpcPrecision, coefficients + i)) { + return DRFLAC_FALSE; + } + } + + if (!drflac__decode_samples_with_residual(bs, bitsPerSample, blockSize, lpcOrder, lpcShift, lpcPrecision, coefficients, pDecodedSamples)) { + return DRFLAC_FALSE; + } + + return DRFLAC_TRUE; +} + + +static drflac_bool32 drflac__read_next_flac_frame_header(drflac_bs* bs, drflac_uint8 streaminfoBitsPerSample, drflac_frame_header* header) +{ + const drflac_uint32 sampleRateTable[12] = {0, 88200, 176400, 192000, 8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000}; + const drflac_uint8 bitsPerSampleTable[8] = {0, 8, 12, (drflac_uint8)-1, 16, 20, 24, (drflac_uint8)-1}; /* -1 = reserved. */ + + DRFLAC_ASSERT(bs != NULL); + DRFLAC_ASSERT(header != NULL); + + /* Keep looping until we find a valid sync code. */ + for (;;) { + drflac_uint8 crc8 = 0xCE; /* 0xCE = drflac_crc8(0, 0x3FFE, 14); */ + drflac_uint8 reserved = 0; + drflac_uint8 blockingStrategy = 0; + drflac_uint8 blockSize = 0; + drflac_uint8 sampleRate = 0; + drflac_uint8 channelAssignment = 0; + drflac_uint8 bitsPerSample = 0; + drflac_bool32 isVariableBlockSize; + + if (!drflac__find_and_seek_to_next_sync_code(bs)) { + return DRFLAC_FALSE; + } + + if (!drflac__read_uint8(bs, 1, &reserved)) { + return DRFLAC_FALSE; + } + if (reserved == 1) { + continue; + } + crc8 = drflac_crc8(crc8, reserved, 1); + + if (!drflac__read_uint8(bs, 1, &blockingStrategy)) { + return DRFLAC_FALSE; + } + crc8 = drflac_crc8(crc8, blockingStrategy, 1); + + if (!drflac__read_uint8(bs, 4, &blockSize)) { + return DRFLAC_FALSE; + } + if (blockSize == 0) { + continue; + } + crc8 = drflac_crc8(crc8, blockSize, 4); + + if (!drflac__read_uint8(bs, 4, &sampleRate)) { + return DRFLAC_FALSE; + } + crc8 = drflac_crc8(crc8, sampleRate, 4); + + if (!drflac__read_uint8(bs, 4, &channelAssignment)) { + return DRFLAC_FALSE; + } + if (channelAssignment > 10) { + continue; + } + crc8 = drflac_crc8(crc8, channelAssignment, 4); + + if (!drflac__read_uint8(bs, 3, &bitsPerSample)) { + return DRFLAC_FALSE; + } + if (bitsPerSample == 3 || bitsPerSample == 7) { + continue; + } + crc8 = drflac_crc8(crc8, bitsPerSample, 3); + + + if (!drflac__read_uint8(bs, 1, &reserved)) { + return DRFLAC_FALSE; + } + if (reserved == 1) { + continue; + } + crc8 = drflac_crc8(crc8, reserved, 1); + + + isVariableBlockSize = blockingStrategy == 1; + if (isVariableBlockSize) { + drflac_uint64 pcmFrameNumber; + drflac_result result = drflac__read_utf8_coded_number(bs, &pcmFrameNumber, &crc8); + if (result != DRFLAC_SUCCESS) { + if (result == DRFLAC_AT_END) { + return DRFLAC_FALSE; + } else { + continue; + } + } + header->flacFrameNumber = 0; + header->pcmFrameNumber = pcmFrameNumber; + } else { + drflac_uint64 flacFrameNumber = 0; + drflac_result result = drflac__read_utf8_coded_number(bs, &flacFrameNumber, &crc8); + if (result != DRFLAC_SUCCESS) { + if (result == DRFLAC_AT_END) { + return DRFLAC_FALSE; + } else { + continue; + } + } + header->flacFrameNumber = (drflac_uint32)flacFrameNumber; /* <-- Safe cast. */ + header->pcmFrameNumber = 0; + } + + + DRFLAC_ASSERT(blockSize > 0); + if (blockSize == 1) { + header->blockSizeInPCMFrames = 192; + } else if (blockSize <= 5) { + DRFLAC_ASSERT(blockSize >= 2); + header->blockSizeInPCMFrames = 576 * (1 << (blockSize - 2)); + } else if (blockSize == 6) { + if (!drflac__read_uint16(bs, 8, &header->blockSizeInPCMFrames)) { + return DRFLAC_FALSE; + } + crc8 = drflac_crc8(crc8, header->blockSizeInPCMFrames, 8); + header->blockSizeInPCMFrames += 1; + } else if (blockSize == 7) { + if (!drflac__read_uint16(bs, 16, &header->blockSizeInPCMFrames)) { + return DRFLAC_FALSE; + } + crc8 = drflac_crc8(crc8, header->blockSizeInPCMFrames, 16); + if (header->blockSizeInPCMFrames == 0xFFFF) { + return DRFLAC_FALSE; /* Frame is too big. This is the size of the frame minus 1. The STREAMINFO block defines the max block size which is 16-bits. Adding one will make it 17 bits and therefore too big. */ + } + header->blockSizeInPCMFrames += 1; + } else { + DRFLAC_ASSERT(blockSize >= 8); + header->blockSizeInPCMFrames = 256 * (1 << (blockSize - 8)); + } + + + if (sampleRate <= 11) { + header->sampleRate = sampleRateTable[sampleRate]; + } else if (sampleRate == 12) { + if (!drflac__read_uint32(bs, 8, &header->sampleRate)) { + return DRFLAC_FALSE; + } + crc8 = drflac_crc8(crc8, header->sampleRate, 8); + header->sampleRate *= 1000; + } else if (sampleRate == 13) { + if (!drflac__read_uint32(bs, 16, &header->sampleRate)) { + return DRFLAC_FALSE; + } + crc8 = drflac_crc8(crc8, header->sampleRate, 16); + } else if (sampleRate == 14) { + if (!drflac__read_uint32(bs, 16, &header->sampleRate)) { + return DRFLAC_FALSE; + } + crc8 = drflac_crc8(crc8, header->sampleRate, 16); + header->sampleRate *= 10; + } else { + continue; /* Invalid. Assume an invalid block. */ + } + + + header->channelAssignment = channelAssignment; + + header->bitsPerSample = bitsPerSampleTable[bitsPerSample]; + if (header->bitsPerSample == 0) { + header->bitsPerSample = streaminfoBitsPerSample; + } + + if (header->bitsPerSample != streaminfoBitsPerSample) { + /* If this subframe has a different bitsPerSample then streaminfo or the first frame, reject it */ + return DRFLAC_FALSE; + } + + if (!drflac__read_uint8(bs, 8, &header->crc8)) { + return DRFLAC_FALSE; + } + +#ifndef DR_FLAC_NO_CRC + if (header->crc8 != crc8) { + continue; /* CRC mismatch. Loop back to the top and find the next sync code. */ + } +#endif + return DRFLAC_TRUE; + } +} + +static drflac_bool32 drflac__read_subframe_header(drflac_bs* bs, drflac_subframe* pSubframe) +{ + drflac_uint8 header; + int type; + + if (!drflac__read_uint8(bs, 8, &header)) { + return DRFLAC_FALSE; + } + + /* First bit should always be 0. */ + if ((header & 0x80) != 0) { + return DRFLAC_FALSE; + } + + /* + Default to 0 for the LPC order. It's important that we always set this to 0 for non LPC + and FIXED subframes because we'll be using it in a generic validation check later. + */ + pSubframe->lpcOrder = 0; + + type = (header & 0x7E) >> 1; + if (type == 0) { + pSubframe->subframeType = DRFLAC_SUBFRAME_CONSTANT; + } else if (type == 1) { + pSubframe->subframeType = DRFLAC_SUBFRAME_VERBATIM; + } else { + if ((type & 0x20) != 0) { + pSubframe->subframeType = DRFLAC_SUBFRAME_LPC; + pSubframe->lpcOrder = (drflac_uint8)(type & 0x1F) + 1; + } else if ((type & 0x08) != 0) { + pSubframe->subframeType = DRFLAC_SUBFRAME_FIXED; + pSubframe->lpcOrder = (drflac_uint8)(type & 0x07); + if (pSubframe->lpcOrder > 4) { + pSubframe->subframeType = DRFLAC_SUBFRAME_RESERVED; + pSubframe->lpcOrder = 0; + } + } else { + pSubframe->subframeType = DRFLAC_SUBFRAME_RESERVED; + } + } + + if (pSubframe->subframeType == DRFLAC_SUBFRAME_RESERVED) { + return DRFLAC_FALSE; + } + + /* Wasted bits per sample. */ + pSubframe->wastedBitsPerSample = 0; + if ((header & 0x01) == 1) { + unsigned int wastedBitsPerSample; + if (!drflac__seek_past_next_set_bit(bs, &wastedBitsPerSample)) { + return DRFLAC_FALSE; + } + pSubframe->wastedBitsPerSample = (drflac_uint8)wastedBitsPerSample + 1; + } + + return DRFLAC_TRUE; +} + +static drflac_bool32 drflac__decode_subframe(drflac_bs* bs, drflac_frame* frame, int subframeIndex, drflac_int32* pDecodedSamplesOut) +{ + drflac_subframe* pSubframe; + drflac_uint32 subframeBitsPerSample; + + DRFLAC_ASSERT(bs != NULL); + DRFLAC_ASSERT(frame != NULL); + + pSubframe = frame->subframes + subframeIndex; + if (!drflac__read_subframe_header(bs, pSubframe)) { + return DRFLAC_FALSE; + } + + /* Side channels require an extra bit per sample. Took a while to figure that one out... */ + subframeBitsPerSample = frame->header.bitsPerSample; + if ((frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) { + subframeBitsPerSample += 1; + } else if (frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) { + subframeBitsPerSample += 1; + } + + if (subframeBitsPerSample > 32) { + /* libFLAC and ffmpeg reject 33-bit subframes as well */ + return DRFLAC_FALSE; + } + + /* Need to handle wasted bits per sample. */ + if (pSubframe->wastedBitsPerSample >= subframeBitsPerSample) { + return DRFLAC_FALSE; + } + subframeBitsPerSample -= pSubframe->wastedBitsPerSample; + + pSubframe->pSamplesS32 = pDecodedSamplesOut; + + /* + pDecodedSamplesOut will be pointing to a buffer that was allocated with enough memory to store + maxBlockSizeInPCMFrames samples (as specified in the FLAC header). We need to guard against an + overflow here. At a higher level we are checking maxBlockSizeInPCMFrames from the header, but + here we need to do an additional check to ensure this frame's block size fully encompasses any + warmup samples which is determined by the LPC order. For non LPC and FIXED subframes, the LPC + order will be have been set to 0 in drflac__read_subframe_header(). + */ + if (frame->header.blockSizeInPCMFrames < pSubframe->lpcOrder) { + return DRFLAC_FALSE; + } + + switch (pSubframe->subframeType) + { + case DRFLAC_SUBFRAME_CONSTANT: + { + drflac__decode_samples__constant(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->pSamplesS32); + } break; + + case DRFLAC_SUBFRAME_VERBATIM: + { + drflac__decode_samples__verbatim(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->pSamplesS32); + } break; + + case DRFLAC_SUBFRAME_FIXED: + { + drflac__decode_samples__fixed(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->lpcOrder, pSubframe->pSamplesS32); + } break; + + case DRFLAC_SUBFRAME_LPC: + { + drflac__decode_samples__lpc(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->lpcOrder, pSubframe->pSamplesS32); + } break; + + default: return DRFLAC_FALSE; + } + + return DRFLAC_TRUE; +} + +static drflac_bool32 drflac__seek_subframe(drflac_bs* bs, drflac_frame* frame, int subframeIndex) +{ + drflac_subframe* pSubframe; + drflac_uint32 subframeBitsPerSample; + + DRFLAC_ASSERT(bs != NULL); + DRFLAC_ASSERT(frame != NULL); + + pSubframe = frame->subframes + subframeIndex; + if (!drflac__read_subframe_header(bs, pSubframe)) { + return DRFLAC_FALSE; + } + + /* Side channels require an extra bit per sample. Took a while to figure that one out... */ + subframeBitsPerSample = frame->header.bitsPerSample; + if ((frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) { + subframeBitsPerSample += 1; + } else if (frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) { + subframeBitsPerSample += 1; + } + + /* Need to handle wasted bits per sample. */ + if (pSubframe->wastedBitsPerSample >= subframeBitsPerSample) { + return DRFLAC_FALSE; + } + subframeBitsPerSample -= pSubframe->wastedBitsPerSample; + + pSubframe->pSamplesS32 = NULL; + + switch (pSubframe->subframeType) + { + case DRFLAC_SUBFRAME_CONSTANT: + { + if (!drflac__seek_bits(bs, subframeBitsPerSample)) { + return DRFLAC_FALSE; + } + } break; + + case DRFLAC_SUBFRAME_VERBATIM: + { + unsigned int bitsToSeek = frame->header.blockSizeInPCMFrames * subframeBitsPerSample; + if (!drflac__seek_bits(bs, bitsToSeek)) { + return DRFLAC_FALSE; + } + } break; + + case DRFLAC_SUBFRAME_FIXED: + { + unsigned int bitsToSeek = pSubframe->lpcOrder * subframeBitsPerSample; + if (!drflac__seek_bits(bs, bitsToSeek)) { + return DRFLAC_FALSE; + } + + if (!drflac__read_and_seek_residual(bs, frame->header.blockSizeInPCMFrames, pSubframe->lpcOrder)) { + return DRFLAC_FALSE; + } + } break; + + case DRFLAC_SUBFRAME_LPC: + { + drflac_uint8 lpcPrecision; + + unsigned int bitsToSeek = pSubframe->lpcOrder * subframeBitsPerSample; + if (!drflac__seek_bits(bs, bitsToSeek)) { + return DRFLAC_FALSE; + } + + if (!drflac__read_uint8(bs, 4, &lpcPrecision)) { + return DRFLAC_FALSE; + } + if (lpcPrecision == 15) { + return DRFLAC_FALSE; /* Invalid. */ + } + lpcPrecision += 1; + + + bitsToSeek = (pSubframe->lpcOrder * lpcPrecision) + 5; /* +5 for shift. */ + if (!drflac__seek_bits(bs, bitsToSeek)) { + return DRFLAC_FALSE; + } + + if (!drflac__read_and_seek_residual(bs, frame->header.blockSizeInPCMFrames, pSubframe->lpcOrder)) { + return DRFLAC_FALSE; + } + } break; + + default: return DRFLAC_FALSE; + } + + return DRFLAC_TRUE; +} + + +static DRFLAC_INLINE drflac_uint8 drflac__get_channel_count_from_channel_assignment(drflac_int8 channelAssignment) +{ + drflac_uint8 lookup[] = {1, 2, 3, 4, 5, 6, 7, 8, 2, 2, 2}; + + DRFLAC_ASSERT(channelAssignment <= 10); + return lookup[channelAssignment]; +} + +static drflac_result drflac__decode_flac_frame(drflac* pFlac) +{ + int channelCount; + int i; + drflac_uint8 paddingSizeInBits; + drflac_uint16 desiredCRC16; +#ifndef DR_FLAC_NO_CRC + drflac_uint16 actualCRC16; +#endif + + /* This function should be called while the stream is sitting on the first byte after the frame header. */ + DRFLAC_ZERO_MEMORY(pFlac->currentFLACFrame.subframes, sizeof(pFlac->currentFLACFrame.subframes)); + + /* The frame block size must never be larger than the maximum block size defined by the FLAC stream. */ + if (pFlac->currentFLACFrame.header.blockSizeInPCMFrames > pFlac->maxBlockSizeInPCMFrames) { + return DRFLAC_ERROR; + } + + /* The number of channels in the frame must match the channel count from the STREAMINFO block. */ + channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment); + if (channelCount != (int)pFlac->channels) { + return DRFLAC_ERROR; + } + + for (i = 0; i < channelCount; ++i) { + if (!drflac__decode_subframe(&pFlac->bs, &pFlac->currentFLACFrame, i, pFlac->pDecodedSamples + (pFlac->currentFLACFrame.header.blockSizeInPCMFrames * i))) { + return DRFLAC_ERROR; + } + } + + paddingSizeInBits = (drflac_uint8)(DRFLAC_CACHE_L1_BITS_REMAINING(&pFlac->bs) & 7); + if (paddingSizeInBits > 0) { + drflac_uint8 padding = 0; + if (!drflac__read_uint8(&pFlac->bs, paddingSizeInBits, &padding)) { + return DRFLAC_AT_END; + } + } + +#ifndef DR_FLAC_NO_CRC + actualCRC16 = drflac__flush_crc16(&pFlac->bs); +#endif + if (!drflac__read_uint16(&pFlac->bs, 16, &desiredCRC16)) { + return DRFLAC_AT_END; + } + +#ifndef DR_FLAC_NO_CRC + if (actualCRC16 != desiredCRC16) { + return DRFLAC_CRC_MISMATCH; /* CRC mismatch. */ + } +#endif + + pFlac->currentFLACFrame.pcmFramesRemaining = pFlac->currentFLACFrame.header.blockSizeInPCMFrames; + + return DRFLAC_SUCCESS; +} + +static drflac_result drflac__seek_flac_frame(drflac* pFlac) +{ + int channelCount; + int i; + drflac_uint16 desiredCRC16; +#ifndef DR_FLAC_NO_CRC + drflac_uint16 actualCRC16; +#endif + + channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment); + for (i = 0; i < channelCount; ++i) { + if (!drflac__seek_subframe(&pFlac->bs, &pFlac->currentFLACFrame, i)) { + return DRFLAC_ERROR; + } + } + + /* Padding. */ + if (!drflac__seek_bits(&pFlac->bs, DRFLAC_CACHE_L1_BITS_REMAINING(&pFlac->bs) & 7)) { + return DRFLAC_ERROR; + } + + /* CRC. */ +#ifndef DR_FLAC_NO_CRC + actualCRC16 = drflac__flush_crc16(&pFlac->bs); +#endif + if (!drflac__read_uint16(&pFlac->bs, 16, &desiredCRC16)) { + return DRFLAC_AT_END; + } + +#ifndef DR_FLAC_NO_CRC + if (actualCRC16 != desiredCRC16) { + return DRFLAC_CRC_MISMATCH; /* CRC mismatch. */ + } +#endif + + return DRFLAC_SUCCESS; +} + +static drflac_bool32 drflac__read_and_decode_next_flac_frame(drflac* pFlac) +{ + DRFLAC_ASSERT(pFlac != NULL); + + for (;;) { + drflac_result result; + + if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) { + return DRFLAC_FALSE; + } + + result = drflac__decode_flac_frame(pFlac); + if (result != DRFLAC_SUCCESS) { + if (result == DRFLAC_CRC_MISMATCH) { + continue; /* CRC mismatch. Skip to the next frame. */ + } else { + return DRFLAC_FALSE; + } + } + + return DRFLAC_TRUE; + } +} + +static void drflac__get_pcm_frame_range_of_current_flac_frame(drflac* pFlac, drflac_uint64* pFirstPCMFrame, drflac_uint64* pLastPCMFrame) +{ + drflac_uint64 firstPCMFrame; + drflac_uint64 lastPCMFrame; + + DRFLAC_ASSERT(pFlac != NULL); + + firstPCMFrame = pFlac->currentFLACFrame.header.pcmFrameNumber; + if (firstPCMFrame == 0) { + firstPCMFrame = ((drflac_uint64)pFlac->currentFLACFrame.header.flacFrameNumber) * pFlac->maxBlockSizeInPCMFrames; + } + + lastPCMFrame = firstPCMFrame + pFlac->currentFLACFrame.header.blockSizeInPCMFrames; + if (lastPCMFrame > 0) { + lastPCMFrame -= 1; /* Needs to be zero based. */ + } + + if (pFirstPCMFrame) { + *pFirstPCMFrame = firstPCMFrame; + } + if (pLastPCMFrame) { + *pLastPCMFrame = lastPCMFrame; + } +} + +static drflac_bool32 drflac__seek_to_first_frame(drflac* pFlac) +{ + drflac_bool32 result; + + DRFLAC_ASSERT(pFlac != NULL); + + result = drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes); + + DRFLAC_ZERO_MEMORY(&pFlac->currentFLACFrame, sizeof(pFlac->currentFLACFrame)); + pFlac->currentPCMFrame = 0; + + return result; +} + +static DRFLAC_INLINE drflac_result drflac__seek_to_next_flac_frame(drflac* pFlac) +{ + /* This function should only ever be called while the decoder is sitting on the first byte past the FRAME_HEADER section. */ + DRFLAC_ASSERT(pFlac != NULL); + return drflac__seek_flac_frame(pFlac); +} + + +static drflac_uint64 drflac__seek_forward_by_pcm_frames(drflac* pFlac, drflac_uint64 pcmFramesToSeek) +{ + drflac_uint64 pcmFramesRead = 0; + while (pcmFramesToSeek > 0) { + if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) { + if (!drflac__read_and_decode_next_flac_frame(pFlac)) { + break; /* Couldn't read the next frame, so just break from the loop and return. */ + } + } else { + if (pFlac->currentFLACFrame.pcmFramesRemaining > pcmFramesToSeek) { + pcmFramesRead += pcmFramesToSeek; + pFlac->currentFLACFrame.pcmFramesRemaining -= (drflac_uint32)pcmFramesToSeek; /* <-- Safe cast. Will always be < currentFrame.pcmFramesRemaining < 65536. */ + pcmFramesToSeek = 0; + } else { + pcmFramesRead += pFlac->currentFLACFrame.pcmFramesRemaining; + pcmFramesToSeek -= pFlac->currentFLACFrame.pcmFramesRemaining; + pFlac->currentFLACFrame.pcmFramesRemaining = 0; + } + } + } + + pFlac->currentPCMFrame += pcmFramesRead; + return pcmFramesRead; +} + + +static drflac_bool32 drflac__seek_to_pcm_frame__brute_force(drflac* pFlac, drflac_uint64 pcmFrameIndex) +{ + drflac_bool32 isMidFrame = DRFLAC_FALSE; + drflac_uint64 runningPCMFrameCount; + + DRFLAC_ASSERT(pFlac != NULL); + + /* If we are seeking forward we start from the current position. Otherwise we need to start all the way from the start of the file. */ + if (pcmFrameIndex >= pFlac->currentPCMFrame) { + /* Seeking forward. Need to seek from the current position. */ + runningPCMFrameCount = pFlac->currentPCMFrame; + + /* The frame header for the first frame may not yet have been read. We need to do that if necessary. */ + if (pFlac->currentPCMFrame == 0 && pFlac->currentFLACFrame.pcmFramesRemaining == 0) { + if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) { + return DRFLAC_FALSE; + } + } else { + isMidFrame = DRFLAC_TRUE; + } + } else { + /* Seeking backwards. Need to seek from the start of the file. */ + runningPCMFrameCount = 0; + + /* Move back to the start. */ + if (!drflac__seek_to_first_frame(pFlac)) { + return DRFLAC_FALSE; + } + + /* Decode the first frame in preparation for sample-exact seeking below. */ + if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) { + return DRFLAC_FALSE; + } + } + + /* + We need to as quickly as possible find the frame that contains the target sample. To do this, we iterate over each frame and inspect its + header. If based on the header we can determine that the frame contains the sample, we do a full decode of that frame. + */ + for (;;) { + drflac_uint64 pcmFrameCountInThisFLACFrame; + drflac_uint64 firstPCMFrameInFLACFrame = 0; + drflac_uint64 lastPCMFrameInFLACFrame = 0; + + drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame); + + pcmFrameCountInThisFLACFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1; + if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFLACFrame)) { + /* + The sample should be in this frame. We need to fully decode it, however if it's an invalid frame (a CRC mismatch), we need to pretend + it never existed and keep iterating. + */ + drflac_uint64 pcmFramesToDecode = pcmFrameIndex - runningPCMFrameCount; + + if (!isMidFrame) { + drflac_result result = drflac__decode_flac_frame(pFlac); + if (result == DRFLAC_SUCCESS) { + /* The frame is valid. We just need to skip over some samples to ensure it's sample-exact. */ + return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode; /* <-- If this fails, something bad has happened (it should never fail). */ + } else { + if (result == DRFLAC_CRC_MISMATCH) { + goto next_iteration; /* CRC mismatch. Pretend this frame never existed. */ + } else { + return DRFLAC_FALSE; + } + } + } else { + /* We started seeking mid-frame which means we need to skip the frame decoding part. */ + return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode; + } + } else { + /* + It's not in this frame. We need to seek past the frame, but check if there was a CRC mismatch. If so, we pretend this + frame never existed and leave the running sample count untouched. + */ + if (!isMidFrame) { + drflac_result result = drflac__seek_to_next_flac_frame(pFlac); + if (result == DRFLAC_SUCCESS) { + runningPCMFrameCount += pcmFrameCountInThisFLACFrame; + } else { + if (result == DRFLAC_CRC_MISMATCH) { + goto next_iteration; /* CRC mismatch. Pretend this frame never existed. */ + } else { + return DRFLAC_FALSE; + } + } + } else { + /* + We started seeking mid-frame which means we need to seek by reading to the end of the frame instead of with + drflac__seek_to_next_flac_frame() which only works if the decoder is sitting on the byte just after the frame header. + */ + runningPCMFrameCount += pFlac->currentFLACFrame.pcmFramesRemaining; + pFlac->currentFLACFrame.pcmFramesRemaining = 0; + isMidFrame = DRFLAC_FALSE; + } + + /* If we are seeking to the end of the file and we've just hit it, we're done. */ + if (pcmFrameIndex == pFlac->totalPCMFrameCount && runningPCMFrameCount == pFlac->totalPCMFrameCount) { + return DRFLAC_TRUE; + } + } + + next_iteration: + /* Grab the next frame in preparation for the next iteration. */ + if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) { + return DRFLAC_FALSE; + } + } +} + + +#if !defined(DR_FLAC_NO_CRC) +/* +We use an average compression ratio to determine our approximate start location. FLAC files are generally about 50%-70% the size of their +uncompressed counterparts so we'll use this as a basis. I'm going to split the middle and use a factor of 0.6 to determine the starting +location. +*/ +#define DRFLAC_BINARY_SEARCH_APPROX_COMPRESSION_RATIO 0.6f + +static drflac_bool32 drflac__seek_to_approximate_flac_frame_to_byte(drflac* pFlac, drflac_uint64 targetByte, drflac_uint64 rangeLo, drflac_uint64 rangeHi, drflac_uint64* pLastSuccessfulSeekOffset) +{ + DRFLAC_ASSERT(pFlac != NULL); + DRFLAC_ASSERT(pLastSuccessfulSeekOffset != NULL); + DRFLAC_ASSERT(targetByte >= rangeLo); + DRFLAC_ASSERT(targetByte <= rangeHi); + + *pLastSuccessfulSeekOffset = pFlac->firstFLACFramePosInBytes; + + for (;;) { + /* After rangeLo == rangeHi == targetByte fails, we need to break out. */ + drflac_uint64 lastTargetByte = targetByte; + + /* When seeking to a byte, failure probably means we've attempted to seek beyond the end of the stream. To counter this we just halve it each attempt. */ + if (!drflac__seek_to_byte(&pFlac->bs, targetByte)) { + /* If we couldn't even seek to the first byte in the stream we have a problem. Just abandon the whole thing. */ + if (targetByte == 0) { + drflac__seek_to_first_frame(pFlac); /* Try to recover. */ + return DRFLAC_FALSE; + } + + /* Halve the byte location and continue. */ + targetByte = rangeLo + ((rangeHi - rangeLo)/2); + rangeHi = targetByte; + } else { + /* Getting here should mean that we have seeked to an appropriate byte. */ + + /* Clear the details of the FLAC frame so we don't misreport data. */ + DRFLAC_ZERO_MEMORY(&pFlac->currentFLACFrame, sizeof(pFlac->currentFLACFrame)); + + /* + Now seek to the next FLAC frame. We need to decode the entire frame (not just the header) because it's possible for the header to incorrectly pass the + CRC check and return bad data. We need to decode the entire frame to be more certain. Although this seems unlikely, this has happened to me in testing + so it needs to stay this way for now. + */ +#if 1 + if (!drflac__read_and_decode_next_flac_frame(pFlac)) { + /* Halve the byte location and continue. */ + targetByte = rangeLo + ((rangeHi - rangeLo)/2); + rangeHi = targetByte; + } else { + break; + } +#else + if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) { + /* Halve the byte location and continue. */ + targetByte = rangeLo + ((rangeHi - rangeLo)/2); + rangeHi = targetByte; + } else { + break; + } +#endif + } + + /* We already tried this byte and there are no more to try, break out. */ + if(targetByte == lastTargetByte) { + return DRFLAC_FALSE; + } + } + + /* The current PCM frame needs to be updated based on the frame we just seeked to. */ + drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &pFlac->currentPCMFrame, NULL); + + DRFLAC_ASSERT(targetByte <= rangeHi); + + *pLastSuccessfulSeekOffset = targetByte; + return DRFLAC_TRUE; +} + +static drflac_bool32 drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(drflac* pFlac, drflac_uint64 offset) +{ + /* This section of code would be used if we were only decoding the FLAC frame header when calling drflac__seek_to_approximate_flac_frame_to_byte(). */ +#if 0 + if (drflac__decode_flac_frame(pFlac) != DRFLAC_SUCCESS) { + /* We failed to decode this frame which may be due to it being corrupt. We'll just use the next valid FLAC frame. */ + if (drflac__read_and_decode_next_flac_frame(pFlac) == DRFLAC_FALSE) { + return DRFLAC_FALSE; + } + } +#endif + + return drflac__seek_forward_by_pcm_frames(pFlac, offset) == offset; +} + + +static drflac_bool32 drflac__seek_to_pcm_frame__binary_search_internal(drflac* pFlac, drflac_uint64 pcmFrameIndex, drflac_uint64 byteRangeLo, drflac_uint64 byteRangeHi) +{ + /* This assumes pFlac->currentPCMFrame is sitting on byteRangeLo upon entry. */ + + drflac_uint64 targetByte; + drflac_uint64 pcmRangeLo = pFlac->totalPCMFrameCount; + drflac_uint64 pcmRangeHi = 0; + drflac_uint64 lastSuccessfulSeekOffset = (drflac_uint64)-1; + drflac_uint64 closestSeekOffsetBeforeTargetPCMFrame = byteRangeLo; + drflac_uint32 seekForwardThreshold = (pFlac->maxBlockSizeInPCMFrames != 0) ? pFlac->maxBlockSizeInPCMFrames*2 : 4096; + + targetByte = byteRangeLo + (drflac_uint64)(((drflac_int64)((pcmFrameIndex - pFlac->currentPCMFrame) * pFlac->channels * pFlac->bitsPerSample)/8.0f) * DRFLAC_BINARY_SEARCH_APPROX_COMPRESSION_RATIO); + if (targetByte > byteRangeHi) { + targetByte = byteRangeHi; + } + + for (;;) { + if (drflac__seek_to_approximate_flac_frame_to_byte(pFlac, targetByte, byteRangeLo, byteRangeHi, &lastSuccessfulSeekOffset)) { + /* We found a FLAC frame. We need to check if it contains the sample we're looking for. */ + drflac_uint64 newPCMRangeLo; + drflac_uint64 newPCMRangeHi; + drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &newPCMRangeLo, &newPCMRangeHi); + + /* If we selected the same frame, it means we should be pretty close. Just decode the rest. */ + if (pcmRangeLo == newPCMRangeLo) { + if (!drflac__seek_to_approximate_flac_frame_to_byte(pFlac, closestSeekOffsetBeforeTargetPCMFrame, closestSeekOffsetBeforeTargetPCMFrame, byteRangeHi, &lastSuccessfulSeekOffset)) { + break; /* Failed to seek to closest frame. */ + } + + if (drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame)) { + return DRFLAC_TRUE; + } else { + break; /* Failed to seek forward. */ + } + } + + pcmRangeLo = newPCMRangeLo; + pcmRangeHi = newPCMRangeHi; + + if (pcmRangeLo <= pcmFrameIndex && pcmRangeHi >= pcmFrameIndex) { + /* The target PCM frame is in this FLAC frame. */ + if (drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame) ) { + return DRFLAC_TRUE; + } else { + break; /* Failed to seek to FLAC frame. */ + } + } else { + const float approxCompressionRatio = (drflac_int64)(lastSuccessfulSeekOffset - pFlac->firstFLACFramePosInBytes) / ((drflac_int64)(pcmRangeLo * pFlac->channels * pFlac->bitsPerSample)/8.0f); + + if (pcmRangeLo > pcmFrameIndex) { + /* We seeked too far forward. We need to move our target byte backward and try again. */ + byteRangeHi = lastSuccessfulSeekOffset; + if (byteRangeLo > byteRangeHi) { + byteRangeLo = byteRangeHi; + } + + targetByte = byteRangeLo + ((byteRangeHi - byteRangeLo) / 2); + if (targetByte < byteRangeLo) { + targetByte = byteRangeLo; + } + } else /*if (pcmRangeHi < pcmFrameIndex)*/ { + /* We didn't seek far enough. We need to move our target byte forward and try again. */ + + /* If we're close enough we can just seek forward. */ + if ((pcmFrameIndex - pcmRangeLo) < seekForwardThreshold) { + if (drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame)) { + return DRFLAC_TRUE; + } else { + break; /* Failed to seek to FLAC frame. */ + } + } else { + byteRangeLo = lastSuccessfulSeekOffset; + if (byteRangeHi < byteRangeLo) { + byteRangeHi = byteRangeLo; + } + + targetByte = lastSuccessfulSeekOffset + (drflac_uint64)(((drflac_int64)((pcmFrameIndex-pcmRangeLo) * pFlac->channels * pFlac->bitsPerSample)/8.0f) * approxCompressionRatio); + if (targetByte > byteRangeHi) { + targetByte = byteRangeHi; + } + + if (closestSeekOffsetBeforeTargetPCMFrame < lastSuccessfulSeekOffset) { + closestSeekOffsetBeforeTargetPCMFrame = lastSuccessfulSeekOffset; + } + } + } + } + } else { + /* Getting here is really bad. We just recover as best we can, but moving to the first frame in the stream, and then abort. */ + break; + } + } + + drflac__seek_to_first_frame(pFlac); /* <-- Try to recover. */ + return DRFLAC_FALSE; +} + +static drflac_bool32 drflac__seek_to_pcm_frame__binary_search(drflac* pFlac, drflac_uint64 pcmFrameIndex) +{ + drflac_uint64 byteRangeLo; + drflac_uint64 byteRangeHi; + drflac_uint32 seekForwardThreshold = (pFlac->maxBlockSizeInPCMFrames != 0) ? pFlac->maxBlockSizeInPCMFrames*2 : 4096; + + /* Our algorithm currently assumes the FLAC stream is currently sitting at the start. */ + if (drflac__seek_to_first_frame(pFlac) == DRFLAC_FALSE) { + return DRFLAC_FALSE; + } + + /* If we're close enough to the start, just move to the start and seek forward. */ + if (pcmFrameIndex < seekForwardThreshold) { + return drflac__seek_forward_by_pcm_frames(pFlac, pcmFrameIndex) == pcmFrameIndex; + } + + /* + Our starting byte range is the byte position of the first FLAC frame and the approximate end of the file as if it were completely uncompressed. This ensures + the entire file is included, even though most of the time it'll exceed the end of the actual stream. This is OK as the frame searching logic will handle it. + */ + byteRangeLo = pFlac->firstFLACFramePosInBytes; + byteRangeHi = pFlac->firstFLACFramePosInBytes + (drflac_uint64)((drflac_int64)(pFlac->totalPCMFrameCount * pFlac->channels * pFlac->bitsPerSample)/8.0f); + + return drflac__seek_to_pcm_frame__binary_search_internal(pFlac, pcmFrameIndex, byteRangeLo, byteRangeHi); +} +#endif /* !DR_FLAC_NO_CRC */ + +static drflac_bool32 drflac__seek_to_pcm_frame__seek_table(drflac* pFlac, drflac_uint64 pcmFrameIndex) +{ + drflac_uint32 iClosestSeekpoint = 0; + drflac_bool32 isMidFrame = DRFLAC_FALSE; + drflac_uint64 runningPCMFrameCount; + drflac_uint32 iSeekpoint; + + + DRFLAC_ASSERT(pFlac != NULL); + + if (pFlac->pSeekpoints == NULL || pFlac->seekpointCount == 0) { + return DRFLAC_FALSE; + } + + /* Do not use the seektable if pcmFramIndex is not coverd by it. */ + if (pFlac->pSeekpoints[0].firstPCMFrame > pcmFrameIndex) { + return DRFLAC_FALSE; + } + + for (iSeekpoint = 0; iSeekpoint < pFlac->seekpointCount; ++iSeekpoint) { + if (pFlac->pSeekpoints[iSeekpoint].firstPCMFrame >= pcmFrameIndex) { + break; + } + + iClosestSeekpoint = iSeekpoint; + } + + /* There's been cases where the seek table contains only zeros. We need to do some basic validation on the closest seekpoint. */ + if (pFlac->pSeekpoints[iClosestSeekpoint].pcmFrameCount == 0 || pFlac->pSeekpoints[iClosestSeekpoint].pcmFrameCount > pFlac->maxBlockSizeInPCMFrames) { + return DRFLAC_FALSE; + } + if (pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame > pFlac->totalPCMFrameCount && pFlac->totalPCMFrameCount > 0) { + return DRFLAC_FALSE; + } + +#if !defined(DR_FLAC_NO_CRC) + /* At this point we should know the closest seek point. We can use a binary search for this. We need to know the total sample count for this. */ + if (pFlac->totalPCMFrameCount > 0) { + drflac_uint64 byteRangeLo; + drflac_uint64 byteRangeHi; + + byteRangeHi = pFlac->firstFLACFramePosInBytes + (drflac_uint64)((drflac_int64)(pFlac->totalPCMFrameCount * pFlac->channels * pFlac->bitsPerSample)/8.0f); + byteRangeLo = pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset; + + /* + If our closest seek point is not the last one, we only need to search between it and the next one. The section below calculates an appropriate starting + value for byteRangeHi which will clamp it appropriately. + + Note that the next seekpoint must have an offset greater than the closest seekpoint because otherwise our binary search algorithm will break down. There + have been cases where a seektable consists of seek points where every byte offset is set to 0 which causes problems. If this happens we need to abort. + */ + if (iClosestSeekpoint < pFlac->seekpointCount-1) { + drflac_uint32 iNextSeekpoint = iClosestSeekpoint + 1; + + /* Basic validation on the seekpoints to ensure they're usable. */ + if (pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset >= pFlac->pSeekpoints[iNextSeekpoint].flacFrameOffset || pFlac->pSeekpoints[iNextSeekpoint].pcmFrameCount == 0) { + return DRFLAC_FALSE; /* The next seekpoint doesn't look right. The seek table cannot be trusted from here. Abort. */ + } + + if (pFlac->pSeekpoints[iNextSeekpoint].firstPCMFrame != (((drflac_uint64)0xFFFFFFFF << 32) | 0xFFFFFFFF)) { /* Make sure it's not a placeholder seekpoint. */ + byteRangeHi = pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iNextSeekpoint].flacFrameOffset - 1; /* byteRangeHi must be zero based. */ + } + } + + if (drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset)) { + if (drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) { + drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &pFlac->currentPCMFrame, NULL); + + if (drflac__seek_to_pcm_frame__binary_search_internal(pFlac, pcmFrameIndex, byteRangeLo, byteRangeHi)) { + return DRFLAC_TRUE; + } + } + } + } +#endif /* !DR_FLAC_NO_CRC */ + + /* Getting here means we need to use a slower algorithm because the binary search method failed or cannot be used. */ + + /* + If we are seeking forward and the closest seekpoint is _before_ the current sample, we just seek forward from where we are. Otherwise we start seeking + from the seekpoint's first sample. + */ + if (pcmFrameIndex >= pFlac->currentPCMFrame && pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame <= pFlac->currentPCMFrame) { + /* Optimized case. Just seek forward from where we are. */ + runningPCMFrameCount = pFlac->currentPCMFrame; + + /* The frame header for the first frame may not yet have been read. We need to do that if necessary. */ + if (pFlac->currentPCMFrame == 0 && pFlac->currentFLACFrame.pcmFramesRemaining == 0) { + if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) { + return DRFLAC_FALSE; + } + } else { + isMidFrame = DRFLAC_TRUE; + } + } else { + /* Slower case. Seek to the start of the seekpoint and then seek forward from there. */ + runningPCMFrameCount = pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame; + + if (!drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset)) { + return DRFLAC_FALSE; + } + + /* Grab the frame the seekpoint is sitting on in preparation for the sample-exact seeking below. */ + if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) { + return DRFLAC_FALSE; + } + } + + for (;;) { + drflac_uint64 pcmFrameCountInThisFLACFrame; + drflac_uint64 firstPCMFrameInFLACFrame = 0; + drflac_uint64 lastPCMFrameInFLACFrame = 0; + + drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame); + + pcmFrameCountInThisFLACFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1; + if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFLACFrame)) { + /* + The sample should be in this frame. We need to fully decode it, but if it's an invalid frame (a CRC mismatch) we need to pretend + it never existed and keep iterating. + */ + drflac_uint64 pcmFramesToDecode = pcmFrameIndex - runningPCMFrameCount; + + if (!isMidFrame) { + drflac_result result = drflac__decode_flac_frame(pFlac); + if (result == DRFLAC_SUCCESS) { + /* The frame is valid. We just need to skip over some samples to ensure it's sample-exact. */ + return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode; /* <-- If this fails, something bad has happened (it should never fail). */ + } else { + if (result == DRFLAC_CRC_MISMATCH) { + goto next_iteration; /* CRC mismatch. Pretend this frame never existed. */ + } else { + return DRFLAC_FALSE; + } + } + } else { + /* We started seeking mid-frame which means we need to skip the frame decoding part. */ + return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode; + } + } else { + /* + It's not in this frame. We need to seek past the frame, but check if there was a CRC mismatch. If so, we pretend this + frame never existed and leave the running sample count untouched. + */ + if (!isMidFrame) { + drflac_result result = drflac__seek_to_next_flac_frame(pFlac); + if (result == DRFLAC_SUCCESS) { + runningPCMFrameCount += pcmFrameCountInThisFLACFrame; + } else { + if (result == DRFLAC_CRC_MISMATCH) { + goto next_iteration; /* CRC mismatch. Pretend this frame never existed. */ + } else { + return DRFLAC_FALSE; + } + } + } else { + /* + We started seeking mid-frame which means we need to seek by reading to the end of the frame instead of with + drflac__seek_to_next_flac_frame() which only works if the decoder is sitting on the byte just after the frame header. + */ + runningPCMFrameCount += pFlac->currentFLACFrame.pcmFramesRemaining; + pFlac->currentFLACFrame.pcmFramesRemaining = 0; + isMidFrame = DRFLAC_FALSE; + } + + /* If we are seeking to the end of the file and we've just hit it, we're done. */ + if (pcmFrameIndex == pFlac->totalPCMFrameCount && runningPCMFrameCount == pFlac->totalPCMFrameCount) { + return DRFLAC_TRUE; + } + } + + next_iteration: + /* Grab the next frame in preparation for the next iteration. */ + if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) { + return DRFLAC_FALSE; + } + } +} + + +#ifndef DR_FLAC_NO_OGG +typedef struct +{ + drflac_uint8 capturePattern[4]; /* Should be "OggS" */ + drflac_uint8 structureVersion; /* Always 0. */ + drflac_uint8 headerType; + drflac_uint64 granulePosition; + drflac_uint32 serialNumber; + drflac_uint32 sequenceNumber; + drflac_uint32 checksum; + drflac_uint8 segmentCount; + drflac_uint8 segmentTable[255]; +} drflac_ogg_page_header; +#endif + +typedef struct +{ + drflac_read_proc onRead; + drflac_seek_proc onSeek; + drflac_tell_proc onTell; + drflac_meta_proc onMeta; + drflac_container container; + void* pUserData; + void* pUserDataMD; + drflac_uint32 sampleRate; + drflac_uint8 channels; + drflac_uint8 bitsPerSample; + drflac_uint64 totalPCMFrameCount; + drflac_uint16 maxBlockSizeInPCMFrames; + drflac_uint64 runningFilePos; + drflac_bool32 hasStreamInfoBlock; + drflac_bool32 hasMetadataBlocks; + drflac_bs bs; /* <-- A bit streamer is required for loading data during initialization. */ + drflac_frame_header firstFrameHeader; /* <-- The header of the first frame that was read during relaxed initalization. Only set if there is no STREAMINFO block. */ + +#ifndef DR_FLAC_NO_OGG + drflac_uint32 oggSerial; + drflac_uint64 oggFirstBytePos; + drflac_ogg_page_header oggBosHeader; +#endif +} drflac_init_info; + +static DRFLAC_INLINE void drflac__decode_block_header(drflac_uint32 blockHeader, drflac_uint8* isLastBlock, drflac_uint8* blockType, drflac_uint32* blockSize) +{ + blockHeader = drflac__be2host_32(blockHeader); + *isLastBlock = (drflac_uint8)((blockHeader & 0x80000000UL) >> 31); + *blockType = (drflac_uint8)((blockHeader & 0x7F000000UL) >> 24); + *blockSize = (blockHeader & 0x00FFFFFFUL); +} + +static DRFLAC_INLINE drflac_bool32 drflac__read_and_decode_block_header(drflac_read_proc onRead, void* pUserData, drflac_uint8* isLastBlock, drflac_uint8* blockType, drflac_uint32* blockSize) +{ + drflac_uint32 blockHeader; + + *blockSize = 0; + if (onRead(pUserData, &blockHeader, 4) != 4) { + return DRFLAC_FALSE; + } + + drflac__decode_block_header(blockHeader, isLastBlock, blockType, blockSize); + return DRFLAC_TRUE; +} + +static drflac_bool32 drflac__read_streaminfo(drflac_read_proc onRead, void* pUserData, drflac_streaminfo* pStreamInfo) +{ + drflac_uint32 blockSizes; + drflac_uint64 frameSizes = 0; + drflac_uint64 importantProps; + drflac_uint8 md5[16]; + + /* min/max block size. */ + if (onRead(pUserData, &blockSizes, 4) != 4) { + return DRFLAC_FALSE; + } + + /* min/max frame size. */ + if (onRead(pUserData, &frameSizes, 6) != 6) { + return DRFLAC_FALSE; + } + + /* Sample rate, channels, bits per sample and total sample count. */ + if (onRead(pUserData, &importantProps, 8) != 8) { + return DRFLAC_FALSE; + } + + /* MD5 */ + if (onRead(pUserData, md5, sizeof(md5)) != sizeof(md5)) { + return DRFLAC_FALSE; + } + + blockSizes = drflac__be2host_32(blockSizes); + frameSizes = drflac__be2host_64(frameSizes); + importantProps = drflac__be2host_64(importantProps); + + pStreamInfo->minBlockSizeInPCMFrames = (drflac_uint16)((blockSizes & 0xFFFF0000) >> 16); + pStreamInfo->maxBlockSizeInPCMFrames = (drflac_uint16) (blockSizes & 0x0000FFFF); + pStreamInfo->minFrameSizeInPCMFrames = (drflac_uint32)((frameSizes & (((drflac_uint64)0x00FFFFFF << 16) << 24)) >> 40); + pStreamInfo->maxFrameSizeInPCMFrames = (drflac_uint32)((frameSizes & (((drflac_uint64)0x00FFFFFF << 16) << 0)) >> 16); + pStreamInfo->sampleRate = (drflac_uint32)((importantProps & (((drflac_uint64)0x000FFFFF << 16) << 28)) >> 44); + pStreamInfo->channels = (drflac_uint8 )((importantProps & (((drflac_uint64)0x0000000E << 16) << 24)) >> 41) + 1; + pStreamInfo->bitsPerSample = (drflac_uint8 )((importantProps & (((drflac_uint64)0x0000001F << 16) << 20)) >> 36) + 1; + pStreamInfo->totalPCMFrameCount = ((importantProps & ((((drflac_uint64)0x0000000F << 16) << 16) | 0xFFFFFFFF))); + DRFLAC_COPY_MEMORY(pStreamInfo->md5, md5, sizeof(md5)); + + return DRFLAC_TRUE; +} + + +static void* drflac__malloc_default(size_t sz, void* pUserData) +{ + (void)pUserData; + return DRFLAC_MALLOC(sz); +} + +static void* drflac__realloc_default(void* p, size_t sz, void* pUserData) +{ + (void)pUserData; + return DRFLAC_REALLOC(p, sz); +} + +static void drflac__free_default(void* p, void* pUserData) +{ + (void)pUserData; + DRFLAC_FREE(p); +} + + +static void* drflac__malloc_from_callbacks(size_t sz, const drflac_allocation_callbacks* pAllocationCallbacks) +{ + if (pAllocationCallbacks == NULL) { + return NULL; + } + + if (pAllocationCallbacks->onMalloc != NULL) { + return pAllocationCallbacks->onMalloc(sz, pAllocationCallbacks->pUserData); + } + + /* Try using realloc(). */ + if (pAllocationCallbacks->onRealloc != NULL) { + return pAllocationCallbacks->onRealloc(NULL, sz, pAllocationCallbacks->pUserData); + } + + return NULL; +} + +static void* drflac__realloc_from_callbacks(void* p, size_t szNew, size_t szOld, const drflac_allocation_callbacks* pAllocationCallbacks) +{ + if (pAllocationCallbacks == NULL) { + return NULL; + } + + if (pAllocationCallbacks->onRealloc != NULL) { + return pAllocationCallbacks->onRealloc(p, szNew, pAllocationCallbacks->pUserData); + } + + /* Try emulating realloc() in terms of malloc()/free(). */ + if (pAllocationCallbacks->onMalloc != NULL && pAllocationCallbacks->onFree != NULL) { + void* p2; + + p2 = pAllocationCallbacks->onMalloc(szNew, pAllocationCallbacks->pUserData); + if (p2 == NULL) { + return NULL; + } + + if (p != NULL) { + DRFLAC_COPY_MEMORY(p2, p, szOld); + pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData); + } + + return p2; + } + + return NULL; +} + +static void drflac__free_from_callbacks(void* p, const drflac_allocation_callbacks* pAllocationCallbacks) +{ + if (p == NULL || pAllocationCallbacks == NULL) { + return; + } + + if (pAllocationCallbacks->onFree != NULL) { + pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData); + } +} + + +static drflac_bool32 drflac__read_and_decode_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, drflac_meta_proc onMeta, void* pUserData, void* pUserDataMD, drflac_uint64* pFirstFramePos, drflac_uint64* pSeektablePos, drflac_uint32* pSeekpointCount, drflac_allocation_callbacks* pAllocationCallbacks) +{ + /* + We want to keep track of the byte position in the stream of the seektable. At the time of calling this function we know that + we'll be sitting on byte 42. + */ + drflac_uint64 runningFilePos = 42; + drflac_uint64 seektablePos = 0; + drflac_uint32 seektableSize = 0; + + (void)onTell; + + for (;;) { + drflac_metadata metadata; + drflac_uint8 isLastBlock = 0; + drflac_uint8 blockType = 0; + drflac_uint32 blockSize; + if (drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize) == DRFLAC_FALSE) { + return DRFLAC_FALSE; + } + runningFilePos += 4; + + metadata.type = blockType; + metadata.rawDataSize = 0; + metadata.rawDataOffset = runningFilePos; + metadata.pRawData = NULL; + + switch (blockType) + { + case DRFLAC_METADATA_BLOCK_TYPE_APPLICATION: + { + if (blockSize < 4) { + return DRFLAC_FALSE; + } + + if (onMeta) { + void* pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks); + if (pRawData == NULL) { + return DRFLAC_FALSE; + } + + if (onRead(pUserData, pRawData, blockSize) != blockSize) { + drflac__free_from_callbacks(pRawData, pAllocationCallbacks); + return DRFLAC_FALSE; + } + + metadata.pRawData = pRawData; + metadata.rawDataSize = blockSize; + metadata.data.application.id = drflac__be2host_32(*(drflac_uint32*)pRawData); + metadata.data.application.pData = (const void*)((drflac_uint8*)pRawData + sizeof(drflac_uint32)); + metadata.data.application.dataSize = blockSize - sizeof(drflac_uint32); + onMeta(pUserDataMD, &metadata); + + drflac__free_from_callbacks(pRawData, pAllocationCallbacks); + } + } break; + + case DRFLAC_METADATA_BLOCK_TYPE_SEEKTABLE: + { + seektablePos = runningFilePos; + seektableSize = blockSize; + + if (onMeta) { + drflac_uint32 seekpointCount; + drflac_uint32 iSeekpoint; + void* pRawData; + + seekpointCount = blockSize/DRFLAC_SEEKPOINT_SIZE_IN_BYTES; + + pRawData = drflac__malloc_from_callbacks(seekpointCount * sizeof(drflac_seekpoint), pAllocationCallbacks); + if (pRawData == NULL) { + return DRFLAC_FALSE; + } + + /* We need to read seekpoint by seekpoint and do some processing. */ + for (iSeekpoint = 0; iSeekpoint < seekpointCount; ++iSeekpoint) { + drflac_seekpoint* pSeekpoint = (drflac_seekpoint*)pRawData + iSeekpoint; + + if (onRead(pUserData, pSeekpoint, DRFLAC_SEEKPOINT_SIZE_IN_BYTES) != DRFLAC_SEEKPOINT_SIZE_IN_BYTES) { + drflac__free_from_callbacks(pRawData, pAllocationCallbacks); + return DRFLAC_FALSE; + } + + /* Endian swap. */ + pSeekpoint->firstPCMFrame = drflac__be2host_64(pSeekpoint->firstPCMFrame); + pSeekpoint->flacFrameOffset = drflac__be2host_64(pSeekpoint->flacFrameOffset); + pSeekpoint->pcmFrameCount = drflac__be2host_16(pSeekpoint->pcmFrameCount); + } + + metadata.pRawData = pRawData; + metadata.rawDataSize = blockSize; + metadata.data.seektable.seekpointCount = seekpointCount; + metadata.data.seektable.pSeekpoints = (const drflac_seekpoint*)pRawData; + + onMeta(pUserDataMD, &metadata); + + drflac__free_from_callbacks(pRawData, pAllocationCallbacks); + } + } break; + + case DRFLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT: + { + if (blockSize < 8) { + return DRFLAC_FALSE; + } + + if (onMeta) { + void* pRawData; + const char* pRunningData; + const char* pRunningDataEnd; + drflac_uint32 i; + + pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks); + if (pRawData == NULL) { + return DRFLAC_FALSE; + } + + if (onRead(pUserData, pRawData, blockSize) != blockSize) { + drflac__free_from_callbacks(pRawData, pAllocationCallbacks); + return DRFLAC_FALSE; + } + + metadata.pRawData = pRawData; + metadata.rawDataSize = blockSize; + + pRunningData = (const char*)pRawData; + pRunningDataEnd = (const char*)pRawData + blockSize; + + metadata.data.vorbis_comment.vendorLength = drflac__le2host_32_ptr_unaligned(pRunningData); pRunningData += 4; + + /* Need space for the rest of the block */ + if ((pRunningDataEnd - pRunningData) - 4 < (drflac_int64)metadata.data.vorbis_comment.vendorLength) { /* <-- Note the order of operations to avoid overflow to a valid value */ + drflac__free_from_callbacks(pRawData, pAllocationCallbacks); + return DRFLAC_FALSE; + } + metadata.data.vorbis_comment.vendor = pRunningData; pRunningData += metadata.data.vorbis_comment.vendorLength; + metadata.data.vorbis_comment.commentCount = drflac__le2host_32_ptr_unaligned(pRunningData); pRunningData += 4; + + /* Need space for 'commentCount' comments after the block, which at minimum is a drflac_uint32 per comment */ + if ((pRunningDataEnd - pRunningData) / sizeof(drflac_uint32) < metadata.data.vorbis_comment.commentCount) { /* <-- Note the order of operations to avoid overflow to a valid value */ + drflac__free_from_callbacks(pRawData, pAllocationCallbacks); + return DRFLAC_FALSE; + } + metadata.data.vorbis_comment.pComments = pRunningData; + + /* Check that the comments section is valid before passing it to the callback */ + for (i = 0; i < metadata.data.vorbis_comment.commentCount; ++i) { + drflac_uint32 commentLength; + + if (pRunningDataEnd - pRunningData < 4) { + drflac__free_from_callbacks(pRawData, pAllocationCallbacks); + return DRFLAC_FALSE; + } + + commentLength = drflac__le2host_32_ptr_unaligned(pRunningData); pRunningData += 4; + if (pRunningDataEnd - pRunningData < (drflac_int64)commentLength) { /* <-- Note the order of operations to avoid overflow to a valid value */ + drflac__free_from_callbacks(pRawData, pAllocationCallbacks); + return DRFLAC_FALSE; + } + pRunningData += commentLength; + } + + onMeta(pUserDataMD, &metadata); + + drflac__free_from_callbacks(pRawData, pAllocationCallbacks); + } + } break; + + case DRFLAC_METADATA_BLOCK_TYPE_CUESHEET: + { + if (blockSize < 396) { + return DRFLAC_FALSE; + } + + if (onMeta) { + void* pRawData; + const char* pRunningData; + const char* pRunningDataEnd; + size_t bufferSize; + drflac_uint8 iTrack; + drflac_uint8 iIndex; + void* pTrackData; + + /* + This needs to be loaded in two passes. The first pass is used to calculate the size of the memory allocation + we need for storing the necessary data. The second pass will fill that buffer with usable data. + */ + pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks); + if (pRawData == NULL) { + return DRFLAC_FALSE; + } + + if (onRead(pUserData, pRawData, blockSize) != blockSize) { + drflac__free_from_callbacks(pRawData, pAllocationCallbacks); + return DRFLAC_FALSE; + } + + metadata.pRawData = pRawData; + metadata.rawDataSize = blockSize; + + pRunningData = (const char*)pRawData; + pRunningDataEnd = (const char*)pRawData + blockSize; + + DRFLAC_COPY_MEMORY(metadata.data.cuesheet.catalog, pRunningData, 128); pRunningData += 128; + metadata.data.cuesheet.leadInSampleCount = drflac__be2host_64(*(const drflac_uint64*)pRunningData); pRunningData += 8; + metadata.data.cuesheet.isCD = (pRunningData[0] & 0x80) != 0; pRunningData += 259; + metadata.data.cuesheet.trackCount = pRunningData[0]; pRunningData += 1; + metadata.data.cuesheet.pTrackData = NULL; /* Will be filled later. */ + + /* Pass 1: Calculate the size of the buffer for the track data. */ + { + const char* pRunningDataSaved = pRunningData; /* Will be restored at the end in preparation for the second pass. */ + + bufferSize = metadata.data.cuesheet.trackCount * DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES; + + for (iTrack = 0; iTrack < metadata.data.cuesheet.trackCount; ++iTrack) { + drflac_uint8 indexCount; + drflac_uint32 indexPointSize; + + if (pRunningDataEnd - pRunningData < DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES) { + drflac__free_from_callbacks(pRawData, pAllocationCallbacks); + return DRFLAC_FALSE; + } + + /* Skip to the index point count */ + pRunningData += 35; + + indexCount = pRunningData[0]; + pRunningData += 1; + + bufferSize += indexCount * sizeof(drflac_cuesheet_track_index); + + /* Quick validation check. */ + indexPointSize = indexCount * DRFLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES; + if (pRunningDataEnd - pRunningData < (drflac_int64)indexPointSize) { + drflac__free_from_callbacks(pRawData, pAllocationCallbacks); + return DRFLAC_FALSE; + } + + pRunningData += indexPointSize; + } + + pRunningData = pRunningDataSaved; + } + + /* Pass 2: Allocate a buffer and fill the data. Validation was done in the step above so can be skipped. */ + { + char* pRunningTrackData; + + pTrackData = drflac__malloc_from_callbacks(bufferSize, pAllocationCallbacks); + if (pTrackData == NULL) { + drflac__free_from_callbacks(pRawData, pAllocationCallbacks); + return DRFLAC_FALSE; + } + + pRunningTrackData = (char*)pTrackData; + + for (iTrack = 0; iTrack < metadata.data.cuesheet.trackCount; ++iTrack) { + drflac_uint8 indexCount; + + DRFLAC_COPY_MEMORY(pRunningTrackData, pRunningData, DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES); + pRunningData += DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES-1; /* Skip forward, but not beyond the last byte in the CUESHEET_TRACK block which is the index count. */ + pRunningTrackData += DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES-1; + + /* Grab the index count for the next part. */ + indexCount = pRunningData[0]; + pRunningData += 1; + pRunningTrackData += 1; + + /* Extract each track index. */ + for (iIndex = 0; iIndex < indexCount; ++iIndex) { + drflac_cuesheet_track_index* pTrackIndex = (drflac_cuesheet_track_index*)pRunningTrackData; + + DRFLAC_COPY_MEMORY(pRunningTrackData, pRunningData, DRFLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES); + pRunningData += DRFLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES; + pRunningTrackData += sizeof(drflac_cuesheet_track_index); + + pTrackIndex->offset = drflac__be2host_64(pTrackIndex->offset); + } + } + + metadata.data.cuesheet.pTrackData = pTrackData; + } + + /* The original data is no longer needed. */ + drflac__free_from_callbacks(pRawData, pAllocationCallbacks); + pRawData = NULL; + + onMeta(pUserDataMD, &metadata); + + drflac__free_from_callbacks(pTrackData, pAllocationCallbacks); + pTrackData = NULL; + } + } break; + + case DRFLAC_METADATA_BLOCK_TYPE_PICTURE: + { + if (blockSize < 32) { + return DRFLAC_FALSE; + } + + if (onMeta) { + drflac_bool32 result = DRFLAC_TRUE; + drflac_uint32 blockSizeRemaining = blockSize; + char* pMime = NULL; + char* pDescription = NULL; + void* pPictureData = NULL; + + if (blockSizeRemaining < 4 || onRead(pUserData, &metadata.data.picture.type, 4) != 4) { + result = DRFLAC_FALSE; + goto done_flac; + } + blockSizeRemaining -= 4; + metadata.data.picture.type = drflac__be2host_32(metadata.data.picture.type); + + + if (blockSizeRemaining < 4 || onRead(pUserData, &metadata.data.picture.mimeLength, 4) != 4) { + result = DRFLAC_FALSE; + goto done_flac; + } + blockSizeRemaining -= 4; + metadata.data.picture.mimeLength = drflac__be2host_32(metadata.data.picture.mimeLength); + + pMime = (char*)drflac__malloc_from_callbacks(metadata.data.picture.mimeLength + 1, pAllocationCallbacks); /* +1 for null terminator. */ + if (pMime == NULL) { + result = DRFLAC_FALSE; + goto done_flac; + } + + if (blockSizeRemaining < metadata.data.picture.mimeLength || onRead(pUserData, pMime, metadata.data.picture.mimeLength) != metadata.data.picture.mimeLength) { + result = DRFLAC_FALSE; + goto done_flac; + } + blockSizeRemaining -= metadata.data.picture.mimeLength; + pMime[metadata.data.picture.mimeLength] = '\0'; /* Null terminate for safety. */ + metadata.data.picture.mime = (const char*)pMime; + + + if (blockSizeRemaining < 4 || onRead(pUserData, &metadata.data.picture.descriptionLength, 4) != 4) { + result = DRFLAC_FALSE; + goto done_flac; + } + blockSizeRemaining -= 4; + metadata.data.picture.descriptionLength = drflac__be2host_32(metadata.data.picture.descriptionLength); + + pDescription = (char*)drflac__malloc_from_callbacks(metadata.data.picture.descriptionLength + 1, pAllocationCallbacks); /* +1 for null terminator. */ + if (pDescription == NULL) { + result = DRFLAC_FALSE; + goto done_flac; + } + + if (blockSizeRemaining < metadata.data.picture.descriptionLength || onRead(pUserData, pDescription, metadata.data.picture.descriptionLength) != metadata.data.picture.descriptionLength) { + result = DRFLAC_FALSE; + goto done_flac; + } + blockSizeRemaining -= metadata.data.picture.descriptionLength; + pDescription[metadata.data.picture.descriptionLength] = '\0'; /* Null terminate for safety. */ + metadata.data.picture.description = (const char*)pDescription; + + + if (blockSizeRemaining < 4 || onRead(pUserData, &metadata.data.picture.width, 4) != 4) { + result = DRFLAC_FALSE; + goto done_flac; + } + blockSizeRemaining -= 4; + metadata.data.picture.width = drflac__be2host_32(metadata.data.picture.width); + + if (blockSizeRemaining < 4 || onRead(pUserData, &metadata.data.picture.height, 4) != 4) { + result = DRFLAC_FALSE; + goto done_flac; + } + blockSizeRemaining -= 4; + metadata.data.picture.height = drflac__be2host_32(metadata.data.picture.height); + + if (blockSizeRemaining < 4 || onRead(pUserData, &metadata.data.picture.colorDepth, 4) != 4) { + result = DRFLAC_FALSE; + goto done_flac; + } + blockSizeRemaining -= 4; + metadata.data.picture.colorDepth = drflac__be2host_32(metadata.data.picture.colorDepth); + + if (blockSizeRemaining < 4 || onRead(pUserData, &metadata.data.picture.indexColorCount, 4) != 4) { + result = DRFLAC_FALSE; + goto done_flac; + } + blockSizeRemaining -= 4; + metadata.data.picture.indexColorCount = drflac__be2host_32(metadata.data.picture.indexColorCount); + + + /* Picture data. */ + if (blockSizeRemaining < 4 || onRead(pUserData, &metadata.data.picture.pictureDataSize, 4) != 4) { + result = DRFLAC_FALSE; + goto done_flac; + } + blockSizeRemaining -= 4; + metadata.data.picture.pictureDataSize = drflac__be2host_32(metadata.data.picture.pictureDataSize); + + if (blockSizeRemaining < metadata.data.picture.pictureDataSize) { + result = DRFLAC_FALSE; + goto done_flac; + } + + /* For the actual image data we want to store the offset to the start of the stream. */ + metadata.data.picture.pictureDataOffset = runningFilePos + (blockSize - blockSizeRemaining); + + /* + For the allocation of image data, we can allow memory allocation to fail, in which case we just leave + the pointer as null. If it fails, we need to fall back to seeking past the image data. + */ + #ifndef DR_FLAC_NO_PICTURE_METADATA_MALLOC + pPictureData = drflac__malloc_from_callbacks(metadata.data.picture.pictureDataSize, pAllocationCallbacks); + if (pPictureData != NULL) { + if (onRead(pUserData, pPictureData, metadata.data.picture.pictureDataSize) != metadata.data.picture.pictureDataSize) { + result = DRFLAC_FALSE; + goto done_flac; + } + } else + #endif + { + /* Allocation failed. We need to seek past the picture data. */ + if (!onSeek(pUserData, metadata.data.picture.pictureDataSize, DRFLAC_SEEK_CUR)) { + result = DRFLAC_FALSE; + goto done_flac; + } + } + + blockSizeRemaining -= metadata.data.picture.pictureDataSize; + (void)blockSizeRemaining; + + metadata.data.picture.pPictureData = (const drflac_uint8*)pPictureData; + + + /* Only fire the callback if we actually have a way to read the image data. We must have either a valid offset, or a valid data pointer. */ + if (metadata.data.picture.pictureDataOffset != 0 || metadata.data.picture.pPictureData != NULL) { + onMeta(pUserDataMD, &metadata); + } else { + /* Don't have a valid offset or data pointer, so just pretend we don't have a picture metadata. */ + } + + done_flac: + drflac__free_from_callbacks(pMime, pAllocationCallbacks); + drflac__free_from_callbacks(pDescription, pAllocationCallbacks); + drflac__free_from_callbacks(pPictureData, pAllocationCallbacks); + + if (result != DRFLAC_TRUE) { + return DRFLAC_FALSE; + } + } + } break; + + case DRFLAC_METADATA_BLOCK_TYPE_PADDING: + { + if (onMeta) { + metadata.data.padding.unused = 0; + + /* Padding doesn't have anything meaningful in it, so just skip over it, but make sure the caller is aware of it by firing the callback. */ + if (!onSeek(pUserData, blockSize, DRFLAC_SEEK_CUR)) { + isLastBlock = DRFLAC_TRUE; /* An error occurred while seeking. Attempt to recover by treating this as the last block which will in turn terminate the loop. */ + } else { + onMeta(pUserDataMD, &metadata); + } + } + } break; + + case DRFLAC_METADATA_BLOCK_TYPE_INVALID: + { + /* Invalid chunk. Just skip over this one. */ + if (onMeta) { + if (!onSeek(pUserData, blockSize, DRFLAC_SEEK_CUR)) { + isLastBlock = DRFLAC_TRUE; /* An error occurred while seeking. Attempt to recover by treating this as the last block which will in turn terminate the loop. */ + } + } + } break; + + default: + { + /* + It's an unknown chunk, but not necessarily invalid. There's a chance more metadata blocks might be defined later on, so we + can at the very least report the chunk to the application and let it look at the raw data. + */ + if (onMeta) { + void* pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks); + if (pRawData != NULL) { + if (onRead(pUserData, pRawData, blockSize) != blockSize) { + drflac__free_from_callbacks(pRawData, pAllocationCallbacks); + return DRFLAC_FALSE; + } + } else { + /* Allocation failed. We need to seek past the block. */ + if (!onSeek(pUserData, blockSize, DRFLAC_SEEK_CUR)) { + return DRFLAC_FALSE; + } + } + + metadata.pRawData = pRawData; + metadata.rawDataSize = blockSize; + onMeta(pUserDataMD, &metadata); + + drflac__free_from_callbacks(pRawData, pAllocationCallbacks); + } + } break; + } + + /* If we're not handling metadata, just skip over the block. If we are, it will have been handled earlier in the switch statement above. */ + if (onMeta == NULL && blockSize > 0) { + if (!onSeek(pUserData, blockSize, DRFLAC_SEEK_CUR)) { + isLastBlock = DRFLAC_TRUE; + } + } + + runningFilePos += blockSize; + if (isLastBlock) { + break; + } + } + + *pSeektablePos = seektablePos; + *pSeekpointCount = seektableSize / DRFLAC_SEEKPOINT_SIZE_IN_BYTES; + *pFirstFramePos = runningFilePos; + + return DRFLAC_TRUE; +} + +static drflac_bool32 drflac__init_private__native(drflac_init_info* pInit, drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, void* pUserDataMD, drflac_bool32 relaxed) +{ + /* Pre Condition: The bit stream should be sitting just past the 4-byte id header. */ + + drflac_uint8 isLastBlock; + drflac_uint8 blockType; + drflac_uint32 blockSize; + + (void)onSeek; + + pInit->container = drflac_container_native; + + /* The first metadata block should be the STREAMINFO block. */ + if (!drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize)) { + return DRFLAC_FALSE; + } + + if (blockType != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) { + if (!relaxed) { + /* We're opening in strict mode and the first block is not the STREAMINFO block. Error. */ + return DRFLAC_FALSE; + } else { + /* + Relaxed mode. To open from here we need to just find the first frame and set the sample rate, etc. to whatever is defined + for that frame. + */ + pInit->hasStreamInfoBlock = DRFLAC_FALSE; + pInit->hasMetadataBlocks = DRFLAC_FALSE; + + if (!drflac__read_next_flac_frame_header(&pInit->bs, 0, &pInit->firstFrameHeader)) { + return DRFLAC_FALSE; /* Couldn't find a frame. */ + } + + if (pInit->firstFrameHeader.bitsPerSample == 0) { + return DRFLAC_FALSE; /* Failed to initialize because the first frame depends on the STREAMINFO block, which does not exist. */ + } + + pInit->sampleRate = pInit->firstFrameHeader.sampleRate; + pInit->channels = drflac__get_channel_count_from_channel_assignment(pInit->firstFrameHeader.channelAssignment); + pInit->bitsPerSample = pInit->firstFrameHeader.bitsPerSample; + pInit->maxBlockSizeInPCMFrames = 65535; /* <-- See notes here: https://xiph.org/flac/format.html#metadata_block_streaminfo */ + return DRFLAC_TRUE; + } + } else { + drflac_streaminfo streaminfo; + if (!drflac__read_streaminfo(onRead, pUserData, &streaminfo)) { + return DRFLAC_FALSE; + } + + pInit->hasStreamInfoBlock = DRFLAC_TRUE; + pInit->sampleRate = streaminfo.sampleRate; + pInit->channels = streaminfo.channels; + pInit->bitsPerSample = streaminfo.bitsPerSample; + pInit->totalPCMFrameCount = streaminfo.totalPCMFrameCount; + pInit->maxBlockSizeInPCMFrames = streaminfo.maxBlockSizeInPCMFrames; /* Don't care about the min block size - only the max (used for determining the size of the memory allocation). */ + pInit->hasMetadataBlocks = !isLastBlock; + + if (onMeta) { + drflac_metadata metadata; + metadata.type = DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO; + metadata.pRawData = NULL; + metadata.rawDataSize = 0; + metadata.data.streaminfo = streaminfo; + onMeta(pUserDataMD, &metadata); + } + + return DRFLAC_TRUE; + } +} + +#ifndef DR_FLAC_NO_OGG +#define DRFLAC_OGG_MAX_PAGE_SIZE 65307 +#define DRFLAC_OGG_CAPTURE_PATTERN_CRC32 1605413199 /* CRC-32 of "OggS". */ + +typedef enum +{ + drflac_ogg_recover_on_crc_mismatch, + drflac_ogg_fail_on_crc_mismatch +} drflac_ogg_crc_mismatch_recovery; + +#ifndef DR_FLAC_NO_CRC +static drflac_uint32 drflac__crc32_table[] = { + 0x00000000L, 0x04C11DB7L, 0x09823B6EL, 0x0D4326D9L, + 0x130476DCL, 0x17C56B6BL, 0x1A864DB2L, 0x1E475005L, + 0x2608EDB8L, 0x22C9F00FL, 0x2F8AD6D6L, 0x2B4BCB61L, + 0x350C9B64L, 0x31CD86D3L, 0x3C8EA00AL, 0x384FBDBDL, + 0x4C11DB70L, 0x48D0C6C7L, 0x4593E01EL, 0x4152FDA9L, + 0x5F15ADACL, 0x5BD4B01BL, 0x569796C2L, 0x52568B75L, + 0x6A1936C8L, 0x6ED82B7FL, 0x639B0DA6L, 0x675A1011L, + 0x791D4014L, 0x7DDC5DA3L, 0x709F7B7AL, 0x745E66CDL, + 0x9823B6E0L, 0x9CE2AB57L, 0x91A18D8EL, 0x95609039L, + 0x8B27C03CL, 0x8FE6DD8BL, 0x82A5FB52L, 0x8664E6E5L, + 0xBE2B5B58L, 0xBAEA46EFL, 0xB7A96036L, 0xB3687D81L, + 0xAD2F2D84L, 0xA9EE3033L, 0xA4AD16EAL, 0xA06C0B5DL, + 0xD4326D90L, 0xD0F37027L, 0xDDB056FEL, 0xD9714B49L, + 0xC7361B4CL, 0xC3F706FBL, 0xCEB42022L, 0xCA753D95L, + 0xF23A8028L, 0xF6FB9D9FL, 0xFBB8BB46L, 0xFF79A6F1L, + 0xE13EF6F4L, 0xE5FFEB43L, 0xE8BCCD9AL, 0xEC7DD02DL, + 0x34867077L, 0x30476DC0L, 0x3D044B19L, 0x39C556AEL, + 0x278206ABL, 0x23431B1CL, 0x2E003DC5L, 0x2AC12072L, + 0x128E9DCFL, 0x164F8078L, 0x1B0CA6A1L, 0x1FCDBB16L, + 0x018AEB13L, 0x054BF6A4L, 0x0808D07DL, 0x0CC9CDCAL, + 0x7897AB07L, 0x7C56B6B0L, 0x71159069L, 0x75D48DDEL, + 0x6B93DDDBL, 0x6F52C06CL, 0x6211E6B5L, 0x66D0FB02L, + 0x5E9F46BFL, 0x5A5E5B08L, 0x571D7DD1L, 0x53DC6066L, + 0x4D9B3063L, 0x495A2DD4L, 0x44190B0DL, 0x40D816BAL, + 0xACA5C697L, 0xA864DB20L, 0xA527FDF9L, 0xA1E6E04EL, + 0xBFA1B04BL, 0xBB60ADFCL, 0xB6238B25L, 0xB2E29692L, + 0x8AAD2B2FL, 0x8E6C3698L, 0x832F1041L, 0x87EE0DF6L, + 0x99A95DF3L, 0x9D684044L, 0x902B669DL, 0x94EA7B2AL, + 0xE0B41DE7L, 0xE4750050L, 0xE9362689L, 0xEDF73B3EL, + 0xF3B06B3BL, 0xF771768CL, 0xFA325055L, 0xFEF34DE2L, + 0xC6BCF05FL, 0xC27DEDE8L, 0xCF3ECB31L, 0xCBFFD686L, + 0xD5B88683L, 0xD1799B34L, 0xDC3ABDEDL, 0xD8FBA05AL, + 0x690CE0EEL, 0x6DCDFD59L, 0x608EDB80L, 0x644FC637L, + 0x7A089632L, 0x7EC98B85L, 0x738AAD5CL, 0x774BB0EBL, + 0x4F040D56L, 0x4BC510E1L, 0x46863638L, 0x42472B8FL, + 0x5C007B8AL, 0x58C1663DL, 0x558240E4L, 0x51435D53L, + 0x251D3B9EL, 0x21DC2629L, 0x2C9F00F0L, 0x285E1D47L, + 0x36194D42L, 0x32D850F5L, 0x3F9B762CL, 0x3B5A6B9BL, + 0x0315D626L, 0x07D4CB91L, 0x0A97ED48L, 0x0E56F0FFL, + 0x1011A0FAL, 0x14D0BD4DL, 0x19939B94L, 0x1D528623L, + 0xF12F560EL, 0xF5EE4BB9L, 0xF8AD6D60L, 0xFC6C70D7L, + 0xE22B20D2L, 0xE6EA3D65L, 0xEBA91BBCL, 0xEF68060BL, + 0xD727BBB6L, 0xD3E6A601L, 0xDEA580D8L, 0xDA649D6FL, + 0xC423CD6AL, 0xC0E2D0DDL, 0xCDA1F604L, 0xC960EBB3L, + 0xBD3E8D7EL, 0xB9FF90C9L, 0xB4BCB610L, 0xB07DABA7L, + 0xAE3AFBA2L, 0xAAFBE615L, 0xA7B8C0CCL, 0xA379DD7BL, + 0x9B3660C6L, 0x9FF77D71L, 0x92B45BA8L, 0x9675461FL, + 0x8832161AL, 0x8CF30BADL, 0x81B02D74L, 0x857130C3L, + 0x5D8A9099L, 0x594B8D2EL, 0x5408ABF7L, 0x50C9B640L, + 0x4E8EE645L, 0x4A4FFBF2L, 0x470CDD2BL, 0x43CDC09CL, + 0x7B827D21L, 0x7F436096L, 0x7200464FL, 0x76C15BF8L, + 0x68860BFDL, 0x6C47164AL, 0x61043093L, 0x65C52D24L, + 0x119B4BE9L, 0x155A565EL, 0x18197087L, 0x1CD86D30L, + 0x029F3D35L, 0x065E2082L, 0x0B1D065BL, 0x0FDC1BECL, + 0x3793A651L, 0x3352BBE6L, 0x3E119D3FL, 0x3AD08088L, + 0x2497D08DL, 0x2056CD3AL, 0x2D15EBE3L, 0x29D4F654L, + 0xC5A92679L, 0xC1683BCEL, 0xCC2B1D17L, 0xC8EA00A0L, + 0xD6AD50A5L, 0xD26C4D12L, 0xDF2F6BCBL, 0xDBEE767CL, + 0xE3A1CBC1L, 0xE760D676L, 0xEA23F0AFL, 0xEEE2ED18L, + 0xF0A5BD1DL, 0xF464A0AAL, 0xF9278673L, 0xFDE69BC4L, + 0x89B8FD09L, 0x8D79E0BEL, 0x803AC667L, 0x84FBDBD0L, + 0x9ABC8BD5L, 0x9E7D9662L, 0x933EB0BBL, 0x97FFAD0CL, + 0xAFB010B1L, 0xAB710D06L, 0xA6322BDFL, 0xA2F33668L, + 0xBCB4666DL, 0xB8757BDAL, 0xB5365D03L, 0xB1F740B4L +}; +#endif + +static DRFLAC_INLINE drflac_uint32 drflac_crc32_byte(drflac_uint32 crc32, drflac_uint8 data) +{ +#ifndef DR_FLAC_NO_CRC + return (crc32 << 8) ^ drflac__crc32_table[(drflac_uint8)((crc32 >> 24) & 0xFF) ^ data]; +#else + (void)data; + return crc32; +#endif +} + +#if 0 +static DRFLAC_INLINE drflac_uint32 drflac_crc32_uint32(drflac_uint32 crc32, drflac_uint32 data) +{ + crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 24) & 0xFF)); + crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 16) & 0xFF)); + crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 8) & 0xFF)); + crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 0) & 0xFF)); + return crc32; +} + +static DRFLAC_INLINE drflac_uint32 drflac_crc32_uint64(drflac_uint32 crc32, drflac_uint64 data) +{ + crc32 = drflac_crc32_uint32(crc32, (drflac_uint32)((data >> 32) & 0xFFFFFFFF)); + crc32 = drflac_crc32_uint32(crc32, (drflac_uint32)((data >> 0) & 0xFFFFFFFF)); + return crc32; +} +#endif + +static DRFLAC_INLINE drflac_uint32 drflac_crc32_buffer(drflac_uint32 crc32, drflac_uint8* pData, drflac_uint32 dataSize) +{ + /* This can be optimized. */ + drflac_uint32 i; + for (i = 0; i < dataSize; ++i) { + crc32 = drflac_crc32_byte(crc32, pData[i]); + } + return crc32; +} + + +static DRFLAC_INLINE drflac_bool32 drflac_ogg__is_capture_pattern(drflac_uint8 pattern[4]) +{ + return pattern[0] == 'O' && pattern[1] == 'g' && pattern[2] == 'g' && pattern[3] == 'S'; +} + +static DRFLAC_INLINE drflac_uint32 drflac_ogg__get_page_header_size(drflac_ogg_page_header* pHeader) +{ + return 27 + pHeader->segmentCount; +} + +static DRFLAC_INLINE drflac_uint32 drflac_ogg__get_page_body_size(drflac_ogg_page_header* pHeader) +{ + drflac_uint32 pageBodySize = 0; + int i; + + for (i = 0; i < pHeader->segmentCount; ++i) { + pageBodySize += pHeader->segmentTable[i]; + } + + return pageBodySize; +} + +static drflac_result drflac_ogg__read_page_header_after_capture_pattern(drflac_read_proc onRead, void* pUserData, drflac_ogg_page_header* pHeader, drflac_uint32* pBytesRead, drflac_uint32* pCRC32) +{ + drflac_uint8 data[23]; + drflac_uint32 i; + + DRFLAC_ASSERT(*pCRC32 == DRFLAC_OGG_CAPTURE_PATTERN_CRC32); + + if (onRead(pUserData, data, 23) != 23) { + return DRFLAC_AT_END; + } + *pBytesRead += 23; + + /* + It's not actually used, but set the capture pattern to 'OggS' for completeness. Not doing this will cause static analysers to complain about + us trying to access uninitialized data. We could alternatively just comment out this member of the drflac_ogg_page_header structure, but I + like to have it map to the structure of the underlying data. + */ + pHeader->capturePattern[0] = 'O'; + pHeader->capturePattern[1] = 'g'; + pHeader->capturePattern[2] = 'g'; + pHeader->capturePattern[3] = 'S'; + + pHeader->structureVersion = data[0]; + pHeader->headerType = data[1]; + DRFLAC_COPY_MEMORY(&pHeader->granulePosition, &data[ 2], 8); + DRFLAC_COPY_MEMORY(&pHeader->serialNumber, &data[10], 4); + DRFLAC_COPY_MEMORY(&pHeader->sequenceNumber, &data[14], 4); + DRFLAC_COPY_MEMORY(&pHeader->checksum, &data[18], 4); + pHeader->segmentCount = data[22]; + + /* Calculate the CRC. Note that for the calculation the checksum part of the page needs to be set to 0. */ + data[18] = 0; + data[19] = 0; + data[20] = 0; + data[21] = 0; + + for (i = 0; i < 23; ++i) { + *pCRC32 = drflac_crc32_byte(*pCRC32, data[i]); + } + + + if (onRead(pUserData, pHeader->segmentTable, pHeader->segmentCount) != pHeader->segmentCount) { + return DRFLAC_AT_END; + } + *pBytesRead += pHeader->segmentCount; + + for (i = 0; i < pHeader->segmentCount; ++i) { + *pCRC32 = drflac_crc32_byte(*pCRC32, pHeader->segmentTable[i]); + } + + return DRFLAC_SUCCESS; +} + +static drflac_result drflac_ogg__read_page_header(drflac_read_proc onRead, void* pUserData, drflac_ogg_page_header* pHeader, drflac_uint32* pBytesRead, drflac_uint32* pCRC32) +{ + drflac_uint8 id[4]; + + *pBytesRead = 0; + + if (onRead(pUserData, id, 4) != 4) { + return DRFLAC_AT_END; + } + *pBytesRead += 4; + + /* We need to read byte-by-byte until we find the OggS capture pattern. */ + for (;;) { + if (drflac_ogg__is_capture_pattern(id)) { + drflac_result result; + + *pCRC32 = DRFLAC_OGG_CAPTURE_PATTERN_CRC32; + + result = drflac_ogg__read_page_header_after_capture_pattern(onRead, pUserData, pHeader, pBytesRead, pCRC32); + if (result == DRFLAC_SUCCESS) { + return DRFLAC_SUCCESS; + } else { + if (result == DRFLAC_CRC_MISMATCH) { + continue; + } else { + return result; + } + } + } else { + /* The first 4 bytes did not equal the capture pattern. Read the next byte and try again. */ + id[0] = id[1]; + id[1] = id[2]; + id[2] = id[3]; + if (onRead(pUserData, &id[3], 1) != 1) { + return DRFLAC_AT_END; + } + *pBytesRead += 1; + } + } +} + + +/* +The main part of the Ogg encapsulation is the conversion from the physical Ogg bitstream to the native FLAC bitstream. It works +in three general stages: Ogg Physical Bitstream -> Ogg/FLAC Logical Bitstream -> FLAC Native Bitstream. dr_flac is designed +in such a way that the core sections assume everything is delivered in native format. Therefore, for each encapsulation type +dr_flac is supporting there needs to be a layer sitting on top of the onRead and onSeek callbacks that ensures the bits read from +the physical Ogg bitstream are converted and delivered in native FLAC format. +*/ +typedef struct +{ + drflac_read_proc onRead; /* The original onRead callback from drflac_open() and family. */ + drflac_seek_proc onSeek; /* The original onSeek callback from drflac_open() and family. */ + drflac_tell_proc onTell; /* The original onTell callback from drflac_open() and family. */ + void* pUserData; /* The user data passed on onRead and onSeek. This is the user data that was passed on drflac_open() and family. */ + drflac_uint64 currentBytePos; /* The position of the byte we are sitting on in the physical byte stream. Used for efficient seeking. */ + drflac_uint64 firstBytePos; /* The position of the first byte in the physical bitstream. Points to the start of the "OggS" identifier of the FLAC bos page. */ + drflac_uint32 serialNumber; /* The serial number of the FLAC audio pages. This is determined by the initial header page that was read during initialization. */ + drflac_ogg_page_header bosPageHeader; /* Used for seeking. */ + drflac_ogg_page_header currentPageHeader; + drflac_uint32 bytesRemainingInPage; + drflac_uint32 pageDataSize; + drflac_uint8 pageData[DRFLAC_OGG_MAX_PAGE_SIZE]; +} drflac_oggbs; /* oggbs = Ogg Bitstream */ + +static size_t drflac_oggbs__read_physical(drflac_oggbs* oggbs, void* bufferOut, size_t bytesToRead) +{ + size_t bytesActuallyRead = oggbs->onRead(oggbs->pUserData, bufferOut, bytesToRead); + oggbs->currentBytePos += bytesActuallyRead; + + return bytesActuallyRead; +} + +static drflac_bool32 drflac_oggbs__seek_physical(drflac_oggbs* oggbs, drflac_uint64 offset, drflac_seek_origin origin) +{ + if (origin == DRFLAC_SEEK_SET) { + if (offset <= 0x7FFFFFFF) { + if (!oggbs->onSeek(oggbs->pUserData, (int)offset, DRFLAC_SEEK_SET)) { + return DRFLAC_FALSE; + } + oggbs->currentBytePos = offset; + + return DRFLAC_TRUE; + } else { + if (!oggbs->onSeek(oggbs->pUserData, 0x7FFFFFFF, DRFLAC_SEEK_SET)) { + return DRFLAC_FALSE; + } + oggbs->currentBytePos = offset; + + return drflac_oggbs__seek_physical(oggbs, offset - 0x7FFFFFFF, DRFLAC_SEEK_CUR); + } + } else { + while (offset > 0x7FFFFFFF) { + if (!oggbs->onSeek(oggbs->pUserData, 0x7FFFFFFF, DRFLAC_SEEK_CUR)) { + return DRFLAC_FALSE; + } + oggbs->currentBytePos += 0x7FFFFFFF; + offset -= 0x7FFFFFFF; + } + + if (!oggbs->onSeek(oggbs->pUserData, (int)offset, DRFLAC_SEEK_CUR)) { /* <-- Safe cast thanks to the loop above. */ + return DRFLAC_FALSE; + } + oggbs->currentBytePos += offset; + + return DRFLAC_TRUE; + } +} + +static drflac_bool32 drflac_oggbs__goto_next_page(drflac_oggbs* oggbs, drflac_ogg_crc_mismatch_recovery recoveryMethod) +{ + drflac_ogg_page_header header; + for (;;) { + drflac_uint32 crc32 = 0; + drflac_uint32 bytesRead; + drflac_uint32 pageBodySize; +#ifndef DR_FLAC_NO_CRC + drflac_uint32 actualCRC32; +#endif + + if (drflac_ogg__read_page_header(oggbs->onRead, oggbs->pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) { + return DRFLAC_FALSE; + } + oggbs->currentBytePos += bytesRead; + + pageBodySize = drflac_ogg__get_page_body_size(&header); + if (pageBodySize > DRFLAC_OGG_MAX_PAGE_SIZE) { + continue; /* Invalid page size. Assume it's corrupted and just move to the next page. */ + } + + if (header.serialNumber != oggbs->serialNumber) { + /* It's not a FLAC page. Skip it. */ + if (pageBodySize > 0 && !drflac_oggbs__seek_physical(oggbs, pageBodySize, DRFLAC_SEEK_CUR)) { + return DRFLAC_FALSE; + } + continue; + } + + + /* We need to read the entire page and then do a CRC check on it. If there's a CRC mismatch we need to skip this page. */ + if (drflac_oggbs__read_physical(oggbs, oggbs->pageData, pageBodySize) != pageBodySize) { + return DRFLAC_FALSE; + } + oggbs->pageDataSize = pageBodySize; + +#ifndef DR_FLAC_NO_CRC + actualCRC32 = drflac_crc32_buffer(crc32, oggbs->pageData, oggbs->pageDataSize); + if (actualCRC32 != header.checksum) { + if (recoveryMethod == drflac_ogg_recover_on_crc_mismatch) { + continue; /* CRC mismatch. Skip this page. */ + } else { + /* + Even though we are failing on a CRC mismatch, we still want our stream to be in a good state. Therefore we + go to the next valid page to ensure we're in a good state, but return false to let the caller know that the + seek did not fully complete. + */ + drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch); + return DRFLAC_FALSE; + } + } +#else + (void)recoveryMethod; /* <-- Silence a warning. */ +#endif + + oggbs->currentPageHeader = header; + oggbs->bytesRemainingInPage = pageBodySize; + return DRFLAC_TRUE; + } +} + +/* Function below is unused at the moment, but I might be re-adding it later. */ +#if 0 +static drflac_uint8 drflac_oggbs__get_current_segment_index(drflac_oggbs* oggbs, drflac_uint8* pBytesRemainingInSeg) +{ + drflac_uint32 bytesConsumedInPage = drflac_ogg__get_page_body_size(&oggbs->currentPageHeader) - oggbs->bytesRemainingInPage; + drflac_uint8 iSeg = 0; + drflac_uint32 iByte = 0; + while (iByte < bytesConsumedInPage) { + drflac_uint8 segmentSize = oggbs->currentPageHeader.segmentTable[iSeg]; + if (iByte + segmentSize > bytesConsumedInPage) { + break; + } else { + iSeg += 1; + iByte += segmentSize; + } + } + + *pBytesRemainingInSeg = oggbs->currentPageHeader.segmentTable[iSeg] - (drflac_uint8)(bytesConsumedInPage - iByte); + return iSeg; +} + +static drflac_bool32 drflac_oggbs__seek_to_next_packet(drflac_oggbs* oggbs) +{ + /* The current packet ends when we get to the segment with a lacing value of < 255 which is not at the end of a page. */ + for (;;) { + drflac_bool32 atEndOfPage = DRFLAC_FALSE; + + drflac_uint8 bytesRemainingInSeg; + drflac_uint8 iFirstSeg = drflac_oggbs__get_current_segment_index(oggbs, &bytesRemainingInSeg); + + drflac_uint32 bytesToEndOfPacketOrPage = bytesRemainingInSeg; + for (drflac_uint8 iSeg = iFirstSeg; iSeg < oggbs->currentPageHeader.segmentCount; ++iSeg) { + drflac_uint8 segmentSize = oggbs->currentPageHeader.segmentTable[iSeg]; + if (segmentSize < 255) { + if (iSeg == oggbs->currentPageHeader.segmentCount-1) { + atEndOfPage = DRFLAC_TRUE; + } + + break; + } + + bytesToEndOfPacketOrPage += segmentSize; + } + + /* + At this point we will have found either the packet or the end of the page. If were at the end of the page we'll + want to load the next page and keep searching for the end of the packet. + */ + drflac_oggbs__seek_physical(oggbs, bytesToEndOfPacketOrPage, DRFLAC_SEEK_CUR); + oggbs->bytesRemainingInPage -= bytesToEndOfPacketOrPage; + + if (atEndOfPage) { + /* + We're potentially at the next packet, but we need to check the next page first to be sure because the packet may + straddle pages. + */ + if (!drflac_oggbs__goto_next_page(oggbs)) { + return DRFLAC_FALSE; + } + + /* If it's a fresh packet it most likely means we're at the next packet. */ + if ((oggbs->currentPageHeader.headerType & 0x01) == 0) { + return DRFLAC_TRUE; + } + } else { + /* We're at the next packet. */ + return DRFLAC_TRUE; + } + } +} + +static drflac_bool32 drflac_oggbs__seek_to_next_frame(drflac_oggbs* oggbs) +{ + /* The bitstream should be sitting on the first byte just after the header of the frame. */ + + /* What we're actually doing here is seeking to the start of the next packet. */ + return drflac_oggbs__seek_to_next_packet(oggbs); +} +#endif + +static size_t drflac__on_read_ogg(void* pUserData, void* bufferOut, size_t bytesToRead) +{ + drflac_oggbs* oggbs = (drflac_oggbs*)pUserData; + drflac_uint8* pRunningBufferOut = (drflac_uint8*)bufferOut; + size_t bytesRead = 0; + + DRFLAC_ASSERT(oggbs != NULL); + DRFLAC_ASSERT(pRunningBufferOut != NULL); + + /* Reading is done page-by-page. If we've run out of bytes in the page we need to move to the next one. */ + while (bytesRead < bytesToRead) { + size_t bytesRemainingToRead = bytesToRead - bytesRead; + + if (oggbs->bytesRemainingInPage >= bytesRemainingToRead) { + DRFLAC_COPY_MEMORY(pRunningBufferOut, oggbs->pageData + (oggbs->pageDataSize - oggbs->bytesRemainingInPage), bytesRemainingToRead); + bytesRead += bytesRemainingToRead; + oggbs->bytesRemainingInPage -= (drflac_uint32)bytesRemainingToRead; + break; + } + + /* If we get here it means some of the requested data is contained in the next pages. */ + if (oggbs->bytesRemainingInPage > 0) { + DRFLAC_COPY_MEMORY(pRunningBufferOut, oggbs->pageData + (oggbs->pageDataSize - oggbs->bytesRemainingInPage), oggbs->bytesRemainingInPage); + bytesRead += oggbs->bytesRemainingInPage; + pRunningBufferOut += oggbs->bytesRemainingInPage; + oggbs->bytesRemainingInPage = 0; + } + + DRFLAC_ASSERT(bytesRemainingToRead > 0); + if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) { + break; /* Failed to go to the next page. Might have simply hit the end of the stream. */ + } + } + + return bytesRead; +} + +static drflac_bool32 drflac__on_seek_ogg(void* pUserData, int offset, drflac_seek_origin origin) +{ + drflac_oggbs* oggbs = (drflac_oggbs*)pUserData; + int bytesSeeked = 0; + + DRFLAC_ASSERT(oggbs != NULL); + DRFLAC_ASSERT(offset >= 0); /* <-- Never seek backwards. */ + + /* Seeking is always forward which makes things a lot simpler. */ + if (origin == DRFLAC_SEEK_SET) { + if (!drflac_oggbs__seek_physical(oggbs, (int)oggbs->firstBytePos, DRFLAC_SEEK_SET)) { + return DRFLAC_FALSE; + } + + if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_fail_on_crc_mismatch)) { + return DRFLAC_FALSE; + } + + return drflac__on_seek_ogg(pUserData, offset, DRFLAC_SEEK_CUR); + } else if (origin == DRFLAC_SEEK_CUR) { + while (bytesSeeked < offset) { + int bytesRemainingToSeek = offset - bytesSeeked; + DRFLAC_ASSERT(bytesRemainingToSeek >= 0); + + if (oggbs->bytesRemainingInPage >= (size_t)bytesRemainingToSeek) { + bytesSeeked += bytesRemainingToSeek; + (void)bytesSeeked; /* <-- Silence a dead store warning emitted by Clang Static Analyzer. */ + oggbs->bytesRemainingInPage -= bytesRemainingToSeek; + break; + } + + /* If we get here it means some of the requested data is contained in the next pages. */ + if (oggbs->bytesRemainingInPage > 0) { + bytesSeeked += (int)oggbs->bytesRemainingInPage; + oggbs->bytesRemainingInPage = 0; + } + + DRFLAC_ASSERT(bytesRemainingToSeek > 0); + if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_fail_on_crc_mismatch)) { + /* Failed to go to the next page. We either hit the end of the stream or had a CRC mismatch. */ + return DRFLAC_FALSE; + } + } + } else if (origin == DRFLAC_SEEK_END) { + /* Seeking to the end is not supported. */ + return DRFLAC_FALSE; + } + + return DRFLAC_TRUE; +} + +static drflac_bool32 drflac__on_tell_ogg(void* pUserData, drflac_int64* pCursor) +{ + /* + Not implemented for Ogg containers because we don't currently track the byte position of the logical bitstream. To support this, we'll need + to track the position in drflac__on_read_ogg and drflac__on_seek_ogg. + */ + (void)pUserData; + (void)pCursor; + return DRFLAC_FALSE; +} + + +static drflac_bool32 drflac_ogg__seek_to_pcm_frame(drflac* pFlac, drflac_uint64 pcmFrameIndex) +{ + drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs; + drflac_uint64 originalBytePos; + drflac_uint64 runningGranulePosition; + drflac_uint64 runningFrameBytePos; + drflac_uint64 runningPCMFrameCount; + + DRFLAC_ASSERT(oggbs != NULL); + + originalBytePos = oggbs->currentBytePos; /* For recovery. Points to the OggS identifier. */ + + /* First seek to the first frame. */ + if (!drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes)) { + return DRFLAC_FALSE; + } + oggbs->bytesRemainingInPage = 0; + + runningGranulePosition = 0; + for (;;) { + if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) { + drflac_oggbs__seek_physical(oggbs, originalBytePos, DRFLAC_SEEK_SET); + return DRFLAC_FALSE; /* Never did find that sample... */ + } + + runningFrameBytePos = oggbs->currentBytePos - drflac_ogg__get_page_header_size(&oggbs->currentPageHeader) - oggbs->pageDataSize; + if (oggbs->currentPageHeader.granulePosition >= pcmFrameIndex) { + break; /* The sample is somewhere in the previous page. */ + } + + /* + At this point we know the sample is not in the previous page. It could possibly be in this page. For simplicity we + disregard any pages that do not begin a fresh packet. + */ + if ((oggbs->currentPageHeader.headerType & 0x01) == 0) { /* <-- Is it a fresh page? */ + if (oggbs->currentPageHeader.segmentTable[0] >= 2) { + drflac_uint8 firstBytesInPage[2]; + firstBytesInPage[0] = oggbs->pageData[0]; + firstBytesInPage[1] = oggbs->pageData[1]; + + if ((firstBytesInPage[0] == 0xFF) && (firstBytesInPage[1] & 0xFC) == 0xF8) { /* <-- Does the page begin with a frame's sync code? */ + runningGranulePosition = oggbs->currentPageHeader.granulePosition; + } + + continue; + } + } + } + + /* + We found the page that that is closest to the sample, so now we need to find it. The first thing to do is seek to the + start of that page. In the loop above we checked that it was a fresh page which means this page is also the start of + a new frame. This property means that after we've seeked to the page we can immediately start looping over frames until + we find the one containing the target sample. + */ + if (!drflac_oggbs__seek_physical(oggbs, runningFrameBytePos, DRFLAC_SEEK_SET)) { + return DRFLAC_FALSE; + } + if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) { + return DRFLAC_FALSE; + } + + /* + At this point we'll be sitting on the first byte of the frame header of the first frame in the page. We just keep + looping over these frames until we find the one containing the sample we're after. + */ + runningPCMFrameCount = runningGranulePosition; + for (;;) { + /* + There are two ways to find the sample and seek past irrelevant frames: + 1) Use the native FLAC decoder. + 2) Use Ogg's framing system. + + Both of these options have their own pros and cons. Using the native FLAC decoder is slower because it needs to + do a full decode of the frame. Using Ogg's framing system is faster, but more complicated and involves some code + duplication for the decoding of frame headers. + + Another thing to consider is that using the Ogg framing system will perform direct seeking of the physical Ogg + bitstream. This is important to consider because it means we cannot read data from the drflac_bs object using the + standard drflac__*() APIs because that will read in extra data for its own internal caching which in turn breaks + the positioning of the read pointer of the physical Ogg bitstream. Therefore, anything that would normally be read + using the native FLAC decoding APIs, such as drflac__read_next_flac_frame_header(), need to be re-implemented so as to + avoid the use of the drflac_bs object. + + Considering these issues, I have decided to use the slower native FLAC decoding method for the following reasons: + 1) Seeking is already partially accelerated using Ogg's paging system in the code block above. + 2) Seeking in an Ogg encapsulated FLAC stream is probably quite uncommon. + 3) Simplicity. + */ + drflac_uint64 firstPCMFrameInFLACFrame = 0; + drflac_uint64 lastPCMFrameInFLACFrame = 0; + drflac_uint64 pcmFrameCountInThisFrame; + + if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) { + return DRFLAC_FALSE; + } + + drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame); + + pcmFrameCountInThisFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1; + + /* If we are seeking to the end of the file and we've just hit it, we're done. */ + if (pcmFrameIndex == pFlac->totalPCMFrameCount && (runningPCMFrameCount + pcmFrameCountInThisFrame) == pFlac->totalPCMFrameCount) { + drflac_result result = drflac__decode_flac_frame(pFlac); + if (result == DRFLAC_SUCCESS) { + pFlac->currentPCMFrame = pcmFrameIndex; + pFlac->currentFLACFrame.pcmFramesRemaining = 0; + return DRFLAC_TRUE; + } else { + return DRFLAC_FALSE; + } + } + + if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFrame)) { + /* + The sample should be in this FLAC frame. We need to fully decode it, however if it's an invalid frame (a CRC mismatch), we need to pretend + it never existed and keep iterating. + */ + drflac_result result = drflac__decode_flac_frame(pFlac); + if (result == DRFLAC_SUCCESS) { + /* The frame is valid. We just need to skip over some samples to ensure it's sample-exact. */ + drflac_uint64 pcmFramesToDecode = (size_t)(pcmFrameIndex - runningPCMFrameCount); /* <-- Safe cast because the maximum number of samples in a frame is 65535. */ + if (pcmFramesToDecode == 0) { + return DRFLAC_TRUE; + } + + pFlac->currentPCMFrame = runningPCMFrameCount; + + return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode; /* <-- If this fails, something bad has happened (it should never fail). */ + } else { + if (result == DRFLAC_CRC_MISMATCH) { + continue; /* CRC mismatch. Pretend this frame never existed. */ + } else { + return DRFLAC_FALSE; + } + } + } else { + /* + It's not in this frame. We need to seek past the frame, but check if there was a CRC mismatch. If so, we pretend this + frame never existed and leave the running sample count untouched. + */ + drflac_result result = drflac__seek_to_next_flac_frame(pFlac); + if (result == DRFLAC_SUCCESS) { + runningPCMFrameCount += pcmFrameCountInThisFrame; + } else { + if (result == DRFLAC_CRC_MISMATCH) { + continue; /* CRC mismatch. Pretend this frame never existed. */ + } else { + return DRFLAC_FALSE; + } + } + } + } +} + + + +static drflac_bool32 drflac__init_private__ogg(drflac_init_info* pInit, drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, void* pUserDataMD, drflac_bool32 relaxed) +{ + drflac_ogg_page_header header; + drflac_uint32 crc32 = DRFLAC_OGG_CAPTURE_PATTERN_CRC32; + drflac_uint32 bytesRead = 0; + + /* Pre Condition: The bit stream should be sitting just past the 4-byte OggS capture pattern. */ + (void)relaxed; + + pInit->container = drflac_container_ogg; + pInit->oggFirstBytePos = 0; + + /* + We'll get here if the first 4 bytes of the stream were the OggS capture pattern, however it doesn't necessarily mean the + stream includes FLAC encoded audio. To check for this we need to scan the beginning-of-stream page markers and check if + any match the FLAC specification. Important to keep in mind that the stream may be multiplexed. + */ + if (drflac_ogg__read_page_header_after_capture_pattern(onRead, pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) { + return DRFLAC_FALSE; + } + pInit->runningFilePos += bytesRead; + + for (;;) { + int pageBodySize; + + /* Break if we're past the beginning of stream page. */ + if ((header.headerType & 0x02) == 0) { + return DRFLAC_FALSE; + } + + /* Check if it's a FLAC header. */ + pageBodySize = drflac_ogg__get_page_body_size(&header); + if (pageBodySize == 51) { /* 51 = the lacing value of the FLAC header packet. */ + /* It could be a FLAC page... */ + drflac_uint32 bytesRemainingInPage = pageBodySize; + drflac_uint8 packetType; + + if (onRead(pUserData, &packetType, 1) != 1) { + return DRFLAC_FALSE; + } + + bytesRemainingInPage -= 1; + if (packetType == 0x7F) { + /* Increasingly more likely to be a FLAC page... */ + drflac_uint8 sig[4]; + if (onRead(pUserData, sig, 4) != 4) { + return DRFLAC_FALSE; + } + + bytesRemainingInPage -= 4; + if (sig[0] == 'F' && sig[1] == 'L' && sig[2] == 'A' && sig[3] == 'C') { + /* Almost certainly a FLAC page... */ + drflac_uint8 mappingVersion[2]; + if (onRead(pUserData, mappingVersion, 2) != 2) { + return DRFLAC_FALSE; + } + + if (mappingVersion[0] != 1) { + return DRFLAC_FALSE; /* Only supporting version 1.x of the Ogg mapping. */ + } + + /* + The next 2 bytes are the non-audio packets, not including this one. We don't care about this because we're going to + be handling it in a generic way based on the serial number and packet types. + */ + if (!onSeek(pUserData, 2, DRFLAC_SEEK_CUR)) { + return DRFLAC_FALSE; + } + + /* Expecting the native FLAC signature "fLaC". */ + if (onRead(pUserData, sig, 4) != 4) { + return DRFLAC_FALSE; + } + + if (sig[0] == 'f' && sig[1] == 'L' && sig[2] == 'a' && sig[3] == 'C') { + /* The remaining data in the page should be the STREAMINFO block. */ + drflac_streaminfo streaminfo; + drflac_uint8 isLastBlock; + drflac_uint8 blockType; + drflac_uint32 blockSize; + if (!drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize)) { + return DRFLAC_FALSE; + } + + if (blockType != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) { + return DRFLAC_FALSE; /* Invalid block type. First block must be the STREAMINFO block. */ + } + + if (drflac__read_streaminfo(onRead, pUserData, &streaminfo)) { + /* Success! */ + pInit->hasStreamInfoBlock = DRFLAC_TRUE; + pInit->sampleRate = streaminfo.sampleRate; + pInit->channels = streaminfo.channels; + pInit->bitsPerSample = streaminfo.bitsPerSample; + pInit->totalPCMFrameCount = streaminfo.totalPCMFrameCount; + pInit->maxBlockSizeInPCMFrames = streaminfo.maxBlockSizeInPCMFrames; + pInit->hasMetadataBlocks = !isLastBlock; + + if (onMeta) { + drflac_metadata metadata; + metadata.type = DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO; + metadata.pRawData = NULL; + metadata.rawDataSize = 0; + metadata.data.streaminfo = streaminfo; + onMeta(pUserDataMD, &metadata); + } + + pInit->runningFilePos += pageBodySize; + pInit->oggFirstBytePos = pInit->runningFilePos - 79; /* Subtracting 79 will place us right on top of the "OggS" identifier of the FLAC bos page. */ + pInit->oggSerial = header.serialNumber; + pInit->oggBosHeader = header; + break; + } else { + /* Failed to read STREAMINFO block. Aww, so close... */ + return DRFLAC_FALSE; + } + } else { + /* Invalid file. */ + return DRFLAC_FALSE; + } + } else { + /* Not a FLAC header. Skip it. */ + if (!onSeek(pUserData, bytesRemainingInPage, DRFLAC_SEEK_CUR)) { + return DRFLAC_FALSE; + } + } + } else { + /* Not a FLAC header. Seek past the entire page and move on to the next. */ + if (!onSeek(pUserData, bytesRemainingInPage, DRFLAC_SEEK_CUR)) { + return DRFLAC_FALSE; + } + } + } else { + if (!onSeek(pUserData, pageBodySize, DRFLAC_SEEK_CUR)) { + return DRFLAC_FALSE; + } + } + + pInit->runningFilePos += pageBodySize; + + + /* Read the header of the next page. */ + if (drflac_ogg__read_page_header(onRead, pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) { + return DRFLAC_FALSE; + } + pInit->runningFilePos += bytesRead; + } + + /* + If we get here it means we found a FLAC audio stream. We should be sitting on the first byte of the header of the next page. The next + packets in the FLAC logical stream contain the metadata. The only thing left to do in the initialization phase for Ogg is to create the + Ogg bistream object. + */ + pInit->hasMetadataBlocks = DRFLAC_TRUE; /* <-- Always have at least VORBIS_COMMENT metadata block. */ + return DRFLAC_TRUE; +} +#endif + +static drflac_bool32 drflac__init_private(drflac_init_info* pInit, drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, drflac_meta_proc onMeta, drflac_container container, void* pUserData, void* pUserDataMD) +{ + drflac_bool32 relaxed; + drflac_uint8 id[4]; + + if (pInit == NULL || onRead == NULL || onSeek == NULL) { /* <-- onTell is optional. */ + return DRFLAC_FALSE; + } + + DRFLAC_ZERO_MEMORY(pInit, sizeof(*pInit)); + pInit->onRead = onRead; + pInit->onSeek = onSeek; + pInit->onTell = onTell; + pInit->onMeta = onMeta; + pInit->container = container; + pInit->pUserData = pUserData; + pInit->pUserDataMD = pUserDataMD; + + pInit->bs.onRead = onRead; + pInit->bs.onSeek = onSeek; + pInit->bs.onTell = onTell; + pInit->bs.pUserData = pUserData; + drflac__reset_cache(&pInit->bs); + + + /* If the container is explicitly defined then we can try opening in relaxed mode. */ + relaxed = container != drflac_container_unknown; + + /* Skip over any ID3 tags. */ + for (;;) { + if (onRead(pUserData, id, 4) != 4) { + return DRFLAC_FALSE; /* Ran out of data. */ + } + pInit->runningFilePos += 4; + + if (id[0] == 'I' && id[1] == 'D' && id[2] == '3') { + drflac_uint8 header[6]; + drflac_uint8 flags; + drflac_uint32 headerSize; + + if (onRead(pUserData, header, 6) != 6) { + return DRFLAC_FALSE; /* Ran out of data. */ + } + pInit->runningFilePos += 6; + + flags = header[1]; + + DRFLAC_COPY_MEMORY(&headerSize, header+2, 4); + headerSize = drflac__unsynchsafe_32(drflac__be2host_32(headerSize)); + if (flags & 0x10) { + headerSize += 10; + } + + if (!onSeek(pUserData, headerSize, DRFLAC_SEEK_CUR)) { + return DRFLAC_FALSE; /* Failed to seek past the tag. */ + } + pInit->runningFilePos += headerSize; + } else { + break; + } + } + + if (id[0] == 'f' && id[1] == 'L' && id[2] == 'a' && id[3] == 'C') { + return drflac__init_private__native(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed); + } +#ifndef DR_FLAC_NO_OGG + if (id[0] == 'O' && id[1] == 'g' && id[2] == 'g' && id[3] == 'S') { + return drflac__init_private__ogg(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed); + } +#endif + + /* If we get here it means we likely don't have a header. Try opening in relaxed mode, if applicable. */ + if (relaxed) { + if (container == drflac_container_native) { + return drflac__init_private__native(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed); + } +#ifndef DR_FLAC_NO_OGG + if (container == drflac_container_ogg) { + return drflac__init_private__ogg(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed); + } +#endif + } + + /* Unsupported container. */ + return DRFLAC_FALSE; +} + +static void drflac__init_from_info(drflac* pFlac, const drflac_init_info* pInit) +{ + DRFLAC_ASSERT(pFlac != NULL); + DRFLAC_ASSERT(pInit != NULL); + + DRFLAC_ZERO_MEMORY(pFlac, sizeof(*pFlac)); + pFlac->bs = pInit->bs; + pFlac->onMeta = pInit->onMeta; + pFlac->pUserDataMD = pInit->pUserDataMD; + pFlac->maxBlockSizeInPCMFrames = pInit->maxBlockSizeInPCMFrames; + pFlac->sampleRate = pInit->sampleRate; + pFlac->channels = (drflac_uint8)pInit->channels; + pFlac->bitsPerSample = (drflac_uint8)pInit->bitsPerSample; + pFlac->totalPCMFrameCount = pInit->totalPCMFrameCount; + pFlac->container = pInit->container; +} + + +static drflac* drflac_open_with_metadata_private(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, drflac_meta_proc onMeta, drflac_container container, void* pUserData, void* pUserDataMD, const drflac_allocation_callbacks* pAllocationCallbacks) +{ + drflac_init_info init; + drflac_uint32 allocationSize; + drflac_uint32 wholeSIMDVectorCountPerChannel; + drflac_uint32 decodedSamplesAllocationSize; +#ifndef DR_FLAC_NO_OGG + drflac_oggbs* pOggbs = NULL; +#endif + drflac_uint64 firstFramePos; + drflac_uint64 seektablePos; + drflac_uint32 seekpointCount; + drflac_allocation_callbacks allocationCallbacks; + drflac* pFlac; + + /* CPU support first. */ + drflac__init_cpu_caps(); + + if (!drflac__init_private(&init, onRead, onSeek, onTell, onMeta, container, pUserData, pUserDataMD)) { + return NULL; + } + + if (pAllocationCallbacks != NULL) { + allocationCallbacks = *pAllocationCallbacks; + if (allocationCallbacks.onFree == NULL || (allocationCallbacks.onMalloc == NULL && allocationCallbacks.onRealloc == NULL)) { + return NULL; /* Invalid allocation callbacks. */ + } + } else { + allocationCallbacks.pUserData = NULL; + allocationCallbacks.onMalloc = drflac__malloc_default; + allocationCallbacks.onRealloc = drflac__realloc_default; + allocationCallbacks.onFree = drflac__free_default; + } + + + /* + The size of the allocation for the drflac object needs to be large enough to fit the following: + 1) The main members of the drflac structure + 2) A block of memory large enough to store the decoded samples of the largest frame in the stream + 3) If the container is Ogg, a drflac_oggbs object + + The complicated part of the allocation is making sure there's enough room the decoded samples, taking into consideration + the different SIMD instruction sets. + */ + allocationSize = sizeof(drflac); + + /* + The allocation size for decoded frames depends on the number of 32-bit integers that fit inside the largest SIMD vector + we are supporting. + */ + if ((init.maxBlockSizeInPCMFrames % (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32))) == 0) { + wholeSIMDVectorCountPerChannel = (init.maxBlockSizeInPCMFrames / (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32))); + } else { + wholeSIMDVectorCountPerChannel = (init.maxBlockSizeInPCMFrames / (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32))) + 1; + } + + decodedSamplesAllocationSize = wholeSIMDVectorCountPerChannel * DRFLAC_MAX_SIMD_VECTOR_SIZE * init.channels; + + allocationSize += decodedSamplesAllocationSize; + allocationSize += DRFLAC_MAX_SIMD_VECTOR_SIZE; /* Allocate extra bytes to ensure we have enough for alignment. */ + +#ifndef DR_FLAC_NO_OGG + /* There's additional data required for Ogg streams. */ + if (init.container == drflac_container_ogg) { + allocationSize += sizeof(drflac_oggbs); + + pOggbs = (drflac_oggbs*)drflac__malloc_from_callbacks(sizeof(*pOggbs), &allocationCallbacks); + if (pOggbs == NULL) { + return NULL; /*DRFLAC_OUT_OF_MEMORY;*/ + } + + DRFLAC_ZERO_MEMORY(pOggbs, sizeof(*pOggbs)); + pOggbs->onRead = onRead; + pOggbs->onSeek = onSeek; + pOggbs->onTell = onTell; + pOggbs->pUserData = pUserData; + pOggbs->currentBytePos = init.oggFirstBytePos; + pOggbs->firstBytePos = init.oggFirstBytePos; + pOggbs->serialNumber = init.oggSerial; + pOggbs->bosPageHeader = init.oggBosHeader; + pOggbs->bytesRemainingInPage = 0; + } +#endif + + /* + This part is a bit awkward. We need to load the seektable so that it can be referenced in-memory, but I want the drflac object to + consist of only a single heap allocation. To this, the size of the seek table needs to be known, which we determine when reading + and decoding the metadata. + */ + firstFramePos = 42; /* <-- We know we are at byte 42 at this point. */ + seektablePos = 0; + seekpointCount = 0; + if (init.hasMetadataBlocks) { + drflac_read_proc onReadOverride = onRead; + drflac_seek_proc onSeekOverride = onSeek; + drflac_tell_proc onTellOverride = onTell; + void* pUserDataOverride = pUserData; + +#ifndef DR_FLAC_NO_OGG + if (init.container == drflac_container_ogg) { + onReadOverride = drflac__on_read_ogg; + onSeekOverride = drflac__on_seek_ogg; + onTellOverride = drflac__on_tell_ogg; + pUserDataOverride = (void*)pOggbs; + } +#endif + + if (!drflac__read_and_decode_metadata(onReadOverride, onSeekOverride, onTellOverride, onMeta, pUserDataOverride, pUserDataMD, &firstFramePos, &seektablePos, &seekpointCount, &allocationCallbacks)) { + #ifndef DR_FLAC_NO_OGG + drflac__free_from_callbacks(pOggbs, &allocationCallbacks); + #endif + return NULL; + } + + allocationSize += seekpointCount * sizeof(drflac_seekpoint); + } + + + pFlac = (drflac*)drflac__malloc_from_callbacks(allocationSize, &allocationCallbacks); + if (pFlac == NULL) { + #ifndef DR_FLAC_NO_OGG + drflac__free_from_callbacks(pOggbs, &allocationCallbacks); + #endif + return NULL; + } + + drflac__init_from_info(pFlac, &init); + pFlac->allocationCallbacks = allocationCallbacks; + pFlac->pDecodedSamples = (drflac_int32*)drflac_align((size_t)pFlac->pExtraData, DRFLAC_MAX_SIMD_VECTOR_SIZE); + +#ifndef DR_FLAC_NO_OGG + if (init.container == drflac_container_ogg) { + drflac_oggbs* pInternalOggbs = (drflac_oggbs*)((drflac_uint8*)pFlac->pDecodedSamples + decodedSamplesAllocationSize + (seekpointCount * sizeof(drflac_seekpoint))); + DRFLAC_COPY_MEMORY(pInternalOggbs, pOggbs, sizeof(*pOggbs)); + + /* At this point the pOggbs object has been handed over to pInternalOggbs and can be freed. */ + drflac__free_from_callbacks(pOggbs, &allocationCallbacks); + pOggbs = NULL; + + /* The Ogg bistream needs to be layered on top of the original bitstream. */ + pFlac->bs.onRead = drflac__on_read_ogg; + pFlac->bs.onSeek = drflac__on_seek_ogg; + pFlac->bs.onTell = drflac__on_tell_ogg; + pFlac->bs.pUserData = (void*)pInternalOggbs; + pFlac->_oggbs = (void*)pInternalOggbs; + } +#endif + + pFlac->firstFLACFramePosInBytes = firstFramePos; + + /* NOTE: Seektables are not currently compatible with Ogg encapsulation (Ogg has its own accelerated seeking system). I may change this later, so I'm leaving this here for now. */ +#ifndef DR_FLAC_NO_OGG + if (init.container == drflac_container_ogg) + { + pFlac->pSeekpoints = NULL; + pFlac->seekpointCount = 0; + } + else +#endif + { + /* If we have a seektable we need to load it now, making sure we move back to where we were previously. */ + if (seektablePos != 0) { + pFlac->seekpointCount = seekpointCount; + pFlac->pSeekpoints = (drflac_seekpoint*)((drflac_uint8*)pFlac->pDecodedSamples + decodedSamplesAllocationSize); + + DRFLAC_ASSERT(pFlac->bs.onSeek != NULL); + DRFLAC_ASSERT(pFlac->bs.onRead != NULL); + + /* Seek to the seektable, then just read directly into our seektable buffer. */ + if (pFlac->bs.onSeek(pFlac->bs.pUserData, (int)seektablePos, DRFLAC_SEEK_SET)) { + drflac_uint32 iSeekpoint; + + for (iSeekpoint = 0; iSeekpoint < seekpointCount; iSeekpoint += 1) { + if (pFlac->bs.onRead(pFlac->bs.pUserData, pFlac->pSeekpoints + iSeekpoint, DRFLAC_SEEKPOINT_SIZE_IN_BYTES) == DRFLAC_SEEKPOINT_SIZE_IN_BYTES) { + /* Endian swap. */ + pFlac->pSeekpoints[iSeekpoint].firstPCMFrame = drflac__be2host_64(pFlac->pSeekpoints[iSeekpoint].firstPCMFrame); + pFlac->pSeekpoints[iSeekpoint].flacFrameOffset = drflac__be2host_64(pFlac->pSeekpoints[iSeekpoint].flacFrameOffset); + pFlac->pSeekpoints[iSeekpoint].pcmFrameCount = drflac__be2host_16(pFlac->pSeekpoints[iSeekpoint].pcmFrameCount); + } else { + /* Failed to read the seektable. Pretend we don't have one. */ + pFlac->pSeekpoints = NULL; + pFlac->seekpointCount = 0; + break; + } + } + + /* We need to seek back to where we were. If this fails it's a critical error. */ + if (!pFlac->bs.onSeek(pFlac->bs.pUserData, (int)pFlac->firstFLACFramePosInBytes, DRFLAC_SEEK_SET)) { + drflac__free_from_callbacks(pFlac, &allocationCallbacks); + return NULL; + } + } else { + /* Failed to seek to the seektable. Ominous sign, but for now we can just pretend we don't have one. */ + pFlac->pSeekpoints = NULL; + pFlac->seekpointCount = 0; + } + } + } + + + /* + If we get here, but don't have a STREAMINFO block, it means we've opened the stream in relaxed mode and need to decode + the first frame. + */ + if (!init.hasStreamInfoBlock) { + pFlac->currentFLACFrame.header = init.firstFrameHeader; + for (;;) { + drflac_result result = drflac__decode_flac_frame(pFlac); + if (result == DRFLAC_SUCCESS) { + break; + } else { + if (result == DRFLAC_CRC_MISMATCH) { + if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) { + drflac__free_from_callbacks(pFlac, &allocationCallbacks); + return NULL; + } + continue; + } else { + drflac__free_from_callbacks(pFlac, &allocationCallbacks); + return NULL; + } + } + } + } + + return pFlac; +} + + + + +static size_t drflac__on_read_memory(void* pUserData, void* bufferOut, size_t bytesToRead) +{ + drflac__memory_stream* memoryStream = (drflac__memory_stream*)pUserData; + size_t bytesRemaining; + + DRFLAC_ASSERT(memoryStream != NULL); + DRFLAC_ASSERT(memoryStream->dataSize >= memoryStream->currentReadPos); + + bytesRemaining = memoryStream->dataSize - memoryStream->currentReadPos; + if (bytesToRead > bytesRemaining) { + bytesToRead = bytesRemaining; + } + + if (bytesToRead > 0) { + DRFLAC_COPY_MEMORY(bufferOut, memoryStream->data + memoryStream->currentReadPos, bytesToRead); + memoryStream->currentReadPos += bytesToRead; + } + + return bytesToRead; +} + +static drflac_bool32 drflac__on_seek_memory(void* pUserData, int offset, drflac_seek_origin origin) +{ + drflac__memory_stream* memoryStream = (drflac__memory_stream*)pUserData; + drflac_int64 newCursor; + + DRFLAC_ASSERT(memoryStream != NULL); + + if (origin == DRFLAC_SEEK_SET) { + newCursor = 0; + } else if (origin == DRFLAC_SEEK_CUR) { + newCursor = (drflac_int64)memoryStream->currentReadPos; + } else if (origin == DRFLAC_SEEK_END) { + newCursor = (drflac_int64)memoryStream->dataSize; + } else { + DRFLAC_ASSERT(!"Invalid seek origin"); + return DRFLAC_FALSE; + } + + newCursor += offset; + + if (newCursor < 0) { + return DRFLAC_FALSE; /* Trying to seek prior to the start of the buffer. */ + } + if ((size_t)newCursor > memoryStream->dataSize) { + return DRFLAC_FALSE; /* Trying to seek beyond the end of the buffer. */ + } + + memoryStream->currentReadPos = (size_t)newCursor; + + return DRFLAC_TRUE; +} + +static drflac_bool32 drflac__on_tell_memory(void* pUserData, drflac_int64* pCursor) +{ + drflac__memory_stream* memoryStream = (drflac__memory_stream*)pUserData; + + DRFLAC_ASSERT(memoryStream != NULL); + DRFLAC_ASSERT(pCursor != NULL); + + *pCursor = (drflac_int64)memoryStream->currentReadPos; + return DRFLAC_TRUE; +} + +DRFLAC_API drflac* drflac_open_memory(const void* pData, size_t dataSize, const drflac_allocation_callbacks* pAllocationCallbacks) +{ + drflac__memory_stream memoryStream; + drflac* pFlac; + + memoryStream.data = (const drflac_uint8*)pData; + memoryStream.dataSize = dataSize; + memoryStream.currentReadPos = 0; + pFlac = drflac_open(drflac__on_read_memory, drflac__on_seek_memory, drflac__on_tell_memory, &memoryStream, pAllocationCallbacks); + if (pFlac == NULL) { + return NULL; + } + + pFlac->memoryStream = memoryStream; + + /* This is an awful hack... */ +#ifndef DR_FLAC_NO_OGG + if (pFlac->container == drflac_container_ogg) + { + drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs; + oggbs->pUserData = &pFlac->memoryStream; + } + else +#endif + { + pFlac->bs.pUserData = &pFlac->memoryStream; + } + + return pFlac; +} + +DRFLAC_API drflac* drflac_open_memory_with_metadata(const void* pData, size_t dataSize, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks) +{ + drflac__memory_stream memoryStream; + drflac* pFlac; + + memoryStream.data = (const drflac_uint8*)pData; + memoryStream.dataSize = dataSize; + memoryStream.currentReadPos = 0; + pFlac = drflac_open_with_metadata_private(drflac__on_read_memory, drflac__on_seek_memory, drflac__on_tell_memory, onMeta, drflac_container_unknown, &memoryStream, pUserData, pAllocationCallbacks); + if (pFlac == NULL) { + return NULL; + } + + pFlac->memoryStream = memoryStream; + + /* This is an awful hack... */ +#ifndef DR_FLAC_NO_OGG + if (pFlac->container == drflac_container_ogg) + { + drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs; + oggbs->pUserData = &pFlac->memoryStream; + } + else +#endif + { + pFlac->bs.pUserData = &pFlac->memoryStream; + } + + return pFlac; +} + + + +DRFLAC_API drflac* drflac_open(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks) +{ + return drflac_open_with_metadata_private(onRead, onSeek, onTell, NULL, drflac_container_unknown, pUserData, pUserData, pAllocationCallbacks); +} +DRFLAC_API drflac* drflac_open_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks) +{ + return drflac_open_with_metadata_private(onRead, onSeek, onTell, NULL, container, pUserData, pUserData, pAllocationCallbacks); +} + +DRFLAC_API drflac* drflac_open_with_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks) +{ + return drflac_open_with_metadata_private(onRead, onSeek, onTell, onMeta, drflac_container_unknown, pUserData, pUserData, pAllocationCallbacks); +} +DRFLAC_API drflac* drflac_open_with_metadata_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, drflac_meta_proc onMeta, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks) +{ + return drflac_open_with_metadata_private(onRead, onSeek, onTell, onMeta, container, pUserData, pUserData, pAllocationCallbacks); +} + +DRFLAC_API void drflac_close(drflac* pFlac) +{ + if (pFlac == NULL) { + return; + } + + + drflac__free_from_callbacks(pFlac, &pFlac->allocationCallbacks); +} + + +#if 0 +static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_left_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples) +{ + drflac_uint64 i; + for (i = 0; i < frameCount; ++i) { + drflac_uint32 left = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + drflac_uint32 right = left - side; + + pOutputSamples[i*2+0] = (drflac_int32)left; + pOutputSamples[i*2+1] = (drflac_int32)right; + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_left_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + for (i = 0; i < frameCount4; ++i) { + drflac_uint32 left0 = pInputSamples0U32[i*4+0] << shift0; + drflac_uint32 left1 = pInputSamples0U32[i*4+1] << shift0; + drflac_uint32 left2 = pInputSamples0U32[i*4+2] << shift0; + drflac_uint32 left3 = pInputSamples0U32[i*4+3] << shift0; + + drflac_uint32 side0 = pInputSamples1U32[i*4+0] << shift1; + drflac_uint32 side1 = pInputSamples1U32[i*4+1] << shift1; + drflac_uint32 side2 = pInputSamples1U32[i*4+2] << shift1; + drflac_uint32 side3 = pInputSamples1U32[i*4+3] << shift1; + + drflac_uint32 right0 = left0 - side0; + drflac_uint32 right1 = left1 - side1; + drflac_uint32 right2 = left2 - side2; + drflac_uint32 right3 = left3 - side3; + + pOutputSamples[i*8+0] = (drflac_int32)left0; + pOutputSamples[i*8+1] = (drflac_int32)right0; + pOutputSamples[i*8+2] = (drflac_int32)left1; + pOutputSamples[i*8+3] = (drflac_int32)right1; + pOutputSamples[i*8+4] = (drflac_int32)left2; + pOutputSamples[i*8+5] = (drflac_int32)right2; + pOutputSamples[i*8+6] = (drflac_int32)left3; + pOutputSamples[i*8+7] = (drflac_int32)right3; + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 left = pInputSamples0U32[i] << shift0; + drflac_uint32 side = pInputSamples1U32[i] << shift1; + drflac_uint32 right = left - side; + + pOutputSamples[i*2+0] = (drflac_int32)left; + pOutputSamples[i*2+1] = (drflac_int32)right; + } +} + +#if defined(DRFLAC_SUPPORT_SSE2) +static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_left_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + DRFLAC_ASSERT(pFlac->bitsPerSample <= 24); + + for (i = 0; i < frameCount4; ++i) { + __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0); + __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1); + __m128i right = _mm_sub_epi32(left, side); + + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right)); + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right)); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 left = pInputSamples0U32[i] << shift0; + drflac_uint32 side = pInputSamples1U32[i] << shift1; + drflac_uint32 right = left - side; + + pOutputSamples[i*2+0] = (drflac_int32)left; + pOutputSamples[i*2+1] = (drflac_int32)right; + } +} +#endif + +#if defined(DRFLAC_SUPPORT_NEON) +static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_left_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + int32x4_t shift0_4; + int32x4_t shift1_4; + + DRFLAC_ASSERT(pFlac->bitsPerSample <= 24); + + shift0_4 = vdupq_n_s32(shift0); + shift1_4 = vdupq_n_s32(shift1); + + for (i = 0; i < frameCount4; ++i) { + uint32x4_t left; + uint32x4_t side; + uint32x4_t right; + + left = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4); + side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4); + right = vsubq_u32(left, side); + + drflac__vst2q_u32((drflac_uint32*)pOutputSamples + i*8, vzipq_u32(left, right)); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 left = pInputSamples0U32[i] << shift0; + drflac_uint32 side = pInputSamples1U32[i] << shift1; + drflac_uint32 right = left - side; + + pOutputSamples[i*2+0] = (drflac_int32)left; + pOutputSamples[i*2+1] = (drflac_int32)right; + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_left_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples) +{ +#if defined(DRFLAC_SUPPORT_SSE2) + if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_s32__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#elif defined(DRFLAC_SUPPORT_NEON) + if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_s32__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { + /* Scalar fallback. */ +#if 0 + drflac_read_pcm_frames_s32__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + drflac_read_pcm_frames_s32__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif + } +} + + +#if 0 +static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_right_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples) +{ + drflac_uint64 i; + for (i = 0; i < frameCount; ++i) { + drflac_uint32 side = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + drflac_uint32 right = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + drflac_uint32 left = right + side; + + pOutputSamples[i*2+0] = (drflac_int32)left; + pOutputSamples[i*2+1] = (drflac_int32)right; + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_right_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + for (i = 0; i < frameCount4; ++i) { + drflac_uint32 side0 = pInputSamples0U32[i*4+0] << shift0; + drflac_uint32 side1 = pInputSamples0U32[i*4+1] << shift0; + drflac_uint32 side2 = pInputSamples0U32[i*4+2] << shift0; + drflac_uint32 side3 = pInputSamples0U32[i*4+3] << shift0; + + drflac_uint32 right0 = pInputSamples1U32[i*4+0] << shift1; + drflac_uint32 right1 = pInputSamples1U32[i*4+1] << shift1; + drflac_uint32 right2 = pInputSamples1U32[i*4+2] << shift1; + drflac_uint32 right3 = pInputSamples1U32[i*4+3] << shift1; + + drflac_uint32 left0 = right0 + side0; + drflac_uint32 left1 = right1 + side1; + drflac_uint32 left2 = right2 + side2; + drflac_uint32 left3 = right3 + side3; + + pOutputSamples[i*8+0] = (drflac_int32)left0; + pOutputSamples[i*8+1] = (drflac_int32)right0; + pOutputSamples[i*8+2] = (drflac_int32)left1; + pOutputSamples[i*8+3] = (drflac_int32)right1; + pOutputSamples[i*8+4] = (drflac_int32)left2; + pOutputSamples[i*8+5] = (drflac_int32)right2; + pOutputSamples[i*8+6] = (drflac_int32)left3; + pOutputSamples[i*8+7] = (drflac_int32)right3; + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 side = pInputSamples0U32[i] << shift0; + drflac_uint32 right = pInputSamples1U32[i] << shift1; + drflac_uint32 left = right + side; + + pOutputSamples[i*2+0] = (drflac_int32)left; + pOutputSamples[i*2+1] = (drflac_int32)right; + } +} + +#if defined(DRFLAC_SUPPORT_SSE2) +static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_right_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + DRFLAC_ASSERT(pFlac->bitsPerSample <= 24); + + for (i = 0; i < frameCount4; ++i) { + __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0); + __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1); + __m128i left = _mm_add_epi32(right, side); + + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right)); + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right)); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 side = pInputSamples0U32[i] << shift0; + drflac_uint32 right = pInputSamples1U32[i] << shift1; + drflac_uint32 left = right + side; + + pOutputSamples[i*2+0] = (drflac_int32)left; + pOutputSamples[i*2+1] = (drflac_int32)right; + } +} +#endif + +#if defined(DRFLAC_SUPPORT_NEON) +static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_right_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + int32x4_t shift0_4; + int32x4_t shift1_4; + + DRFLAC_ASSERT(pFlac->bitsPerSample <= 24); + + shift0_4 = vdupq_n_s32(shift0); + shift1_4 = vdupq_n_s32(shift1); + + for (i = 0; i < frameCount4; ++i) { + uint32x4_t side; + uint32x4_t right; + uint32x4_t left; + + side = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4); + right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4); + left = vaddq_u32(right, side); + + drflac__vst2q_u32((drflac_uint32*)pOutputSamples + i*8, vzipq_u32(left, right)); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 side = pInputSamples0U32[i] << shift0; + drflac_uint32 right = pInputSamples1U32[i] << shift1; + drflac_uint32 left = right + side; + + pOutputSamples[i*2+0] = (drflac_int32)left; + pOutputSamples[i*2+1] = (drflac_int32)right; + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_right_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples) +{ +#if defined(DRFLAC_SUPPORT_SSE2) + if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_s32__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#elif defined(DRFLAC_SUPPORT_NEON) + if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_s32__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { + /* Scalar fallback. */ +#if 0 + drflac_read_pcm_frames_s32__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + drflac_read_pcm_frames_s32__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif + } +} + + +#if 0 +static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_mid_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples) +{ + for (drflac_uint64 i = 0; i < frameCount; ++i) { + drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + mid = (mid << 1) | (side & 0x01); + + pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample); + pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample); + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_mid_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_int32 shift = unusedBitsPerSample; + + if (shift > 0) { + shift -= 1; + for (i = 0; i < frameCount4; ++i) { + drflac_uint32 temp0L; + drflac_uint32 temp1L; + drflac_uint32 temp2L; + drflac_uint32 temp3L; + drflac_uint32 temp0R; + drflac_uint32 temp1R; + drflac_uint32 temp2R; + drflac_uint32 temp3R; + + drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + + drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + mid0 = (mid0 << 1) | (side0 & 0x01); + mid1 = (mid1 << 1) | (side1 & 0x01); + mid2 = (mid2 << 1) | (side2 & 0x01); + mid3 = (mid3 << 1) | (side3 & 0x01); + + temp0L = (mid0 + side0) << shift; + temp1L = (mid1 + side1) << shift; + temp2L = (mid2 + side2) << shift; + temp3L = (mid3 + side3) << shift; + + temp0R = (mid0 - side0) << shift; + temp1R = (mid1 - side1) << shift; + temp2R = (mid2 - side2) << shift; + temp3R = (mid3 - side3) << shift; + + pOutputSamples[i*8+0] = (drflac_int32)temp0L; + pOutputSamples[i*8+1] = (drflac_int32)temp0R; + pOutputSamples[i*8+2] = (drflac_int32)temp1L; + pOutputSamples[i*8+3] = (drflac_int32)temp1R; + pOutputSamples[i*8+4] = (drflac_int32)temp2L; + pOutputSamples[i*8+5] = (drflac_int32)temp2R; + pOutputSamples[i*8+6] = (drflac_int32)temp3L; + pOutputSamples[i*8+7] = (drflac_int32)temp3R; + } + } else { + for (i = 0; i < frameCount4; ++i) { + drflac_uint32 temp0L; + drflac_uint32 temp1L; + drflac_uint32 temp2L; + drflac_uint32 temp3L; + drflac_uint32 temp0R; + drflac_uint32 temp1R; + drflac_uint32 temp2R; + drflac_uint32 temp3R; + + drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + + drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + mid0 = (mid0 << 1) | (side0 & 0x01); + mid1 = (mid1 << 1) | (side1 & 0x01); + mid2 = (mid2 << 1) | (side2 & 0x01); + mid3 = (mid3 << 1) | (side3 & 0x01); + + temp0L = (drflac_uint32)((drflac_int32)(mid0 + side0) >> 1); + temp1L = (drflac_uint32)((drflac_int32)(mid1 + side1) >> 1); + temp2L = (drflac_uint32)((drflac_int32)(mid2 + side2) >> 1); + temp3L = (drflac_uint32)((drflac_int32)(mid3 + side3) >> 1); + + temp0R = (drflac_uint32)((drflac_int32)(mid0 - side0) >> 1); + temp1R = (drflac_uint32)((drflac_int32)(mid1 - side1) >> 1); + temp2R = (drflac_uint32)((drflac_int32)(mid2 - side2) >> 1); + temp3R = (drflac_uint32)((drflac_int32)(mid3 - side3) >> 1); + + pOutputSamples[i*8+0] = (drflac_int32)temp0L; + pOutputSamples[i*8+1] = (drflac_int32)temp0R; + pOutputSamples[i*8+2] = (drflac_int32)temp1L; + pOutputSamples[i*8+3] = (drflac_int32)temp1R; + pOutputSamples[i*8+4] = (drflac_int32)temp2L; + pOutputSamples[i*8+5] = (drflac_int32)temp2R; + pOutputSamples[i*8+6] = (drflac_int32)temp3L; + pOutputSamples[i*8+7] = (drflac_int32)temp3R; + } + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + mid = (mid << 1) | (side & 0x01); + + pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample); + pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample); + } +} + +#if defined(DRFLAC_SUPPORT_SSE2) +static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_mid_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_int32 shift = unusedBitsPerSample; + + DRFLAC_ASSERT(pFlac->bitsPerSample <= 24); + + if (shift == 0) { + for (i = 0; i < frameCount4; ++i) { + __m128i mid; + __m128i side; + __m128i left; + __m128i right; + + mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + + mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01))); + + left = _mm_srai_epi32(_mm_add_epi32(mid, side), 1); + right = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1); + + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right)); + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right)); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + mid = (mid << 1) | (side & 0x01); + + pOutputSamples[i*2+0] = (drflac_int32)(mid + side) >> 1; + pOutputSamples[i*2+1] = (drflac_int32)(mid - side) >> 1; + } + } else { + shift -= 1; + for (i = 0; i < frameCount4; ++i) { + __m128i mid; + __m128i side; + __m128i left; + __m128i right; + + mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + + mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01))); + + left = _mm_slli_epi32(_mm_add_epi32(mid, side), shift); + right = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift); + + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right)); + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right)); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + mid = (mid << 1) | (side & 0x01); + + pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift); + pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift); + } + } +} +#endif + +#if defined(DRFLAC_SUPPORT_NEON) +static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_mid_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_int32 shift = unusedBitsPerSample; + int32x4_t wbpsShift0_4; /* wbps = Wasted Bits Per Sample */ + int32x4_t wbpsShift1_4; /* wbps = Wasted Bits Per Sample */ + uint32x4_t one4; + + DRFLAC_ASSERT(pFlac->bitsPerSample <= 24); + + wbpsShift0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + wbpsShift1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + one4 = vdupq_n_u32(1); + + if (shift == 0) { + for (i = 0; i < frameCount4; ++i) { + uint32x4_t mid; + uint32x4_t side; + int32x4_t left; + int32x4_t right; + + mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4); + side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4); + + mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, one4)); + + left = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1); + right = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1); + + drflac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right)); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + mid = (mid << 1) | (side & 0x01); + + pOutputSamples[i*2+0] = (drflac_int32)(mid + side) >> 1; + pOutputSamples[i*2+1] = (drflac_int32)(mid - side) >> 1; + } + } else { + int32x4_t shift4; + + shift -= 1; + shift4 = vdupq_n_s32(shift); + + for (i = 0; i < frameCount4; ++i) { + uint32x4_t mid; + uint32x4_t side; + int32x4_t left; + int32x4_t right; + + mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4); + side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4); + + mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, one4)); + + left = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4)); + right = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4)); + + drflac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right)); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + mid = (mid << 1) | (side & 0x01); + + pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift); + pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift); + } + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_mid_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples) +{ +#if defined(DRFLAC_SUPPORT_SSE2) + if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_s32__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#elif defined(DRFLAC_SUPPORT_NEON) + if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_s32__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { + /* Scalar fallback. */ +#if 0 + drflac_read_pcm_frames_s32__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + drflac_read_pcm_frames_s32__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif + } +} + + +#if 0 +static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_independent_stereo__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples) +{ + for (drflac_uint64 i = 0; i < frameCount; ++i) { + pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample)); + pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample)); + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_independent_stereo__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + for (i = 0; i < frameCount4; ++i) { + drflac_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0; + drflac_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0; + drflac_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0; + drflac_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0; + + drflac_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1; + drflac_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1; + drflac_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1; + drflac_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1; + + pOutputSamples[i*8+0] = (drflac_int32)tempL0; + pOutputSamples[i*8+1] = (drflac_int32)tempR0; + pOutputSamples[i*8+2] = (drflac_int32)tempL1; + pOutputSamples[i*8+3] = (drflac_int32)tempR1; + pOutputSamples[i*8+4] = (drflac_int32)tempL2; + pOutputSamples[i*8+5] = (drflac_int32)tempR2; + pOutputSamples[i*8+6] = (drflac_int32)tempL3; + pOutputSamples[i*8+7] = (drflac_int32)tempR3; + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0); + pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1); + } +} + +#if defined(DRFLAC_SUPPORT_SSE2) +static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_independent_stereo__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + for (i = 0; i < frameCount4; ++i) { + __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0); + __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1); + + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right)); + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right)); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0); + pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1); + } +} +#endif + +#if defined(DRFLAC_SUPPORT_NEON) +static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_independent_stereo__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + int32x4_t shift4_0 = vdupq_n_s32(shift0); + int32x4_t shift4_1 = vdupq_n_s32(shift1); + + for (i = 0; i < frameCount4; ++i) { + int32x4_t left; + int32x4_t right; + + left = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift4_0)); + right = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift4_1)); + + drflac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right)); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0); + pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1); + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_independent_stereo(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples) +{ +#if defined(DRFLAC_SUPPORT_SSE2) + if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_s32__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#elif defined(DRFLAC_SUPPORT_NEON) + if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_s32__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { + /* Scalar fallback. */ +#if 0 + drflac_read_pcm_frames_s32__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + drflac_read_pcm_frames_s32__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif + } +} + + +DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s32(drflac* pFlac, drflac_uint64 framesToRead, drflac_int32* pBufferOut) +{ + drflac_uint64 framesRead; + drflac_uint32 unusedBitsPerSample; + + if (pFlac == NULL || framesToRead == 0) { + return 0; + } + + if (pBufferOut == NULL) { + return drflac__seek_forward_by_pcm_frames(pFlac, framesToRead); + } + + DRFLAC_ASSERT(pFlac->bitsPerSample <= 32); + unusedBitsPerSample = 32 - pFlac->bitsPerSample; + + framesRead = 0; + while (framesToRead > 0) { + /* If we've run out of samples in this frame, go to the next. */ + if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) { + if (!drflac__read_and_decode_next_flac_frame(pFlac)) { + break; /* Couldn't read the next frame, so just break from the loop and return. */ + } + } else { + unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment); + drflac_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining; + drflac_uint64 frameCountThisIteration = framesToRead; + + if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) { + frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining; + } + + if (channelCount == 2) { + const drflac_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame; + const drflac_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame; + + switch (pFlac->currentFLACFrame.header.channelAssignment) + { + case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE: + { + drflac_read_pcm_frames_s32__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + + case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE: + { + drflac_read_pcm_frames_s32__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + + case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE: + { + drflac_read_pcm_frames_s32__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + + case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT: + default: + { + drflac_read_pcm_frames_s32__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + } + } else { + /* Generic interleaving. */ + drflac_uint64 i; + for (i = 0; i < frameCountThisIteration; ++i) { + unsigned int j; + for (j = 0; j < channelCount; ++j) { + pBufferOut[(i*channelCount)+j] = (drflac_int32)((drflac_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample)); + } + } + } + + framesRead += frameCountThisIteration; + pBufferOut += frameCountThisIteration * channelCount; + framesToRead -= frameCountThisIteration; + pFlac->currentPCMFrame += frameCountThisIteration; + pFlac->currentFLACFrame.pcmFramesRemaining -= (drflac_uint32)frameCountThisIteration; + } + } + + return framesRead; +} + + +#if 0 +static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_left_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples) +{ + drflac_uint64 i; + for (i = 0; i < frameCount; ++i) { + drflac_uint32 left = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + drflac_uint32 right = left - side; + + left >>= 16; + right >>= 16; + + pOutputSamples[i*2+0] = (drflac_int16)left; + pOutputSamples[i*2+1] = (drflac_int16)right; + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_left_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + for (i = 0; i < frameCount4; ++i) { + drflac_uint32 left0 = pInputSamples0U32[i*4+0] << shift0; + drflac_uint32 left1 = pInputSamples0U32[i*4+1] << shift0; + drflac_uint32 left2 = pInputSamples0U32[i*4+2] << shift0; + drflac_uint32 left3 = pInputSamples0U32[i*4+3] << shift0; + + drflac_uint32 side0 = pInputSamples1U32[i*4+0] << shift1; + drflac_uint32 side1 = pInputSamples1U32[i*4+1] << shift1; + drflac_uint32 side2 = pInputSamples1U32[i*4+2] << shift1; + drflac_uint32 side3 = pInputSamples1U32[i*4+3] << shift1; + + drflac_uint32 right0 = left0 - side0; + drflac_uint32 right1 = left1 - side1; + drflac_uint32 right2 = left2 - side2; + drflac_uint32 right3 = left3 - side3; + + left0 >>= 16; + left1 >>= 16; + left2 >>= 16; + left3 >>= 16; + + right0 >>= 16; + right1 >>= 16; + right2 >>= 16; + right3 >>= 16; + + pOutputSamples[i*8+0] = (drflac_int16)left0; + pOutputSamples[i*8+1] = (drflac_int16)right0; + pOutputSamples[i*8+2] = (drflac_int16)left1; + pOutputSamples[i*8+3] = (drflac_int16)right1; + pOutputSamples[i*8+4] = (drflac_int16)left2; + pOutputSamples[i*8+5] = (drflac_int16)right2; + pOutputSamples[i*8+6] = (drflac_int16)left3; + pOutputSamples[i*8+7] = (drflac_int16)right3; + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 left = pInputSamples0U32[i] << shift0; + drflac_uint32 side = pInputSamples1U32[i] << shift1; + drflac_uint32 right = left - side; + + left >>= 16; + right >>= 16; + + pOutputSamples[i*2+0] = (drflac_int16)left; + pOutputSamples[i*2+1] = (drflac_int16)right; + } +} + +#if defined(DRFLAC_SUPPORT_SSE2) +static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_left_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + DRFLAC_ASSERT(pFlac->bitsPerSample <= 24); + + for (i = 0; i < frameCount4; ++i) { + __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0); + __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1); + __m128i right = _mm_sub_epi32(left, side); + + left = _mm_srai_epi32(left, 16); + right = _mm_srai_epi32(right, 16); + + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right)); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 left = pInputSamples0U32[i] << shift0; + drflac_uint32 side = pInputSamples1U32[i] << shift1; + drflac_uint32 right = left - side; + + left >>= 16; + right >>= 16; + + pOutputSamples[i*2+0] = (drflac_int16)left; + pOutputSamples[i*2+1] = (drflac_int16)right; + } +} +#endif + +#if defined(DRFLAC_SUPPORT_NEON) +static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_left_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + int32x4_t shift0_4; + int32x4_t shift1_4; + + DRFLAC_ASSERT(pFlac->bitsPerSample <= 24); + + shift0_4 = vdupq_n_s32(shift0); + shift1_4 = vdupq_n_s32(shift1); + + for (i = 0; i < frameCount4; ++i) { + uint32x4_t left; + uint32x4_t side; + uint32x4_t right; + + left = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4); + side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4); + right = vsubq_u32(left, side); + + left = vshrq_n_u32(left, 16); + right = vshrq_n_u32(right, 16); + + drflac__vst2q_u16((drflac_uint16*)pOutputSamples + i*8, vzip_u16(vmovn_u32(left), vmovn_u32(right))); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 left = pInputSamples0U32[i] << shift0; + drflac_uint32 side = pInputSamples1U32[i] << shift1; + drflac_uint32 right = left - side; + + left >>= 16; + right >>= 16; + + pOutputSamples[i*2+0] = (drflac_int16)left; + pOutputSamples[i*2+1] = (drflac_int16)right; + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_left_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples) +{ +#if defined(DRFLAC_SUPPORT_SSE2) + if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_s16__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#elif defined(DRFLAC_SUPPORT_NEON) + if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_s16__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { + /* Scalar fallback. */ +#if 0 + drflac_read_pcm_frames_s16__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + drflac_read_pcm_frames_s16__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif + } +} + + +#if 0 +static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_right_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples) +{ + drflac_uint64 i; + for (i = 0; i < frameCount; ++i) { + drflac_uint32 side = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + drflac_uint32 right = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + drflac_uint32 left = right + side; + + left >>= 16; + right >>= 16; + + pOutputSamples[i*2+0] = (drflac_int16)left; + pOutputSamples[i*2+1] = (drflac_int16)right; + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_right_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + for (i = 0; i < frameCount4; ++i) { + drflac_uint32 side0 = pInputSamples0U32[i*4+0] << shift0; + drflac_uint32 side1 = pInputSamples0U32[i*4+1] << shift0; + drflac_uint32 side2 = pInputSamples0U32[i*4+2] << shift0; + drflac_uint32 side3 = pInputSamples0U32[i*4+3] << shift0; + + drflac_uint32 right0 = pInputSamples1U32[i*4+0] << shift1; + drflac_uint32 right1 = pInputSamples1U32[i*4+1] << shift1; + drflac_uint32 right2 = pInputSamples1U32[i*4+2] << shift1; + drflac_uint32 right3 = pInputSamples1U32[i*4+3] << shift1; + + drflac_uint32 left0 = right0 + side0; + drflac_uint32 left1 = right1 + side1; + drflac_uint32 left2 = right2 + side2; + drflac_uint32 left3 = right3 + side3; + + left0 >>= 16; + left1 >>= 16; + left2 >>= 16; + left3 >>= 16; + + right0 >>= 16; + right1 >>= 16; + right2 >>= 16; + right3 >>= 16; + + pOutputSamples[i*8+0] = (drflac_int16)left0; + pOutputSamples[i*8+1] = (drflac_int16)right0; + pOutputSamples[i*8+2] = (drflac_int16)left1; + pOutputSamples[i*8+3] = (drflac_int16)right1; + pOutputSamples[i*8+4] = (drflac_int16)left2; + pOutputSamples[i*8+5] = (drflac_int16)right2; + pOutputSamples[i*8+6] = (drflac_int16)left3; + pOutputSamples[i*8+7] = (drflac_int16)right3; + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 side = pInputSamples0U32[i] << shift0; + drflac_uint32 right = pInputSamples1U32[i] << shift1; + drflac_uint32 left = right + side; + + left >>= 16; + right >>= 16; + + pOutputSamples[i*2+0] = (drflac_int16)left; + pOutputSamples[i*2+1] = (drflac_int16)right; + } +} + +#if defined(DRFLAC_SUPPORT_SSE2) +static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_right_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + DRFLAC_ASSERT(pFlac->bitsPerSample <= 24); + + for (i = 0; i < frameCount4; ++i) { + __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0); + __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1); + __m128i left = _mm_add_epi32(right, side); + + left = _mm_srai_epi32(left, 16); + right = _mm_srai_epi32(right, 16); + + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right)); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 side = pInputSamples0U32[i] << shift0; + drflac_uint32 right = pInputSamples1U32[i] << shift1; + drflac_uint32 left = right + side; + + left >>= 16; + right >>= 16; + + pOutputSamples[i*2+0] = (drflac_int16)left; + pOutputSamples[i*2+1] = (drflac_int16)right; + } +} +#endif + +#if defined(DRFLAC_SUPPORT_NEON) +static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_right_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + int32x4_t shift0_4; + int32x4_t shift1_4; + + DRFLAC_ASSERT(pFlac->bitsPerSample <= 24); + + shift0_4 = vdupq_n_s32(shift0); + shift1_4 = vdupq_n_s32(shift1); + + for (i = 0; i < frameCount4; ++i) { + uint32x4_t side; + uint32x4_t right; + uint32x4_t left; + + side = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4); + right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4); + left = vaddq_u32(right, side); + + left = vshrq_n_u32(left, 16); + right = vshrq_n_u32(right, 16); + + drflac__vst2q_u16((drflac_uint16*)pOutputSamples + i*8, vzip_u16(vmovn_u32(left), vmovn_u32(right))); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 side = pInputSamples0U32[i] << shift0; + drflac_uint32 right = pInputSamples1U32[i] << shift1; + drflac_uint32 left = right + side; + + left >>= 16; + right >>= 16; + + pOutputSamples[i*2+0] = (drflac_int16)left; + pOutputSamples[i*2+1] = (drflac_int16)right; + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_right_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples) +{ +#if defined(DRFLAC_SUPPORT_SSE2) + if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_s16__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#elif defined(DRFLAC_SUPPORT_NEON) + if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_s16__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { + /* Scalar fallback. */ +#if 0 + drflac_read_pcm_frames_s16__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + drflac_read_pcm_frames_s16__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif + } +} + + +#if 0 +static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_mid_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples) +{ + for (drflac_uint64 i = 0; i < frameCount; ++i) { + drflac_uint32 mid = (drflac_uint32)pInputSamples0[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + mid = (mid << 1) | (side & 0x01); + + pOutputSamples[i*2+0] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample) >> 16); + pOutputSamples[i*2+1] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample) >> 16); + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_mid_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift = unusedBitsPerSample; + + if (shift > 0) { + shift -= 1; + for (i = 0; i < frameCount4; ++i) { + drflac_uint32 temp0L; + drflac_uint32 temp1L; + drflac_uint32 temp2L; + drflac_uint32 temp3L; + drflac_uint32 temp0R; + drflac_uint32 temp1R; + drflac_uint32 temp2R; + drflac_uint32 temp3R; + + drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + + drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + mid0 = (mid0 << 1) | (side0 & 0x01); + mid1 = (mid1 << 1) | (side1 & 0x01); + mid2 = (mid2 << 1) | (side2 & 0x01); + mid3 = (mid3 << 1) | (side3 & 0x01); + + temp0L = (mid0 + side0) << shift; + temp1L = (mid1 + side1) << shift; + temp2L = (mid2 + side2) << shift; + temp3L = (mid3 + side3) << shift; + + temp0R = (mid0 - side0) << shift; + temp1R = (mid1 - side1) << shift; + temp2R = (mid2 - side2) << shift; + temp3R = (mid3 - side3) << shift; + + temp0L >>= 16; + temp1L >>= 16; + temp2L >>= 16; + temp3L >>= 16; + + temp0R >>= 16; + temp1R >>= 16; + temp2R >>= 16; + temp3R >>= 16; + + pOutputSamples[i*8+0] = (drflac_int16)temp0L; + pOutputSamples[i*8+1] = (drflac_int16)temp0R; + pOutputSamples[i*8+2] = (drflac_int16)temp1L; + pOutputSamples[i*8+3] = (drflac_int16)temp1R; + pOutputSamples[i*8+4] = (drflac_int16)temp2L; + pOutputSamples[i*8+5] = (drflac_int16)temp2R; + pOutputSamples[i*8+6] = (drflac_int16)temp3L; + pOutputSamples[i*8+7] = (drflac_int16)temp3R; + } + } else { + for (i = 0; i < frameCount4; ++i) { + drflac_uint32 temp0L; + drflac_uint32 temp1L; + drflac_uint32 temp2L; + drflac_uint32 temp3L; + drflac_uint32 temp0R; + drflac_uint32 temp1R; + drflac_uint32 temp2R; + drflac_uint32 temp3R; + + drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + + drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + mid0 = (mid0 << 1) | (side0 & 0x01); + mid1 = (mid1 << 1) | (side1 & 0x01); + mid2 = (mid2 << 1) | (side2 & 0x01); + mid3 = (mid3 << 1) | (side3 & 0x01); + + temp0L = ((drflac_int32)(mid0 + side0) >> 1); + temp1L = ((drflac_int32)(mid1 + side1) >> 1); + temp2L = ((drflac_int32)(mid2 + side2) >> 1); + temp3L = ((drflac_int32)(mid3 + side3) >> 1); + + temp0R = ((drflac_int32)(mid0 - side0) >> 1); + temp1R = ((drflac_int32)(mid1 - side1) >> 1); + temp2R = ((drflac_int32)(mid2 - side2) >> 1); + temp3R = ((drflac_int32)(mid3 - side3) >> 1); + + temp0L >>= 16; + temp1L >>= 16; + temp2L >>= 16; + temp3L >>= 16; + + temp0R >>= 16; + temp1R >>= 16; + temp2R >>= 16; + temp3R >>= 16; + + pOutputSamples[i*8+0] = (drflac_int16)temp0L; + pOutputSamples[i*8+1] = (drflac_int16)temp0R; + pOutputSamples[i*8+2] = (drflac_int16)temp1L; + pOutputSamples[i*8+3] = (drflac_int16)temp1R; + pOutputSamples[i*8+4] = (drflac_int16)temp2L; + pOutputSamples[i*8+5] = (drflac_int16)temp2R; + pOutputSamples[i*8+6] = (drflac_int16)temp3L; + pOutputSamples[i*8+7] = (drflac_int16)temp3R; + } + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + mid = (mid << 1) | (side & 0x01); + + pOutputSamples[i*2+0] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample) >> 16); + pOutputSamples[i*2+1] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample) >> 16); + } +} + +#if defined(DRFLAC_SUPPORT_SSE2) +static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_mid_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift = unusedBitsPerSample; + + DRFLAC_ASSERT(pFlac->bitsPerSample <= 24); + + if (shift == 0) { + for (i = 0; i < frameCount4; ++i) { + __m128i mid; + __m128i side; + __m128i left; + __m128i right; + + mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + + mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01))); + + left = _mm_srai_epi32(_mm_add_epi32(mid, side), 1); + right = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1); + + left = _mm_srai_epi32(left, 16); + right = _mm_srai_epi32(right, 16); + + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right)); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + mid = (mid << 1) | (side & 0x01); + + pOutputSamples[i*2+0] = (drflac_int16)(((drflac_int32)(mid + side) >> 1) >> 16); + pOutputSamples[i*2+1] = (drflac_int16)(((drflac_int32)(mid - side) >> 1) >> 16); + } + } else { + shift -= 1; + for (i = 0; i < frameCount4; ++i) { + __m128i mid; + __m128i side; + __m128i left; + __m128i right; + + mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + + mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01))); + + left = _mm_slli_epi32(_mm_add_epi32(mid, side), shift); + right = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift); + + left = _mm_srai_epi32(left, 16); + right = _mm_srai_epi32(right, 16); + + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right)); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + mid = (mid << 1) | (side & 0x01); + + pOutputSamples[i*2+0] = (drflac_int16)(((mid + side) << shift) >> 16); + pOutputSamples[i*2+1] = (drflac_int16)(((mid - side) << shift) >> 16); + } + } +} +#endif + +#if defined(DRFLAC_SUPPORT_NEON) +static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_mid_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift = unusedBitsPerSample; + int32x4_t wbpsShift0_4; /* wbps = Wasted Bits Per Sample */ + int32x4_t wbpsShift1_4; /* wbps = Wasted Bits Per Sample */ + + DRFLAC_ASSERT(pFlac->bitsPerSample <= 24); + + wbpsShift0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + wbpsShift1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + + if (shift == 0) { + for (i = 0; i < frameCount4; ++i) { + uint32x4_t mid; + uint32x4_t side; + int32x4_t left; + int32x4_t right; + + mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4); + side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4); + + mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1))); + + left = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1); + right = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1); + + left = vshrq_n_s32(left, 16); + right = vshrq_n_s32(right, 16); + + drflac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right))); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + mid = (mid << 1) | (side & 0x01); + + pOutputSamples[i*2+0] = (drflac_int16)(((drflac_int32)(mid + side) >> 1) >> 16); + pOutputSamples[i*2+1] = (drflac_int16)(((drflac_int32)(mid - side) >> 1) >> 16); + } + } else { + int32x4_t shift4; + + shift -= 1; + shift4 = vdupq_n_s32(shift); + + for (i = 0; i < frameCount4; ++i) { + uint32x4_t mid; + uint32x4_t side; + int32x4_t left; + int32x4_t right; + + mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4); + side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4); + + mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1))); + + left = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4)); + right = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4)); + + left = vshrq_n_s32(left, 16); + right = vshrq_n_s32(right, 16); + + drflac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right))); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + mid = (mid << 1) | (side & 0x01); + + pOutputSamples[i*2+0] = (drflac_int16)(((mid + side) << shift) >> 16); + pOutputSamples[i*2+1] = (drflac_int16)(((mid - side) << shift) >> 16); + } + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_mid_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples) +{ +#if defined(DRFLAC_SUPPORT_SSE2) + if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_s16__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#elif defined(DRFLAC_SUPPORT_NEON) + if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_s16__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { + /* Scalar fallback. */ +#if 0 + drflac_read_pcm_frames_s16__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + drflac_read_pcm_frames_s16__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif + } +} + + +#if 0 +static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_independent_stereo__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples) +{ + for (drflac_uint64 i = 0; i < frameCount; ++i) { + pOutputSamples[i*2+0] = (drflac_int16)((drflac_int32)((drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample)) >> 16); + pOutputSamples[i*2+1] = (drflac_int16)((drflac_int32)((drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample)) >> 16); + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_independent_stereo__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + for (i = 0; i < frameCount4; ++i) { + drflac_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0; + drflac_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0; + drflac_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0; + drflac_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0; + + drflac_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1; + drflac_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1; + drflac_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1; + drflac_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1; + + tempL0 >>= 16; + tempL1 >>= 16; + tempL2 >>= 16; + tempL3 >>= 16; + + tempR0 >>= 16; + tempR1 >>= 16; + tempR2 >>= 16; + tempR3 >>= 16; + + pOutputSamples[i*8+0] = (drflac_int16)tempL0; + pOutputSamples[i*8+1] = (drflac_int16)tempR0; + pOutputSamples[i*8+2] = (drflac_int16)tempL1; + pOutputSamples[i*8+3] = (drflac_int16)tempR1; + pOutputSamples[i*8+4] = (drflac_int16)tempL2; + pOutputSamples[i*8+5] = (drflac_int16)tempR2; + pOutputSamples[i*8+6] = (drflac_int16)tempL3; + pOutputSamples[i*8+7] = (drflac_int16)tempR3; + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + pOutputSamples[i*2+0] = (drflac_int16)((pInputSamples0U32[i] << shift0) >> 16); + pOutputSamples[i*2+1] = (drflac_int16)((pInputSamples1U32[i] << shift1) >> 16); + } +} + +#if defined(DRFLAC_SUPPORT_SSE2) +static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_independent_stereo__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + for (i = 0; i < frameCount4; ++i) { + __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0); + __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1); + + left = _mm_srai_epi32(left, 16); + right = _mm_srai_epi32(right, 16); + + /* At this point we have results. We can now pack and interleave these into a single __m128i object and then store the in the output buffer. */ + _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right)); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + pOutputSamples[i*2+0] = (drflac_int16)((pInputSamples0U32[i] << shift0) >> 16); + pOutputSamples[i*2+1] = (drflac_int16)((pInputSamples1U32[i] << shift1) >> 16); + } +} +#endif + +#if defined(DRFLAC_SUPPORT_NEON) +static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_independent_stereo__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + int32x4_t shift0_4 = vdupq_n_s32(shift0); + int32x4_t shift1_4 = vdupq_n_s32(shift1); + + for (i = 0; i < frameCount4; ++i) { + int32x4_t left; + int32x4_t right; + + left = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4)); + right = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4)); + + left = vshrq_n_s32(left, 16); + right = vshrq_n_s32(right, 16); + + drflac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right))); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + pOutputSamples[i*2+0] = (drflac_int16)((pInputSamples0U32[i] << shift0) >> 16); + pOutputSamples[i*2+1] = (drflac_int16)((pInputSamples1U32[i] << shift1) >> 16); + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_independent_stereo(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples) +{ +#if defined(DRFLAC_SUPPORT_SSE2) + if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_s16__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#elif defined(DRFLAC_SUPPORT_NEON) + if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_s16__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { + /* Scalar fallback. */ +#if 0 + drflac_read_pcm_frames_s16__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + drflac_read_pcm_frames_s16__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif + } +} + +DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s16(drflac* pFlac, drflac_uint64 framesToRead, drflac_int16* pBufferOut) +{ + drflac_uint64 framesRead; + drflac_uint32 unusedBitsPerSample; + + if (pFlac == NULL || framesToRead == 0) { + return 0; + } + + if (pBufferOut == NULL) { + return drflac__seek_forward_by_pcm_frames(pFlac, framesToRead); + } + + DRFLAC_ASSERT(pFlac->bitsPerSample <= 32); + unusedBitsPerSample = 32 - pFlac->bitsPerSample; + + framesRead = 0; + while (framesToRead > 0) { + /* If we've run out of samples in this frame, go to the next. */ + if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) { + if (!drflac__read_and_decode_next_flac_frame(pFlac)) { + break; /* Couldn't read the next frame, so just break from the loop and return. */ + } + } else { + unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment); + drflac_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining; + drflac_uint64 frameCountThisIteration = framesToRead; + + if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) { + frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining; + } + + if (channelCount == 2) { + const drflac_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame; + const drflac_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame; + + switch (pFlac->currentFLACFrame.header.channelAssignment) + { + case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE: + { + drflac_read_pcm_frames_s16__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + + case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE: + { + drflac_read_pcm_frames_s16__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + + case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE: + { + drflac_read_pcm_frames_s16__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + + case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT: + default: + { + drflac_read_pcm_frames_s16__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + } + } else { + /* Generic interleaving. */ + drflac_uint64 i; + for (i = 0; i < frameCountThisIteration; ++i) { + unsigned int j; + for (j = 0; j < channelCount; ++j) { + drflac_int32 sampleS32 = (drflac_int32)((drflac_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample)); + pBufferOut[(i*channelCount)+j] = (drflac_int16)(sampleS32 >> 16); + } + } + } + + framesRead += frameCountThisIteration; + pBufferOut += frameCountThisIteration * channelCount; + framesToRead -= frameCountThisIteration; + pFlac->currentPCMFrame += frameCountThisIteration; + pFlac->currentFLACFrame.pcmFramesRemaining -= (drflac_uint32)frameCountThisIteration; + } + } + + return framesRead; +} + + +#if 0 +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ + drflac_uint64 i; + for (i = 0; i < frameCount; ++i) { + drflac_uint32 left = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + drflac_uint32 right = left - side; + + pOutputSamples[i*2+0] = (float)((drflac_int32)left / 2147483648.0); + pOutputSamples[i*2+1] = (float)((drflac_int32)right / 2147483648.0); + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + float factor = 1 / 2147483648.0; + + for (i = 0; i < frameCount4; ++i) { + drflac_uint32 left0 = pInputSamples0U32[i*4+0] << shift0; + drflac_uint32 left1 = pInputSamples0U32[i*4+1] << shift0; + drflac_uint32 left2 = pInputSamples0U32[i*4+2] << shift0; + drflac_uint32 left3 = pInputSamples0U32[i*4+3] << shift0; + + drflac_uint32 side0 = pInputSamples1U32[i*4+0] << shift1; + drflac_uint32 side1 = pInputSamples1U32[i*4+1] << shift1; + drflac_uint32 side2 = pInputSamples1U32[i*4+2] << shift1; + drflac_uint32 side3 = pInputSamples1U32[i*4+3] << shift1; + + drflac_uint32 right0 = left0 - side0; + drflac_uint32 right1 = left1 - side1; + drflac_uint32 right2 = left2 - side2; + drflac_uint32 right3 = left3 - side3; + + pOutputSamples[i*8+0] = (drflac_int32)left0 * factor; + pOutputSamples[i*8+1] = (drflac_int32)right0 * factor; + pOutputSamples[i*8+2] = (drflac_int32)left1 * factor; + pOutputSamples[i*8+3] = (drflac_int32)right1 * factor; + pOutputSamples[i*8+4] = (drflac_int32)left2 * factor; + pOutputSamples[i*8+5] = (drflac_int32)right2 * factor; + pOutputSamples[i*8+6] = (drflac_int32)left3 * factor; + pOutputSamples[i*8+7] = (drflac_int32)right3 * factor; + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 left = pInputSamples0U32[i] << shift0; + drflac_uint32 side = pInputSamples1U32[i] << shift1; + drflac_uint32 right = left - side; + + pOutputSamples[i*2+0] = (drflac_int32)left * factor; + pOutputSamples[i*2+1] = (drflac_int32)right * factor; + } +} + +#if defined(DRFLAC_SUPPORT_SSE2) +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8; + drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8; + __m128 factor; + + DRFLAC_ASSERT(pFlac->bitsPerSample <= 24); + + factor = _mm_set1_ps(1.0f / 8388608.0f); + + for (i = 0; i < frameCount4; ++i) { + __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0); + __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1); + __m128i right = _mm_sub_epi32(left, side); + __m128 leftf = _mm_mul_ps(_mm_cvtepi32_ps(left), factor); + __m128 rightf = _mm_mul_ps(_mm_cvtepi32_ps(right), factor); + + _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf)); + _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf)); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 left = pInputSamples0U32[i] << shift0; + drflac_uint32 side = pInputSamples1U32[i] << shift1; + drflac_uint32 right = left - side; + + pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f; + pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f; + } +} +#endif + +#if defined(DRFLAC_SUPPORT_NEON) +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8; + drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8; + float32x4_t factor4; + int32x4_t shift0_4; + int32x4_t shift1_4; + + DRFLAC_ASSERT(pFlac->bitsPerSample <= 24); + + factor4 = vdupq_n_f32(1.0f / 8388608.0f); + shift0_4 = vdupq_n_s32(shift0); + shift1_4 = vdupq_n_s32(shift1); + + for (i = 0; i < frameCount4; ++i) { + uint32x4_t left; + uint32x4_t side; + uint32x4_t right; + float32x4_t leftf; + float32x4_t rightf; + + left = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4); + side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4); + right = vsubq_u32(left, side); + leftf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(left)), factor4); + rightf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(right)), factor4); + + drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf)); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 left = pInputSamples0U32[i] << shift0; + drflac_uint32 side = pInputSamples1U32[i] << shift1; + drflac_uint32 right = left - side; + + pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f; + pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f; + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ +#if defined(DRFLAC_SUPPORT_SSE2) + if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_f32__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#elif defined(DRFLAC_SUPPORT_NEON) + if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_f32__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { + /* Scalar fallback. */ +#if 0 + drflac_read_pcm_frames_f32__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + drflac_read_pcm_frames_f32__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif + } +} + + +#if 0 +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ + drflac_uint64 i; + for (i = 0; i < frameCount; ++i) { + drflac_uint32 side = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + drflac_uint32 right = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + drflac_uint32 left = right + side; + + pOutputSamples[i*2+0] = (float)((drflac_int32)left / 2147483648.0); + pOutputSamples[i*2+1] = (float)((drflac_int32)right / 2147483648.0); + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + float factor = 1 / 2147483648.0; + + for (i = 0; i < frameCount4; ++i) { + drflac_uint32 side0 = pInputSamples0U32[i*4+0] << shift0; + drflac_uint32 side1 = pInputSamples0U32[i*4+1] << shift0; + drflac_uint32 side2 = pInputSamples0U32[i*4+2] << shift0; + drflac_uint32 side3 = pInputSamples0U32[i*4+3] << shift0; + + drflac_uint32 right0 = pInputSamples1U32[i*4+0] << shift1; + drflac_uint32 right1 = pInputSamples1U32[i*4+1] << shift1; + drflac_uint32 right2 = pInputSamples1U32[i*4+2] << shift1; + drflac_uint32 right3 = pInputSamples1U32[i*4+3] << shift1; + + drflac_uint32 left0 = right0 + side0; + drflac_uint32 left1 = right1 + side1; + drflac_uint32 left2 = right2 + side2; + drflac_uint32 left3 = right3 + side3; + + pOutputSamples[i*8+0] = (drflac_int32)left0 * factor; + pOutputSamples[i*8+1] = (drflac_int32)right0 * factor; + pOutputSamples[i*8+2] = (drflac_int32)left1 * factor; + pOutputSamples[i*8+3] = (drflac_int32)right1 * factor; + pOutputSamples[i*8+4] = (drflac_int32)left2 * factor; + pOutputSamples[i*8+5] = (drflac_int32)right2 * factor; + pOutputSamples[i*8+6] = (drflac_int32)left3 * factor; + pOutputSamples[i*8+7] = (drflac_int32)right3 * factor; + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 side = pInputSamples0U32[i] << shift0; + drflac_uint32 right = pInputSamples1U32[i] << shift1; + drflac_uint32 left = right + side; + + pOutputSamples[i*2+0] = (drflac_int32)left * factor; + pOutputSamples[i*2+1] = (drflac_int32)right * factor; + } +} + +#if defined(DRFLAC_SUPPORT_SSE2) +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8; + drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8; + __m128 factor; + + DRFLAC_ASSERT(pFlac->bitsPerSample <= 24); + + factor = _mm_set1_ps(1.0f / 8388608.0f); + + for (i = 0; i < frameCount4; ++i) { + __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0); + __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1); + __m128i left = _mm_add_epi32(right, side); + __m128 leftf = _mm_mul_ps(_mm_cvtepi32_ps(left), factor); + __m128 rightf = _mm_mul_ps(_mm_cvtepi32_ps(right), factor); + + _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf)); + _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf)); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 side = pInputSamples0U32[i] << shift0; + drflac_uint32 right = pInputSamples1U32[i] << shift1; + drflac_uint32 left = right + side; + + pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f; + pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f; + } +} +#endif + +#if defined(DRFLAC_SUPPORT_NEON) +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8; + drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8; + float32x4_t factor4; + int32x4_t shift0_4; + int32x4_t shift1_4; + + DRFLAC_ASSERT(pFlac->bitsPerSample <= 24); + + factor4 = vdupq_n_f32(1.0f / 8388608.0f); + shift0_4 = vdupq_n_s32(shift0); + shift1_4 = vdupq_n_s32(shift1); + + for (i = 0; i < frameCount4; ++i) { + uint32x4_t side; + uint32x4_t right; + uint32x4_t left; + float32x4_t leftf; + float32x4_t rightf; + + side = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4); + right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4); + left = vaddq_u32(right, side); + leftf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(left)), factor4); + rightf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(right)), factor4); + + drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf)); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 side = pInputSamples0U32[i] << shift0; + drflac_uint32 right = pInputSamples1U32[i] << shift1; + drflac_uint32 left = right + side; + + pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f; + pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f; + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ +#if defined(DRFLAC_SUPPORT_SSE2) + if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_f32__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#elif defined(DRFLAC_SUPPORT_NEON) + if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_f32__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { + /* Scalar fallback. */ +#if 0 + drflac_read_pcm_frames_f32__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + drflac_read_pcm_frames_f32__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif + } +} + + +#if 0 +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ + for (drflac_uint64 i = 0; i < frameCount; ++i) { + drflac_uint32 mid = (drflac_uint32)pInputSamples0[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + mid = (mid << 1) | (side & 0x01); + + pOutputSamples[i*2+0] = (float)((((drflac_int32)(mid + side) >> 1) << (unusedBitsPerSample)) / 2147483648.0); + pOutputSamples[i*2+1] = (float)((((drflac_int32)(mid - side) >> 1) << (unusedBitsPerSample)) / 2147483648.0); + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift = unusedBitsPerSample; + float factor = 1 / 2147483648.0; + + if (shift > 0) { + shift -= 1; + for (i = 0; i < frameCount4; ++i) { + drflac_uint32 temp0L; + drflac_uint32 temp1L; + drflac_uint32 temp2L; + drflac_uint32 temp3L; + drflac_uint32 temp0R; + drflac_uint32 temp1R; + drflac_uint32 temp2R; + drflac_uint32 temp3R; + + drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + + drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + mid0 = (mid0 << 1) | (side0 & 0x01); + mid1 = (mid1 << 1) | (side1 & 0x01); + mid2 = (mid2 << 1) | (side2 & 0x01); + mid3 = (mid3 << 1) | (side3 & 0x01); + + temp0L = (mid0 + side0) << shift; + temp1L = (mid1 + side1) << shift; + temp2L = (mid2 + side2) << shift; + temp3L = (mid3 + side3) << shift; + + temp0R = (mid0 - side0) << shift; + temp1R = (mid1 - side1) << shift; + temp2R = (mid2 - side2) << shift; + temp3R = (mid3 - side3) << shift; + + pOutputSamples[i*8+0] = (drflac_int32)temp0L * factor; + pOutputSamples[i*8+1] = (drflac_int32)temp0R * factor; + pOutputSamples[i*8+2] = (drflac_int32)temp1L * factor; + pOutputSamples[i*8+3] = (drflac_int32)temp1R * factor; + pOutputSamples[i*8+4] = (drflac_int32)temp2L * factor; + pOutputSamples[i*8+5] = (drflac_int32)temp2R * factor; + pOutputSamples[i*8+6] = (drflac_int32)temp3L * factor; + pOutputSamples[i*8+7] = (drflac_int32)temp3R * factor; + } + } else { + for (i = 0; i < frameCount4; ++i) { + drflac_uint32 temp0L; + drflac_uint32 temp1L; + drflac_uint32 temp2L; + drflac_uint32 temp3L; + drflac_uint32 temp0R; + drflac_uint32 temp1R; + drflac_uint32 temp2R; + drflac_uint32 temp3R; + + drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + + drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + mid0 = (mid0 << 1) | (side0 & 0x01); + mid1 = (mid1 << 1) | (side1 & 0x01); + mid2 = (mid2 << 1) | (side2 & 0x01); + mid3 = (mid3 << 1) | (side3 & 0x01); + + temp0L = (drflac_uint32)((drflac_int32)(mid0 + side0) >> 1); + temp1L = (drflac_uint32)((drflac_int32)(mid1 + side1) >> 1); + temp2L = (drflac_uint32)((drflac_int32)(mid2 + side2) >> 1); + temp3L = (drflac_uint32)((drflac_int32)(mid3 + side3) >> 1); + + temp0R = (drflac_uint32)((drflac_int32)(mid0 - side0) >> 1); + temp1R = (drflac_uint32)((drflac_int32)(mid1 - side1) >> 1); + temp2R = (drflac_uint32)((drflac_int32)(mid2 - side2) >> 1); + temp3R = (drflac_uint32)((drflac_int32)(mid3 - side3) >> 1); + + pOutputSamples[i*8+0] = (drflac_int32)temp0L * factor; + pOutputSamples[i*8+1] = (drflac_int32)temp0R * factor; + pOutputSamples[i*8+2] = (drflac_int32)temp1L * factor; + pOutputSamples[i*8+3] = (drflac_int32)temp1R * factor; + pOutputSamples[i*8+4] = (drflac_int32)temp2L * factor; + pOutputSamples[i*8+5] = (drflac_int32)temp2R * factor; + pOutputSamples[i*8+6] = (drflac_int32)temp3L * factor; + pOutputSamples[i*8+7] = (drflac_int32)temp3R * factor; + } + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + mid = (mid << 1) | (side & 0x01); + + pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample) * factor; + pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample) * factor; + } +} + +#if defined(DRFLAC_SUPPORT_SSE2) +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift = unusedBitsPerSample - 8; + float factor; + __m128 factor128; + + DRFLAC_ASSERT(pFlac->bitsPerSample <= 24); + + factor = 1.0f / 8388608.0f; + factor128 = _mm_set1_ps(factor); + + if (shift == 0) { + for (i = 0; i < frameCount4; ++i) { + __m128i mid; + __m128i side; + __m128i tempL; + __m128i tempR; + __m128 leftf; + __m128 rightf; + + mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + + mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01))); + + tempL = _mm_srai_epi32(_mm_add_epi32(mid, side), 1); + tempR = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1); + + leftf = _mm_mul_ps(_mm_cvtepi32_ps(tempL), factor128); + rightf = _mm_mul_ps(_mm_cvtepi32_ps(tempR), factor128); + + _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf)); + _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf)); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + mid = (mid << 1) | (side & 0x01); + + pOutputSamples[i*2+0] = ((drflac_int32)(mid + side) >> 1) * factor; + pOutputSamples[i*2+1] = ((drflac_int32)(mid - side) >> 1) * factor; + } + } else { + shift -= 1; + for (i = 0; i < frameCount4; ++i) { + __m128i mid; + __m128i side; + __m128i tempL; + __m128i tempR; + __m128 leftf; + __m128 rightf; + + mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + + mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01))); + + tempL = _mm_slli_epi32(_mm_add_epi32(mid, side), shift); + tempR = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift); + + leftf = _mm_mul_ps(_mm_cvtepi32_ps(tempL), factor128); + rightf = _mm_mul_ps(_mm_cvtepi32_ps(tempR), factor128); + + _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf)); + _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf)); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + mid = (mid << 1) | (side & 0x01); + + pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift) * factor; + pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift) * factor; + } + } +} +#endif + +#if defined(DRFLAC_SUPPORT_NEON) +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift = unusedBitsPerSample - 8; + float factor; + float32x4_t factor4; + int32x4_t shift4; + int32x4_t wbps0_4; /* Wasted Bits Per Sample */ + int32x4_t wbps1_4; /* Wasted Bits Per Sample */ + + DRFLAC_ASSERT(pFlac->bitsPerSample <= 24); + + factor = 1.0f / 8388608.0f; + factor4 = vdupq_n_f32(factor); + wbps0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample); + wbps1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample); + + if (shift == 0) { + for (i = 0; i < frameCount4; ++i) { + int32x4_t lefti; + int32x4_t righti; + float32x4_t leftf; + float32x4_t rightf; + + uint32x4_t mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbps0_4); + uint32x4_t side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbps1_4); + + mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1))); + + lefti = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1); + righti = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1); + + leftf = vmulq_f32(vcvtq_f32_s32(lefti), factor4); + rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4); + + drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf)); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + mid = (mid << 1) | (side & 0x01); + + pOutputSamples[i*2+0] = ((drflac_int32)(mid + side) >> 1) * factor; + pOutputSamples[i*2+1] = ((drflac_int32)(mid - side) >> 1) * factor; + } + } else { + shift -= 1; + shift4 = vdupq_n_s32(shift); + for (i = 0; i < frameCount4; ++i) { + uint32x4_t mid; + uint32x4_t side; + int32x4_t lefti; + int32x4_t righti; + float32x4_t leftf; + float32x4_t rightf; + + mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbps0_4); + side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbps1_4); + + mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1))); + + lefti = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4)); + righti = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4)); + + leftf = vmulq_f32(vcvtq_f32_s32(lefti), factor4); + rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4); + + drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf)); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + + mid = (mid << 1) | (side & 0x01); + + pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift) * factor; + pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift) * factor; + } + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ +#if defined(DRFLAC_SUPPORT_SSE2) + if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_f32__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#elif defined(DRFLAC_SUPPORT_NEON) + if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_f32__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { + /* Scalar fallback. */ +#if 0 + drflac_read_pcm_frames_f32__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + drflac_read_pcm_frames_f32__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif + } +} + +#if 0 +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ + for (drflac_uint64 i = 0; i < frameCount; ++i) { + pOutputSamples[i*2+0] = (float)((drflac_int32)((drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample)) / 2147483648.0); + pOutputSamples[i*2+1] = (float)((drflac_int32)((drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample)) / 2147483648.0); + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample; + drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample; + float factor = 1 / 2147483648.0; + + for (i = 0; i < frameCount4; ++i) { + drflac_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0; + drflac_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0; + drflac_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0; + drflac_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0; + + drflac_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1; + drflac_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1; + drflac_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1; + drflac_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1; + + pOutputSamples[i*8+0] = (drflac_int32)tempL0 * factor; + pOutputSamples[i*8+1] = (drflac_int32)tempR0 * factor; + pOutputSamples[i*8+2] = (drflac_int32)tempL1 * factor; + pOutputSamples[i*8+3] = (drflac_int32)tempR1 * factor; + pOutputSamples[i*8+4] = (drflac_int32)tempL2 * factor; + pOutputSamples[i*8+5] = (drflac_int32)tempR2 * factor; + pOutputSamples[i*8+6] = (drflac_int32)tempL3 * factor; + pOutputSamples[i*8+7] = (drflac_int32)tempR3 * factor; + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0) * factor; + pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1) * factor; + } +} + +#if defined(DRFLAC_SUPPORT_SSE2) +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8; + drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8; + + float factor = 1.0f / 8388608.0f; + __m128 factor128 = _mm_set1_ps(factor); + + for (i = 0; i < frameCount4; ++i) { + __m128i lefti; + __m128i righti; + __m128 leftf; + __m128 rightf; + + lefti = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0); + righti = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1); + + leftf = _mm_mul_ps(_mm_cvtepi32_ps(lefti), factor128); + rightf = _mm_mul_ps(_mm_cvtepi32_ps(righti), factor128); + + _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf)); + _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf)); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0) * factor; + pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1) * factor; + } +} +#endif + +#if defined(DRFLAC_SUPPORT_NEON) +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0; + const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1; + drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8; + drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8; + + float factor = 1.0f / 8388608.0f; + float32x4_t factor4 = vdupq_n_f32(factor); + int32x4_t shift0_4 = vdupq_n_s32(shift0); + int32x4_t shift1_4 = vdupq_n_s32(shift1); + + for (i = 0; i < frameCount4; ++i) { + int32x4_t lefti; + int32x4_t righti; + float32x4_t leftf; + float32x4_t rightf; + + lefti = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4)); + righti = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4)); + + leftf = vmulq_f32(vcvtq_f32_s32(lefti), factor4); + rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4); + + drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf)); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0) * factor; + pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1) * factor; + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ +#if defined(DRFLAC_SUPPORT_SSE2) + if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_f32__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#elif defined(DRFLAC_SUPPORT_NEON) + if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_f32__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { + /* Scalar fallback. */ +#if 0 + drflac_read_pcm_frames_f32__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + drflac_read_pcm_frames_f32__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif + } +} + +DRFLAC_API drflac_uint64 drflac_read_pcm_frames_f32(drflac* pFlac, drflac_uint64 framesToRead, float* pBufferOut) +{ + drflac_uint64 framesRead; + drflac_uint32 unusedBitsPerSample; + + if (pFlac == NULL || framesToRead == 0) { + return 0; + } + + if (pBufferOut == NULL) { + return drflac__seek_forward_by_pcm_frames(pFlac, framesToRead); + } + + DRFLAC_ASSERT(pFlac->bitsPerSample <= 32); + unusedBitsPerSample = 32 - pFlac->bitsPerSample; + + framesRead = 0; + while (framesToRead > 0) { + /* If we've run out of samples in this frame, go to the next. */ + if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) { + if (!drflac__read_and_decode_next_flac_frame(pFlac)) { + break; /* Couldn't read the next frame, so just break from the loop and return. */ + } + } else { + unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment); + drflac_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining; + drflac_uint64 frameCountThisIteration = framesToRead; + + if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) { + frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining; + } + + if (channelCount == 2) { + const drflac_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame; + const drflac_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame; + + switch (pFlac->currentFLACFrame.header.channelAssignment) + { + case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE: + { + drflac_read_pcm_frames_f32__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + + case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE: + { + drflac_read_pcm_frames_f32__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + + case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE: + { + drflac_read_pcm_frames_f32__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + + case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT: + default: + { + drflac_read_pcm_frames_f32__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + } + } else { + /* Generic interleaving. */ + drflac_uint64 i; + for (i = 0; i < frameCountThisIteration; ++i) { + unsigned int j; + for (j = 0; j < channelCount; ++j) { + drflac_int32 sampleS32 = (drflac_int32)((drflac_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample)); + pBufferOut[(i*channelCount)+j] = (float)(sampleS32 / 2147483648.0); + } + } + } + + framesRead += frameCountThisIteration; + pBufferOut += frameCountThisIteration * channelCount; + framesToRead -= frameCountThisIteration; + pFlac->currentPCMFrame += frameCountThisIteration; + pFlac->currentFLACFrame.pcmFramesRemaining -= (unsigned int)frameCountThisIteration; + } + } + + return framesRead; +} + + +DRFLAC_API drflac_bool32 drflac_seek_to_pcm_frame(drflac* pFlac, drflac_uint64 pcmFrameIndex) +{ + if (pFlac == NULL) { + return DRFLAC_FALSE; + } + + /* Don't do anything if we're already on the seek point. */ + if (pFlac->currentPCMFrame == pcmFrameIndex) { + return DRFLAC_TRUE; + } + + /* + If we don't know where the first frame begins then we can't seek. This will happen when the STREAMINFO block was not present + when the decoder was opened. + */ + if (pFlac->firstFLACFramePosInBytes == 0) { + return DRFLAC_FALSE; + } + + if (pcmFrameIndex == 0) { + pFlac->currentPCMFrame = 0; + return drflac__seek_to_first_frame(pFlac); + } else { + drflac_bool32 wasSuccessful = DRFLAC_FALSE; + drflac_uint64 originalPCMFrame = pFlac->currentPCMFrame; + + /* Clamp the sample to the end. */ + if (pcmFrameIndex > pFlac->totalPCMFrameCount) { + pcmFrameIndex = pFlac->totalPCMFrameCount; + } + + /* If the target sample and the current sample are in the same frame we just move the position forward. */ + if (pcmFrameIndex > pFlac->currentPCMFrame) { + /* Forward. */ + drflac_uint32 offset = (drflac_uint32)(pcmFrameIndex - pFlac->currentPCMFrame); + if (pFlac->currentFLACFrame.pcmFramesRemaining > offset) { + pFlac->currentFLACFrame.pcmFramesRemaining -= offset; + pFlac->currentPCMFrame = pcmFrameIndex; + return DRFLAC_TRUE; + } + } else { + /* Backward. */ + drflac_uint32 offsetAbs = (drflac_uint32)(pFlac->currentPCMFrame - pcmFrameIndex); + drflac_uint32 currentFLACFramePCMFrameCount = pFlac->currentFLACFrame.header.blockSizeInPCMFrames; + drflac_uint32 currentFLACFramePCMFramesConsumed = currentFLACFramePCMFrameCount - pFlac->currentFLACFrame.pcmFramesRemaining; + if (currentFLACFramePCMFramesConsumed > offsetAbs) { + pFlac->currentFLACFrame.pcmFramesRemaining += offsetAbs; + pFlac->currentPCMFrame = pcmFrameIndex; + return DRFLAC_TRUE; + } + } + + /* + Different techniques depending on encapsulation. Using the native FLAC seektable with Ogg encapsulation is a bit awkward so + we'll instead use Ogg's natural seeking facility. + */ +#ifndef DR_FLAC_NO_OGG + if (pFlac->container == drflac_container_ogg) + { + wasSuccessful = drflac_ogg__seek_to_pcm_frame(pFlac, pcmFrameIndex); + } + else +#endif + { + /* First try seeking via the seek table. If this fails, fall back to a brute force seek which is much slower. */ + if (/*!wasSuccessful && */!pFlac->_noSeekTableSeek) { + wasSuccessful = drflac__seek_to_pcm_frame__seek_table(pFlac, pcmFrameIndex); + } + +#if !defined(DR_FLAC_NO_CRC) + /* Fall back to binary search if seek table seeking fails. This requires the length of the stream to be known. */ + if (!wasSuccessful && !pFlac->_noBinarySearchSeek && pFlac->totalPCMFrameCount > 0) { + wasSuccessful = drflac__seek_to_pcm_frame__binary_search(pFlac, pcmFrameIndex); + } +#endif + + /* Fall back to brute force if all else fails. */ + if (!wasSuccessful && !pFlac->_noBruteForceSeek) { + wasSuccessful = drflac__seek_to_pcm_frame__brute_force(pFlac, pcmFrameIndex); + } + } + + if (wasSuccessful) { + pFlac->currentPCMFrame = pcmFrameIndex; + } else { + /* Seek failed. Try putting the decoder back to it's original state. */ + if (drflac_seek_to_pcm_frame(pFlac, originalPCMFrame) == DRFLAC_FALSE) { + /* Failed to seek back to the original PCM frame. Fall back to 0. */ + drflac_seek_to_pcm_frame(pFlac, 0); + } + } + + return wasSuccessful; + } +} + + + +/* High Level APIs */ + +/* SIZE_MAX */ +#if defined(SIZE_MAX) + #define DRFLAC_SIZE_MAX SIZE_MAX +#else + #if defined(DRFLAC_64BIT) + #define DRFLAC_SIZE_MAX ((drflac_uint64)0xFFFFFFFFFFFFFFFF) + #else + #define DRFLAC_SIZE_MAX 0xFFFFFFFF + #endif +#endif +/* End SIZE_MAX */ + + +/* Using a macro as the definition of the drflac__full_decode_and_close_*() API family. Sue me. */ +#define DRFLAC_DEFINE_FULL_READ_AND_CLOSE(extension, type) \ +static type* drflac__full_read_and_close_ ## extension (drflac* pFlac, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut)\ +{ \ + type* pSampleData = NULL; \ + drflac_uint64 totalPCMFrameCount; \ + type buffer[4096]; \ + drflac_uint64 pcmFramesRead; \ + size_t sampleDataBufferSize = sizeof(buffer); \ + \ + DRFLAC_ASSERT(pFlac != NULL); \ + \ + totalPCMFrameCount = 0; \ + \ + pSampleData = (type*)drflac__malloc_from_callbacks(sampleDataBufferSize, &pFlac->allocationCallbacks); \ + if (pSampleData == NULL) { \ + goto on_error; \ + } \ + \ + while ((pcmFramesRead = (drflac_uint64)drflac_read_pcm_frames_##extension(pFlac, sizeof(buffer)/sizeof(buffer[0])/pFlac->channels, buffer)) > 0) { \ + if (((totalPCMFrameCount + pcmFramesRead) * pFlac->channels * sizeof(type)) > sampleDataBufferSize) { \ + type* pNewSampleData; \ + size_t newSampleDataBufferSize; \ + \ + newSampleDataBufferSize = sampleDataBufferSize * 2; \ + pNewSampleData = (type*)drflac__realloc_from_callbacks(pSampleData, newSampleDataBufferSize, sampleDataBufferSize, &pFlac->allocationCallbacks); \ + if (pNewSampleData == NULL) { \ + drflac__free_from_callbacks(pSampleData, &pFlac->allocationCallbacks); \ + goto on_error; \ + } \ + \ + sampleDataBufferSize = newSampleDataBufferSize; \ + pSampleData = pNewSampleData; \ + } \ + \ + DRFLAC_COPY_MEMORY(pSampleData + (totalPCMFrameCount*pFlac->channels), buffer, (size_t)(pcmFramesRead*pFlac->channels*sizeof(type))); \ + totalPCMFrameCount += pcmFramesRead; \ + } \ + \ + /* At this point everything should be decoded, but we just want to fill the unused part buffer with silence - need to \ + protect those ears from random noise! */ \ + DRFLAC_ZERO_MEMORY(pSampleData + (totalPCMFrameCount*pFlac->channels), (size_t)(sampleDataBufferSize - totalPCMFrameCount*pFlac->channels*sizeof(type))); \ + \ + if (sampleRateOut) *sampleRateOut = pFlac->sampleRate; \ + if (channelsOut) *channelsOut = pFlac->channels; \ + if (totalPCMFrameCountOut) *totalPCMFrameCountOut = totalPCMFrameCount; \ + \ + drflac_close(pFlac); \ + return pSampleData; \ + \ +on_error: \ + drflac_close(pFlac); \ + return NULL; \ +} + +DRFLAC_DEFINE_FULL_READ_AND_CLOSE(s32, drflac_int32) +DRFLAC_DEFINE_FULL_READ_AND_CLOSE(s16, drflac_int16) +DRFLAC_DEFINE_FULL_READ_AND_CLOSE(f32, float) + +DRFLAC_API drflac_int32* drflac_open_and_read_pcm_frames_s32(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut, const drflac_allocation_callbacks* pAllocationCallbacks) +{ + drflac* pFlac; + + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalPCMFrameCountOut) { + *totalPCMFrameCountOut = 0; + } + + pFlac = drflac_open(onRead, onSeek, onTell, pUserData, pAllocationCallbacks); + if (pFlac == NULL) { + return NULL; + } + + return drflac__full_read_and_close_s32(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut); +} + +DRFLAC_API drflac_int16* drflac_open_and_read_pcm_frames_s16(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut, const drflac_allocation_callbacks* pAllocationCallbacks) +{ + drflac* pFlac; + + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalPCMFrameCountOut) { + *totalPCMFrameCountOut = 0; + } + + pFlac = drflac_open(onRead, onSeek, onTell, pUserData, pAllocationCallbacks); + if (pFlac == NULL) { + return NULL; + } + + return drflac__full_read_and_close_s16(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut); +} + +DRFLAC_API float* drflac_open_and_read_pcm_frames_f32(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut, const drflac_allocation_callbacks* pAllocationCallbacks) +{ + drflac* pFlac; + + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalPCMFrameCountOut) { + *totalPCMFrameCountOut = 0; + } + + pFlac = drflac_open(onRead, onSeek, onTell, pUserData, pAllocationCallbacks); + if (pFlac == NULL) { + return NULL; + } + + return drflac__full_read_and_close_f32(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut); +} + + +DRFLAC_API drflac_int32* drflac_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks) +{ + drflac* pFlac; + + if (sampleRate) { + *sampleRate = 0; + } + if (channels) { + *channels = 0; + } + if (totalPCMFrameCount) { + *totalPCMFrameCount = 0; + } + + pFlac = drflac_open_memory(data, dataSize, pAllocationCallbacks); + if (pFlac == NULL) { + return NULL; + } + + return drflac__full_read_and_close_s32(pFlac, channels, sampleRate, totalPCMFrameCount); +} + +DRFLAC_API drflac_int16* drflac_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks) +{ + drflac* pFlac; + + if (sampleRate) { + *sampleRate = 0; + } + if (channels) { + *channels = 0; + } + if (totalPCMFrameCount) { + *totalPCMFrameCount = 0; + } + + pFlac = drflac_open_memory(data, dataSize, pAllocationCallbacks); + if (pFlac == NULL) { + return NULL; + } + + return drflac__full_read_and_close_s16(pFlac, channels, sampleRate, totalPCMFrameCount); +} + +DRFLAC_API float* drflac_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks) +{ + drflac* pFlac; + + if (sampleRate) { + *sampleRate = 0; + } + if (channels) { + *channels = 0; + } + if (totalPCMFrameCount) { + *totalPCMFrameCount = 0; + } + + pFlac = drflac_open_memory(data, dataSize, pAllocationCallbacks); + if (pFlac == NULL) { + return NULL; + } + + return drflac__full_read_and_close_f32(pFlac, channels, sampleRate, totalPCMFrameCount); +} + + +DRFLAC_API void drflac_free(void* p, const drflac_allocation_callbacks* pAllocationCallbacks) +{ + if (pAllocationCallbacks != NULL) { + drflac__free_from_callbacks(p, pAllocationCallbacks); + } else { + drflac__free_default(p, NULL); + } +} + + + + +DRFLAC_API void drflac_init_vorbis_comment_iterator(drflac_vorbis_comment_iterator* pIter, drflac_uint32 commentCount, const void* pComments) +{ + if (pIter == NULL) { + return; + } + + pIter->countRemaining = commentCount; + pIter->pRunningData = (const char*)pComments; +} + +DRFLAC_API const char* drflac_next_vorbis_comment(drflac_vorbis_comment_iterator* pIter, drflac_uint32* pCommentLengthOut) +{ + drflac_int32 length; + const char* pComment; + + /* Safety. */ + if (pCommentLengthOut) { + *pCommentLengthOut = 0; + } + + if (pIter == NULL || pIter->countRemaining == 0 || pIter->pRunningData == NULL) { + return NULL; + } + + length = drflac__le2host_32_ptr_unaligned(pIter->pRunningData); + pIter->pRunningData += 4; + + pComment = pIter->pRunningData; + pIter->pRunningData += length; + pIter->countRemaining -= 1; + + if (pCommentLengthOut) { + *pCommentLengthOut = length; + } + + return pComment; +} + + + + +DRFLAC_API void drflac_init_cuesheet_track_iterator(drflac_cuesheet_track_iterator* pIter, drflac_uint32 trackCount, const void* pTrackData) +{ + if (pIter == NULL) { + return; + } + + pIter->countRemaining = trackCount; + pIter->pRunningData = (const char*)pTrackData; +} + +DRFLAC_API drflac_bool32 drflac_next_cuesheet_track(drflac_cuesheet_track_iterator* pIter, drflac_cuesheet_track* pCuesheetTrack) +{ + drflac_cuesheet_track cuesheetTrack; + const char* pRunningData; + drflac_uint64 offsetHi; + drflac_uint64 offsetLo; + + if (pIter == NULL || pIter->countRemaining == 0 || pIter->pRunningData == NULL) { + return DRFLAC_FALSE; + } + + pRunningData = pIter->pRunningData; + + offsetHi = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4; + offsetLo = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4; + cuesheetTrack.offset = offsetLo | (offsetHi << 32); + cuesheetTrack.trackNumber = pRunningData[0]; pRunningData += 1; + DRFLAC_COPY_MEMORY(cuesheetTrack.ISRC, pRunningData, sizeof(cuesheetTrack.ISRC)); pRunningData += 12; + cuesheetTrack.isAudio = (pRunningData[0] & 0x80) != 0; + cuesheetTrack.preEmphasis = (pRunningData[0] & 0x40) != 0; pRunningData += 14; + cuesheetTrack.indexCount = pRunningData[0]; pRunningData += 1; + cuesheetTrack.pIndexPoints = (const drflac_cuesheet_track_index*)pRunningData; pRunningData += cuesheetTrack.indexCount * sizeof(drflac_cuesheet_track_index); + + pIter->pRunningData = pRunningData; + pIter->countRemaining -= 1; + + if (pCuesheetTrack) { + *pCuesheetTrack = cuesheetTrack; + } + + return DRFLAC_TRUE; +} + +#if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))) + #pragma GCC diagnostic pop +#endif +#endif /* dr_flac_c */ +#endif /* DR_FLAC_IMPLEMENTATION */ + + +/* +REVISION HISTORY +================ +v0.13.3 - 2026-01-17 + - Fix a compiler compatibility issue with some inlined assembly. + - Fix a compilation warning. + +v0.13.2 - 2025-12-02 + - Improve robustness of the parsing of picture metadata to improve support for memory constrained embedded devices. + - Fix a warning about an assigned by unused variable. + - Improvements to drflac_open_and_read_pcm_frames_*() and family to avoid excessively large memory allocations from malformed files. + +v0.13.1 - 2025-09-10 + - Fix an error with the NXDK build. + +v0.13.0 - 2025-07-23 + - API CHANGE: Seek origin enums have been renamed to match the naming convention used by other dr_libs libraries: + - drflac_seek_origin_start -> DRFLAC_SEEK_SET + - drflac_seek_origin_current -> DRFLAC_SEEK_CUR + - DRFLAC_SEEK_END (new) + - API CHANGE: A new seek origin has been added to allow seeking from the end of the file. If you implement your own `onSeek` callback, you should now detect and handle `DRFLAC_SEEK_END`. If seeking to the end is not supported, return `DRFLAC_FALSE`. If you only use `*_open_file()` or `*_open_memory()`, you need not change anything. + - API CHANGE: An `onTell` callback has been added to the following functions: + - drflac_open() + - drflac_open_relaxed() + - drflac_open_with_metadata() + - drflac_open_with_metadata_relaxed() + - drflac_open_and_read_pcm_frames_s32() + - drflac_open_and_read_pcm_frames_s16() + - drflac_open_and_read_pcm_frames_f32() + - Fix compilation for AIX OS. + +v0.12.43 - 2024-12-17 + - Fix a possible buffer overflow during decoding. + - Improve detection of ARM64EC + +v0.12.42 - 2023-11-02 + - Fix build for ARMv6-M. + - Fix a compilation warning with GCC. + +v0.12.41 - 2023-06-17 + - Fix an incorrect date in revision history. No functional change. + +v0.12.40 - 2023-05-22 + - Minor code restructure. No functional change. + +v0.12.39 - 2022-09-17 + - Fix compilation with DJGPP. + - Fix compilation error with Visual Studio 2019 and the ARM build. + - Fix an error with SSE 4.1 detection. + - Add support for disabling wchar_t with DR_WAV_NO_WCHAR. + - Improve compatibility with compilers which lack support for explicit struct packing. + - Improve compatibility with low-end and embedded hardware by reducing the amount of stack + allocation when loading an Ogg encapsulated file. + +v0.12.38 - 2022-04-10 + - Fix compilation error on older versions of GCC. + +v0.12.37 - 2022-02-12 + - Improve ARM detection. + +v0.12.36 - 2022-02-07 + - Fix a compilation error with the ARM build. + +v0.12.35 - 2022-02-06 + - Fix a bug due to underestimating the amount of precision required for the prediction stage. + - Fix some bugs found from fuzz testing. + +v0.12.34 - 2022-01-07 + - Fix some misalignment bugs when reading metadata. + +v0.12.33 - 2021-12-22 + - Fix a bug with seeking when the seek table does not start at PCM frame 0. + +v0.12.32 - 2021-12-11 + - Fix a warning with Clang. + +v0.12.31 - 2021-08-16 + - Silence some warnings. + +v0.12.30 - 2021-07-31 + - Fix platform detection for ARM64. + +v0.12.29 - 2021-04-02 + - Fix a bug where the running PCM frame index is set to an invalid value when over-seeking. + - Fix a decoding error due to an incorrect validation check. + +v0.12.28 - 2021-02-21 + - Fix a warning due to referencing _MSC_VER when it is undefined. + +v0.12.27 - 2021-01-31 + - Fix a static analysis warning. + +v0.12.26 - 2021-01-17 + - Fix a compilation warning due to _BSD_SOURCE being deprecated. + +v0.12.25 - 2020-12-26 + - Update documentation. + +v0.12.24 - 2020-11-29 + - Fix ARM64/NEON detection when compiling with MSVC. + +v0.12.23 - 2020-11-21 + - Fix compilation with OpenWatcom. + +v0.12.22 - 2020-11-01 + - Fix an error with the previous release. + +v0.12.21 - 2020-11-01 + - Fix a possible deadlock when seeking. + - Improve compiler support for older versions of GCC. + +v0.12.20 - 2020-09-08 + - Fix a compilation error on older compilers. + +v0.12.19 - 2020-08-30 + - Fix a bug due to an undefined 32-bit shift. + +v0.12.18 - 2020-08-14 + - Fix a crash when compiling with clang-cl. + +v0.12.17 - 2020-08-02 + - Simplify sized types. + +v0.12.16 - 2020-07-25 + - Fix a compilation warning. + +v0.12.15 - 2020-07-06 + - Check for negative LPC shifts and return an error. + +v0.12.14 - 2020-06-23 + - Add include guard for the implementation section. + +v0.12.13 - 2020-05-16 + - Add compile-time and run-time version querying. + - DRFLAC_VERSION_MINOR + - DRFLAC_VERSION_MAJOR + - DRFLAC_VERSION_REVISION + - DRFLAC_VERSION_STRING + - drflac_version() + - drflac_version_string() + +v0.12.12 - 2020-04-30 + - Fix compilation errors with VC6. + +v0.12.11 - 2020-04-19 + - Fix some pedantic warnings. + - Fix some undefined behaviour warnings. + +v0.12.10 - 2020-04-10 + - Fix some bugs when trying to seek with an invalid seek table. + +v0.12.9 - 2020-04-05 + - Fix warnings. + +v0.12.8 - 2020-04-04 + - Add drflac_open_file_w() and drflac_open_file_with_metadata_w(). + - Fix some static analysis warnings. + - Minor documentation updates. + +v0.12.7 - 2020-03-14 + - Fix compilation errors with VC6. + +v0.12.6 - 2020-03-07 + - Fix compilation error with Visual Studio .NET 2003. + +v0.12.5 - 2020-01-30 + - Silence some static analysis warnings. + +v0.12.4 - 2020-01-29 + - Silence some static analysis warnings. + +v0.12.3 - 2019-12-02 + - Fix some warnings when compiling with GCC and the -Og flag. + - Fix a crash in out-of-memory situations. + - Fix potential integer overflow bug. + - Fix some static analysis warnings. + - Fix a possible crash when using custom memory allocators without a custom realloc() implementation. + - Fix a bug with binary search seeking where the bits per sample is not a multiple of 8. + +v0.12.2 - 2019-10-07 + - Internal code clean up. + +v0.12.1 - 2019-09-29 + - Fix some Clang Static Analyzer warnings. + - Fix an unused variable warning. + +v0.12.0 - 2019-09-23 + - API CHANGE: Add support for user defined memory allocation routines. This system allows the program to specify their own memory allocation + routines with a user data pointer for client-specific contextual data. This adds an extra parameter to the end of the following APIs: + - drflac_open() + - drflac_open_relaxed() + - drflac_open_with_metadata() + - drflac_open_with_metadata_relaxed() + - drflac_open_file() + - drflac_open_file_with_metadata() + - drflac_open_memory() + - drflac_open_memory_with_metadata() + - drflac_open_and_read_pcm_frames_s32() + - drflac_open_and_read_pcm_frames_s16() + - drflac_open_and_read_pcm_frames_f32() + - drflac_open_file_and_read_pcm_frames_s32() + - drflac_open_file_and_read_pcm_frames_s16() + - drflac_open_file_and_read_pcm_frames_f32() + - drflac_open_memory_and_read_pcm_frames_s32() + - drflac_open_memory_and_read_pcm_frames_s16() + - drflac_open_memory_and_read_pcm_frames_f32() + Set this extra parameter to NULL to use defaults which is the same as the previous behaviour. Setting this NULL will use + DRFLAC_MALLOC, DRFLAC_REALLOC and DRFLAC_FREE. + - Remove deprecated APIs: + - drflac_read_s32() + - drflac_read_s16() + - drflac_read_f32() + - drflac_seek_to_sample() + - drflac_open_and_decode_s32() + - drflac_open_and_decode_s16() + - drflac_open_and_decode_f32() + - drflac_open_and_decode_file_s32() + - drflac_open_and_decode_file_s16() + - drflac_open_and_decode_file_f32() + - drflac_open_and_decode_memory_s32() + - drflac_open_and_decode_memory_s16() + - drflac_open_and_decode_memory_f32() + - Remove drflac.totalSampleCount which is now replaced with drflac.totalPCMFrameCount. You can emulate drflac.totalSampleCount + by doing pFlac->totalPCMFrameCount*pFlac->channels. + - Rename drflac.currentFrame to drflac.currentFLACFrame to remove ambiguity with PCM frames. + - Fix errors when seeking to the end of a stream. + - Optimizations to seeking. + - SSE improvements and optimizations. + - ARM NEON optimizations. + - Optimizations to drflac_read_pcm_frames_s16(). + - Optimizations to drflac_read_pcm_frames_s32(). + +v0.11.10 - 2019-06-26 + - Fix a compiler error. + +v0.11.9 - 2019-06-16 + - Silence some ThreadSanitizer warnings. + +v0.11.8 - 2019-05-21 + - Fix warnings. + +v0.11.7 - 2019-05-06 + - C89 fixes. + +v0.11.6 - 2019-05-05 + - Add support for C89. + - Fix a compiler warning when CRC is disabled. + - Change license to choice of public domain or MIT-0. + +v0.11.5 - 2019-04-19 + - Fix a compiler error with GCC. + +v0.11.4 - 2019-04-17 + - Fix some warnings with GCC when compiling with -std=c99. + +v0.11.3 - 2019-04-07 + - Silence warnings with GCC. + +v0.11.2 - 2019-03-10 + - Fix a warning. + +v0.11.1 - 2019-02-17 + - Fix a potential bug with seeking. + +v0.11.0 - 2018-12-16 + - API CHANGE: Deprecated drflac_read_s32(), drflac_read_s16() and drflac_read_f32() and replaced them with + drflac_read_pcm_frames_s32(), drflac_read_pcm_frames_s16() and drflac_read_pcm_frames_f32(). The new APIs take + and return PCM frame counts instead of sample counts. To upgrade you will need to change the input count by + dividing it by the channel count, and then do the same with the return value. + - API_CHANGE: Deprecated drflac_seek_to_sample() and replaced with drflac_seek_to_pcm_frame(). Same rules as + the changes to drflac_read_*() apply. + - API CHANGE: Deprecated drflac_open_and_decode_*() and replaced with drflac_open_*_and_read_*(). Same rules as + the changes to drflac_read_*() apply. + - Optimizations. + +v0.10.0 - 2018-09-11 + - Remove the DR_FLAC_NO_WIN32_IO option and the Win32 file IO functionality. If you need to use Win32 file IO you + need to do it yourself via the callback API. + - Fix the clang build. + - Fix undefined behavior. + - Fix errors with CUESHEET metdata blocks. + - Add an API for iterating over each cuesheet track in the CUESHEET metadata block. This works the same way as the + Vorbis comment API. + - Other miscellaneous bug fixes, mostly relating to invalid FLAC streams. + - Minor optimizations. + +v0.9.11 - 2018-08-29 + - Fix a bug with sample reconstruction. + +v0.9.10 - 2018-08-07 + - Improve 64-bit detection. + +v0.9.9 - 2018-08-05 + - Fix C++ build on older versions of GCC. + +v0.9.8 - 2018-07-24 + - Fix compilation errors. + +v0.9.7 - 2018-07-05 + - Fix a warning. + +v0.9.6 - 2018-06-29 + - Fix some typos. + +v0.9.5 - 2018-06-23 + - Fix some warnings. + +v0.9.4 - 2018-06-14 + - Optimizations to seeking. + - Clean up. + +v0.9.3 - 2018-05-22 + - Bug fix. + +v0.9.2 - 2018-05-12 + - Fix a compilation error due to a missing break statement. + +v0.9.1 - 2018-04-29 + - Fix compilation error with Clang. + +v0.9 - 2018-04-24 + - Fix Clang build. + - Start using major.minor.revision versioning. + +v0.8g - 2018-04-19 + - Fix build on non-x86/x64 architectures. + +v0.8f - 2018-02-02 + - Stop pretending to support changing rate/channels mid stream. + +v0.8e - 2018-02-01 + - Fix a crash when the block size of a frame is larger than the maximum block size defined by the FLAC stream. + - Fix a crash the the Rice partition order is invalid. + +v0.8d - 2017-09-22 + - Add support for decoding streams with ID3 tags. ID3 tags are just skipped. + +v0.8c - 2017-09-07 + - Fix warning on non-x86/x64 architectures. + +v0.8b - 2017-08-19 + - Fix build on non-x86/x64 architectures. + +v0.8a - 2017-08-13 + - A small optimization for the Clang build. + +v0.8 - 2017-08-12 + - API CHANGE: Rename dr_* types to drflac_*. + - Optimizations. This brings dr_flac back to about the same class of efficiency as the reference implementation. + - Add support for custom implementations of malloc(), realloc(), etc. + - Add CRC checking to Ogg encapsulated streams. + - Fix VC++ 6 build. This is only for the C++ compiler. The C compiler is not currently supported. + - Bug fixes. + +v0.7 - 2017-07-23 + - Add support for opening a stream without a header block. To do this, use drflac_open_relaxed() / drflac_open_with_metadata_relaxed(). + +v0.6 - 2017-07-22 + - Add support for recovering from invalid frames. With this change, dr_flac will simply skip over invalid frames as if they + never existed. Frames are checked against their sync code, the CRC-8 of the frame header and the CRC-16 of the whole frame. + +v0.5 - 2017-07-16 + - Fix typos. + - Change drflac_bool* types to unsigned. + - Add CRC checking. This makes dr_flac slower, but can be disabled with #define DR_FLAC_NO_CRC. + +v0.4f - 2017-03-10 + - Fix a couple of bugs with the bitstreaming code. + +v0.4e - 2017-02-17 + - Fix some warnings. + +v0.4d - 2016-12-26 + - Add support for 32-bit floating-point PCM decoding. + - Use drflac_int* and drflac_uint* sized types to improve compiler support. + - Minor improvements to documentation. + +v0.4c - 2016-12-26 + - Add support for signed 16-bit integer PCM decoding. + +v0.4b - 2016-10-23 + - A minor change to drflac_bool8 and drflac_bool32 types. + +v0.4a - 2016-10-11 + - Rename drBool32 to drflac_bool32 for styling consistency. + +v0.4 - 2016-09-29 + - API/ABI CHANGE: Use fixed size 32-bit booleans instead of the built-in bool type. + - API CHANGE: Rename drflac_open_and_decode*() to drflac_open_and_decode*_s32(). + - API CHANGE: Swap the order of "channels" and "sampleRate" parameters in drflac_open_and_decode*(). Rationale for this is to + keep it consistent with drflac_audio. + +v0.3f - 2016-09-21 + - Fix a warning with GCC. + +v0.3e - 2016-09-18 + - Fixed a bug where GCC 4.3+ was not getting properly identified. + - Fixed a few typos. + - Changed date formats to ISO 8601 (YYYY-MM-DD). + +v0.3d - 2016-06-11 + - Minor clean up. + +v0.3c - 2016-05-28 + - Fixed compilation error. + +v0.3b - 2016-05-16 + - Fixed Linux/GCC build. + - Updated documentation. + +v0.3a - 2016-05-15 + - Minor fixes to documentation. + +v0.3 - 2016-05-11 + - Optimizations. Now at about parity with the reference implementation on 32-bit builds. + - Lots of clean up. + +v0.2b - 2016-05-10 + - Bug fixes. + +v0.2a - 2016-05-10 + - Made drflac_open_and_decode() more robust. + - Removed an unused debugging variable + +v0.2 - 2016-05-09 + - Added support for Ogg encapsulation. + - API CHANGE. Have the onSeek callback take a third argument which specifies whether or not the seek + should be relative to the start or the current position. Also changes the seeking rules such that + seeking offsets will never be negative. + - Have drflac_open_and_decode() fail gracefully if the stream has an unknown total sample count. + +v0.1b - 2016-05-07 + - Properly close the file handle in drflac_open_file() and family when the decoder fails to initialize. + - Removed a stale comment. + +v0.1a - 2016-05-05 + - Minor formatting changes. + - Fixed a warning on the GCC build. + +v0.1 - 2016-05-03 + - Initial versioned release. +*/ + +/* +This software is available as a choice of the following licenses. Choose +whichever you prefer. + +=============================================================================== +ALTERNATIVE 1 - Public Domain (www.unlicense.org) +=============================================================================== +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 + +=============================================================================== +ALTERNATIVE 2 - MIT No Attribution +=============================================================================== +Copyright 2023 David Reid + +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. + +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/libretrodroid/src/main/cpp/libchdr/include/libchdr/bitstream.h b/libretrodroid/src/main/cpp/libchdr/include/libchdr/bitstream.h new file mode 100644 index 000000000..f2642f14f --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/include/libchdr/bitstream.h @@ -0,0 +1,43 @@ +/* license:BSD-3-Clause + * copyright-holders:Aaron Giles +*************************************************************************** + + bitstream.h + + Helper classes for reading/writing at the bit level. + +***************************************************************************/ + +#pragma once + +#ifndef __BITSTREAM_H__ +#define __BITSTREAM_H__ + +#include + +/*************************************************************************** + * TYPE DEFINITIONS + *************************************************************************** + */ + +/* helper class for reading from a bit buffer */ +struct bitstream +{ + uint32_t buffer; /* current bit accumulator */ + int bits; /* number of bits in the accumulator */ + const uint8_t * read; /* read pointer */ + uint32_t doffset; /* byte offset within the data */ + uint32_t dlength; /* length of the data */ +}; + +struct bitstream* create_bitstream(const void *src, uint32_t srclength); +int bitstream_overflow(struct bitstream* bitstream); +uint32_t bitstream_read_offset(struct bitstream* bitstream); + +uint32_t bitstream_read(struct bitstream* bitstream, int numbits); +uint32_t bitstream_peek(struct bitstream* bitstream, int numbits); +void bitstream_remove(struct bitstream* bitstream, int numbits); +uint32_t bitstream_flush(struct bitstream* bitstream); + + +#endif diff --git a/libretrodroid/src/main/cpp/libchdr/include/libchdr/cdrom.h b/libretrodroid/src/main/cpp/libchdr/include/libchdr/cdrom.h new file mode 100644 index 000000000..6d8e95062 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/include/libchdr/cdrom.h @@ -0,0 +1,119 @@ +/* license:BSD-3-Clause + * copyright-holders:Aaron Giles +*************************************************************************** + + cdrom.h + + Generic MAME cd-rom implementation + +***************************************************************************/ + +#pragma once + +#ifndef __CDROM_H__ +#define __CDROM_H__ + +#include +#include "chd.h" +#include "chdconfig.h" +#include "macros.h" + +/*************************************************************************** + CONSTANTS +***************************************************************************/ + +/* tracks are padded to a multiple of this many frames */ +#define CD_TRACK_PADDING (4) +#define CD_MAX_TRACKS (99) /* AFAIK the theoretical limit */ +#define CD_MAX_SECTOR_DATA (2352) +#define CD_MAX_SUBCODE_DATA (96) + +#define CD_FRAME_SIZE (CD_MAX_SECTOR_DATA + CD_MAX_SUBCODE_DATA) +#define CD_FRAMES_PER_HUNK (8) + +#define CD_METADATA_WORDS (1+(CD_MAX_TRACKS * 6)) + +enum +{ + CD_TRACK_MODE1 = 0, /* mode 1 2048 bytes/sector */ + CD_TRACK_MODE1_RAW, /* mode 1 2352 bytes/sector */ + CD_TRACK_MODE2, /* mode 2 2336 bytes/sector */ + CD_TRACK_MODE2_FORM1, /* mode 2 2048 bytes/sector */ + CD_TRACK_MODE2_FORM2, /* mode 2 2324 bytes/sector */ + CD_TRACK_MODE2_FORM_MIX, /* mode 2 2336 bytes/sector */ + CD_TRACK_MODE2_RAW, /* mode 2 2352 bytes / sector */ + CD_TRACK_AUDIO, /* redbook audio track 2352 bytes/sector (588 samples) */ + + CD_TRACK_RAW_DONTCARE /* special flag for cdrom_read_data: just return me whatever is there */ +}; + +enum +{ + CD_SUB_NORMAL = 0, /* "cooked" 96 bytes per sector */ + CD_SUB_RAW, /* raw uninterleaved 96 bytes per sector */ + CD_SUB_NONE /* no subcode data stored */ +}; + +#define CD_FLAG_GDROM 0x00000001 /* disc is a GD-ROM, all tracks should be stored with GD-ROM metadata */ +#define CD_FLAG_GDROMLE 0x00000002 /* legacy GD-ROM, with little-endian CDDA data */ + +/*************************************************************************** + FUNCTION PROTOTYPES +***************************************************************************/ + +#if WANT_RAW_DATA_SECTOR +/* ECC utilities */ +int ecc_verify(const uint8_t *sector); +void ecc_generate(uint8_t *sector); +void ecc_clear(uint8_t *sector); +#endif + +chd_error cd_codec_decompress( + uint8_t *buffer, + void *base_decompressor, chd_codec_interface_decompress base_decompress, +#if WANT_SUBCODE + void *subcode_decompressor, chd_codec_interface_decompress subcode_decompress, +#endif + const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen); + + +/*************************************************************************** + INLINE FUNCTIONS +***************************************************************************/ + +static CHDR_INLINE uint32_t msf_to_lba(uint32_t msf) +{ + return ( ((msf&0x00ff0000)>>16) * 60 * 75) + (((msf&0x0000ff00)>>8) * 75) + ((msf&0x000000ff)>>0); +} + +static CHDR_INLINE uint32_t lba_to_msf(uint32_t lba) +{ + uint8_t m, s, f; + + m = lba / (60 * 75); + lba -= m * (60 * 75); + s = lba / 75; + f = lba % 75; + + return ((m / 10) << 20) | ((m % 10) << 16) | + ((s / 10) << 12) | ((s % 10) << 8) | + ((f / 10) << 4) | ((f % 10) << 0); +} + +/** + * segacd needs it like this.. investigate + * Angelo also says PCE tracks often start playing at the + * wrong address.. related? + **/ +static CHDR_INLINE uint32_t lba_to_msf_alt(int lba) +{ + uint32_t ret = 0; + + ret |= ((lba / (60 * 75))&0xff)<<16; + ret |= (((lba / 75) % 60)&0xff)<<8; + ret |= ((lba % 75)&0xff)<<0; + + return ret; +} + +#endif /* __CDROM_H__ */ diff --git a/libretrodroid/src/main/cpp/libchdr/include/libchdr/chd.h b/libretrodroid/src/main/cpp/libchdr/include/libchdr/chd.h new file mode 100644 index 000000000..3d64eeb7f --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/include/libchdr/chd.h @@ -0,0 +1,430 @@ +/*************************************************************************** + + chd.h + + MAME Compressed Hunks of Data file format + +**************************************************************************** + + Copyright Aaron Giles + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + * Neither the name 'MAME' nor the names of its contributors may be + used to endorse or promote products derived from this software + without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY AARON GILES ''AS IS'' AND ANY EXPRESS OR + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL AARON GILES BE LIABLE FOR ANY DIRECT, + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + +***************************************************************************/ + +#pragma once + +#ifndef __CHD_H__ +#define __CHD_H__ + +#include "coretypes.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/*************************************************************************** + + Compressed Hunks of Data header format. All numbers are stored in + Motorola (big-endian) byte ordering. The header is 76 (V1) or 80 (V2) + bytes long. + + V1 header: + + [ 0] char tag[8]; // 'MComprHD' + [ 8] uint32_t length; // length of header (including tag and length fields) + [ 12] uint32_t version; // drive format version + [ 16] uint32_t flags; // flags (see below) + [ 20] uint32_t compression; // compression type + [ 24] uint32_t hunksize; // 512-byte sectors per hunk + [ 28] uint32_t totalhunks; // total # of hunks represented + [ 32] uint32_t cylinders; // number of cylinders on hard disk + [ 36] uint32_t heads; // number of heads on hard disk + [ 40] uint32_t sectors; // number of sectors on hard disk + [ 44] uint8_t md5[16]; // MD5 checksum of raw data + [ 60] uint8_t parentmd5[16]; // MD5 checksum of parent file + [ 76] (V1 header length) + + V2 header: + + [ 0] char tag[8]; // 'MComprHD' + [ 8] uint32_t length; // length of header (including tag and length fields) + [ 12] uint32_t version; // drive format version + [ 16] uint32_t flags; // flags (see below) + [ 20] uint32_t compression; // compression type + [ 24] uint32_t hunksize; // seclen-byte sectors per hunk + [ 28] uint32_t totalhunks; // total # of hunks represented + [ 32] uint32_t cylinders; // number of cylinders on hard disk + [ 36] uint32_t heads; // number of heads on hard disk + [ 40] uint32_t sectors; // number of sectors on hard disk + [ 44] uint8_t md5[16]; // MD5 checksum of raw data + [ 60] uint8_t parentmd5[16]; // MD5 checksum of parent file + [ 76] uint32_t seclen; // number of bytes per sector + [ 80] (V2 header length) + + V3 header: + + [ 0] char tag[8]; // 'MComprHD' + [ 8] uint32_t length; // length of header (including tag and length fields) + [ 12] uint32_t version; // drive format version + [ 16] uint32_t flags; // flags (see below) + [ 20] uint32_t compression; // compression type + [ 24] uint32_t totalhunks; // total # of hunks represented + [ 28] uint64_t logicalbytes; // logical size of the data (in bytes) + [ 36] uint64_t metaoffset; // offset to the first blob of metadata + [ 44] uint8_t md5[16]; // MD5 checksum of raw data + [ 60] uint8_t parentmd5[16]; // MD5 checksum of parent file + [ 76] uint32_t hunkbytes; // number of bytes per hunk + [ 80] uint8_t sha1[20]; // SHA1 checksum of raw data + [100] uint8_t parentsha1[20];// SHA1 checksum of parent file + [120] (V3 header length) + + V4 header: + + [ 0] char tag[8]; // 'MComprHD' + [ 8] uint32_t length; // length of header (including tag and length fields) + [ 12] uint32_t version; // drive format version + [ 16] uint32_t flags; // flags (see below) + [ 20] uint32_t compression; // compression type + [ 24] uint32_t totalhunks; // total # of hunks represented + [ 28] uint64_t logicalbytes; // logical size of the data (in bytes) + [ 36] uint64_t metaoffset; // offset to the first blob of metadata + [ 44] uint32_t hunkbytes; // number of bytes per hunk + [ 48] uint8_t sha1[20]; // combined raw+meta SHA1 + [ 68] uint8_t parentsha1[20];// combined raw+meta SHA1 of parent + [ 88] uint8_t rawsha1[20]; // raw data SHA1 + [108] (V4 header length) + + Flags: + 0x00000001 - set if this drive has a parent + 0x00000002 - set if this drive allows writes + + ========================================================================= + + V5 header: + + [ 0] char tag[8]; // 'MComprHD' + [ 8] uint32_t length; // length of header (including tag and length fields) + [ 12] uint32_t version; // drive format version + [ 16] uint32_t compressors[4];// which custom compressors are used? + [ 32] uint64_t logicalbytes; // logical size of the data (in bytes) + [ 40] uint64_t mapoffset; // offset to the map + [ 48] uint64_t metaoffset; // offset to the first blob of metadata + [ 56] uint32_t hunkbytes; // number of bytes per hunk (512k maximum) + [ 60] uint32_t unitbytes; // number of bytes per unit within each hunk + [ 64] uint8_t rawsha1[20]; // raw data SHA1 + [ 84] uint8_t sha1[20]; // combined raw+meta SHA1 + [104] uint8_t parentsha1[20];// combined raw+meta SHA1 of parent + [124] (V5 header length) + + If parentsha1 != 0, we have a parent (no need for flags) + If compressors[0] == 0, we are uncompressed (including maps) + + V5 uncompressed map format: + + [ 0] uint32_t offset; // starting offset / hunk size + + V5 compressed map format header: + + [ 0] uint32_t length; // length of compressed map + [ 4] UINT48 datastart; // offset of first block + [ 10] uint16_t crc; // crc-16 of the map + [ 12] uint8_t lengthbits; // bits used to encode complength + [ 13] uint8_t hunkbits; // bits used to encode self-refs + [ 14] uint8_t parentunitbits; // bits used to encode parent unit refs + [ 15] uint8_t reserved; // future use + [ 16] (compressed header length) + + Each compressed map entry, once expanded, looks like: + + [ 0] uint8_t compression; // compression type + [ 1] UINT24 complength; // compressed length + [ 4] UINT48 offset; // offset + [ 10] uint16_t crc; // crc-16 of the data + +***************************************************************************/ + + +/*************************************************************************** + CONSTANTS +***************************************************************************/ + +/* header information */ +#define CHD_HEADER_VERSION 5 +#define CHD_V1_HEADER_SIZE 76 +#define CHD_V2_HEADER_SIZE 80 +#define CHD_V3_HEADER_SIZE 120 +#define CHD_V4_HEADER_SIZE 108 +#define CHD_V5_HEADER_SIZE 124 + +#define CHD_MAX_HEADER_SIZE CHD_V5_HEADER_SIZE + +/* checksumming information */ +#define CHD_MD5_BYTES 16 +#define CHD_SHA1_BYTES 20 + +/* CHD global flags */ +#define CHDFLAGS_HAS_PARENT 0x00000001 +#define CHDFLAGS_IS_WRITEABLE 0x00000002 +#define CHDFLAGS_UNDEFINED 0xfffffffc + +#define CHD_MAKE_TAG(a,b,c,d) (((a) << 24) | ((b) << 16) | ((c) << 8) | (d)) + +/* compression types */ +#define CHDCOMPRESSION_NONE 0 +#define CHDCOMPRESSION_ZLIB 1 +#define CHDCOMPRESSION_ZLIB_PLUS 2 +#define CHDCOMPRESSION_AV 3 + +#define CHD_CODEC_NONE 0 +#define CHD_CODEC_ZLIB CHD_MAKE_TAG('z','l','i','b') +#define CHD_CODEC_LZMA CHD_MAKE_TAG('l','z','m','a') +#define CHD_CODEC_HUFFMAN CHD_MAKE_TAG('h','u','f','f') +#define CHD_CODEC_FLAC CHD_MAKE_TAG('f','l','a','c') +#define CHD_CODEC_ZSTD CHD_MAKE_TAG('z', 's', 't', 'd') +/* general codecs with CD frontend */ +#define CHD_CODEC_CD_ZLIB CHD_MAKE_TAG('c','d','z','l') +#define CHD_CODEC_CD_LZMA CHD_MAKE_TAG('c','d','l','z') +#define CHD_CODEC_CD_FLAC CHD_MAKE_TAG('c','d','f','l') +#define CHD_CODEC_CD_ZSTD CHD_MAKE_TAG('c','d','z','s') + +/* A/V codec configuration parameters */ +#define AV_CODEC_COMPRESS_CONFIG 1 +#define AV_CODEC_DECOMPRESS_CONFIG 2 + +/* metadata parameters */ +#define CHDMETATAG_WILDCARD 0 +#define CHD_METAINDEX_APPEND ((uint32_t)-1) + +/* metadata flags */ +#define CHD_MDFLAGS_CHECKSUM 0x01 /* indicates data is checksummed */ + +/* standard hard disk metadata */ +#define HARD_DISK_METADATA_TAG CHD_MAKE_TAG('G','D','D','D') +#define HARD_DISK_METADATA_FORMAT "CYLS:%d,HEADS:%d,SECS:%d,BPS:%d" + +/* hard disk identify information */ +#define HARD_DISK_IDENT_METADATA_TAG CHD_MAKE_TAG('I','D','N','T') + +/* hard disk key information */ +#define HARD_DISK_KEY_METADATA_TAG CHD_MAKE_TAG('K','E','Y',' ') + +/* pcmcia CIS information */ +#define PCMCIA_CIS_METADATA_TAG CHD_MAKE_TAG('C','I','S',' ') + +/* standard CD-ROM metadata */ +#define CDROM_OLD_METADATA_TAG CHD_MAKE_TAG('C','H','C','D') +#define CDROM_TRACK_METADATA_TAG CHD_MAKE_TAG('C','H','T','R') +#define CDROM_TRACK_METADATA_FORMAT "TRACK:%d TYPE:%s SUBTYPE:%s FRAMES:%d" +#define CDROM_TRACK_METADATA2_TAG CHD_MAKE_TAG('C','H','T','2') +#define CDROM_TRACK_METADATA2_FORMAT "TRACK:%d TYPE:%s SUBTYPE:%s FRAMES:%d PREGAP:%d PGTYPE:%s PGSUB:%s POSTGAP:%d" +#define GDROM_OLD_METADATA_TAG CHD_MAKE_TAG('C','H','G','T') +#define GDROM_TRACK_METADATA_TAG CHD_MAKE_TAG('C', 'H', 'G', 'D') +#define GDROM_TRACK_METADATA_FORMAT "TRACK:%d TYPE:%s SUBTYPE:%s FRAMES:%d PAD:%d PREGAP:%d PGTYPE:%s PGSUB:%s POSTGAP:%d" + +/* standard A/V metadata */ +#define AV_METADATA_TAG CHD_MAKE_TAG('A','V','A','V') +#define AV_METADATA_FORMAT "FPS:%d.%06d WIDTH:%d HEIGHT:%d INTERLACED:%d CHANNELS:%d SAMPLERATE:%d" + +/* A/V laserdisc frame metadata */ +#define AV_LD_METADATA_TAG CHD_MAKE_TAG('A','V','L','D') + +/* DVD metadata */ +#define DVD_METADATA_TAG CHD_MAKE_TAG('D','V','D',' ') + +/* CHD open values */ +#define CHD_OPEN_READ 1 +#define CHD_OPEN_READWRITE 2 + +/* error types */ +enum _chd_error +{ + CHDERR_NONE, + CHDERR_NO_INTERFACE, + CHDERR_OUT_OF_MEMORY, + CHDERR_INVALID_FILE, + CHDERR_INVALID_PARAMETER, + CHDERR_INVALID_DATA, + CHDERR_FILE_NOT_FOUND, + CHDERR_REQUIRES_PARENT, + CHDERR_FILE_NOT_WRITEABLE, + CHDERR_READ_ERROR, + CHDERR_WRITE_ERROR, + CHDERR_CODEC_ERROR, + CHDERR_INVALID_PARENT, + CHDERR_HUNK_OUT_OF_RANGE, + CHDERR_DECOMPRESSION_ERROR, + CHDERR_COMPRESSION_ERROR, + CHDERR_CANT_CREATE_FILE, + CHDERR_CANT_VERIFY, + CHDERR_NOT_SUPPORTED, + CHDERR_METADATA_NOT_FOUND, + CHDERR_INVALID_METADATA_SIZE, + CHDERR_UNSUPPORTED_VERSION, + CHDERR_VERIFY_INCOMPLETE, + CHDERR_INVALID_METADATA, + CHDERR_INVALID_STATE, + CHDERR_OPERATION_PENDING, + CHDERR_NO_ASYNC_OPERATION, + CHDERR_UNSUPPORTED_FORMAT +}; +typedef enum _chd_error chd_error; + + + +/*************************************************************************** + TYPE DEFINITIONS +***************************************************************************/ + +/* opaque types */ +typedef struct _chd_file chd_file; + + +/* extract header structure (NOT the on-disk header structure) */ +typedef struct _chd_header chd_header; +struct _chd_header +{ + uint32_t length; /* length of header data */ + uint32_t version; /* drive format version */ + uint32_t flags; /* flags field */ + uint32_t compression[4]; /* compression type */ + uint32_t hunkbytes; /* number of bytes per hunk */ + uint32_t totalhunks; /* total # of hunks represented */ + uint64_t logicalbytes; /* logical size of the data */ + uint64_t metaoffset; /* offset in file of first metadata */ + uint64_t mapoffset; /* TOOD V5 */ + uint8_t md5[CHD_MD5_BYTES]; /* overall MD5 checksum */ + uint8_t parentmd5[CHD_MD5_BYTES]; /* overall MD5 checksum of parent */ + uint8_t sha1[CHD_SHA1_BYTES]; /* overall SHA1 checksum */ + uint8_t rawsha1[CHD_SHA1_BYTES]; /* SHA1 checksum of raw data */ + uint8_t parentsha1[CHD_SHA1_BYTES]; /* overall SHA1 checksum of parent */ + uint32_t unitbytes; /* TODO V5 */ + uint64_t unitcount; /* TODO V5 */ + uint32_t hunkcount; /* TODO V5 */ + + /* map information */ + uint32_t mapentrybytes; /* length of each entry in a map (V5) */ + uint8_t* rawmap; /* raw map data */ + + uint32_t obsolete_cylinders; /* obsolete field -- do not use! */ + uint32_t obsolete_sectors; /* obsolete field -- do not use! */ + uint32_t obsolete_heads; /* obsolete field -- do not use! */ + uint32_t obsolete_hunksize; /* obsolete field -- do not use! */ +}; + + +/* structure for returning information about a verification pass */ +typedef struct _chd_verify_result chd_verify_result; +struct _chd_verify_result +{ + uint8_t md5[CHD_MD5_BYTES]; /* overall MD5 checksum */ + uint8_t sha1[CHD_SHA1_BYTES]; /* overall SHA1 checksum */ + uint8_t rawsha1[CHD_SHA1_BYTES]; /* SHA1 checksum of raw data */ + uint8_t metasha1[CHD_SHA1_BYTES]; /* SHA1 checksum of metadata */ +}; + +typedef chd_error (*chd_codec_interface_decompress)(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen); + + + +/*************************************************************************** + FUNCTION PROTOTYPES +***************************************************************************/ + +#ifdef _MSC_VER +#ifdef CHD_DLL +#ifdef CHD_DLL_EXPORTS +#define CHD_EXPORT __declspec(dllexport) +#else +#define CHD_EXPORT __declspec(dllimport) +#endif +#else +#define CHD_EXPORT +#endif +#else +#define CHD_EXPORT __attribute__ ((visibility("default"))) +#endif + +/* ----- CHD file management ----- */ + +/* create a new CHD file fitting the given description */ +/* chd_error chd_create(const char *filename, uint64_t logicalbytes, uint32_t hunkbytes, uint32_t compression, chd_file *parent); */ + +/* same as chd_create(), but accepts an already-opened core_file object */ +/* chd_error chd_create_file(core_file *file, uint64_t logicalbytes, uint32_t hunkbytes, uint32_t compression, chd_file *parent); */ + +/* open an existing CHD file */ +CHD_EXPORT chd_error chd_open_core_file_callbacks(const core_file_callbacks *callbacks, const void *user_data, int mode, chd_file *parent, chd_file **chd); +CHD_EXPORT chd_error chd_open_core_file(core_file *file, int mode, chd_file *parent, chd_file **chd); /* Legacy; use chd_open_core_file_callbacks instead! */ +CHD_EXPORT chd_error chd_open_file(RFILE *file, int mode, chd_file *parent, chd_file **chd); +CHD_EXPORT chd_error chd_open(const char *filename, int mode, chd_file *parent, chd_file **chd); + +/* precache underlying file */ +CHD_EXPORT chd_error chd_precache(chd_file *chd); + +/* close a CHD file */ +CHD_EXPORT void chd_close(chd_file *chd); + +/* return the associated core_file */ +CHD_EXPORT core_file *chd_core_file(chd_file *chd); + +/* return an error string for the given CHD error */ +CHD_EXPORT const char *chd_error_string(chd_error err); + + + +/* ----- CHD header management ----- */ + +/* return a pointer to the extracted CHD header data */ +CHD_EXPORT const chd_header *chd_get_header(chd_file *chd); + +/* read CHD header data from file into the pointed struct */ +CHD_EXPORT chd_error chd_read_header_core_file_callbacks(const core_file_callbacks *callback, const void *user_data, chd_header *header); +CHD_EXPORT chd_error chd_read_header_core_file(core_file *file, chd_header *header); /* Legacy; use chd_read_header_core_file_callbacks instead! */ +CHD_EXPORT chd_error chd_read_header_file(FILE *file, chd_header *header); +CHD_EXPORT chd_error chd_read_header(const char *filename, chd_header *header); + + + +/* ----- core data read/write ----- */ + +/* read one hunk from the CHD file */ +CHD_EXPORT chd_error chd_read(chd_file *chd, uint32_t hunknum, void *buffer); + + + +/* ----- metadata management ----- */ + +/* get indexed metadata of a particular sort */ +CHD_EXPORT chd_error chd_get_metadata(chd_file *chd, uint32_t searchtag, uint32_t searchindex, void *output, uint32_t outputlen, uint32_t *resultlen, uint32_t *resulttag, uint8_t *resultflags); + +#ifdef __cplusplus +} +#endif + +#endif /* __CHD_H__ */ diff --git a/libretrodroid/src/main/cpp/libchdr/include/libchdr/chdconfig.h b/libretrodroid/src/main/cpp/libchdr/include/libchdr/chdconfig.h new file mode 100644 index 000000000..8dccf883c --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/include/libchdr/chdconfig.h @@ -0,0 +1,18 @@ +#ifndef __CHDCONFIG_H__ +#define __CHDCONFIG_H__ + +/* Configure CHDR features by defining these beforehand. */ + +#ifndef WANT_RAW_DATA_SECTOR +#define WANT_RAW_DATA_SECTOR 1 +#endif + +#ifndef WANT_SUBCODE +#define WANT_SUBCODE 1 +#endif + +#ifndef VERIFY_BLOCK_CRC +#define VERIFY_BLOCK_CRC 1 +#endif + +#endif diff --git a/libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_cdfl.h b/libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_cdfl.h new file mode 100644 index 000000000..dfce0a5d2 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_cdfl.h @@ -0,0 +1,28 @@ +#ifndef LIBCHDR_CODEC_CDFL_H +#define LIBCHDR_CODEC_CDFL_H + +#include + +#include "chd.h" +#include "chdconfig.h" +#include "flac.h" +#include "codec_zlib.h" + +/* codec-private data for the CDFL codec */ +typedef struct _cdfl_codec_data cdfl_codec_data; +struct _cdfl_codec_data { + /* internal state */ + int swap_endian; + flac_decoder decoder; +#if WANT_SUBCODE + zlib_codec_data subcode_decompressor; +#endif + uint8_t* buffer; +}; + +/* cdfl compression codec */ +chd_error cdfl_codec_init(void* codec, uint32_t hunkbytes); +void cdfl_codec_free(void* codec); +chd_error cdfl_codec_decompress(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen); + +#endif /* LIBCHDR_CODEC_CDFL_H */ diff --git a/libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_cdlz.h b/libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_cdlz.h new file mode 100644 index 000000000..35ca3ecfd --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_cdlz.h @@ -0,0 +1,27 @@ +#ifndef LIBCHDR_CODEC_CDLZ_H +#define LIBCHDR_CODEC_CDLZ_H + +#include + +#include "chd.h" +#include "chdconfig.h" +#include "codec_lzma.h" +#include "codec_zlib.h" + +/* codec-private data for the CDLZ codec */ +typedef struct _cdlz_codec_data cdlz_codec_data; +struct _cdlz_codec_data { + /* internal state */ + lzma_codec_data base_decompressor; +#if WANT_SUBCODE + zlib_codec_data subcode_decompressor; +#endif + uint8_t* buffer; +}; + +/* cdlz compression codec */ +chd_error cdlz_codec_init(void* codec, uint32_t hunkbytes); +void cdlz_codec_free(void* codec); +chd_error cdlz_codec_decompress(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen); + +#endif /* LIBCHDR_CODEC_CDLZ_H */ diff --git a/libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_cdzl.h b/libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_cdzl.h new file mode 100644 index 000000000..58ed938b4 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_cdzl.h @@ -0,0 +1,26 @@ +#ifndef LIBCHDR_CODEC_CDZL_H +#define LIBCHDR_CODEC_CDZL_H + +#include + +#include "chd.h" +#include "chdconfig.h" +#include "codec_zlib.h" + +/* codec-private data for the CDZL codec */ +typedef struct _cdzl_codec_data cdzl_codec_data; +struct _cdzl_codec_data { + /* internal state */ + zlib_codec_data base_decompressor; +#if WANT_SUBCODE + zlib_codec_data subcode_decompressor; +#endif + uint8_t* buffer; +}; + +/* cdzl compression codec */ +chd_error cdzl_codec_init(void* codec, uint32_t hunkbytes); +void cdzl_codec_free(void* codec); +chd_error cdzl_codec_decompress(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen); + +#endif /* LIBCHDR_CODEC_CDZL_H */ diff --git a/libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_cdzs.h b/libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_cdzs.h new file mode 100644 index 000000000..57f982f54 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_cdzs.h @@ -0,0 +1,26 @@ +#ifndef LIBCHDR_CODEC_CDZS_H +#define LIBCHDR_CODEC_CDZS_H + +#include + +#include "chd.h" +#include "chdconfig.h" +#include "codec_zstd.h" + +/* codec-private data for the CDZS codec */ +typedef struct _cdzs_codec_data cdzs_codec_data; +struct _cdzs_codec_data +{ + zstd_codec_data base_decompressor; +#if WANT_SUBCODE + zstd_codec_data subcode_decompressor; +#endif + uint8_t* buffer; +}; + +/* cdlz compression codec */ +chd_error cdzs_codec_init(void *codec, uint32_t hunkbytes); +void cdzs_codec_free(void *codec); +chd_error cdzs_codec_decompress(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen); + +#endif /* LIBCHDR_CODEC_CDZS_H */ diff --git a/libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_flac.h b/libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_flac.h new file mode 100644 index 000000000..5fa4de853 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_flac.h @@ -0,0 +1,22 @@ +#ifndef LIBCHDR_CODEC_FLAC_H +#define LIBCHDR_CODEC_FLAC_H + +#include + +#include "chd.h" +#include "flac.h" + +/* codec-private data for the FLAC codec */ +typedef struct _flac_codec_data flac_codec_data; +struct _flac_codec_data { + /* internal state */ + int native_endian; + flac_decoder decoder; +}; + +/* flac compression codec */ +chd_error flac_codec_init(void *codec, uint32_t hunkbytes); +void flac_codec_free(void *codec); +chd_error flac_codec_decompress(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen); + +#endif /* LIBCHDR_CODEC_FLAC_H */ diff --git a/libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_huff.h b/libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_huff.h new file mode 100644 index 000000000..2ae47d168 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_huff.h @@ -0,0 +1,22 @@ +#ifndef LIBCHDR_CODEC_HUFF_H +#define LIBCHDR_CODEC_HUFF_H + +#include + +#include "chd.h" + +struct huffman_decoder; + +/* codec-private data for the FLAC codec */ +typedef struct _huff_codec_data huff_codec_data; +struct _huff_codec_data +{ + struct huffman_decoder* decoder; +}; + +/* huff compression codec */ +chd_error huff_codec_init(void *codec, uint32_t hunkbytes); +void huff_codec_free(void *codec); +chd_error huff_codec_decompress(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen); + +#endif /* LIBCHDR_CODEC_HUFF_H */ diff --git a/libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_lzma.h b/libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_lzma.h new file mode 100644 index 000000000..48f95dd3b --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_lzma.h @@ -0,0 +1,35 @@ +#ifndef LIBCHDR_CODEC_LZMA_H +#define LIBCHDR_CODEC_LZMA_H + +#include + +#include "../../deps/lzma-25.01/include/LzmaDec.h" + +#include "chd.h" + +/* codec-private data for the LZMA codec */ +#define MAX_LZMA_ALLOCS 64 + +typedef struct _lzma_allocator lzma_allocator; +struct _lzma_allocator +{ + void *(*Alloc)(void *p, size_t size); + void (*Free)(void *p, void *address); /* address can be 0 */ + void (*FreeSz)(void *p, void *address, size_t size); /* address can be 0 */ + uint32_t* allocptr[MAX_LZMA_ALLOCS]; + uint32_t* allocptr2[MAX_LZMA_ALLOCS]; +}; + +typedef struct _lzma_codec_data lzma_codec_data; +struct _lzma_codec_data +{ + CLzmaDec decoder; + lzma_allocator allocator; +}; + +/* lzma compression codec */ +chd_error lzma_codec_init(void *codec, uint32_t hunkbytes); +void lzma_codec_free(void *codec); +chd_error lzma_codec_decompress(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen); + +#endif /* LIBCHDR_CODEC_LZMA_H */ diff --git a/libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_zlib.h b/libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_zlib.h new file mode 100644 index 000000000..7671d7043 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_zlib.h @@ -0,0 +1,36 @@ +#ifndef LIBCHDR_CODEC_ZLIB_H +#define LIBCHDR_CODEC_ZLIB_H + +#include + +#if defined(__PS3__) || defined(__PSL1GHT__) +#define __MACTYPES__ +#endif +#include +typedef uInt zlib_alloc_size; + +#include "chd.h" + +/* codec-private data for the ZLIB codec */ +#define MAX_ZLIB_ALLOCS 64 + +typedef struct _zlib_allocator zlib_allocator; +struct _zlib_allocator +{ + uint32_t * allocptr[MAX_ZLIB_ALLOCS]; + uint32_t * allocptr2[MAX_ZLIB_ALLOCS]; +}; + +typedef struct _zlib_codec_data zlib_codec_data; +struct _zlib_codec_data +{ + z_stream inflater; + zlib_allocator allocator; +}; + +/* zlib compression codec */ +chd_error zlib_codec_init(void *codec, uint32_t hunkbytes); +void zlib_codec_free(void *codec); +chd_error zlib_codec_decompress(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen); + +#endif /* LIBCHDR_CODEC_ZLIB_H */ diff --git a/libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_zstd.h b/libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_zstd.h new file mode 100644 index 000000000..94b3a8cfa --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/include/libchdr/codec_zstd.h @@ -0,0 +1,27 @@ +#ifndef LIBCHDR_CODEC_ZSTD_H +#define LIBCHDR_CODEC_ZSTD_H + +#include + +#ifdef CHDR_SYSTEM_ZSTD +#include +#else +#include "../../deps/zstd-1.5.7/zstd.h" +#endif + +#include "chd.h" + +/* codec-private data for the ZSTD codec */ + +typedef struct _zstd_codec_data zstd_codec_data; +struct _zstd_codec_data +{ + ZSTD_DStream *dstream; +}; + +/* zstd compression codec */ +chd_error zstd_codec_init(void *codec, uint32_t hunkbytes); +void zstd_codec_free(void *codec); +chd_error zstd_codec_decompress(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen); + +#endif /* LIBCHDR_CODEC_ZSTD_H */ diff --git a/libretrodroid/src/main/cpp/libchdr/include/libchdr/coretypes.h b/libretrodroid/src/main/cpp/libchdr/include/libchdr/coretypes.h new file mode 100644 index 000000000..d5ff6ab2b --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/include/libchdr/coretypes.h @@ -0,0 +1,71 @@ +#ifndef __CORETYPES_H__ +#define __CORETYPES_H__ + +#include +#include + +#include "macros.h" + +typedef struct chd_core_file_callbacks { + /* + * return the size of a given file as a 64-bit unsigned integer. + * the position of the file pointer after calling this function is + * undefined because many implementations will seek to the end of the + * file and call ftell. + * + * on error, (uint64_t)-1 is returned. + */ + uint64_t(*fsize)(void*); + + /* + * should match the behavior of fread, except the FILE* argument at the end + * will be replaced with a void* (libretro VFS RFILE*). + */ + size_t(*fread)(void*,size_t,size_t,void*); + + // closes the given file. + int (*fclose)(void*); + + // fseek clone + int (*fseek)(void*, int64_t, int); +} core_file_callbacks; + +typedef struct chd_core_file_callbacks_and_argp { + const core_file_callbacks *callbacks; + + /* + * arbitrary pointer to data the implementation uses to implement the above functions + */ + void *argp; +} core_file_callbacks_and_argp; + +/* Legacy API */ + +typedef struct chd_core_file { + void *argp; + uint64_t(*fsize)(struct chd_core_file*); + size_t(*fread)(void*,size_t,size_t,struct chd_core_file*); + int (*fclose)(struct chd_core_file*); + int (*fseek)(struct chd_core_file*, int64_t, int); +} core_file; + +/* File IO shortcuts */ + +static CHDR_INLINE int core_fclose(const core_file_callbacks_and_argp *fp) { + return fp->callbacks->fclose(fp->argp); +} + +static CHDR_INLINE size_t core_fread(const core_file_callbacks_and_argp *fp, void *ptr, size_t len) { + return fp->callbacks->fread(ptr, 1, len, fp->argp); +} + +static CHDR_INLINE int core_fseek(const core_file_callbacks_and_argp* fp, int64_t offset, int whence) { + return fp->callbacks->fseek(fp->argp, offset, whence); +} + +static CHDR_INLINE uint64_t core_fsize(const core_file_callbacks_and_argp *fp) +{ + return fp->callbacks->fsize(fp->argp); +} + +#endif diff --git a/libretrodroid/src/main/cpp/libchdr/include/libchdr/flac.h b/libretrodroid/src/main/cpp/libchdr/include/libchdr/flac.h new file mode 100644 index 000000000..cfc268b4b --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/include/libchdr/flac.h @@ -0,0 +1,51 @@ +/* license:BSD-3-Clause + * copyright-holders:Aaron Giles + *************************************************************************** + + flac.h + + FLAC compression wrappers + +***************************************************************************/ + +#pragma once + +#ifndef __FLAC_H__ +#define __FLAC_H__ + +#include + +/*************************************************************************** + * TYPE DEFINITIONS + *************************************************************************** + */ + +typedef struct _flac_decoder flac_decoder; +struct _flac_decoder { + /* output state */ + void * decoder; /* actual encoder */ + uint32_t sample_rate; /* decoded sample rate */ + uint8_t channels; /* decoded number of channels */ + uint8_t bits_per_sample; /* decoded bits per sample */ + uint32_t compressed_offset; /* current offset in compressed data */ + const uint8_t * compressed_start; /* start of compressed data */ + uint32_t compressed_length; /* length of compressed data */ + const uint8_t * compressed2_start; /* start of compressed data */ + uint32_t compressed2_length; /* length of compressed data */ + int16_t * uncompressed_start[8]; /* pointer to start of uncompressed data (up to 8 streams) */ + uint32_t uncompressed_offset; /* current position in uncompressed data */ + uint32_t uncompressed_length; /* length of uncompressed data */ + int uncompressed_swap; /* swap uncompressed sample data */ + uint8_t custom_header[0x2a]; /* custom header */ +}; + +/* ======================> flac_decoder */ + +int flac_decoder_init(flac_decoder* decoder); +void flac_decoder_free(flac_decoder* decoder); +int flac_decoder_reset(flac_decoder* decoder, uint32_t sample_rate, uint8_t num_channels, uint32_t block_size, const void *buffer, uint32_t length); +int flac_decoder_decode_interleaved(flac_decoder* decoder, int16_t *samples, uint32_t num_samples, int swap_endian); +uint32_t flac_decoder_finish(flac_decoder* decoder); +int flac_decoder_detect_native_endian(void); + +#endif /* __FLAC_H__ */ diff --git a/libretrodroid/src/main/cpp/libchdr/include/libchdr/huffman.h b/libretrodroid/src/main/cpp/libchdr/include/libchdr/huffman.h new file mode 100644 index 000000000..e0dd67639 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/include/libchdr/huffman.h @@ -0,0 +1,90 @@ +/* license:BSD-3-Clause + * copyright-holders:Aaron Giles + *************************************************************************** + + huffman.h + + Static Huffman compression and decompression helpers. + +***************************************************************************/ + +#pragma once + +#ifndef __HUFFMAN_H__ +#define __HUFFMAN_H__ + +#include "bitstream.h" + + +/*************************************************************************** + * CONSTANTS + *************************************************************************** + */ + +enum huffman_error +{ + HUFFERR_NONE = 0, + HUFFERR_TOO_MANY_BITS, + HUFFERR_INVALID_DATA, + HUFFERR_INPUT_BUFFER_TOO_SMALL, + HUFFERR_OUTPUT_BUFFER_TOO_SMALL, + HUFFERR_INTERNAL_INCONSISTENCY, + HUFFERR_TOO_MANY_CONTEXTS +}; + +/*************************************************************************** + * TYPE DEFINITIONS + *************************************************************************** + */ + +typedef uint16_t lookup_value; + +/* a node in the huffman tree */ +struct node_t +{ + struct node_t* parent; /* pointer to parent node */ + uint32_t count; /* number of hits on this node */ + uint32_t weight; /* assigned weight of this node */ + uint32_t bits; /* bits used to encode the node */ + uint8_t numbits; /* number of bits needed for this node */ +}; + +/* ======================> huffman_context_base */ + +/* context class for decoding */ +struct huffman_decoder +{ + /* internal state */ + uint32_t numcodes; /* number of total codes being processed */ + uint8_t maxbits; /* maximum bits per code */ + uint8_t prevdata; /* value of the previous data (for delta-RLE encoding) */ + int rleremaining; /* number of RLE bytes remaining (for delta-RLE encoding) */ + lookup_value * lookup; /* pointer to the lookup table */ + struct node_t * huffnode; /* array of nodes */ + uint32_t * datahisto; /* histogram of data values */ + + /* array versions of the info we need */ +#if 0 + node_t* huffnode_array; /* [_NumCodes]; */ + lookup_value* lookup_array; /* [1 << _MaxBits]; */ +#endif +}; + +/* ======================> huffman_decoder */ + +struct huffman_decoder* create_huffman_decoder(int numcodes, int maxbits); +void delete_huffman_decoder(struct huffman_decoder* decoder); + +/* single item operations */ +uint32_t huffman_decode_one(struct huffman_decoder* decoder, struct bitstream* bitbuf); + +enum huffman_error huffman_import_tree_rle(struct huffman_decoder* decoder, struct bitstream* bitbuf); +enum huffman_error huffman_import_tree_huffman(struct huffman_decoder* decoder, struct bitstream* bitbuf); + +int huffman_build_tree(struct huffman_decoder* decoder, uint32_t totaldata, uint32_t totalweight); +enum huffman_error huffman_assign_canonical_codes(struct huffman_decoder* decoder); +enum huffman_error huffman_compute_tree_from_histo(struct huffman_decoder* decoder); + +enum huffman_error huffman_build_lookup_table(struct huffman_decoder* decoder); + +#endif diff --git a/libretrodroid/src/main/cpp/libchdr/include/libchdr/macros.h b/libretrodroid/src/main/cpp/libchdr/include/libchdr/macros.h new file mode 100644 index 000000000..445b3b247 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/include/libchdr/macros.h @@ -0,0 +1,24 @@ +#ifndef LIBCHDR_MACROS_H +#define LIBCHDR_MACROS_H + +#undef ARRAY_LENGTH +#define ARRAY_LENGTH(x) (sizeof(x)/sizeof(x[0])) + +#undef MAX +#undef MIN +#define MAX(x, y) (((x) > (y)) ? (x) : (y)) +#define MIN(x, y) (((x) < (y)) ? (x) : (y)) + +#ifndef CHDR_INLINE + #if defined(_WIN32) || defined(__INTEL_COMPILER) + #define CHDR_INLINE __inline + #elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CHDR_INLINE inline + #elif defined(__GNUC__) + #define CHDR_INLINE __inline__ + #else + #define CHDR_INLINE + #endif +#endif + +#endif /* LIBCHDR_MACROS_H */ diff --git a/libretrodroid/src/main/cpp/libchdr/src/libchdr_bitstream.c b/libretrodroid/src/main/cpp/libchdr/src/libchdr_bitstream.c new file mode 100644 index 000000000..2b59b593b --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/src/libchdr_bitstream.c @@ -0,0 +1,125 @@ +/* license:BSD-3-Clause + * copyright-holders:Aaron Giles +*************************************************************************** + + bitstream.c + + Helper classes for reading/writing at the bit level. + +***************************************************************************/ + +#include +#include "../include/libchdr/bitstream.h" + +/*************************************************************************** + * INLINE FUNCTIONS + *************************************************************************** + */ + +int bitstream_overflow(struct bitstream* bitstream) { return ((bitstream->doffset - bitstream->bits / 8) > bitstream->dlength); } + +/*------------------------------------------------- + * create_bitstream - constructor + *------------------------------------------------- + */ + +struct bitstream* create_bitstream(const void *src, uint32_t srclength) +{ + struct bitstream* bitstream = (struct bitstream*)malloc(sizeof(struct bitstream)); + bitstream->buffer = 0; + bitstream->bits = 0; + bitstream->read = (const uint8_t*)src; + bitstream->doffset = 0; + bitstream->dlength = srclength; + return bitstream; +} + + +/*----------------------------------------------------- + * bitstream_peek - fetch the requested number of bits + * but don't advance the input pointer + *----------------------------------------------------- + */ + +uint32_t bitstream_peek(struct bitstream* bitstream, int numbits) +{ + if (numbits == 0) + return 0; + + /* fetch data if we need more */ + if (numbits > bitstream->bits) + { + while (bitstream->bits <= 24) + { + if (bitstream->doffset < bitstream->dlength) + bitstream->buffer |= bitstream->read[bitstream->doffset] << (24 - bitstream->bits); + bitstream->doffset++; + bitstream->bits += 8; + } + } + + /* return the data */ + return bitstream->buffer >> (32 - numbits); +} + + +/*----------------------------------------------------- + * bitstream_remove - advance the input pointer by the + * specified number of bits + *----------------------------------------------------- + */ + +void bitstream_remove(struct bitstream* bitstream, int numbits) +{ + bitstream->buffer <<= numbits; + bitstream->bits -= numbits; +} + + +/*----------------------------------------------------- + * bitstream_read - fetch the requested number of bits + *----------------------------------------------------- + */ + +uint32_t bitstream_read(struct bitstream* bitstream, int numbits) +{ + uint32_t result = bitstream_peek(bitstream, numbits); + bitstream_remove(bitstream, numbits); + return result; +} + + +/*------------------------------------------------- + * read_offset - return the current read offset + *------------------------------------------------- + */ + +uint32_t bitstream_read_offset(struct bitstream* bitstream) +{ + uint32_t result = bitstream->doffset; + int bits = bitstream->bits; + while (bits >= 8) + { + result--; + bits -= 8; + } + return result; +} + + +/*------------------------------------------------- + * flush - flush to the nearest byte + *------------------------------------------------- + */ + +uint32_t bitstream_flush(struct bitstream* bitstream) +{ + while (bitstream->bits >= 8) + { + bitstream->doffset--; + bitstream->bits -= 8; + } + bitstream->bits = bitstream->buffer = 0; + return bitstream->doffset; +} + diff --git a/libretrodroid/src/main/cpp/libchdr/src/libchdr_cdrom.c b/libretrodroid/src/main/cpp/libchdr/src/libchdr_cdrom.c new file mode 100644 index 000000000..9e22593f5 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/src/libchdr_cdrom.c @@ -0,0 +1,490 @@ +/* license:BSD-3-Clause + * copyright-holders:Aaron Giles +*************************************************************************** + + cdrom.c + + Generic MAME CD-ROM utilities - build IDE and SCSI CD-ROMs on top of this + +**************************************************************************** + + IMPORTANT: + "physical" block addresses are the actual addresses on the emulated CD. + "chd" block addresses are the block addresses in the CHD file. + Because we pad each track to a 4-frame boundary, these addressing + schemes will differ after track 1! + +***************************************************************************/ + +#include + +#include "../include/libchdr/cdrom.h" + +#if WANT_RAW_DATA_SECTOR + +/*************************************************************************** + DEBUGGING +***************************************************************************/ + +/** @brief The verbose. */ +#define VERBOSE (0) +#if VERBOSE + +/** + * @def LOG(x) do + * + * @brief A macro that defines log. + * + * @param x The void to process. + */ + +#define LOG(x) do { if (VERBOSE) logerror x; } while (0) + +/** + * @fn void CLIB_DECL logerror(const char *text, ...) ATTR_PRINTF(1,2); + * + * @brief Logerrors the given text. + * + * @param text The text. + * + * @return A CLIB_DECL. + */ + +void CLIB_DECL logerror(const char *text, ...) ATTR_PRINTF(1,2); +#else + +/** + * @def LOG(x); + * + * @brief A macro that defines log. + * + * @param x The void to process. + */ + +#define LOG(x) +#endif + +/*************************************************************************** + CONSTANTS +***************************************************************************/ + +/** @brief offset within sector. */ +#define SYNC_OFFSET 0x000 +/** @brief 12 bytes. */ +#define SYNC_NUM_BYTES 12 + +/** @brief offset within sector. */ +#define MODE_OFFSET 0x00f + +/** @brief offset within sector. */ +#define ECC_P_OFFSET 0x81c +/** @brief 2 lots of 86. */ +#define ECC_P_NUM_BYTES 86 +/** @brief 24 bytes each. */ +#define ECC_P_COMP 24 + +/** @brief The ECC q offset. */ +#define ECC_Q_OFFSET (ECC_P_OFFSET + 2 * ECC_P_NUM_BYTES) +/** @brief 2 lots of 52. */ +#define ECC_Q_NUM_BYTES 52 +/** @brief 43 bytes each. */ +#define ECC_Q_COMP 43 + +#if WANT_RAW_DATA_SECTOR +static const uint8_t s_cd_sync_header[12] = { 0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00 }; +#endif + +/** + * @brief ------------------------------------------------- + * ECC lookup tables pre-calculated tables for ECC data calcs + * -------------------------------------------------. + */ + +static const uint8_t ecclow[256] = +{ + 0x00, 0x02, 0x04, 0x06, 0x08, 0x0a, 0x0c, 0x0e, 0x10, 0x12, 0x14, 0x16, 0x18, 0x1a, 0x1c, 0x1e, + 0x20, 0x22, 0x24, 0x26, 0x28, 0x2a, 0x2c, 0x2e, 0x30, 0x32, 0x34, 0x36, 0x38, 0x3a, 0x3c, 0x3e, + 0x40, 0x42, 0x44, 0x46, 0x48, 0x4a, 0x4c, 0x4e, 0x50, 0x52, 0x54, 0x56, 0x58, 0x5a, 0x5c, 0x5e, + 0x60, 0x62, 0x64, 0x66, 0x68, 0x6a, 0x6c, 0x6e, 0x70, 0x72, 0x74, 0x76, 0x78, 0x7a, 0x7c, 0x7e, + 0x80, 0x82, 0x84, 0x86, 0x88, 0x8a, 0x8c, 0x8e, 0x90, 0x92, 0x94, 0x96, 0x98, 0x9a, 0x9c, 0x9e, + 0xa0, 0xa2, 0xa4, 0xa6, 0xa8, 0xaa, 0xac, 0xae, 0xb0, 0xb2, 0xb4, 0xb6, 0xb8, 0xba, 0xbc, 0xbe, + 0xc0, 0xc2, 0xc4, 0xc6, 0xc8, 0xca, 0xcc, 0xce, 0xd0, 0xd2, 0xd4, 0xd6, 0xd8, 0xda, 0xdc, 0xde, + 0xe0, 0xe2, 0xe4, 0xe6, 0xe8, 0xea, 0xec, 0xee, 0xf0, 0xf2, 0xf4, 0xf6, 0xf8, 0xfa, 0xfc, 0xfe, + 0x1d, 0x1f, 0x19, 0x1b, 0x15, 0x17, 0x11, 0x13, 0x0d, 0x0f, 0x09, 0x0b, 0x05, 0x07, 0x01, 0x03, + 0x3d, 0x3f, 0x39, 0x3b, 0x35, 0x37, 0x31, 0x33, 0x2d, 0x2f, 0x29, 0x2b, 0x25, 0x27, 0x21, 0x23, + 0x5d, 0x5f, 0x59, 0x5b, 0x55, 0x57, 0x51, 0x53, 0x4d, 0x4f, 0x49, 0x4b, 0x45, 0x47, 0x41, 0x43, + 0x7d, 0x7f, 0x79, 0x7b, 0x75, 0x77, 0x71, 0x73, 0x6d, 0x6f, 0x69, 0x6b, 0x65, 0x67, 0x61, 0x63, + 0x9d, 0x9f, 0x99, 0x9b, 0x95, 0x97, 0x91, 0x93, 0x8d, 0x8f, 0x89, 0x8b, 0x85, 0x87, 0x81, 0x83, + 0xbd, 0xbf, 0xb9, 0xbb, 0xb5, 0xb7, 0xb1, 0xb3, 0xad, 0xaf, 0xa9, 0xab, 0xa5, 0xa7, 0xa1, 0xa3, + 0xdd, 0xdf, 0xd9, 0xdb, 0xd5, 0xd7, 0xd1, 0xd3, 0xcd, 0xcf, 0xc9, 0xcb, 0xc5, 0xc7, 0xc1, 0xc3, + 0xfd, 0xff, 0xf9, 0xfb, 0xf5, 0xf7, 0xf1, 0xf3, 0xed, 0xef, 0xe9, 0xeb, 0xe5, 0xe7, 0xe1, 0xe3 +}; + +/** @brief The ecchigh[ 256]. */ +static const uint8_t ecchigh[256] = +{ + 0x00, 0xf4, 0xf5, 0x01, 0xf7, 0x03, 0x02, 0xf6, 0xf3, 0x07, 0x06, 0xf2, 0x04, 0xf0, 0xf1, 0x05, + 0xfb, 0x0f, 0x0e, 0xfa, 0x0c, 0xf8, 0xf9, 0x0d, 0x08, 0xfc, 0xfd, 0x09, 0xff, 0x0b, 0x0a, 0xfe, + 0xeb, 0x1f, 0x1e, 0xea, 0x1c, 0xe8, 0xe9, 0x1d, 0x18, 0xec, 0xed, 0x19, 0xef, 0x1b, 0x1a, 0xee, + 0x10, 0xe4, 0xe5, 0x11, 0xe7, 0x13, 0x12, 0xe6, 0xe3, 0x17, 0x16, 0xe2, 0x14, 0xe0, 0xe1, 0x15, + 0xcb, 0x3f, 0x3e, 0xca, 0x3c, 0xc8, 0xc9, 0x3d, 0x38, 0xcc, 0xcd, 0x39, 0xcf, 0x3b, 0x3a, 0xce, + 0x30, 0xc4, 0xc5, 0x31, 0xc7, 0x33, 0x32, 0xc6, 0xc3, 0x37, 0x36, 0xc2, 0x34, 0xc0, 0xc1, 0x35, + 0x20, 0xd4, 0xd5, 0x21, 0xd7, 0x23, 0x22, 0xd6, 0xd3, 0x27, 0x26, 0xd2, 0x24, 0xd0, 0xd1, 0x25, + 0xdb, 0x2f, 0x2e, 0xda, 0x2c, 0xd8, 0xd9, 0x2d, 0x28, 0xdc, 0xdd, 0x29, 0xdf, 0x2b, 0x2a, 0xde, + 0x8b, 0x7f, 0x7e, 0x8a, 0x7c, 0x88, 0x89, 0x7d, 0x78, 0x8c, 0x8d, 0x79, 0x8f, 0x7b, 0x7a, 0x8e, + 0x70, 0x84, 0x85, 0x71, 0x87, 0x73, 0x72, 0x86, 0x83, 0x77, 0x76, 0x82, 0x74, 0x80, 0x81, 0x75, + 0x60, 0x94, 0x95, 0x61, 0x97, 0x63, 0x62, 0x96, 0x93, 0x67, 0x66, 0x92, 0x64, 0x90, 0x91, 0x65, + 0x9b, 0x6f, 0x6e, 0x9a, 0x6c, 0x98, 0x99, 0x6d, 0x68, 0x9c, 0x9d, 0x69, 0x9f, 0x6b, 0x6a, 0x9e, + 0x40, 0xb4, 0xb5, 0x41, 0xb7, 0x43, 0x42, 0xb6, 0xb3, 0x47, 0x46, 0xb2, 0x44, 0xb0, 0xb1, 0x45, + 0xbb, 0x4f, 0x4e, 0xba, 0x4c, 0xb8, 0xb9, 0x4d, 0x48, 0xbc, 0xbd, 0x49, 0xbf, 0x4b, 0x4a, 0xbe, + 0xab, 0x5f, 0x5e, 0xaa, 0x5c, 0xa8, 0xa9, 0x5d, 0x58, 0xac, 0xad, 0x59, 0xaf, 0x5b, 0x5a, 0xae, + 0x50, 0xa4, 0xa5, 0x51, 0xa7, 0x53, 0x52, 0xa6, 0xa3, 0x57, 0x56, 0xa2, 0x54, 0xa0, 0xa1, 0x55 +}; + +/** + * @brief ------------------------------------------------- + * poffsets - each row represents the addresses used to calculate a byte of the ECC P + * data 86 (*2) ECC P bytes, 24 values represented by each + * -------------------------------------------------. + */ + +static const uint16_t poffsets[ECC_P_NUM_BYTES][ECC_P_COMP] = +{ + { 0x000,0x056,0x0ac,0x102,0x158,0x1ae,0x204,0x25a,0x2b0,0x306,0x35c,0x3b2,0x408,0x45e,0x4b4,0x50a,0x560,0x5b6,0x60c,0x662,0x6b8,0x70e,0x764,0x7ba }, + { 0x001,0x057,0x0ad,0x103,0x159,0x1af,0x205,0x25b,0x2b1,0x307,0x35d,0x3b3,0x409,0x45f,0x4b5,0x50b,0x561,0x5b7,0x60d,0x663,0x6b9,0x70f,0x765,0x7bb }, + { 0x002,0x058,0x0ae,0x104,0x15a,0x1b0,0x206,0x25c,0x2b2,0x308,0x35e,0x3b4,0x40a,0x460,0x4b6,0x50c,0x562,0x5b8,0x60e,0x664,0x6ba,0x710,0x766,0x7bc }, + { 0x003,0x059,0x0af,0x105,0x15b,0x1b1,0x207,0x25d,0x2b3,0x309,0x35f,0x3b5,0x40b,0x461,0x4b7,0x50d,0x563,0x5b9,0x60f,0x665,0x6bb,0x711,0x767,0x7bd }, + { 0x004,0x05a,0x0b0,0x106,0x15c,0x1b2,0x208,0x25e,0x2b4,0x30a,0x360,0x3b6,0x40c,0x462,0x4b8,0x50e,0x564,0x5ba,0x610,0x666,0x6bc,0x712,0x768,0x7be }, + { 0x005,0x05b,0x0b1,0x107,0x15d,0x1b3,0x209,0x25f,0x2b5,0x30b,0x361,0x3b7,0x40d,0x463,0x4b9,0x50f,0x565,0x5bb,0x611,0x667,0x6bd,0x713,0x769,0x7bf }, + { 0x006,0x05c,0x0b2,0x108,0x15e,0x1b4,0x20a,0x260,0x2b6,0x30c,0x362,0x3b8,0x40e,0x464,0x4ba,0x510,0x566,0x5bc,0x612,0x668,0x6be,0x714,0x76a,0x7c0 }, + { 0x007,0x05d,0x0b3,0x109,0x15f,0x1b5,0x20b,0x261,0x2b7,0x30d,0x363,0x3b9,0x40f,0x465,0x4bb,0x511,0x567,0x5bd,0x613,0x669,0x6bf,0x715,0x76b,0x7c1 }, + { 0x008,0x05e,0x0b4,0x10a,0x160,0x1b6,0x20c,0x262,0x2b8,0x30e,0x364,0x3ba,0x410,0x466,0x4bc,0x512,0x568,0x5be,0x614,0x66a,0x6c0,0x716,0x76c,0x7c2 }, + { 0x009,0x05f,0x0b5,0x10b,0x161,0x1b7,0x20d,0x263,0x2b9,0x30f,0x365,0x3bb,0x411,0x467,0x4bd,0x513,0x569,0x5bf,0x615,0x66b,0x6c1,0x717,0x76d,0x7c3 }, + { 0x00a,0x060,0x0b6,0x10c,0x162,0x1b8,0x20e,0x264,0x2ba,0x310,0x366,0x3bc,0x412,0x468,0x4be,0x514,0x56a,0x5c0,0x616,0x66c,0x6c2,0x718,0x76e,0x7c4 }, + { 0x00b,0x061,0x0b7,0x10d,0x163,0x1b9,0x20f,0x265,0x2bb,0x311,0x367,0x3bd,0x413,0x469,0x4bf,0x515,0x56b,0x5c1,0x617,0x66d,0x6c3,0x719,0x76f,0x7c5 }, + { 0x00c,0x062,0x0b8,0x10e,0x164,0x1ba,0x210,0x266,0x2bc,0x312,0x368,0x3be,0x414,0x46a,0x4c0,0x516,0x56c,0x5c2,0x618,0x66e,0x6c4,0x71a,0x770,0x7c6 }, + { 0x00d,0x063,0x0b9,0x10f,0x165,0x1bb,0x211,0x267,0x2bd,0x313,0x369,0x3bf,0x415,0x46b,0x4c1,0x517,0x56d,0x5c3,0x619,0x66f,0x6c5,0x71b,0x771,0x7c7 }, + { 0x00e,0x064,0x0ba,0x110,0x166,0x1bc,0x212,0x268,0x2be,0x314,0x36a,0x3c0,0x416,0x46c,0x4c2,0x518,0x56e,0x5c4,0x61a,0x670,0x6c6,0x71c,0x772,0x7c8 }, + { 0x00f,0x065,0x0bb,0x111,0x167,0x1bd,0x213,0x269,0x2bf,0x315,0x36b,0x3c1,0x417,0x46d,0x4c3,0x519,0x56f,0x5c5,0x61b,0x671,0x6c7,0x71d,0x773,0x7c9 }, + { 0x010,0x066,0x0bc,0x112,0x168,0x1be,0x214,0x26a,0x2c0,0x316,0x36c,0x3c2,0x418,0x46e,0x4c4,0x51a,0x570,0x5c6,0x61c,0x672,0x6c8,0x71e,0x774,0x7ca }, + { 0x011,0x067,0x0bd,0x113,0x169,0x1bf,0x215,0x26b,0x2c1,0x317,0x36d,0x3c3,0x419,0x46f,0x4c5,0x51b,0x571,0x5c7,0x61d,0x673,0x6c9,0x71f,0x775,0x7cb }, + { 0x012,0x068,0x0be,0x114,0x16a,0x1c0,0x216,0x26c,0x2c2,0x318,0x36e,0x3c4,0x41a,0x470,0x4c6,0x51c,0x572,0x5c8,0x61e,0x674,0x6ca,0x720,0x776,0x7cc }, + { 0x013,0x069,0x0bf,0x115,0x16b,0x1c1,0x217,0x26d,0x2c3,0x319,0x36f,0x3c5,0x41b,0x471,0x4c7,0x51d,0x573,0x5c9,0x61f,0x675,0x6cb,0x721,0x777,0x7cd }, + { 0x014,0x06a,0x0c0,0x116,0x16c,0x1c2,0x218,0x26e,0x2c4,0x31a,0x370,0x3c6,0x41c,0x472,0x4c8,0x51e,0x574,0x5ca,0x620,0x676,0x6cc,0x722,0x778,0x7ce }, + { 0x015,0x06b,0x0c1,0x117,0x16d,0x1c3,0x219,0x26f,0x2c5,0x31b,0x371,0x3c7,0x41d,0x473,0x4c9,0x51f,0x575,0x5cb,0x621,0x677,0x6cd,0x723,0x779,0x7cf }, + { 0x016,0x06c,0x0c2,0x118,0x16e,0x1c4,0x21a,0x270,0x2c6,0x31c,0x372,0x3c8,0x41e,0x474,0x4ca,0x520,0x576,0x5cc,0x622,0x678,0x6ce,0x724,0x77a,0x7d0 }, + { 0x017,0x06d,0x0c3,0x119,0x16f,0x1c5,0x21b,0x271,0x2c7,0x31d,0x373,0x3c9,0x41f,0x475,0x4cb,0x521,0x577,0x5cd,0x623,0x679,0x6cf,0x725,0x77b,0x7d1 }, + { 0x018,0x06e,0x0c4,0x11a,0x170,0x1c6,0x21c,0x272,0x2c8,0x31e,0x374,0x3ca,0x420,0x476,0x4cc,0x522,0x578,0x5ce,0x624,0x67a,0x6d0,0x726,0x77c,0x7d2 }, + { 0x019,0x06f,0x0c5,0x11b,0x171,0x1c7,0x21d,0x273,0x2c9,0x31f,0x375,0x3cb,0x421,0x477,0x4cd,0x523,0x579,0x5cf,0x625,0x67b,0x6d1,0x727,0x77d,0x7d3 }, + { 0x01a,0x070,0x0c6,0x11c,0x172,0x1c8,0x21e,0x274,0x2ca,0x320,0x376,0x3cc,0x422,0x478,0x4ce,0x524,0x57a,0x5d0,0x626,0x67c,0x6d2,0x728,0x77e,0x7d4 }, + { 0x01b,0x071,0x0c7,0x11d,0x173,0x1c9,0x21f,0x275,0x2cb,0x321,0x377,0x3cd,0x423,0x479,0x4cf,0x525,0x57b,0x5d1,0x627,0x67d,0x6d3,0x729,0x77f,0x7d5 }, + { 0x01c,0x072,0x0c8,0x11e,0x174,0x1ca,0x220,0x276,0x2cc,0x322,0x378,0x3ce,0x424,0x47a,0x4d0,0x526,0x57c,0x5d2,0x628,0x67e,0x6d4,0x72a,0x780,0x7d6 }, + { 0x01d,0x073,0x0c9,0x11f,0x175,0x1cb,0x221,0x277,0x2cd,0x323,0x379,0x3cf,0x425,0x47b,0x4d1,0x527,0x57d,0x5d3,0x629,0x67f,0x6d5,0x72b,0x781,0x7d7 }, + { 0x01e,0x074,0x0ca,0x120,0x176,0x1cc,0x222,0x278,0x2ce,0x324,0x37a,0x3d0,0x426,0x47c,0x4d2,0x528,0x57e,0x5d4,0x62a,0x680,0x6d6,0x72c,0x782,0x7d8 }, + { 0x01f,0x075,0x0cb,0x121,0x177,0x1cd,0x223,0x279,0x2cf,0x325,0x37b,0x3d1,0x427,0x47d,0x4d3,0x529,0x57f,0x5d5,0x62b,0x681,0x6d7,0x72d,0x783,0x7d9 }, + { 0x020,0x076,0x0cc,0x122,0x178,0x1ce,0x224,0x27a,0x2d0,0x326,0x37c,0x3d2,0x428,0x47e,0x4d4,0x52a,0x580,0x5d6,0x62c,0x682,0x6d8,0x72e,0x784,0x7da }, + { 0x021,0x077,0x0cd,0x123,0x179,0x1cf,0x225,0x27b,0x2d1,0x327,0x37d,0x3d3,0x429,0x47f,0x4d5,0x52b,0x581,0x5d7,0x62d,0x683,0x6d9,0x72f,0x785,0x7db }, + { 0x022,0x078,0x0ce,0x124,0x17a,0x1d0,0x226,0x27c,0x2d2,0x328,0x37e,0x3d4,0x42a,0x480,0x4d6,0x52c,0x582,0x5d8,0x62e,0x684,0x6da,0x730,0x786,0x7dc }, + { 0x023,0x079,0x0cf,0x125,0x17b,0x1d1,0x227,0x27d,0x2d3,0x329,0x37f,0x3d5,0x42b,0x481,0x4d7,0x52d,0x583,0x5d9,0x62f,0x685,0x6db,0x731,0x787,0x7dd }, + { 0x024,0x07a,0x0d0,0x126,0x17c,0x1d2,0x228,0x27e,0x2d4,0x32a,0x380,0x3d6,0x42c,0x482,0x4d8,0x52e,0x584,0x5da,0x630,0x686,0x6dc,0x732,0x788,0x7de }, + { 0x025,0x07b,0x0d1,0x127,0x17d,0x1d3,0x229,0x27f,0x2d5,0x32b,0x381,0x3d7,0x42d,0x483,0x4d9,0x52f,0x585,0x5db,0x631,0x687,0x6dd,0x733,0x789,0x7df }, + { 0x026,0x07c,0x0d2,0x128,0x17e,0x1d4,0x22a,0x280,0x2d6,0x32c,0x382,0x3d8,0x42e,0x484,0x4da,0x530,0x586,0x5dc,0x632,0x688,0x6de,0x734,0x78a,0x7e0 }, + { 0x027,0x07d,0x0d3,0x129,0x17f,0x1d5,0x22b,0x281,0x2d7,0x32d,0x383,0x3d9,0x42f,0x485,0x4db,0x531,0x587,0x5dd,0x633,0x689,0x6df,0x735,0x78b,0x7e1 }, + { 0x028,0x07e,0x0d4,0x12a,0x180,0x1d6,0x22c,0x282,0x2d8,0x32e,0x384,0x3da,0x430,0x486,0x4dc,0x532,0x588,0x5de,0x634,0x68a,0x6e0,0x736,0x78c,0x7e2 }, + { 0x029,0x07f,0x0d5,0x12b,0x181,0x1d7,0x22d,0x283,0x2d9,0x32f,0x385,0x3db,0x431,0x487,0x4dd,0x533,0x589,0x5df,0x635,0x68b,0x6e1,0x737,0x78d,0x7e3 }, + { 0x02a,0x080,0x0d6,0x12c,0x182,0x1d8,0x22e,0x284,0x2da,0x330,0x386,0x3dc,0x432,0x488,0x4de,0x534,0x58a,0x5e0,0x636,0x68c,0x6e2,0x738,0x78e,0x7e4 }, + { 0x02b,0x081,0x0d7,0x12d,0x183,0x1d9,0x22f,0x285,0x2db,0x331,0x387,0x3dd,0x433,0x489,0x4df,0x535,0x58b,0x5e1,0x637,0x68d,0x6e3,0x739,0x78f,0x7e5 }, + { 0x02c,0x082,0x0d8,0x12e,0x184,0x1da,0x230,0x286,0x2dc,0x332,0x388,0x3de,0x434,0x48a,0x4e0,0x536,0x58c,0x5e2,0x638,0x68e,0x6e4,0x73a,0x790,0x7e6 }, + { 0x02d,0x083,0x0d9,0x12f,0x185,0x1db,0x231,0x287,0x2dd,0x333,0x389,0x3df,0x435,0x48b,0x4e1,0x537,0x58d,0x5e3,0x639,0x68f,0x6e5,0x73b,0x791,0x7e7 }, + { 0x02e,0x084,0x0da,0x130,0x186,0x1dc,0x232,0x288,0x2de,0x334,0x38a,0x3e0,0x436,0x48c,0x4e2,0x538,0x58e,0x5e4,0x63a,0x690,0x6e6,0x73c,0x792,0x7e8 }, + { 0x02f,0x085,0x0db,0x131,0x187,0x1dd,0x233,0x289,0x2df,0x335,0x38b,0x3e1,0x437,0x48d,0x4e3,0x539,0x58f,0x5e5,0x63b,0x691,0x6e7,0x73d,0x793,0x7e9 }, + { 0x030,0x086,0x0dc,0x132,0x188,0x1de,0x234,0x28a,0x2e0,0x336,0x38c,0x3e2,0x438,0x48e,0x4e4,0x53a,0x590,0x5e6,0x63c,0x692,0x6e8,0x73e,0x794,0x7ea }, + { 0x031,0x087,0x0dd,0x133,0x189,0x1df,0x235,0x28b,0x2e1,0x337,0x38d,0x3e3,0x439,0x48f,0x4e5,0x53b,0x591,0x5e7,0x63d,0x693,0x6e9,0x73f,0x795,0x7eb }, + { 0x032,0x088,0x0de,0x134,0x18a,0x1e0,0x236,0x28c,0x2e2,0x338,0x38e,0x3e4,0x43a,0x490,0x4e6,0x53c,0x592,0x5e8,0x63e,0x694,0x6ea,0x740,0x796,0x7ec }, + { 0x033,0x089,0x0df,0x135,0x18b,0x1e1,0x237,0x28d,0x2e3,0x339,0x38f,0x3e5,0x43b,0x491,0x4e7,0x53d,0x593,0x5e9,0x63f,0x695,0x6eb,0x741,0x797,0x7ed }, + { 0x034,0x08a,0x0e0,0x136,0x18c,0x1e2,0x238,0x28e,0x2e4,0x33a,0x390,0x3e6,0x43c,0x492,0x4e8,0x53e,0x594,0x5ea,0x640,0x696,0x6ec,0x742,0x798,0x7ee }, + { 0x035,0x08b,0x0e1,0x137,0x18d,0x1e3,0x239,0x28f,0x2e5,0x33b,0x391,0x3e7,0x43d,0x493,0x4e9,0x53f,0x595,0x5eb,0x641,0x697,0x6ed,0x743,0x799,0x7ef }, + { 0x036,0x08c,0x0e2,0x138,0x18e,0x1e4,0x23a,0x290,0x2e6,0x33c,0x392,0x3e8,0x43e,0x494,0x4ea,0x540,0x596,0x5ec,0x642,0x698,0x6ee,0x744,0x79a,0x7f0 }, + { 0x037,0x08d,0x0e3,0x139,0x18f,0x1e5,0x23b,0x291,0x2e7,0x33d,0x393,0x3e9,0x43f,0x495,0x4eb,0x541,0x597,0x5ed,0x643,0x699,0x6ef,0x745,0x79b,0x7f1 }, + { 0x038,0x08e,0x0e4,0x13a,0x190,0x1e6,0x23c,0x292,0x2e8,0x33e,0x394,0x3ea,0x440,0x496,0x4ec,0x542,0x598,0x5ee,0x644,0x69a,0x6f0,0x746,0x79c,0x7f2 }, + { 0x039,0x08f,0x0e5,0x13b,0x191,0x1e7,0x23d,0x293,0x2e9,0x33f,0x395,0x3eb,0x441,0x497,0x4ed,0x543,0x599,0x5ef,0x645,0x69b,0x6f1,0x747,0x79d,0x7f3 }, + { 0x03a,0x090,0x0e6,0x13c,0x192,0x1e8,0x23e,0x294,0x2ea,0x340,0x396,0x3ec,0x442,0x498,0x4ee,0x544,0x59a,0x5f0,0x646,0x69c,0x6f2,0x748,0x79e,0x7f4 }, + { 0x03b,0x091,0x0e7,0x13d,0x193,0x1e9,0x23f,0x295,0x2eb,0x341,0x397,0x3ed,0x443,0x499,0x4ef,0x545,0x59b,0x5f1,0x647,0x69d,0x6f3,0x749,0x79f,0x7f5 }, + { 0x03c,0x092,0x0e8,0x13e,0x194,0x1ea,0x240,0x296,0x2ec,0x342,0x398,0x3ee,0x444,0x49a,0x4f0,0x546,0x59c,0x5f2,0x648,0x69e,0x6f4,0x74a,0x7a0,0x7f6 }, + { 0x03d,0x093,0x0e9,0x13f,0x195,0x1eb,0x241,0x297,0x2ed,0x343,0x399,0x3ef,0x445,0x49b,0x4f1,0x547,0x59d,0x5f3,0x649,0x69f,0x6f5,0x74b,0x7a1,0x7f7 }, + { 0x03e,0x094,0x0ea,0x140,0x196,0x1ec,0x242,0x298,0x2ee,0x344,0x39a,0x3f0,0x446,0x49c,0x4f2,0x548,0x59e,0x5f4,0x64a,0x6a0,0x6f6,0x74c,0x7a2,0x7f8 }, + { 0x03f,0x095,0x0eb,0x141,0x197,0x1ed,0x243,0x299,0x2ef,0x345,0x39b,0x3f1,0x447,0x49d,0x4f3,0x549,0x59f,0x5f5,0x64b,0x6a1,0x6f7,0x74d,0x7a3,0x7f9 }, + { 0x040,0x096,0x0ec,0x142,0x198,0x1ee,0x244,0x29a,0x2f0,0x346,0x39c,0x3f2,0x448,0x49e,0x4f4,0x54a,0x5a0,0x5f6,0x64c,0x6a2,0x6f8,0x74e,0x7a4,0x7fa }, + { 0x041,0x097,0x0ed,0x143,0x199,0x1ef,0x245,0x29b,0x2f1,0x347,0x39d,0x3f3,0x449,0x49f,0x4f5,0x54b,0x5a1,0x5f7,0x64d,0x6a3,0x6f9,0x74f,0x7a5,0x7fb }, + { 0x042,0x098,0x0ee,0x144,0x19a,0x1f0,0x246,0x29c,0x2f2,0x348,0x39e,0x3f4,0x44a,0x4a0,0x4f6,0x54c,0x5a2,0x5f8,0x64e,0x6a4,0x6fa,0x750,0x7a6,0x7fc }, + { 0x043,0x099,0x0ef,0x145,0x19b,0x1f1,0x247,0x29d,0x2f3,0x349,0x39f,0x3f5,0x44b,0x4a1,0x4f7,0x54d,0x5a3,0x5f9,0x64f,0x6a5,0x6fb,0x751,0x7a7,0x7fd }, + { 0x044,0x09a,0x0f0,0x146,0x19c,0x1f2,0x248,0x29e,0x2f4,0x34a,0x3a0,0x3f6,0x44c,0x4a2,0x4f8,0x54e,0x5a4,0x5fa,0x650,0x6a6,0x6fc,0x752,0x7a8,0x7fe }, + { 0x045,0x09b,0x0f1,0x147,0x19d,0x1f3,0x249,0x29f,0x2f5,0x34b,0x3a1,0x3f7,0x44d,0x4a3,0x4f9,0x54f,0x5a5,0x5fb,0x651,0x6a7,0x6fd,0x753,0x7a9,0x7ff }, + { 0x046,0x09c,0x0f2,0x148,0x19e,0x1f4,0x24a,0x2a0,0x2f6,0x34c,0x3a2,0x3f8,0x44e,0x4a4,0x4fa,0x550,0x5a6,0x5fc,0x652,0x6a8,0x6fe,0x754,0x7aa,0x800 }, + { 0x047,0x09d,0x0f3,0x149,0x19f,0x1f5,0x24b,0x2a1,0x2f7,0x34d,0x3a3,0x3f9,0x44f,0x4a5,0x4fb,0x551,0x5a7,0x5fd,0x653,0x6a9,0x6ff,0x755,0x7ab,0x801 }, + { 0x048,0x09e,0x0f4,0x14a,0x1a0,0x1f6,0x24c,0x2a2,0x2f8,0x34e,0x3a4,0x3fa,0x450,0x4a6,0x4fc,0x552,0x5a8,0x5fe,0x654,0x6aa,0x700,0x756,0x7ac,0x802 }, + { 0x049,0x09f,0x0f5,0x14b,0x1a1,0x1f7,0x24d,0x2a3,0x2f9,0x34f,0x3a5,0x3fb,0x451,0x4a7,0x4fd,0x553,0x5a9,0x5ff,0x655,0x6ab,0x701,0x757,0x7ad,0x803 }, + { 0x04a,0x0a0,0x0f6,0x14c,0x1a2,0x1f8,0x24e,0x2a4,0x2fa,0x350,0x3a6,0x3fc,0x452,0x4a8,0x4fe,0x554,0x5aa,0x600,0x656,0x6ac,0x702,0x758,0x7ae,0x804 }, + { 0x04b,0x0a1,0x0f7,0x14d,0x1a3,0x1f9,0x24f,0x2a5,0x2fb,0x351,0x3a7,0x3fd,0x453,0x4a9,0x4ff,0x555,0x5ab,0x601,0x657,0x6ad,0x703,0x759,0x7af,0x805 }, + { 0x04c,0x0a2,0x0f8,0x14e,0x1a4,0x1fa,0x250,0x2a6,0x2fc,0x352,0x3a8,0x3fe,0x454,0x4aa,0x500,0x556,0x5ac,0x602,0x658,0x6ae,0x704,0x75a,0x7b0,0x806 }, + { 0x04d,0x0a3,0x0f9,0x14f,0x1a5,0x1fb,0x251,0x2a7,0x2fd,0x353,0x3a9,0x3ff,0x455,0x4ab,0x501,0x557,0x5ad,0x603,0x659,0x6af,0x705,0x75b,0x7b1,0x807 }, + { 0x04e,0x0a4,0x0fa,0x150,0x1a6,0x1fc,0x252,0x2a8,0x2fe,0x354,0x3aa,0x400,0x456,0x4ac,0x502,0x558,0x5ae,0x604,0x65a,0x6b0,0x706,0x75c,0x7b2,0x808 }, + { 0x04f,0x0a5,0x0fb,0x151,0x1a7,0x1fd,0x253,0x2a9,0x2ff,0x355,0x3ab,0x401,0x457,0x4ad,0x503,0x559,0x5af,0x605,0x65b,0x6b1,0x707,0x75d,0x7b3,0x809 }, + { 0x050,0x0a6,0x0fc,0x152,0x1a8,0x1fe,0x254,0x2aa,0x300,0x356,0x3ac,0x402,0x458,0x4ae,0x504,0x55a,0x5b0,0x606,0x65c,0x6b2,0x708,0x75e,0x7b4,0x80a }, + { 0x051,0x0a7,0x0fd,0x153,0x1a9,0x1ff,0x255,0x2ab,0x301,0x357,0x3ad,0x403,0x459,0x4af,0x505,0x55b,0x5b1,0x607,0x65d,0x6b3,0x709,0x75f,0x7b5,0x80b }, + { 0x052,0x0a8,0x0fe,0x154,0x1aa,0x200,0x256,0x2ac,0x302,0x358,0x3ae,0x404,0x45a,0x4b0,0x506,0x55c,0x5b2,0x608,0x65e,0x6b4,0x70a,0x760,0x7b6,0x80c }, + { 0x053,0x0a9,0x0ff,0x155,0x1ab,0x201,0x257,0x2ad,0x303,0x359,0x3af,0x405,0x45b,0x4b1,0x507,0x55d,0x5b3,0x609,0x65f,0x6b5,0x70b,0x761,0x7b7,0x80d }, + { 0x054,0x0aa,0x100,0x156,0x1ac,0x202,0x258,0x2ae,0x304,0x35a,0x3b0,0x406,0x45c,0x4b2,0x508,0x55e,0x5b4,0x60a,0x660,0x6b6,0x70c,0x762,0x7b8,0x80e }, + { 0x055,0x0ab,0x101,0x157,0x1ad,0x203,0x259,0x2af,0x305,0x35b,0x3b1,0x407,0x45d,0x4b3,0x509,0x55f,0x5b5,0x60b,0x661,0x6b7,0x70d,0x763,0x7b9,0x80f } +}; + +/** + * @brief ------------------------------------------------- + * qoffsets - each row represents the addresses used to calculate a byte of the ECC Q + * data 52 (*2) ECC Q bytes, 43 values represented by each + * -------------------------------------------------. + */ + +static const uint16_t qoffsets[ECC_Q_NUM_BYTES][ECC_Q_COMP] = +{ + { 0x000,0x058,0x0b0,0x108,0x160,0x1b8,0x210,0x268,0x2c0,0x318,0x370,0x3c8,0x420,0x478,0x4d0,0x528,0x580,0x5d8,0x630,0x688,0x6e0,0x738,0x790,0x7e8,0x840,0x898,0x034,0x08c,0x0e4,0x13c,0x194,0x1ec,0x244,0x29c,0x2f4,0x34c,0x3a4,0x3fc,0x454,0x4ac,0x504,0x55c,0x5b4 }, + { 0x001,0x059,0x0b1,0x109,0x161,0x1b9,0x211,0x269,0x2c1,0x319,0x371,0x3c9,0x421,0x479,0x4d1,0x529,0x581,0x5d9,0x631,0x689,0x6e1,0x739,0x791,0x7e9,0x841,0x899,0x035,0x08d,0x0e5,0x13d,0x195,0x1ed,0x245,0x29d,0x2f5,0x34d,0x3a5,0x3fd,0x455,0x4ad,0x505,0x55d,0x5b5 }, + { 0x056,0x0ae,0x106,0x15e,0x1b6,0x20e,0x266,0x2be,0x316,0x36e,0x3c6,0x41e,0x476,0x4ce,0x526,0x57e,0x5d6,0x62e,0x686,0x6de,0x736,0x78e,0x7e6,0x83e,0x896,0x032,0x08a,0x0e2,0x13a,0x192,0x1ea,0x242,0x29a,0x2f2,0x34a,0x3a2,0x3fa,0x452,0x4aa,0x502,0x55a,0x5b2,0x60a }, + { 0x057,0x0af,0x107,0x15f,0x1b7,0x20f,0x267,0x2bf,0x317,0x36f,0x3c7,0x41f,0x477,0x4cf,0x527,0x57f,0x5d7,0x62f,0x687,0x6df,0x737,0x78f,0x7e7,0x83f,0x897,0x033,0x08b,0x0e3,0x13b,0x193,0x1eb,0x243,0x29b,0x2f3,0x34b,0x3a3,0x3fb,0x453,0x4ab,0x503,0x55b,0x5b3,0x60b }, + { 0x0ac,0x104,0x15c,0x1b4,0x20c,0x264,0x2bc,0x314,0x36c,0x3c4,0x41c,0x474,0x4cc,0x524,0x57c,0x5d4,0x62c,0x684,0x6dc,0x734,0x78c,0x7e4,0x83c,0x894,0x030,0x088,0x0e0,0x138,0x190,0x1e8,0x240,0x298,0x2f0,0x348,0x3a0,0x3f8,0x450,0x4a8,0x500,0x558,0x5b0,0x608,0x660 }, + { 0x0ad,0x105,0x15d,0x1b5,0x20d,0x265,0x2bd,0x315,0x36d,0x3c5,0x41d,0x475,0x4cd,0x525,0x57d,0x5d5,0x62d,0x685,0x6dd,0x735,0x78d,0x7e5,0x83d,0x895,0x031,0x089,0x0e1,0x139,0x191,0x1e9,0x241,0x299,0x2f1,0x349,0x3a1,0x3f9,0x451,0x4a9,0x501,0x559,0x5b1,0x609,0x661 }, + { 0x102,0x15a,0x1b2,0x20a,0x262,0x2ba,0x312,0x36a,0x3c2,0x41a,0x472,0x4ca,0x522,0x57a,0x5d2,0x62a,0x682,0x6da,0x732,0x78a,0x7e2,0x83a,0x892,0x02e,0x086,0x0de,0x136,0x18e,0x1e6,0x23e,0x296,0x2ee,0x346,0x39e,0x3f6,0x44e,0x4a6,0x4fe,0x556,0x5ae,0x606,0x65e,0x6b6 }, + { 0x103,0x15b,0x1b3,0x20b,0x263,0x2bb,0x313,0x36b,0x3c3,0x41b,0x473,0x4cb,0x523,0x57b,0x5d3,0x62b,0x683,0x6db,0x733,0x78b,0x7e3,0x83b,0x893,0x02f,0x087,0x0df,0x137,0x18f,0x1e7,0x23f,0x297,0x2ef,0x347,0x39f,0x3f7,0x44f,0x4a7,0x4ff,0x557,0x5af,0x607,0x65f,0x6b7 }, + { 0x158,0x1b0,0x208,0x260,0x2b8,0x310,0x368,0x3c0,0x418,0x470,0x4c8,0x520,0x578,0x5d0,0x628,0x680,0x6d8,0x730,0x788,0x7e0,0x838,0x890,0x02c,0x084,0x0dc,0x134,0x18c,0x1e4,0x23c,0x294,0x2ec,0x344,0x39c,0x3f4,0x44c,0x4a4,0x4fc,0x554,0x5ac,0x604,0x65c,0x6b4,0x70c }, + { 0x159,0x1b1,0x209,0x261,0x2b9,0x311,0x369,0x3c1,0x419,0x471,0x4c9,0x521,0x579,0x5d1,0x629,0x681,0x6d9,0x731,0x789,0x7e1,0x839,0x891,0x02d,0x085,0x0dd,0x135,0x18d,0x1e5,0x23d,0x295,0x2ed,0x345,0x39d,0x3f5,0x44d,0x4a5,0x4fd,0x555,0x5ad,0x605,0x65d,0x6b5,0x70d }, + { 0x1ae,0x206,0x25e,0x2b6,0x30e,0x366,0x3be,0x416,0x46e,0x4c6,0x51e,0x576,0x5ce,0x626,0x67e,0x6d6,0x72e,0x786,0x7de,0x836,0x88e,0x02a,0x082,0x0da,0x132,0x18a,0x1e2,0x23a,0x292,0x2ea,0x342,0x39a,0x3f2,0x44a,0x4a2,0x4fa,0x552,0x5aa,0x602,0x65a,0x6b2,0x70a,0x762 }, + { 0x1af,0x207,0x25f,0x2b7,0x30f,0x367,0x3bf,0x417,0x46f,0x4c7,0x51f,0x577,0x5cf,0x627,0x67f,0x6d7,0x72f,0x787,0x7df,0x837,0x88f,0x02b,0x083,0x0db,0x133,0x18b,0x1e3,0x23b,0x293,0x2eb,0x343,0x39b,0x3f3,0x44b,0x4a3,0x4fb,0x553,0x5ab,0x603,0x65b,0x6b3,0x70b,0x763 }, + { 0x204,0x25c,0x2b4,0x30c,0x364,0x3bc,0x414,0x46c,0x4c4,0x51c,0x574,0x5cc,0x624,0x67c,0x6d4,0x72c,0x784,0x7dc,0x834,0x88c,0x028,0x080,0x0d8,0x130,0x188,0x1e0,0x238,0x290,0x2e8,0x340,0x398,0x3f0,0x448,0x4a0,0x4f8,0x550,0x5a8,0x600,0x658,0x6b0,0x708,0x760,0x7b8 }, + { 0x205,0x25d,0x2b5,0x30d,0x365,0x3bd,0x415,0x46d,0x4c5,0x51d,0x575,0x5cd,0x625,0x67d,0x6d5,0x72d,0x785,0x7dd,0x835,0x88d,0x029,0x081,0x0d9,0x131,0x189,0x1e1,0x239,0x291,0x2e9,0x341,0x399,0x3f1,0x449,0x4a1,0x4f9,0x551,0x5a9,0x601,0x659,0x6b1,0x709,0x761,0x7b9 }, + { 0x25a,0x2b2,0x30a,0x362,0x3ba,0x412,0x46a,0x4c2,0x51a,0x572,0x5ca,0x622,0x67a,0x6d2,0x72a,0x782,0x7da,0x832,0x88a,0x026,0x07e,0x0d6,0x12e,0x186,0x1de,0x236,0x28e,0x2e6,0x33e,0x396,0x3ee,0x446,0x49e,0x4f6,0x54e,0x5a6,0x5fe,0x656,0x6ae,0x706,0x75e,0x7b6,0x80e }, + { 0x25b,0x2b3,0x30b,0x363,0x3bb,0x413,0x46b,0x4c3,0x51b,0x573,0x5cb,0x623,0x67b,0x6d3,0x72b,0x783,0x7db,0x833,0x88b,0x027,0x07f,0x0d7,0x12f,0x187,0x1df,0x237,0x28f,0x2e7,0x33f,0x397,0x3ef,0x447,0x49f,0x4f7,0x54f,0x5a7,0x5ff,0x657,0x6af,0x707,0x75f,0x7b7,0x80f }, + { 0x2b0,0x308,0x360,0x3b8,0x410,0x468,0x4c0,0x518,0x570,0x5c8,0x620,0x678,0x6d0,0x728,0x780,0x7d8,0x830,0x888,0x024,0x07c,0x0d4,0x12c,0x184,0x1dc,0x234,0x28c,0x2e4,0x33c,0x394,0x3ec,0x444,0x49c,0x4f4,0x54c,0x5a4,0x5fc,0x654,0x6ac,0x704,0x75c,0x7b4,0x80c,0x864 }, + { 0x2b1,0x309,0x361,0x3b9,0x411,0x469,0x4c1,0x519,0x571,0x5c9,0x621,0x679,0x6d1,0x729,0x781,0x7d9,0x831,0x889,0x025,0x07d,0x0d5,0x12d,0x185,0x1dd,0x235,0x28d,0x2e5,0x33d,0x395,0x3ed,0x445,0x49d,0x4f5,0x54d,0x5a5,0x5fd,0x655,0x6ad,0x705,0x75d,0x7b5,0x80d,0x865 }, + { 0x306,0x35e,0x3b6,0x40e,0x466,0x4be,0x516,0x56e,0x5c6,0x61e,0x676,0x6ce,0x726,0x77e,0x7d6,0x82e,0x886,0x022,0x07a,0x0d2,0x12a,0x182,0x1da,0x232,0x28a,0x2e2,0x33a,0x392,0x3ea,0x442,0x49a,0x4f2,0x54a,0x5a2,0x5fa,0x652,0x6aa,0x702,0x75a,0x7b2,0x80a,0x862,0x8ba }, + { 0x307,0x35f,0x3b7,0x40f,0x467,0x4bf,0x517,0x56f,0x5c7,0x61f,0x677,0x6cf,0x727,0x77f,0x7d7,0x82f,0x887,0x023,0x07b,0x0d3,0x12b,0x183,0x1db,0x233,0x28b,0x2e3,0x33b,0x393,0x3eb,0x443,0x49b,0x4f3,0x54b,0x5a3,0x5fb,0x653,0x6ab,0x703,0x75b,0x7b3,0x80b,0x863,0x8bb }, + { 0x35c,0x3b4,0x40c,0x464,0x4bc,0x514,0x56c,0x5c4,0x61c,0x674,0x6cc,0x724,0x77c,0x7d4,0x82c,0x884,0x020,0x078,0x0d0,0x128,0x180,0x1d8,0x230,0x288,0x2e0,0x338,0x390,0x3e8,0x440,0x498,0x4f0,0x548,0x5a0,0x5f8,0x650,0x6a8,0x700,0x758,0x7b0,0x808,0x860,0x8b8,0x054 }, + { 0x35d,0x3b5,0x40d,0x465,0x4bd,0x515,0x56d,0x5c5,0x61d,0x675,0x6cd,0x725,0x77d,0x7d5,0x82d,0x885,0x021,0x079,0x0d1,0x129,0x181,0x1d9,0x231,0x289,0x2e1,0x339,0x391,0x3e9,0x441,0x499,0x4f1,0x549,0x5a1,0x5f9,0x651,0x6a9,0x701,0x759,0x7b1,0x809,0x861,0x8b9,0x055 }, + { 0x3b2,0x40a,0x462,0x4ba,0x512,0x56a,0x5c2,0x61a,0x672,0x6ca,0x722,0x77a,0x7d2,0x82a,0x882,0x01e,0x076,0x0ce,0x126,0x17e,0x1d6,0x22e,0x286,0x2de,0x336,0x38e,0x3e6,0x43e,0x496,0x4ee,0x546,0x59e,0x5f6,0x64e,0x6a6,0x6fe,0x756,0x7ae,0x806,0x85e,0x8b6,0x052,0x0aa }, + { 0x3b3,0x40b,0x463,0x4bb,0x513,0x56b,0x5c3,0x61b,0x673,0x6cb,0x723,0x77b,0x7d3,0x82b,0x883,0x01f,0x077,0x0cf,0x127,0x17f,0x1d7,0x22f,0x287,0x2df,0x337,0x38f,0x3e7,0x43f,0x497,0x4ef,0x547,0x59f,0x5f7,0x64f,0x6a7,0x6ff,0x757,0x7af,0x807,0x85f,0x8b7,0x053,0x0ab }, + { 0x408,0x460,0x4b8,0x510,0x568,0x5c0,0x618,0x670,0x6c8,0x720,0x778,0x7d0,0x828,0x880,0x01c,0x074,0x0cc,0x124,0x17c,0x1d4,0x22c,0x284,0x2dc,0x334,0x38c,0x3e4,0x43c,0x494,0x4ec,0x544,0x59c,0x5f4,0x64c,0x6a4,0x6fc,0x754,0x7ac,0x804,0x85c,0x8b4,0x050,0x0a8,0x100 }, + { 0x409,0x461,0x4b9,0x511,0x569,0x5c1,0x619,0x671,0x6c9,0x721,0x779,0x7d1,0x829,0x881,0x01d,0x075,0x0cd,0x125,0x17d,0x1d5,0x22d,0x285,0x2dd,0x335,0x38d,0x3e5,0x43d,0x495,0x4ed,0x545,0x59d,0x5f5,0x64d,0x6a5,0x6fd,0x755,0x7ad,0x805,0x85d,0x8b5,0x051,0x0a9,0x101 }, + { 0x45e,0x4b6,0x50e,0x566,0x5be,0x616,0x66e,0x6c6,0x71e,0x776,0x7ce,0x826,0x87e,0x01a,0x072,0x0ca,0x122,0x17a,0x1d2,0x22a,0x282,0x2da,0x332,0x38a,0x3e2,0x43a,0x492,0x4ea,0x542,0x59a,0x5f2,0x64a,0x6a2,0x6fa,0x752,0x7aa,0x802,0x85a,0x8b2,0x04e,0x0a6,0x0fe,0x156 }, + { 0x45f,0x4b7,0x50f,0x567,0x5bf,0x617,0x66f,0x6c7,0x71f,0x777,0x7cf,0x827,0x87f,0x01b,0x073,0x0cb,0x123,0x17b,0x1d3,0x22b,0x283,0x2db,0x333,0x38b,0x3e3,0x43b,0x493,0x4eb,0x543,0x59b,0x5f3,0x64b,0x6a3,0x6fb,0x753,0x7ab,0x803,0x85b,0x8b3,0x04f,0x0a7,0x0ff,0x157 }, + { 0x4b4,0x50c,0x564,0x5bc,0x614,0x66c,0x6c4,0x71c,0x774,0x7cc,0x824,0x87c,0x018,0x070,0x0c8,0x120,0x178,0x1d0,0x228,0x280,0x2d8,0x330,0x388,0x3e0,0x438,0x490,0x4e8,0x540,0x598,0x5f0,0x648,0x6a0,0x6f8,0x750,0x7a8,0x800,0x858,0x8b0,0x04c,0x0a4,0x0fc,0x154,0x1ac }, + { 0x4b5,0x50d,0x565,0x5bd,0x615,0x66d,0x6c5,0x71d,0x775,0x7cd,0x825,0x87d,0x019,0x071,0x0c9,0x121,0x179,0x1d1,0x229,0x281,0x2d9,0x331,0x389,0x3e1,0x439,0x491,0x4e9,0x541,0x599,0x5f1,0x649,0x6a1,0x6f9,0x751,0x7a9,0x801,0x859,0x8b1,0x04d,0x0a5,0x0fd,0x155,0x1ad }, + { 0x50a,0x562,0x5ba,0x612,0x66a,0x6c2,0x71a,0x772,0x7ca,0x822,0x87a,0x016,0x06e,0x0c6,0x11e,0x176,0x1ce,0x226,0x27e,0x2d6,0x32e,0x386,0x3de,0x436,0x48e,0x4e6,0x53e,0x596,0x5ee,0x646,0x69e,0x6f6,0x74e,0x7a6,0x7fe,0x856,0x8ae,0x04a,0x0a2,0x0fa,0x152,0x1aa,0x202 }, + { 0x50b,0x563,0x5bb,0x613,0x66b,0x6c3,0x71b,0x773,0x7cb,0x823,0x87b,0x017,0x06f,0x0c7,0x11f,0x177,0x1cf,0x227,0x27f,0x2d7,0x32f,0x387,0x3df,0x437,0x48f,0x4e7,0x53f,0x597,0x5ef,0x647,0x69f,0x6f7,0x74f,0x7a7,0x7ff,0x857,0x8af,0x04b,0x0a3,0x0fb,0x153,0x1ab,0x203 }, + { 0x560,0x5b8,0x610,0x668,0x6c0,0x718,0x770,0x7c8,0x820,0x878,0x014,0x06c,0x0c4,0x11c,0x174,0x1cc,0x224,0x27c,0x2d4,0x32c,0x384,0x3dc,0x434,0x48c,0x4e4,0x53c,0x594,0x5ec,0x644,0x69c,0x6f4,0x74c,0x7a4,0x7fc,0x854,0x8ac,0x048,0x0a0,0x0f8,0x150,0x1a8,0x200,0x258 }, + { 0x561,0x5b9,0x611,0x669,0x6c1,0x719,0x771,0x7c9,0x821,0x879,0x015,0x06d,0x0c5,0x11d,0x175,0x1cd,0x225,0x27d,0x2d5,0x32d,0x385,0x3dd,0x435,0x48d,0x4e5,0x53d,0x595,0x5ed,0x645,0x69d,0x6f5,0x74d,0x7a5,0x7fd,0x855,0x8ad,0x049,0x0a1,0x0f9,0x151,0x1a9,0x201,0x259 }, + { 0x5b6,0x60e,0x666,0x6be,0x716,0x76e,0x7c6,0x81e,0x876,0x012,0x06a,0x0c2,0x11a,0x172,0x1ca,0x222,0x27a,0x2d2,0x32a,0x382,0x3da,0x432,0x48a,0x4e2,0x53a,0x592,0x5ea,0x642,0x69a,0x6f2,0x74a,0x7a2,0x7fa,0x852,0x8aa,0x046,0x09e,0x0f6,0x14e,0x1a6,0x1fe,0x256,0x2ae }, + { 0x5b7,0x60f,0x667,0x6bf,0x717,0x76f,0x7c7,0x81f,0x877,0x013,0x06b,0x0c3,0x11b,0x173,0x1cb,0x223,0x27b,0x2d3,0x32b,0x383,0x3db,0x433,0x48b,0x4e3,0x53b,0x593,0x5eb,0x643,0x69b,0x6f3,0x74b,0x7a3,0x7fb,0x853,0x8ab,0x047,0x09f,0x0f7,0x14f,0x1a7,0x1ff,0x257,0x2af }, + { 0x60c,0x664,0x6bc,0x714,0x76c,0x7c4,0x81c,0x874,0x010,0x068,0x0c0,0x118,0x170,0x1c8,0x220,0x278,0x2d0,0x328,0x380,0x3d8,0x430,0x488,0x4e0,0x538,0x590,0x5e8,0x640,0x698,0x6f0,0x748,0x7a0,0x7f8,0x850,0x8a8,0x044,0x09c,0x0f4,0x14c,0x1a4,0x1fc,0x254,0x2ac,0x304 }, + { 0x60d,0x665,0x6bd,0x715,0x76d,0x7c5,0x81d,0x875,0x011,0x069,0x0c1,0x119,0x171,0x1c9,0x221,0x279,0x2d1,0x329,0x381,0x3d9,0x431,0x489,0x4e1,0x539,0x591,0x5e9,0x641,0x699,0x6f1,0x749,0x7a1,0x7f9,0x851,0x8a9,0x045,0x09d,0x0f5,0x14d,0x1a5,0x1fd,0x255,0x2ad,0x305 }, + { 0x662,0x6ba,0x712,0x76a,0x7c2,0x81a,0x872,0x00e,0x066,0x0be,0x116,0x16e,0x1c6,0x21e,0x276,0x2ce,0x326,0x37e,0x3d6,0x42e,0x486,0x4de,0x536,0x58e,0x5e6,0x63e,0x696,0x6ee,0x746,0x79e,0x7f6,0x84e,0x8a6,0x042,0x09a,0x0f2,0x14a,0x1a2,0x1fa,0x252,0x2aa,0x302,0x35a }, + { 0x663,0x6bb,0x713,0x76b,0x7c3,0x81b,0x873,0x00f,0x067,0x0bf,0x117,0x16f,0x1c7,0x21f,0x277,0x2cf,0x327,0x37f,0x3d7,0x42f,0x487,0x4df,0x537,0x58f,0x5e7,0x63f,0x697,0x6ef,0x747,0x79f,0x7f7,0x84f,0x8a7,0x043,0x09b,0x0f3,0x14b,0x1a3,0x1fb,0x253,0x2ab,0x303,0x35b }, + { 0x6b8,0x710,0x768,0x7c0,0x818,0x870,0x00c,0x064,0x0bc,0x114,0x16c,0x1c4,0x21c,0x274,0x2cc,0x324,0x37c,0x3d4,0x42c,0x484,0x4dc,0x534,0x58c,0x5e4,0x63c,0x694,0x6ec,0x744,0x79c,0x7f4,0x84c,0x8a4,0x040,0x098,0x0f0,0x148,0x1a0,0x1f8,0x250,0x2a8,0x300,0x358,0x3b0 }, + { 0x6b9,0x711,0x769,0x7c1,0x819,0x871,0x00d,0x065,0x0bd,0x115,0x16d,0x1c5,0x21d,0x275,0x2cd,0x325,0x37d,0x3d5,0x42d,0x485,0x4dd,0x535,0x58d,0x5e5,0x63d,0x695,0x6ed,0x745,0x79d,0x7f5,0x84d,0x8a5,0x041,0x099,0x0f1,0x149,0x1a1,0x1f9,0x251,0x2a9,0x301,0x359,0x3b1 }, + { 0x70e,0x766,0x7be,0x816,0x86e,0x00a,0x062,0x0ba,0x112,0x16a,0x1c2,0x21a,0x272,0x2ca,0x322,0x37a,0x3d2,0x42a,0x482,0x4da,0x532,0x58a,0x5e2,0x63a,0x692,0x6ea,0x742,0x79a,0x7f2,0x84a,0x8a2,0x03e,0x096,0x0ee,0x146,0x19e,0x1f6,0x24e,0x2a6,0x2fe,0x356,0x3ae,0x406 }, + { 0x70f,0x767,0x7bf,0x817,0x86f,0x00b,0x063,0x0bb,0x113,0x16b,0x1c3,0x21b,0x273,0x2cb,0x323,0x37b,0x3d3,0x42b,0x483,0x4db,0x533,0x58b,0x5e3,0x63b,0x693,0x6eb,0x743,0x79b,0x7f3,0x84b,0x8a3,0x03f,0x097,0x0ef,0x147,0x19f,0x1f7,0x24f,0x2a7,0x2ff,0x357,0x3af,0x407 }, + { 0x764,0x7bc,0x814,0x86c,0x008,0x060,0x0b8,0x110,0x168,0x1c0,0x218,0x270,0x2c8,0x320,0x378,0x3d0,0x428,0x480,0x4d8,0x530,0x588,0x5e0,0x638,0x690,0x6e8,0x740,0x798,0x7f0,0x848,0x8a0,0x03c,0x094,0x0ec,0x144,0x19c,0x1f4,0x24c,0x2a4,0x2fc,0x354,0x3ac,0x404,0x45c }, + { 0x765,0x7bd,0x815,0x86d,0x009,0x061,0x0b9,0x111,0x169,0x1c1,0x219,0x271,0x2c9,0x321,0x379,0x3d1,0x429,0x481,0x4d9,0x531,0x589,0x5e1,0x639,0x691,0x6e9,0x741,0x799,0x7f1,0x849,0x8a1,0x03d,0x095,0x0ed,0x145,0x19d,0x1f5,0x24d,0x2a5,0x2fd,0x355,0x3ad,0x405,0x45d }, + { 0x7ba,0x812,0x86a,0x006,0x05e,0x0b6,0x10e,0x166,0x1be,0x216,0x26e,0x2c6,0x31e,0x376,0x3ce,0x426,0x47e,0x4d6,0x52e,0x586,0x5de,0x636,0x68e,0x6e6,0x73e,0x796,0x7ee,0x846,0x89e,0x03a,0x092,0x0ea,0x142,0x19a,0x1f2,0x24a,0x2a2,0x2fa,0x352,0x3aa,0x402,0x45a,0x4b2 }, + { 0x7bb,0x813,0x86b,0x007,0x05f,0x0b7,0x10f,0x167,0x1bf,0x217,0x26f,0x2c7,0x31f,0x377,0x3cf,0x427,0x47f,0x4d7,0x52f,0x587,0x5df,0x637,0x68f,0x6e7,0x73f,0x797,0x7ef,0x847,0x89f,0x03b,0x093,0x0eb,0x143,0x19b,0x1f3,0x24b,0x2a3,0x2fb,0x353,0x3ab,0x403,0x45b,0x4b3 }, + { 0x810,0x868,0x004,0x05c,0x0b4,0x10c,0x164,0x1bc,0x214,0x26c,0x2c4,0x31c,0x374,0x3cc,0x424,0x47c,0x4d4,0x52c,0x584,0x5dc,0x634,0x68c,0x6e4,0x73c,0x794,0x7ec,0x844,0x89c,0x038,0x090,0x0e8,0x140,0x198,0x1f0,0x248,0x2a0,0x2f8,0x350,0x3a8,0x400,0x458,0x4b0,0x508 }, + { 0x811,0x869,0x005,0x05d,0x0b5,0x10d,0x165,0x1bd,0x215,0x26d,0x2c5,0x31d,0x375,0x3cd,0x425,0x47d,0x4d5,0x52d,0x585,0x5dd,0x635,0x68d,0x6e5,0x73d,0x795,0x7ed,0x845,0x89d,0x039,0x091,0x0e9,0x141,0x199,0x1f1,0x249,0x2a1,0x2f9,0x351,0x3a9,0x401,0x459,0x4b1,0x509 }, + { 0x866,0x002,0x05a,0x0b2,0x10a,0x162,0x1ba,0x212,0x26a,0x2c2,0x31a,0x372,0x3ca,0x422,0x47a,0x4d2,0x52a,0x582,0x5da,0x632,0x68a,0x6e2,0x73a,0x792,0x7ea,0x842,0x89a,0x036,0x08e,0x0e6,0x13e,0x196,0x1ee,0x246,0x29e,0x2f6,0x34e,0x3a6,0x3fe,0x456,0x4ae,0x506,0x55e }, + { 0x867,0x003,0x05b,0x0b3,0x10b,0x163,0x1bb,0x213,0x26b,0x2c3,0x31b,0x373,0x3cb,0x423,0x47b,0x4d3,0x52b,0x583,0x5db,0x633,0x68b,0x6e3,0x73b,0x793,0x7eb,0x843,0x89b,0x037,0x08f,0x0e7,0x13f,0x197,0x1ef,0x247,0x29f,0x2f7,0x34f,0x3a7,0x3ff,0x457,0x4af,0x507,0x55f } +}; + +/*------------------------------------------------- + * ecc_source_byte - return data from the sector + * at the given offset, masking anything + * particular to a mode + *------------------------------------------------- + */ + +static CHDR_INLINE uint8_t ecc_source_byte(const uint8_t *sector, uint32_t offset) +{ + /* in mode 2 always treat these as 0 bytes */ + return (sector[MODE_OFFSET] == 2 && offset < 4) ? 0x00 : sector[SYNC_OFFSET + SYNC_NUM_BYTES + offset]; +} + +/** + * @fn void ecc_compute_bytes(const uint8_t *sector, const uint16_t *row, int rowlen, uint8_t &val1, uint8_t &val2) + * + * @brief ------------------------------------------------- + * ecc_compute_bytes - calculate an ECC value (P or Q) + * -------------------------------------------------. + * + * @param sector The sector. + * @param row The row. + * @param rowlen The rowlen. + * @param [in,out] val1 The first value. + * @param [in,out] val2 The second value. + */ + +void ecc_compute_bytes(const uint8_t *sector, const uint16_t *row, int rowlen, uint8_t *val1, uint8_t *val2) +{ + int component; + *val1 = *val2 = 0; + for (component = 0; component < rowlen; component++) + { + *val1 ^= ecc_source_byte(sector, row[component]); + *val2 ^= ecc_source_byte(sector, row[component]); + *val1 = ecclow[*val1]; + } + *val1 = ecchigh[ecclow[*val1] ^ *val2]; + *val2 ^= *val1; +} + +/** + * @fn int ecc_verify(const uint8_t *sector) + * + * @brief ------------------------------------------------- + * ecc_verify - verify the P and Q ECC codes in a sector + * -------------------------------------------------. + * + * @param sector The sector. + * + * @return true if it succeeds, false if it fails. + */ + +int ecc_verify(const uint8_t *sector) +{ + int byte; + /* first verify P bytes */ + for (byte = 0; byte < ECC_P_NUM_BYTES; byte++) + { + uint8_t val1, val2; + ecc_compute_bytes(sector, poffsets[byte], ECC_P_COMP, &val1, &val2); + if (sector[ECC_P_OFFSET + byte] != val1 || sector[ECC_P_OFFSET + ECC_P_NUM_BYTES + byte] != val2) + return 0; + } + + /* then verify Q bytes */ + for (byte = 0; byte < ECC_Q_NUM_BYTES; byte++) + { + uint8_t val1, val2; + ecc_compute_bytes(sector, qoffsets[byte], ECC_Q_COMP, &val1, &val2); + if (sector[ECC_Q_OFFSET + byte] != val1 || sector[ECC_Q_OFFSET + ECC_Q_NUM_BYTES + byte] != val2) + return 0; + } + return 1; +} + +/** + * @fn void ecc_generate(uint8_t *sector) + * + * @brief ------------------------------------------------- + * ecc_generate - generate the P and Q ECC codes for a sector, overwriting any + * existing codes + * -------------------------------------------------. + * + * @param [in,out] sector If non-null, the sector. + */ + +void ecc_generate(uint8_t *sector) +{ + int byte; + /* first verify P bytes */ + for (byte = 0; byte < ECC_P_NUM_BYTES; byte++) + ecc_compute_bytes(sector, poffsets[byte], ECC_P_COMP, §or[ECC_P_OFFSET + byte], §or[ECC_P_OFFSET + ECC_P_NUM_BYTES + byte]); + + /* then verify Q bytes */ + for (byte = 0; byte < ECC_Q_NUM_BYTES; byte++) + ecc_compute_bytes(sector, qoffsets[byte], ECC_Q_COMP, §or[ECC_Q_OFFSET + byte], §or[ECC_Q_OFFSET + ECC_Q_NUM_BYTES + byte]); +} + +/** + * @fn void ecc_clear(uint8_t *sector) + * + * @brief ------------------------------------------------- + * ecc_clear - erase the ECC P and Q cods to 0 within a sector + * -------------------------------------------------. + * + * @param [in,out] sector If non-null, the sector. + */ + +void ecc_clear(uint8_t *sector) +{ + memset(§or[ECC_P_OFFSET], 0, 2 * ECC_P_NUM_BYTES); + memset(§or[ECC_Q_OFFSET], 0, 2 * ECC_Q_NUM_BYTES); +} + +#endif /* WANT_RAW_DATA_SECTOR */ + +/* Handles decompression for CDZL, CDLZ, CDZS, and co. */ + +chd_error cd_codec_decompress( + uint8_t *buffer, + void *base_decompressor, chd_codec_interface_decompress base_decompress, +#if WANT_SUBCODE + void *subcode_decompressor, chd_codec_interface_decompress subcode_decompress, +#endif + const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen) +{ + uint32_t framenum; + chd_error decomp_err; + uint32_t complen_base; + + /* determine header bytes */ + const uint32_t frames = destlen / CD_FRAME_SIZE; + const uint32_t complen_bytes = (destlen < 65536) ? 2 : 3; + const uint32_t ecc_bytes = (frames + 7) / 8; + const uint32_t header_bytes = ecc_bytes + complen_bytes; + + /* input may be truncated, double-check */ + if (complen < (ecc_bytes + 2)) + return CHDERR_DECOMPRESSION_ERROR; + + /* extract compressed length of base */ + complen_base = (src[ecc_bytes + 0] << 8) | src[ecc_bytes + 1]; + if (complen_bytes > 2) + { + if (complen < (ecc_bytes + 3)) + return CHDERR_DECOMPRESSION_ERROR; + + complen_base = (complen_base << 8) | src[ecc_bytes + 2]; + } + if (complen < (header_bytes + complen_base)) + return CHDERR_DECOMPRESSION_ERROR; + + /* reset and decode */ + decomp_err = base_decompress(base_decompressor, &src[header_bytes], complen_base, &buffer[0], frames * CD_MAX_SECTOR_DATA); + if (decomp_err != CHDERR_NONE) + return decomp_err; +#if WANT_SUBCODE + decomp_err = subcode_decompress(subcode_decompressor, &src[header_bytes + complen_base], complen - complen_base - header_bytes, &buffer[frames * CD_MAX_SECTOR_DATA], frames * CD_MAX_SUBCODE_DATA); + if (decomp_err != CHDERR_NONE) + return decomp_err; +#endif + + /* reassemble the data */ + for (framenum = 0; framenum < frames; framenum++) + { +#if WANT_RAW_DATA_SECTOR + uint8_t *sector; +#endif + + memcpy(&dest[framenum * CD_FRAME_SIZE], &buffer[framenum * CD_MAX_SECTOR_DATA], CD_MAX_SECTOR_DATA); +#if WANT_SUBCODE + memcpy(&dest[framenum * CD_FRAME_SIZE + CD_MAX_SECTOR_DATA], &buffer[frames * CD_MAX_SECTOR_DATA + framenum * CD_MAX_SUBCODE_DATA], CD_MAX_SUBCODE_DATA); +#endif + +#if WANT_RAW_DATA_SECTOR + /* reconstitute the ECC data and sync header */ + sector = (uint8_t *)&dest[framenum * CD_FRAME_SIZE]; + if ((src[framenum / 8] & (1 << (framenum % 8))) != 0) + { + memcpy(sector, s_cd_sync_header, sizeof(s_cd_sync_header)); + ecc_generate(sector); + } +#endif + } + return CHDERR_NONE; +} diff --git a/libretrodroid/src/main/cpp/libchdr/src/libchdr_chd.c b/libretrodroid/src/main/cpp/libchdr/src/libchdr_chd.c new file mode 100644 index 000000000..8a9fe6c07 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/src/libchdr_chd.c @@ -0,0 +1,2190 @@ +/*************************************************************************** + + chd.c + + MAME Compressed Hunks of Data file format + +**************************************************************************** + + Copyright Aaron Giles + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + * Neither the name 'MAME' nor the names of its contributors may be + used to endorse or promote products derived from this software + without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY AARON GILES ''AS IS'' AND ANY EXPRESS OR + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL AARON GILES BE LIABLE FOR ANY DIRECT, + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + +***************************************************************************/ + +#include +#include +#include +#include +#include +#include + +#include "../include/libchdr/chd.h" +#include "../include/libchdr/cdrom.h" +#include "../include/libchdr/codec_cdfl.h" +#include "../include/libchdr/codec_cdlz.h" +#include "../include/libchdr/codec_cdzl.h" +#include "../include/libchdr/codec_cdzs.h" +#include "../include/libchdr/codec_flac.h" +#include "../include/libchdr/codec_huff.h" +#include "../include/libchdr/codec_lzma.h" +#include "../include/libchdr/codec_zlib.h" +#include "../include/libchdr/codec_zstd.h" +#include "../include/libchdr/huffman.h" +#include "../include/libchdr/macros.h" + +#include "../deps/lzma-25.01/include/LzmaDec.h" + +#undef TRUE +#undef FALSE +#define TRUE 1 +#define FALSE 0 + +#define SHA1_DIGEST_SIZE 20 + +/*************************************************************************** + CONSTANTS +***************************************************************************/ + +#define MAP_STACK_ENTRIES 512 /* max number of entries to use on the stack */ +#define MAP_ENTRY_SIZE 16 /* V3 and later */ +#define OLD_MAP_ENTRY_SIZE 8 /* V1-V2 */ +#define METADATA_HEADER_SIZE 16 /* metadata header size */ + +#define MAP_ENTRY_FLAG_TYPE_MASK 0x0f /* what type of hunk */ +#define MAP_ENTRY_FLAG_NO_CRC 0x10 /* no CRC is present */ + +#define CHD_V1_SECTOR_SIZE 512 /* size of a "sector" in the V1 header */ + +#define CHD_MAX_HUNK_SIZE (128 * 1024 * 1024) /* hunk size probably shouldn't be more than 128MB */ + +/* we're currently only using this for CD/DVDs, if we end up with more than 10GB data, it's probably invalid */ +#define CHD_MAX_FILE_SIZE (10ULL * 1024 * 1024 * 1024) + +#define COOKIE_VALUE 0xbaadf00d + +#define END_OF_LIST_COOKIE "EndOfListCookie" + +#define NO_MATCH (~0) + +/* V3-V4 entry types */ +enum +{ + V34_MAP_ENTRY_TYPE_INVALID = 0, /* invalid type */ + V34_MAP_ENTRY_TYPE_COMPRESSED = 1, /* standard compression */ + V34_MAP_ENTRY_TYPE_UNCOMPRESSED = 2, /* uncompressed data */ + V34_MAP_ENTRY_TYPE_MINI = 3, /* mini: use offset as raw data */ + V34_MAP_ENTRY_TYPE_SELF_HUNK = 4, /* same as another hunk in this file */ + V34_MAP_ENTRY_TYPE_PARENT_HUNK = 5, /* same as a hunk in the parent file */ + V34_MAP_ENTRY_TYPE_2ND_COMPRESSED = 6 /* compressed with secondary algorithm (usually FLAC CDDA) */ +}; + +/* V5 compression types */ +enum +{ + /* codec #0 + * these types are live when running */ + COMPRESSION_TYPE_0 = 0, + /* codec #1 */ + COMPRESSION_TYPE_1 = 1, + /* codec #2 */ + COMPRESSION_TYPE_2 = 2, + /* codec #3 */ + COMPRESSION_TYPE_3 = 3, + /* no compression; implicit length = hunkbytes */ + COMPRESSION_NONE = 4, + /* same as another block in this chd */ + COMPRESSION_SELF = 5, + /* same as a hunk's worth of units in the parent chd */ + COMPRESSION_PARENT = 6, + + /* start of small RLE run (4-bit length) + * these additional pseudo-types are used for compressed encodings: */ + COMPRESSION_RLE_SMALL, + /* start of large RLE run (8-bit length) */ + COMPRESSION_RLE_LARGE, + /* same as the last COMPRESSION_SELF block */ + COMPRESSION_SELF_0, + /* same as the last COMPRESSION_SELF block + 1 */ + COMPRESSION_SELF_1, + /* same block in the parent */ + COMPRESSION_PARENT_SELF, + /* same as the last COMPRESSION_PARENT block */ + COMPRESSION_PARENT_0, + /* same as the last COMPRESSION_PARENT block + 1 */ + COMPRESSION_PARENT_1 +}; + +/*************************************************************************** + MACROS +***************************************************************************/ + +#define EARLY_EXIT(x) do { (void)(x); goto cleanup; } while (0) + +/*************************************************************************** + TYPE DEFINITIONS +***************************************************************************/ + +/* interface to a codec */ +typedef struct _codec_interface codec_interface; +struct _codec_interface +{ + uint32_t compression; /* type of compression */ + const char *compname; /* name of the algorithm */ + uint8_t lossy; /* is this a lossy algorithm? */ + chd_error (*init)(void *codec, uint32_t hunkbytes); /* codec initialize */ + void (*free)(void *codec); /* codec free */ + chd_codec_interface_decompress decompress; /* decompress data */ + chd_error (*config)(void *codec, int param, void *config); /* configure */ +}; + +/* a single map entry */ +typedef struct _map_entry map_entry; +struct _map_entry +{ + uint64_t offset; /* offset within the file of the data */ + uint32_t crc; /* 32-bit CRC of the data */ + uint32_t length; /* length of the data */ + uint8_t flags; /* misc flags */ +}; + +/* a single metadata entry */ +typedef struct _metadata_entry metadata_entry; +struct _metadata_entry +{ + uint64_t offset; /* offset within the file of the header */ + uint64_t next; /* offset within the file of the next header */ + uint64_t prev; /* offset within the file of the previous header */ + uint32_t length; /* length of the metadata */ + uint32_t metatag; /* metadata tag */ + uint8_t flags; /* flag bits */ +}; + +/* internal representation of an open CHD file */ +struct _chd_file +{ + uint32_t cookie; /* cookie, should equal COOKIE_VALUE */ + + core_file_callbacks_and_argp file; /* handle to the open core file */ + uint64_t file_size; /* size of the core file */ + chd_header header; /* header, extracted from file */ + + chd_file * parent; /* pointer to parent file, or NULL */ + + map_entry * map; /* array of map entries */ + + uint8_t * compressed; /* pointer to buffer for compressed data */ + const codec_interface * codecintf[4]; /* interface to the codec */ + + struct + { + zlib_codec_data zlib; /* zlib codec data */ + lzma_codec_data lzma; /* lzma codec data */ + huff_codec_data huff; /* huff codec data */ + flac_codec_data flac; /* flac codec data */ + zstd_codec_data zstd; /* zstd codec data */ + cdzl_codec_data cdzl; /* cdzl codec data */ + cdlz_codec_data cdlz; /* cdlz codec data */ + cdfl_codec_data cdfl; /* cdfl codec data */ + cdzs_codec_data cdzs; /* cdzs codec data */ + } codec_data; + + uint8_t * file_cache; /* cache of underlying file */ +}; + + +/*************************************************************************** + GLOBAL VARIABLES +***************************************************************************/ + +static const uint8_t nullmd5[CHD_MD5_BYTES] = { 0 }; +static const uint8_t nullsha1[CHD_SHA1_BYTES] = { 0 }; + +/*************************************************************************** + PROTOTYPES +***************************************************************************/ + +/* core_file_callbacks wrappers over stdio */ +static void *core_stdio_fopen(char const *path); +static uint64_t core_stdio_fsize(void *file); +static size_t core_stdio_fread(void *ptr, size_t size, size_t nmemb, void *file); +static int core_stdio_fclose(void *file); +static int core_stdio_fclose_nonowner(void *file); /* alternate fclose used by chd_open_file */ +static int core_stdio_fseek(void* file, int64_t offset, int whence); + +/* Legacy core_file wrappers */ +static uint64_t core_legacy_fsize(void *file); +static size_t core_legacy_fread(void *ptr, size_t size, size_t nmemb, void *file); +static int core_legacy_fclose(void *file); +static int core_legacy_fseek(void* file, int64_t offset, int whence); + +/* internal header operations */ +static chd_error header_read(chd_file *chd, chd_header *header); + +/* internal hunk read/write */ +static chd_error hunk_read_into_memory(chd_file *chd, uint32_t hunknum, uint8_t *dest); + +/* internal map access */ +static chd_error map_read(chd_file *chd); + +/* metadata management */ +static chd_error metadata_find_entry(chd_file *chd, uint32_t metatag, uint32_t metaindex, metadata_entry *metaentry); + + +/*************************************************************************** + CODEC INTERFACES +***************************************************************************/ + +static const codec_interface codec_interfaces[] = +{ + /* "none" or no compression */ + { + CHDCOMPRESSION_NONE, + "none", + FALSE, + NULL, + NULL, + NULL, + NULL + }, + + /* standard zlib compression */ + { + CHDCOMPRESSION_ZLIB, + "zlib", + FALSE, + zlib_codec_init, + zlib_codec_free, + zlib_codec_decompress, + NULL + }, + + /* zlib+ compression */ + { + CHDCOMPRESSION_ZLIB_PLUS, + "zlib+", + FALSE, + zlib_codec_init, + zlib_codec_free, + zlib_codec_decompress, + NULL + }, + + /* V5 zlib compression */ + { + CHD_CODEC_ZLIB, + "zlib (Deflate)", + FALSE, + zlib_codec_init, + zlib_codec_free, + zlib_codec_decompress, + NULL + }, + + /* V5 lzma compression */ + { + CHD_CODEC_LZMA, + "lzma (LZMA)", + FALSE, + lzma_codec_init, + lzma_codec_free, + lzma_codec_decompress, + NULL + }, + + /* V5 huffman compression */ + { + CHD_CODEC_HUFFMAN, + "Huffman", + FALSE, + huff_codec_init, + huff_codec_free, + huff_codec_decompress, + NULL + }, + + /* V5 flac compression */ + { + CHD_CODEC_FLAC, + "flac (FLAC)", + FALSE, + flac_codec_init, + flac_codec_free, + flac_codec_decompress, + NULL + }, + /* V5 zstd compression */ + { + CHD_CODEC_ZSTD, + "ZStandard", + FALSE, + zstd_codec_init, + zstd_codec_free, + zstd_codec_decompress, + NULL + }, + + /* V5 CD zlib compression */ + { + CHD_CODEC_CD_ZLIB, + "cdzl (CD Deflate)", + FALSE, + cdzl_codec_init, + cdzl_codec_free, + cdzl_codec_decompress, + NULL + }, + + /* V5 CD lzma compression */ + { + CHD_CODEC_CD_LZMA, + "cdlz (CD LZMA)", + FALSE, + cdlz_codec_init, + cdlz_codec_free, + cdlz_codec_decompress, + NULL + }, + + /* V5 CD flac compression */ + { + CHD_CODEC_CD_FLAC, + "cdfl (CD FLAC)", + FALSE, + cdfl_codec_init, + cdfl_codec_free, + cdfl_codec_decompress, + NULL + }, + /* V5 CD zstd compression */ + { + CHD_CODEC_CD_ZSTD, + "cdzs (CD ZStandard)", + FALSE, + cdzs_codec_init, + cdzs_codec_free, + cdzs_codec_decompress, + NULL + } + +}; + +/*************************************************************************** + INLINE FUNCTIONS +***************************************************************************/ + +/*------------------------------------------------- + seek_and_read - read data from file at + specified position +-------------------------------------------------*/ + +static CHDR_INLINE int seek_and_read(chd_file *chd, uint64_t position, void *buffer, size_t total_bytes) +{ + if (core_fseek(&chd->file, position, SEEK_SET) != 0) + return FALSE; + if (core_fread(&chd->file, buffer, total_bytes) != total_bytes) + return FALSE; + + return TRUE; +} + +/*------------------------------------------------- + get_bigendian_uint64_t - fetch a uint64_t from + the data stream in bigendian order +-------------------------------------------------*/ + +static CHDR_INLINE uint64_t get_bigendian_uint64_t(const uint8_t *base) +{ + return ((uint64_t)base[0] << 56) | ((uint64_t)base[1] << 48) | ((uint64_t)base[2] << 40) | ((uint64_t)base[3] << 32) | + ((uint64_t)base[4] << 24) | ((uint64_t)base[5] << 16) | ((uint64_t)base[6] << 8) | (uint64_t)base[7]; +} + +/*------------------------------------------------- + put_bigendian_uint64_t - write a uint64_t to + the data stream in bigendian order +-------------------------------------------------*/ + +static CHDR_INLINE void put_bigendian_uint64_t(uint8_t *base, uint64_t value) +{ + base[0] = value >> 56; + base[1] = value >> 48; + base[2] = value >> 40; + base[3] = value >> 32; + base[4] = value >> 24; + base[5] = value >> 16; + base[6] = value >> 8; + base[7] = value; +} + +/*------------------------------------------------- + get_bigendian_uint48 - fetch a UINT48 from + the data stream in bigendian order +-------------------------------------------------*/ + +static CHDR_INLINE uint64_t get_bigendian_uint48(const uint8_t *base) +{ + return ((uint64_t)base[0] << 40) | ((uint64_t)base[1] << 32) | + ((uint64_t)base[2] << 24) | ((uint64_t)base[3] << 16) | ((uint64_t)base[4] << 8) | (uint64_t)base[5]; +} + +/*------------------------------------------------- + put_bigendian_uint48 - write a UINT48 to + the data stream in bigendian order +-------------------------------------------------*/ + +static CHDR_INLINE void put_bigendian_uint48(uint8_t *base, uint64_t value) +{ + value &= 0xffffffffffff; + base[0] = value >> 40; + base[1] = value >> 32; + base[2] = value >> 24; + base[3] = value >> 16; + base[4] = value >> 8; + base[5] = value; +} +/*------------------------------------------------- + get_bigendian_uint32_t - fetch a uint32_t from + the data stream in bigendian order +-------------------------------------------------*/ + +static CHDR_INLINE uint32_t get_bigendian_uint32_t(const uint8_t *base) +{ + return (base[0] << 24) | (base[1] << 16) | (base[2] << 8) | base[3]; +} + +/*------------------------------------------------- + put_bigendian_uint32_t - write a uint32_t to + the data stream in bigendian order +-------------------------------------------------*/ + +static CHDR_INLINE void put_bigendian_uint32_t(uint8_t *base, uint32_t value) +{ + base[0] = value >> 24; + base[1] = value >> 16; + base[2] = value >> 8; + base[3] = value; +} + +/*------------------------------------------------- + put_bigendian_uint24 - write a UINT24 to + the data stream in bigendian order +-------------------------------------------------*/ + +static CHDR_INLINE void put_bigendian_uint24(uint8_t *base, uint32_t value) +{ + value &= 0xffffff; + base[0] = value >> 16; + base[1] = value >> 8; + base[2] = value; +} + +/*------------------------------------------------- + get_bigendian_uint24 - fetch a UINT24 from + the data stream in bigendian order +-------------------------------------------------*/ + +static CHDR_INLINE uint32_t get_bigendian_uint24(const uint8_t *base) +{ + return (base[0] << 16) | (base[1] << 8) | base[2]; +} + +/*------------------------------------------------- + get_bigendian_uint16 - fetch a uint16_t from + the data stream in bigendian order +-------------------------------------------------*/ + +static CHDR_INLINE uint16_t get_bigendian_uint16(const uint8_t *base) +{ + return (base[0] << 8) | base[1]; +} + +/*------------------------------------------------- + put_bigendian_uint16 - write a uint16_t to + the data stream in bigendian order +-------------------------------------------------*/ + +static CHDR_INLINE void put_bigendian_uint16(uint8_t *base, uint16_t value) +{ + base[0] = value >> 8; + base[1] = value; +} + +/*------------------------------------------------- + map_extract - extract a single map + entry from the datastream +-------------------------------------------------*/ + +static CHDR_INLINE void map_extract(const uint8_t *base, map_entry *entry) +{ + entry->offset = get_bigendian_uint64_t(&base[0]); + entry->crc = get_bigendian_uint32_t(&base[8]); + entry->length = get_bigendian_uint16(&base[12]) | (base[14] << 16); + entry->flags = base[15]; +} + +/*------------------------------------------------- + map_size_v5 - calculate CHDv5 map size +-------------------------------------------------*/ +static CHDR_INLINE int map_size_v5(chd_header* header, size_t *size) +{ + /* Avoid overflow due to corrupted data. */ + const size_t max_hunkcount = ((size_t)-1 / header->mapentrybytes); + if (header->hunkcount > max_hunkcount) + return FALSE; + + *size = (size_t)header->hunkcount * header->mapentrybytes; + return TRUE; +} + +/*------------------------------------------------- + crc16 - calculate CRC16 (from hashing.cpp) +-------------------------------------------------*/ +uint16_t crc16(const void *data, uint32_t length) +{ + uint16_t crc = 0xffff; + + static const uint16_t s_table[256] = + { + 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, + 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, + 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, + 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, + 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, + 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, + 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, + 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, + 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, + 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, + 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, + 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, + 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, + 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, + 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, + 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, + 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, + 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, + 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, + 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, + 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, + 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, + 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, + 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, + 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, + 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, + 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, + 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, + 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, + 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, + 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, + 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0 + }; + + const uint8_t *src = (uint8_t*)data; + + /* fetch the current value into a local and rip through the source data */ + while (length-- != 0) + crc = (crc << 8) ^ s_table[(crc >> 8) ^ *src++]; + return crc; +} + +/*------------------------------------------------- + compressed - test if CHD file is compressed ++-------------------------------------------------*/ +static CHDR_INLINE int chd_compressed(chd_header* header) { + return header->compression[0] != CHD_CODEC_NONE; +} + +/*------------------------------------------------- + decompress_v5_map - decompress the v5 map +-------------------------------------------------*/ + +static chd_error decompress_v5_map(chd_file* chd, chd_header* header) +{ + uint32_t hunknum; + int repcount = 0; + uint8_t lastcomp = 0; + uint32_t last_self = 0; + uint64_t last_parent = 0; + struct bitstream* bitbuf; + uint32_t mapbytes; + uint64_t firstoffs; + uint16_t mapcrc; + uint8_t lengthbits; + uint8_t selfbits; + uint8_t parentbits; + uint8_t *compressed_ptr; + uint8_t rawbuf[16]; + struct huffman_decoder* decoder; + enum huffman_error err; + uint64_t curoffset; + size_t rawmapsize; + + if (!map_size_v5(header, &rawmapsize)) + return CHDERR_INVALID_FILE; + + if (!chd_compressed(header)) + { + if ((header->mapoffset + rawmapsize) >= chd->file_size || (header->mapoffset + rawmapsize) < header->mapoffset) + return CHDERR_INVALID_FILE; + + header->rawmap = (uint8_t*)malloc(rawmapsize); + if (header->rawmap == NULL) + return CHDERR_OUT_OF_MEMORY; + if (!seek_and_read(chd, header->mapoffset, header->rawmap, rawmapsize)) + return CHDERR_READ_ERROR; + return CHDERR_NONE; + } + + /* read the header */ + if (!seek_and_read(chd, header->mapoffset, rawbuf, sizeof(rawbuf))) + return CHDERR_READ_ERROR; + mapbytes = get_bigendian_uint32_t(&rawbuf[0]); + firstoffs = get_bigendian_uint48(&rawbuf[4]); + mapcrc = get_bigendian_uint16(&rawbuf[10]); + lengthbits = rawbuf[12]; + selfbits = rawbuf[13]; + parentbits = rawbuf[14]; + + /* now read the map */ + if ((header->mapoffset + mapbytes) < header->mapoffset || (header->mapoffset + mapbytes) >= chd->file_size) + return CHDERR_INVALID_FILE; + compressed_ptr = (uint8_t*)malloc(sizeof(uint8_t) * mapbytes); + if (compressed_ptr == NULL) + return CHDERR_OUT_OF_MEMORY; + if (!seek_and_read(chd, header->mapoffset + 16, compressed_ptr, mapbytes)) + { + free(compressed_ptr); + return CHDERR_READ_ERROR; + } + bitbuf = create_bitstream(compressed_ptr, sizeof(uint8_t) * mapbytes); + header->rawmap = (uint8_t*)malloc(rawmapsize); + if (header->rawmap == NULL) + { + free(compressed_ptr); + free(bitbuf); + return CHDERR_OUT_OF_MEMORY; + } + + /* first decode the compression types */ + decoder = create_huffman_decoder(16, 8); + if (decoder == NULL) + { + free(compressed_ptr); + free(bitbuf); + return CHDERR_OUT_OF_MEMORY; + } + + err = huffman_import_tree_rle(decoder, bitbuf); + if (err != HUFFERR_NONE) + { + free(compressed_ptr); + free(bitbuf); + delete_huffman_decoder(decoder); + return CHDERR_DECOMPRESSION_ERROR; + } + + for (hunknum = 0; hunknum < header->hunkcount; hunknum++) + { + uint8_t *rawmap = header->rawmap + (hunknum * 12); + if (repcount > 0) + rawmap[0] = lastcomp, repcount--; + else + { + uint8_t val; + if (bitstream_overflow(bitbuf)) + { + free(compressed_ptr); + free(bitbuf); + delete_huffman_decoder(decoder); + return CHDERR_DECOMPRESSION_ERROR; + } + + val = huffman_decode_one(decoder, bitbuf); + if (val == COMPRESSION_RLE_SMALL) + rawmap[0] = lastcomp, repcount = 2 + huffman_decode_one(decoder, bitbuf); + else if (val == COMPRESSION_RLE_LARGE) + rawmap[0] = lastcomp, repcount = 2 + 16 + (huffman_decode_one(decoder, bitbuf) << 4), repcount += huffman_decode_one(decoder, bitbuf); + else + rawmap[0] = lastcomp = val; + } + } + + /* then iterate through the hunks and extract the needed data */ + curoffset = firstoffs; + for (hunknum = 0; hunknum < header->hunkcount; hunknum++) + { + uint8_t *rawmap = header->rawmap + (hunknum * 12); + uint64_t offset = curoffset; + uint32_t length = 0; + uint16_t crc = 0; + switch (rawmap[0]) + { + /* base types */ + case COMPRESSION_TYPE_0: + case COMPRESSION_TYPE_1: + case COMPRESSION_TYPE_2: + case COMPRESSION_TYPE_3: + curoffset += length = bitstream_read(bitbuf, lengthbits); + crc = bitstream_read(bitbuf, 16); + break; + + case COMPRESSION_NONE: + curoffset += length = header->hunkbytes; + crc = bitstream_read(bitbuf, 16); + break; + + case COMPRESSION_SELF: + last_self = offset = bitstream_read(bitbuf, selfbits); + break; + + case COMPRESSION_PARENT: + offset = bitstream_read(bitbuf, parentbits); + last_parent = offset; + break; + + /* pseudo-types; convert into base types */ + case COMPRESSION_SELF_1: + last_self++; + /* Fallthrough */ + case COMPRESSION_SELF_0: + rawmap[0] = COMPRESSION_SELF; + offset = last_self; + break; + + case COMPRESSION_PARENT_SELF: + rawmap[0] = COMPRESSION_PARENT; + last_parent = offset = ( ((uint64_t)hunknum) * ((uint64_t)header->hunkbytes) ) / header->unitbytes; + break; + + case COMPRESSION_PARENT_1: + last_parent += header->hunkbytes / header->unitbytes; + /* Fallthrough */ + case COMPRESSION_PARENT_0: + rawmap[0] = COMPRESSION_PARENT; + offset = last_parent; + break; + } + /* UINT24 length */ + put_bigendian_uint24(&rawmap[1], length); + + /* UINT48 offset */ + put_bigendian_uint48(&rawmap[4], offset); + + /* crc16 */ + put_bigendian_uint16(&rawmap[10], crc); + } + + /* free memory */ + free(compressed_ptr); + free(bitbuf); + delete_huffman_decoder(decoder); + + /* verify the final CRC */ + if (crc16(&header->rawmap[0], header->hunkcount * 12) != mapcrc) + return CHDERR_DECOMPRESSION_ERROR; + + return CHDERR_NONE; +} + +/*------------------------------------------------- + map_extract_old - extract a single map + entry in old format from the datastream +-------------------------------------------------*/ + +static CHDR_INLINE void map_extract_old(const uint8_t *base, map_entry *entry, uint32_t hunkbytes) +{ + entry->offset = get_bigendian_uint64_t(&base[0]); + entry->crc = 0; + entry->length = entry->offset >> 44; + entry->flags = MAP_ENTRY_FLAG_NO_CRC | ((entry->length == hunkbytes) ? V34_MAP_ENTRY_TYPE_UNCOMPRESSED : V34_MAP_ENTRY_TYPE_COMPRESSED); +#ifdef __MWERKS__ + entry->offset = entry->offset & 0x00000FFFFFFFFFFFLL; +#else + entry->offset = (entry->offset << 20) >> 20; +#endif +} + +/*************************************************************************** + CHD FILE MANAGEMENT +***************************************************************************/ + +static const core_file_callbacks core_stdio = { + core_stdio_fsize, + core_stdio_fread, + core_stdio_fclose, + core_stdio_fseek +}; + +static const core_file_callbacks core_stdio_nonowner = { + core_stdio_fsize, + core_stdio_fread, + core_stdio_fclose_nonowner, + core_stdio_fseek +}; + +static const core_file_callbacks core_legacy = { + core_legacy_fsize, + core_legacy_fread, + core_legacy_fclose, + core_legacy_fseek +}; + +/*------------------------------------------------- + chd_open_file - open a CHD file for access +-------------------------------------------------*/ + +CHD_EXPORT chd_error chd_open_file(RFILE *file, int mode, chd_file *parent, chd_file **chd) { + return chd_open_core_file_callbacks(&core_stdio_nonowner, file, mode, parent, chd); +} + +/*------------------------------------------------- + chd_open_core_file - open a CHD file for access +-------------------------------------------------*/ + +CHD_EXPORT chd_error chd_open_core_file(core_file *file, int mode, chd_file *parent, chd_file **chd) +{ + if (file == NULL) + return CHDERR_INVALID_PARAMETER; + + return chd_open_core_file_callbacks(&core_legacy, file, mode, parent, chd); +} + +/*------------------------------------------------- + chd_open_core_file_callbacks - open a CHD file for access +-------------------------------------------------*/ + +CHD_EXPORT chd_error chd_open_core_file_callbacks(const core_file_callbacks *callbacks, const void *user_data, int mode, chd_file *parent, chd_file **chd) +{ + chd_file *newchd = NULL; + chd_error err; + + /* verify parameters */ + if (callbacks == NULL) + EARLY_EXIT(err = CHDERR_INVALID_PARAMETER); + + /* punt if invalid parent */ + if (parent != NULL && parent->cookie != COOKIE_VALUE) + EARLY_EXIT(err = CHDERR_INVALID_PARAMETER); + + /* allocate memory for the final result */ + newchd = (chd_file *)malloc(sizeof(**chd)); + if (newchd == NULL) + EARLY_EXIT(err = CHDERR_OUT_OF_MEMORY); + memset(newchd, 0, sizeof(*newchd)); + newchd->cookie = COOKIE_VALUE; + newchd->parent = parent; + newchd->file.callbacks = callbacks; + newchd->file.argp = (void*)user_data; + newchd->file_size = core_fsize(&newchd->file); + if ((int64_t)newchd->file_size <= 0) + EARLY_EXIT(err = CHDERR_INVALID_FILE); + + /* now attempt to read the header */ + err = header_read(newchd, &newchd->header); + if (err != CHDERR_NONE) + EARLY_EXIT(err); + + /* make sure we don't open a read-only file writeable */ + if (mode == CHD_OPEN_READWRITE && !(newchd->header.flags & CHDFLAGS_IS_WRITEABLE)) + EARLY_EXIT(err = CHDERR_FILE_NOT_WRITEABLE); + + /* also, never open an older version writeable */ + if (mode == CHD_OPEN_READWRITE && newchd->header.version < CHD_HEADER_VERSION) + EARLY_EXIT(err = CHDERR_UNSUPPORTED_VERSION); + + /* if we need a parent, make sure we have one */ + if (parent == NULL) + { + /* Detect parent requirement for versions below 5 */ + if (newchd->header.version < 5 && newchd->header.flags & CHDFLAGS_HAS_PARENT) + EARLY_EXIT(err = CHDERR_REQUIRES_PARENT); + /* Detection for version 5 and above - if parentsha1 != 0, we have a parent */ + else if (newchd->header.version >= 5 && memcmp(nullsha1, newchd->header.parentsha1, sizeof(newchd->header.parentsha1)) != 0) + EARLY_EXIT(err = CHDERR_REQUIRES_PARENT); + } + + /* make sure we have a valid parent */ + if (parent != NULL) + { + /* check MD5 if it isn't empty */ + if (memcmp(nullmd5, newchd->header.parentmd5, sizeof(newchd->header.parentmd5)) != 0 && + memcmp(nullmd5, newchd->parent->header.md5, sizeof(newchd->parent->header.md5)) != 0 && + memcmp(newchd->parent->header.md5, newchd->header.parentmd5, sizeof(newchd->header.parentmd5)) != 0) + EARLY_EXIT(err = CHDERR_INVALID_PARENT); + + /* check SHA1 if it isn't empty */ + if (memcmp(nullsha1, newchd->header.parentsha1, sizeof(newchd->header.parentsha1)) != 0 && + memcmp(nullsha1, newchd->parent->header.sha1, sizeof(newchd->parent->header.sha1)) != 0 && + memcmp(newchd->parent->header.sha1, newchd->header.parentsha1, sizeof(newchd->header.parentsha1)) != 0) + EARLY_EXIT(err = CHDERR_INVALID_PARENT); + } + + /* now read the hunk map */ + if (newchd->header.version < 5) + { + err = map_read(newchd); + if (err != CHDERR_NONE) + EARLY_EXIT(err); + } + else + { + err = decompress_v5_map(newchd, &(newchd->header)); + } + if (err != CHDERR_NONE) + EARLY_EXIT(err); + + /* allocate the temporary compressed buffer */ + newchd->compressed = (uint8_t *)malloc(newchd->header.hunkbytes); + if (newchd->compressed == NULL) + EARLY_EXIT(err = CHDERR_OUT_OF_MEMORY); + + /* find the codec interface */ + if (newchd->header.version < 5) + { + size_t intfnum; + for (intfnum = 0; intfnum < ARRAY_LENGTH(codec_interfaces); intfnum++) + { + if (codec_interfaces[intfnum].compression == newchd->header.compression[0]) + { + newchd->codecintf[0] = &codec_interfaces[intfnum]; + break; + } + } + + if (intfnum == ARRAY_LENGTH(codec_interfaces)) + EARLY_EXIT(err = CHDERR_UNSUPPORTED_FORMAT); + + /* initialize the codec */ + if (newchd->codecintf[0]->init != NULL) + { + err = newchd->codecintf[0]->init(&newchd->codec_data.zlib, newchd->header.hunkbytes); + if (err != CHDERR_NONE) + EARLY_EXIT(err); + } + } + else + { + size_t decompnum; + int needsinit; + + /* verify the compression types and initialize the codecs */ + for (decompnum = 0; decompnum < ARRAY_LENGTH(newchd->header.compression); decompnum++) + { + size_t i; + for (i = 0 ; i < ARRAY_LENGTH(codec_interfaces) ; i++) + { + if (codec_interfaces[i].compression == newchd->header.compression[decompnum]) + { + newchd->codecintf[decompnum] = &codec_interfaces[i]; + break; + } + } + + if (newchd->codecintf[decompnum] == NULL && newchd->header.compression[decompnum] != 0) + EARLY_EXIT(err = CHDERR_UNSUPPORTED_FORMAT); + + /* ensure we don't try to initialize the same codec twice */ + /* this is "normal" for chds where the user overrides the codecs, it'll have none repeated */ + needsinit = (newchd->codecintf[decompnum]->init != NULL); + for (i = 0; i < decompnum; i++) + { + if (newchd->codecintf[decompnum] == newchd->codecintf[i]) + { + /* already initialized */ + needsinit = FALSE; + break; + } + } + + /* initialize the codec */ + if (needsinit) + { + void* codec = NULL; + switch (newchd->header.compression[decompnum]) + { + case CHD_CODEC_ZLIB: + codec = &newchd->codec_data.zlib; + break; + + case CHD_CODEC_LZMA: + codec = &newchd->codec_data.lzma; + break; + + case CHD_CODEC_HUFFMAN: + codec = &newchd->codec_data.huff; + break; + + case CHD_CODEC_FLAC: + codec = &newchd->codec_data.flac; + break; + + case CHD_CODEC_ZSTD: + codec = &newchd->codec_data.zstd; + break; + + case CHD_CODEC_CD_ZLIB: + codec = &newchd->codec_data.cdzl; + break; + + case CHD_CODEC_CD_LZMA: + codec = &newchd->codec_data.cdlz; + break; + + case CHD_CODEC_CD_FLAC: + codec = &newchd->codec_data.cdfl; + break; + + case CHD_CODEC_CD_ZSTD: + codec = &newchd->codec_data.cdzs; + break; + } + + if (codec == NULL) + EARLY_EXIT(err = CHDERR_UNSUPPORTED_FORMAT); + + err = newchd->codecintf[decompnum]->init(codec, newchd->header.hunkbytes); + if (err != CHDERR_NONE) + EARLY_EXIT(err); + } + } + } + + /* all done */ + *chd = newchd; + return CHDERR_NONE; + +cleanup: + if (newchd != NULL) + chd_close(newchd); + return err; +} + +/*------------------------------------------------- + chd_precache - precache underlying file in + memory +-------------------------------------------------*/ + +CHD_EXPORT chd_error chd_precache(chd_file *chd) +{ + if (chd->file_cache == NULL) + { + chd->file_cache = (uint8_t*)malloc(chd->file_size); + if (chd->file_cache == NULL) + return CHDERR_OUT_OF_MEMORY; + if (!seek_and_read(chd, 0, chd->file_cache, chd->file_size)) + { + free(chd->file_cache); + chd->file_cache = NULL; + return CHDERR_READ_ERROR; + } + } + + return CHDERR_NONE; +} + +/*------------------------------------------------- + chd_open - open a CHD file by + filename +-------------------------------------------------*/ + +CHD_EXPORT chd_error chd_open(const char *filename, int mode, chd_file *parent, chd_file **chd) +{ + chd_error err; + void *file = NULL; + + if (filename == NULL) + EARLY_EXIT(err = CHDERR_INVALID_PARAMETER); + + /* choose the proper mode */ + switch(mode) + { + case CHD_OPEN_READ: + break; + + default: + EARLY_EXIT(err = CHDERR_INVALID_PARAMETER); + } + + /* open the file */ + file = core_stdio_fopen(filename); + if (file == NULL) + EARLY_EXIT(err = CHDERR_FILE_NOT_FOUND); + + /* now open the CHD */ + return chd_open_core_file_callbacks(&core_stdio, file, mode, parent, chd); + +cleanup: + if ((err != CHDERR_NONE) && (file != NULL)) + core_stdio_fclose(file); + return err; +} + +/*------------------------------------------------- + chd_close - close a CHD file for access +-------------------------------------------------*/ + +CHD_EXPORT void chd_close(chd_file *chd) +{ + /* punt if NULL or invalid */ + if (chd == NULL || chd->cookie != COOKIE_VALUE) + return; + + /* deinit the codec */ + if (chd->header.version < 5) + { + if (chd->codecintf[0] != NULL && chd->codecintf[0]->free != NULL) + chd->codecintf[0]->free(&chd->codec_data.zlib); + } + else + { + size_t i; + /* Free the codecs */ + for (i = 0 ; i < ARRAY_LENGTH(chd->codecintf); i++) + { + void* codec = NULL; + size_t j; + int needsfree; + + if (chd->codecintf[i] == NULL) + continue; + + /* only free each codec at max once */ + needsfree = 1; + for (j = 0; j < i; j++) + { + if (chd->codecintf[i] == chd->codecintf[j]) + { + needsfree = FALSE; + break; + } + } + if (!needsfree) + continue; + + switch (chd->codecintf[i]->compression) + { + case CHD_CODEC_ZLIB: + codec = &chd->codec_data.zlib; + break; + + case CHD_CODEC_LZMA: + codec = &chd->codec_data.lzma; + break; + + case CHD_CODEC_HUFFMAN: + codec = &chd->codec_data.huff; + break; + + case CHD_CODEC_FLAC: + codec = &chd->codec_data.flac; + break; + + case CHD_CODEC_ZSTD: + codec = &chd->codec_data.zstd; + break; + + case CHD_CODEC_CD_ZLIB: + codec = &chd->codec_data.cdzl; + break; + + case CHD_CODEC_CD_LZMA: + codec = &chd->codec_data.cdlz; + break; + + case CHD_CODEC_CD_FLAC: + codec = &chd->codec_data.cdfl; + break; + + case CHD_CODEC_CD_ZSTD: + codec = &chd->codec_data.cdzs; + break; + } + + if (codec) + { + chd->codecintf[i]->free(codec); + } + } + + /* Free the raw map */ + if (chd->header.rawmap != NULL) + free(chd->header.rawmap); + } + + /* free the compressed data buffer */ + if (chd->compressed != NULL) + free(chd->compressed); + + /* free the hunk map */ + if (chd->map != NULL) + free(chd->map); + + /* close the file */ + if (chd->file.callbacks != NULL) + core_fclose(&chd->file); + + if (chd->file_cache) + free(chd->file_cache); + + if (chd->parent) + chd_close(chd->parent); + + /* free our memory */ + free(chd); +} + +/*------------------------------------------------- + chd_core_file - return the associated + core_file +-------------------------------------------------*/ + +CHD_EXPORT core_file *chd_core_file(chd_file *chd) +{ + if (chd->file.callbacks != &core_legacy) + return NULL; + + return (core_file*)chd->file.argp; +} + +/*------------------------------------------------- + chd_error_string - return an error string for + the given CHD error +-------------------------------------------------*/ + +CHD_EXPORT const char *chd_error_string(chd_error err) +{ + switch (err) + { + case CHDERR_NONE: return "no error"; + case CHDERR_NO_INTERFACE: return "no drive interface"; + case CHDERR_OUT_OF_MEMORY: return "out of memory"; + case CHDERR_INVALID_FILE: return "invalid file"; + case CHDERR_INVALID_PARAMETER: return "invalid parameter"; + case CHDERR_INVALID_DATA: return "invalid data"; + case CHDERR_FILE_NOT_FOUND: return "file not found"; + case CHDERR_REQUIRES_PARENT: return "requires parent"; + case CHDERR_FILE_NOT_WRITEABLE: return "file not writeable"; + case CHDERR_READ_ERROR: return "read error"; + case CHDERR_WRITE_ERROR: return "write error"; + case CHDERR_CODEC_ERROR: return "codec error"; + case CHDERR_INVALID_PARENT: return "invalid parent"; + case CHDERR_HUNK_OUT_OF_RANGE: return "hunk out of range"; + case CHDERR_DECOMPRESSION_ERROR: return "decompression error"; + case CHDERR_COMPRESSION_ERROR: return "compression error"; + case CHDERR_CANT_CREATE_FILE: return "can't create file"; + case CHDERR_CANT_VERIFY: return "can't verify file"; + case CHDERR_NOT_SUPPORTED: return "operation not supported"; + case CHDERR_METADATA_NOT_FOUND: return "can't find metadata"; + case CHDERR_INVALID_METADATA_SIZE: return "invalid metadata size"; + case CHDERR_UNSUPPORTED_VERSION: return "unsupported CHD version"; + case CHDERR_VERIFY_INCOMPLETE: return "incomplete verify"; + case CHDERR_INVALID_METADATA: return "invalid metadata"; + case CHDERR_INVALID_STATE: return "invalid state"; + case CHDERR_OPERATION_PENDING: return "operation pending"; + case CHDERR_NO_ASYNC_OPERATION: return "no async operation in progress"; + case CHDERR_UNSUPPORTED_FORMAT: return "unsupported format"; + default: return "undocumented error"; + } +} + +/*************************************************************************** + CHD HEADER MANAGEMENT +***************************************************************************/ + +/*------------------------------------------------- + chd_get_header - return a pointer to the + extracted header data +-------------------------------------------------*/ + +CHD_EXPORT const chd_header *chd_get_header(chd_file *chd) +{ + /* punt if NULL or invalid */ + if (chd == NULL || chd->cookie != COOKIE_VALUE) + return NULL; + + return &chd->header; +} + +/*------------------------------------------------- + chd_read_header_core_file_callbacks - read CHD header data + from file into the pointed struct +-------------------------------------------------*/ + +CHD_EXPORT chd_error chd_read_header_core_file_callbacks(const core_file_callbacks *callbacks, const void *user_data, chd_header *header) +{ + chd_file chd; + + /* verify parameters */ + if (callbacks == NULL || header == NULL) + return CHDERR_INVALID_PARAMETER; + + chd.file.callbacks = callbacks; + chd.file.argp = (void*)user_data; + + /* attempt to read the header */ + return header_read(&chd, header); +} + +/*------------------------------------------------- + chd_read_header_core_file - read CHD header data + from file into the pointed struct +-------------------------------------------------*/ + +CHD_EXPORT chd_error chd_read_header_core_file(core_file *file, chd_header *header) +{ + if (file == NULL) + return CHDERR_INVALID_PARAMETER; + + return chd_read_header_core_file_callbacks(&core_legacy, file, header); +} + +/*------------------------------------------------- + chd_read_header - read CHD header data + from file into the pointed struct +-------------------------------------------------*/ + +CHD_EXPORT chd_error chd_read_header_file(FILE *file, chd_header *header) +{ + return chd_read_header_core_file_callbacks(&core_stdio_nonowner, file, header); +} + +/*------------------------------------------------- + chd_read_header - read CHD header data + from file into the pointed struct +-------------------------------------------------*/ + +CHD_EXPORT chd_error chd_read_header(const char *filename, chd_header *header) +{ + chd_error err; + void *file = NULL; + + if (filename == NULL) + EARLY_EXIT(err = CHDERR_INVALID_PARAMETER); + + /* open the file */ + file = core_stdio_fopen(filename); + if (file == NULL) + EARLY_EXIT(err = CHDERR_FILE_NOT_FOUND); + + err = chd_read_header_core_file_callbacks(&core_stdio, file, header); + + cleanup: + if (file != NULL) + core_stdio_fclose(file); + return err; +} + +/*************************************************************************** + CORE DATA READ/WRITE +***************************************************************************/ + +/*------------------------------------------------- + chd_read - read a single hunk from the CHD + file +-------------------------------------------------*/ + +CHD_EXPORT chd_error chd_read(chd_file *chd, uint32_t hunknum, void *buffer) +{ + /* punt if NULL or invalid */ + if (chd == NULL || chd->cookie != COOKIE_VALUE) + return CHDERR_INVALID_PARAMETER; + + /* if we're past the end, fail */ + if (hunknum >= chd->header.totalhunks) + return CHDERR_HUNK_OUT_OF_RANGE; + + /* perform the read */ + return hunk_read_into_memory(chd, hunknum, (uint8_t *)buffer); +} + +/*************************************************************************** + METADATA MANAGEMENT +***************************************************************************/ + +/*------------------------------------------------- + chd_get_metadata - get the indexed metadata + of the given type +-------------------------------------------------*/ + +CHD_EXPORT chd_error chd_get_metadata(chd_file *chd, uint32_t searchtag, uint32_t searchindex, void *output, uint32_t outputlen, uint32_t *resultlen, uint32_t *resulttag, uint8_t *resultflags) +{ + metadata_entry metaentry; + chd_error err; + + /* if we didn't find it, just return */ + err = metadata_find_entry(chd, searchtag, searchindex, &metaentry); + if (err != CHDERR_NONE) + { + /* unless we're an old version and they are requesting hard disk metadata */ + if (chd->header.version < 3 && (searchtag == HARD_DISK_METADATA_TAG || searchtag == CHDMETATAG_WILDCARD) && searchindex == 0) + { + char faux_metadata[256]; + uint32_t faux_length; + + /* fill in the faux metadata */ + sprintf(faux_metadata, HARD_DISK_METADATA_FORMAT, chd->header.obsolete_cylinders, chd->header.obsolete_heads, chd->header.obsolete_sectors, (chd->header.obsolete_hunksize != 0) ? (chd->header.hunkbytes / chd->header.obsolete_hunksize) : 0); + faux_length = (uint32_t)strlen(faux_metadata) + 1; + + /* copy the metadata itself */ + memcpy(output, faux_metadata, MIN(outputlen, faux_length)); + + /* return the length of the data and the tag */ + if (resultlen != NULL) + *resultlen = faux_length; + if (resulttag != NULL) + *resulttag = HARD_DISK_METADATA_TAG; + return CHDERR_NONE; + } + return err; + } + + /* read the metadata */ + outputlen = MIN(outputlen, metaentry.length); + if (!seek_and_read(chd, metaentry.offset + METADATA_HEADER_SIZE, output, outputlen)) + return CHDERR_READ_ERROR; + + /* return the length of the data and the tag */ + if (resultlen != NULL) + *resultlen = metaentry.length; + if (resulttag != NULL) + *resulttag = metaentry.metatag; + if (resultflags != NULL) + *resultflags = metaentry.flags; + return CHDERR_NONE; +} + +/*************************************************************************** + INTERNAL HEADER OPERATIONS +***************************************************************************/ + +/*------------------------------------------------- + header_guess_unitbytes - for older CHD formats, + guess at the bytes/unit based on metadata +-------------------------------------------------*/ + +static uint32_t header_guess_unitbytes(chd_file *chd) +{ + /* look for hard disk metadata; if found, then the unit size == sector size */ + char metadata[512]; + int i0, i1, i2, i3; + if (chd_get_metadata(chd, HARD_DISK_METADATA_TAG, 0, metadata, sizeof(metadata), NULL, NULL, NULL) == CHDERR_NONE && + sscanf(metadata, HARD_DISK_METADATA_FORMAT, &i0, &i1, &i2, &i3) == 4) + return i3; + + /* look for CD-ROM metadata; if found, then the unit size == CD frame size */ + if (chd_get_metadata(chd, CDROM_OLD_METADATA_TAG, 0, metadata, sizeof(metadata), NULL, NULL, NULL) == CHDERR_NONE || + chd_get_metadata(chd, CDROM_TRACK_METADATA_TAG, 0, metadata, sizeof(metadata), NULL, NULL, NULL) == CHDERR_NONE || + chd_get_metadata(chd, CDROM_TRACK_METADATA2_TAG, 0, metadata, sizeof(metadata), NULL, NULL, NULL) == CHDERR_NONE || + chd_get_metadata(chd, GDROM_OLD_METADATA_TAG, 0, metadata, sizeof(metadata), NULL, NULL, NULL) == CHDERR_NONE || + chd_get_metadata(chd, GDROM_TRACK_METADATA_TAG, 0, metadata, sizeof(metadata), NULL, NULL, NULL) == CHDERR_NONE) + return CD_FRAME_SIZE; + + /* otherwise, just map 1:1 with the hunk size */ + return chd->header.hunkbytes; +} + +/*------------------------------------------------- + header_read - read a CHD header into the + internal data structure and perform validation +-------------------------------------------------*/ + +static chd_error header_read(chd_file *chd, chd_header *header) +{ + static const uint32_t header_sizes[CHD_HEADER_VERSION] = { + CHD_V1_HEADER_SIZE, + CHD_V2_HEADER_SIZE, + CHD_V3_HEADER_SIZE, + CHD_V4_HEADER_SIZE, + CHD_V5_HEADER_SIZE, + }; + + uint8_t rawheader[CHD_MAX_HEADER_SIZE]; + + /* punt if NULL */ + if (header == NULL) + return CHDERR_INVALID_PARAMETER; + + /* punt if invalid file */ + if (chd->file.callbacks == NULL) + return CHDERR_INVALID_FILE; + + /* read the start of the header */ + if (!seek_and_read(chd, 0, rawheader, 8 + 4 + 4)) + return CHDERR_READ_ERROR; + + /* verify the tag */ + if (memcmp(rawheader, "MComprHD", 8) != 0) + return CHDERR_INVALID_DATA; + + /* extract the direct data */ + memset(header, 0, sizeof(*header)); + header->length = get_bigendian_uint32_t(&rawheader[8]); + header->version = get_bigendian_uint32_t(&rawheader[12]); + + /* Unknown version */ + if (header->version == 0 || header->version > ARRAY_LENGTH(header_sizes)) + return CHDERR_UNSUPPORTED_VERSION; + + /* make sure the length is expected */ + if (header->length != header_sizes[header->version - 1]) + return CHDERR_INVALID_DATA; + + /* read the full header, now that we know its size */ + if (!seek_and_read(chd, 0, rawheader, header->length)) + return CHDERR_READ_ERROR; + + switch (header->version) + { + default: + /* Unknown version */ + return CHDERR_UNSUPPORTED_VERSION; + + case 1: + case 2: + header->flags = get_bigendian_uint32_t(&rawheader[16]); + header->compression[0] = get_bigendian_uint32_t(&rawheader[20]); + header->obsolete_hunksize = get_bigendian_uint32_t(&rawheader[24]); + header->totalhunks = get_bigendian_uint32_t(&rawheader[28]); + header->obsolete_cylinders = get_bigendian_uint32_t(&rawheader[32]); + header->obsolete_heads = get_bigendian_uint32_t(&rawheader[36]); + header->obsolete_sectors = get_bigendian_uint32_t(&rawheader[40]); + memcpy(header->md5, &rawheader[44], CHD_MD5_BYTES); + memcpy(header->parentmd5, &rawheader[60], CHD_MD5_BYTES); + { + uint32_t seclen = (header->version == 1) ? CHD_V1_SECTOR_SIZE : get_bigendian_uint32_t(&rawheader[76]); + header->logicalbytes = (uint64_t)header->obsolete_cylinders * (uint64_t)header->obsolete_heads * (uint64_t)header->obsolete_sectors * (uint64_t)seclen; + header->hunkbytes = seclen * header->obsolete_hunksize; + } + header->unitbytes = header_guess_unitbytes(chd); + if (header->unitbytes == 0) + return CHDERR_INVALID_DATA; + header->unitcount = (header->logicalbytes + header->unitbytes - 1) / header->unitbytes; + header->metaoffset = 0; + + break; + + case 3: + header->flags = get_bigendian_uint32_t(&rawheader[16]); + header->compression[0] = get_bigendian_uint32_t(&rawheader[20]); + header->totalhunks = get_bigendian_uint32_t(&rawheader[24]); + header->logicalbytes = get_bigendian_uint64_t(&rawheader[28]); + header->metaoffset = get_bigendian_uint64_t(&rawheader[36]); + memcpy(header->md5, &rawheader[44], CHD_MD5_BYTES); + memcpy(header->parentmd5, &rawheader[60], CHD_MD5_BYTES); + header->hunkbytes = get_bigendian_uint32_t(&rawheader[76]); + header->unitbytes = header_guess_unitbytes(chd); + if (header->unitbytes == 0) + return CHDERR_INVALID_DATA; + header->unitcount = (header->logicalbytes + header->unitbytes - 1) / header->unitbytes; + memcpy(header->sha1, &rawheader[80], CHD_SHA1_BYTES); + memcpy(header->parentsha1, &rawheader[100], CHD_SHA1_BYTES); + + break; + + case 4: + header->flags = get_bigendian_uint32_t(&rawheader[16]); + header->compression[0] = get_bigendian_uint32_t(&rawheader[20]); + header->totalhunks = get_bigendian_uint32_t(&rawheader[24]); + header->logicalbytes = get_bigendian_uint64_t(&rawheader[28]); + header->metaoffset = get_bigendian_uint64_t(&rawheader[36]); + header->hunkbytes = get_bigendian_uint32_t(&rawheader[44]); + header->unitbytes = header_guess_unitbytes(chd); + if (header->unitbytes == 0) + return CHDERR_INVALID_DATA; + header->unitcount = (header->logicalbytes + header->unitbytes - 1) / header->unitbytes; + memcpy(header->sha1, &rawheader[48], CHD_SHA1_BYTES); + memcpy(header->parentsha1, &rawheader[68], CHD_SHA1_BYTES); + memcpy(header->rawsha1, &rawheader[88], CHD_SHA1_BYTES); + + break; + + case 5: + header->compression[0] = get_bigendian_uint32_t(&rawheader[16]); + header->compression[1] = get_bigendian_uint32_t(&rawheader[20]); + header->compression[2] = get_bigendian_uint32_t(&rawheader[24]); + header->compression[3] = get_bigendian_uint32_t(&rawheader[28]); + header->logicalbytes = get_bigendian_uint64_t(&rawheader[32]); + header->mapoffset = get_bigendian_uint64_t(&rawheader[40]); + header->metaoffset = get_bigendian_uint64_t(&rawheader[48]); + header->hunkbytes = get_bigendian_uint32_t(&rawheader[56]); + if (header->hunkbytes == 0) + return CHDERR_INVALID_DATA; + header->hunkcount = (header->logicalbytes + header->hunkbytes - 1) / header->hunkbytes; + header->unitbytes = get_bigendian_uint32_t(&rawheader[60]); + if (header->unitbytes == 0) + return CHDERR_INVALID_DATA; + header->unitcount = (header->logicalbytes + header->unitbytes - 1) / header->unitbytes; + memcpy(header->sha1, &rawheader[84], CHD_SHA1_BYTES); + memcpy(header->parentsha1, &rawheader[104], CHD_SHA1_BYTES); + memcpy(header->rawsha1, &rawheader[64], CHD_SHA1_BYTES); + + /* determine properties of map entries */ + header->mapentrybytes = chd_compressed(header) ? 12 : 4; + + /* hack */ + header->totalhunks = header->hunkcount; + + break; + } + + /* Do not validate v5 header */ + if (header->version <= 4) + { + size_t intfnum; + + /* require valid flags */ + if (header->flags & CHDFLAGS_UNDEFINED) + return CHDERR_INVALID_DATA; + + /* require a supported compression mechanism */ + for (intfnum = 0; intfnum < ARRAY_LENGTH(codec_interfaces); intfnum++) + if (codec_interfaces[intfnum].compression == header->compression[0]) + break; + + if (intfnum == ARRAY_LENGTH(codec_interfaces)) + return CHDERR_INVALID_DATA; + + /* require a valid hunksize */ + if (header->hunkbytes == 0 || header->hunkbytes >= 65536 * 256) + return CHDERR_INVALID_DATA; + + /* require a valid hunk count */ + if (header->totalhunks == 0) + return CHDERR_INVALID_DATA; + + /* require a valid MD5 and/or SHA1 if we're using a parent */ + if ((header->flags & CHDFLAGS_HAS_PARENT) && memcmp(header->parentmd5, nullmd5, sizeof(nullmd5)) == 0 && memcmp(header->parentsha1, nullsha1, sizeof(nullsha1)) == 0) + return CHDERR_INVALID_DATA; + + /* if we're V3 or later, the obsolete fields must be 0 */ + if (header->version >= 3 && + (header->obsolete_cylinders != 0 || header->obsolete_sectors != 0 || + header->obsolete_heads != 0 || header->obsolete_hunksize != 0)) + return CHDERR_INVALID_DATA; + + /* if we're pre-V3, the obsolete fields must NOT be 0 */ + if (header->version < 3 && + (header->obsolete_cylinders == 0 || header->obsolete_sectors == 0 || + header->obsolete_heads == 0 || header->obsolete_hunksize == 0)) + return CHDERR_INVALID_DATA; + } + + /* some basic size checks to prevent huge mallocs */ + if (header->hunkbytes >= CHD_MAX_HUNK_SIZE || ((uint64_t)header->hunkbytes * (uint64_t)header->totalhunks) >= CHD_MAX_FILE_SIZE) + return CHDERR_INVALID_DATA; + + /* guess it worked */ + return CHDERR_NONE; +} + +/*************************************************************************** + INTERNAL HUNK READ/WRITE +***************************************************************************/ + +/*------------------------------------------------- + hunk_read_compressed - read a compressed + hunk +-------------------------------------------------*/ + +static uint8_t* hunk_read_compressed(chd_file *chd, uint64_t offset, size_t size) +{ + if (chd->file_cache != NULL) + { + if ((offset + size) > chd->file_size || (offset + size) < offset) + return NULL; + else + return chd->file_cache + offset; + } + else + { + /* make sure it isn't larger than the compressed buffer */ + if (size > chd->header.hunkbytes) + return NULL; + + if (!seek_and_read(chd, offset, chd->compressed, size)) + return NULL; + return chd->compressed; + } +} + +/*------------------------------------------------- + hunk_read_uncompressed - read an uncompressed + hunk +-------------------------------------------------*/ + +static chd_error hunk_read_uncompressed(chd_file *chd, uint64_t offset, size_t size, uint8_t *dest) +{ + if (chd->file_cache != NULL) + { + if ((offset + size) > chd->file_size || (offset + size) < offset) + return CHDERR_READ_ERROR; + + memcpy(dest, chd->file_cache + offset, size); + } + else + { + if (!seek_and_read(chd, offset, dest, size)) + return CHDERR_READ_ERROR; + } + return CHDERR_NONE; +} + +/*------------------------------------------------- + hunk_read_into_memory - read a hunk into + memory at the given location +-------------------------------------------------*/ + +static chd_error hunk_read_into_memory(chd_file *chd, uint32_t hunknum, uint8_t *dest) +{ + chd_error err; + + /* punt if no file */ + if (chd->file.callbacks == NULL) + return CHDERR_INVALID_FILE; + + /* return an error if out of range */ + if (hunknum >= chd->header.totalhunks) + return CHDERR_HUNK_OUT_OF_RANGE; + + if (dest == NULL) + return CHDERR_INVALID_PARAMETER; + + if (chd->header.version < 5) + { + map_entry *entry = &chd->map[hunknum]; + uint32_t bytes; + uint8_t* compressed_bytes; + + /* switch off the entry type */ + switch (entry->flags & MAP_ENTRY_FLAG_TYPE_MASK) + { + /* compressed data */ + case V34_MAP_ENTRY_TYPE_COMPRESSED: + { + void *codec = NULL; + + /* read it into the decompression buffer */ + compressed_bytes = hunk_read_compressed(chd, entry->offset, entry->length); + if (compressed_bytes == NULL) + return CHDERR_READ_ERROR; + + /* now decompress using the codec */ + err = CHDERR_NONE; + codec = &chd->codec_data.zlib; + if (chd->codecintf[0]->decompress != NULL) + err = chd->codecintf[0]->decompress(codec, compressed_bytes, entry->length, dest, chd->header.hunkbytes); + if (err != CHDERR_NONE) + return err; + break; + } + + /* uncompressed data */ + case V34_MAP_ENTRY_TYPE_UNCOMPRESSED: + err = hunk_read_uncompressed(chd, entry->offset, chd->header.hunkbytes, dest); + if (err != CHDERR_NONE) + return err; + break; + + /* mini-compressed data */ + case V34_MAP_ENTRY_TYPE_MINI: + put_bigendian_uint64_t(&dest[0], entry->offset); + for (bytes = 8; bytes < chd->header.hunkbytes; bytes++) + dest[bytes] = dest[bytes - 8]; + break; + + /* self-referenced data */ + case V34_MAP_ENTRY_TYPE_SELF_HUNK: + return hunk_read_into_memory(chd, entry->offset, dest); + + /* parent-referenced data */ + case V34_MAP_ENTRY_TYPE_PARENT_HUNK: + err = hunk_read_into_memory(chd->parent, entry->offset, dest); + if (err != CHDERR_NONE) + return err; + break; + } + return CHDERR_NONE; + } + else + { + void* codec = NULL; + /* get a pointer to the map entry */ + uint64_t blockoffs; + uint32_t blocklen; +#if VERIFY_BLOCK_CRC + uint16_t blockcrc; +#endif + uint8_t *rawmap = &chd->header.rawmap[chd->header.mapentrybytes * hunknum]; + uint8_t* compressed_bytes; + + /* uncompressed case */ + if (!chd_compressed(&chd->header)) + { + blockoffs = (uint64_t)get_bigendian_uint32_t(rawmap) * (uint64_t)chd->header.hunkbytes; + if (blockoffs != 0) { + if (!seek_and_read(chd, blockoffs, dest, chd->header.hunkbytes)) + return CHDERR_READ_ERROR; + /* TODO + else if (m_parent_missing) + throw CHDERR_REQUIRES_PARENT; */ + } else if (chd->parent) { + err = hunk_read_into_memory(chd->parent, hunknum, dest); + if (err != CHDERR_NONE) + return err; + } else { + memset(dest, 0, chd->header.hunkbytes); + } + + return CHDERR_NONE; + } + + /* compressed case */ + blocklen = get_bigendian_uint24(&rawmap[1]); + blockoffs = get_bigendian_uint48(&rawmap[4]); +#if VERIFY_BLOCK_CRC + blockcrc = get_bigendian_uint16(&rawmap[10]); +#endif + codec = NULL; + switch (rawmap[0]) + { + case COMPRESSION_TYPE_0: + case COMPRESSION_TYPE_1: + case COMPRESSION_TYPE_2: + case COMPRESSION_TYPE_3: + compressed_bytes = hunk_read_compressed(chd, blockoffs, blocklen); + if (compressed_bytes == NULL) + return CHDERR_READ_ERROR; + switch (chd->codecintf[rawmap[0]]->compression) + { + case CHD_CODEC_ZLIB: + codec = &chd->codec_data.zlib; + break; + + case CHD_CODEC_LZMA: + codec = &chd->codec_data.lzma; + break; + + case CHD_CODEC_HUFFMAN: + codec = &chd->codec_data.huff; + break; + + case CHD_CODEC_FLAC: + codec = &chd->codec_data.flac; + break; + + case CHD_CODEC_ZSTD: + codec = &chd->codec_data.zstd; + break; + + case CHD_CODEC_CD_ZLIB: + codec = &chd->codec_data.cdzl; + break; + + case CHD_CODEC_CD_LZMA: + codec = &chd->codec_data.cdlz; + break; + + case CHD_CODEC_CD_FLAC: + codec = &chd->codec_data.cdfl; + break; + + case CHD_CODEC_CD_ZSTD: + codec = &chd->codec_data.cdzs; + break; + } + if (codec==NULL) + return CHDERR_CODEC_ERROR; + err = chd->codecintf[rawmap[0]]->decompress(codec, compressed_bytes, blocklen, dest, chd->header.hunkbytes); + if (err != CHDERR_NONE) + return err; +#if VERIFY_BLOCK_CRC + if (crc16(dest, chd->header.hunkbytes) != blockcrc) + return CHDERR_DECOMPRESSION_ERROR; +#endif + return CHDERR_NONE; + + case COMPRESSION_NONE: + err = hunk_read_uncompressed(chd, blockoffs, blocklen, dest); + if (err != CHDERR_NONE) + return err; +#if VERIFY_BLOCK_CRC + if (crc16(dest, chd->header.hunkbytes) != blockcrc) + return CHDERR_DECOMPRESSION_ERROR; +#endif + return CHDERR_NONE; + + case COMPRESSION_SELF: + return hunk_read_into_memory(chd, blockoffs, dest); + + case COMPRESSION_PARENT: + { + uint8_t units_in_hunk; + + if (chd->parent == NULL) + return CHDERR_REQUIRES_PARENT; + units_in_hunk = chd->header.hunkbytes / chd->header.unitbytes; + + /* blockoffs is aligned to units_in_hunk */ + if (blockoffs % units_in_hunk == 0) { + return hunk_read_into_memory(chd->parent, blockoffs / units_in_hunk, dest); + /* blockoffs is not aligned to units_in_hunk */ + } else { + uint32_t unit_in_hunk = blockoffs % units_in_hunk; + uint8_t *buf = (uint8_t*)malloc(chd->header.hunkbytes); + /* Read first half of hunk which contains blockoffs */ + err = hunk_read_into_memory(chd->parent, blockoffs / units_in_hunk, buf); + if (err != CHDERR_NONE) { + free(buf); + return err; + } + memcpy(dest, buf + unit_in_hunk * chd->header.unitbytes, (units_in_hunk - unit_in_hunk) * chd->header.unitbytes); + /* Read second half of hunk which contains blockoffs */ + err = hunk_read_into_memory(chd->parent, (blockoffs / units_in_hunk) + 1, buf); + if (err != CHDERR_NONE) { + free(buf); + return err; + } + memcpy(dest + (units_in_hunk - unit_in_hunk) * chd->header.unitbytes, buf, unit_in_hunk * chd->header.unitbytes); + free(buf); + } + break; + } + } + return CHDERR_NONE; + } + + /* We should not reach this code */ + return CHDERR_DECOMPRESSION_ERROR; +} + +/*************************************************************************** + INTERNAL MAP ACCESS +***************************************************************************/ + +/*------------------------------------------------- + map_read - read the initial sector map +-------------------------------------------------*/ + +static chd_error map_read(chd_file *chd) +{ + uint32_t entrysize = (chd->header.version < 3) ? OLD_MAP_ENTRY_SIZE : MAP_ENTRY_SIZE; + uint8_t raw_map_entries[MAP_STACK_ENTRIES * MAP_ENTRY_SIZE]; + uint64_t fileoffset, maxoffset = 0; + uint8_t cookie[MAP_ENTRY_SIZE]; + chd_error err; + uint32_t i; + + /* first allocate memory */ + chd->map = (map_entry *)malloc(sizeof(chd->map[0]) * chd->header.totalhunks); + if (!chd->map) + return CHDERR_OUT_OF_MEMORY; + + /* read the map entries in in chunks and extract to the map list */ + fileoffset = chd->header.length; + for (i = 0; i < chd->header.totalhunks; i += MAP_STACK_ENTRIES) + { + /* compute how many entries this time */ + int entries = chd->header.totalhunks - i, j; + if (entries > MAP_STACK_ENTRIES) + entries = MAP_STACK_ENTRIES; + + /* read that many */ + if (!seek_and_read(chd, fileoffset, raw_map_entries, entries * entrysize)) + EARLY_EXIT(err = CHDERR_READ_ERROR); + fileoffset += entries * entrysize; + + /* process that many */ + if (entrysize == MAP_ENTRY_SIZE) + { + for (j = 0; j < entries; j++) + map_extract(&raw_map_entries[j * MAP_ENTRY_SIZE], &chd->map[i + j]); + } + else + { + for (j = 0; j < entries; j++) + map_extract_old(&raw_map_entries[j * OLD_MAP_ENTRY_SIZE], &chd->map[i + j], chd->header.hunkbytes); + } + + /* track the maximum offset */ + for (j = 0; j < entries; j++) + if ((chd->map[i + j].flags & MAP_ENTRY_FLAG_TYPE_MASK) == V34_MAP_ENTRY_TYPE_COMPRESSED || + (chd->map[i + j].flags & MAP_ENTRY_FLAG_TYPE_MASK) == V34_MAP_ENTRY_TYPE_UNCOMPRESSED) + maxoffset = MAX(maxoffset, chd->map[i + j].offset + chd->map[i + j].length); + } + + /* verify the cookie */ + if (!seek_and_read(chd, fileoffset, &cookie, entrysize) || memcmp(&cookie, END_OF_LIST_COOKIE, entrysize)) + EARLY_EXIT(err = CHDERR_INVALID_FILE); + + /* verify the length */ + if (maxoffset > chd->file_size) + EARLY_EXIT(err = CHDERR_INVALID_FILE); + return CHDERR_NONE; + +cleanup: + if (chd->map) + free(chd->map); + chd->map = NULL; + return err; +} + +/*************************************************************************** + INTERNAL METADATA ACCESS +***************************************************************************/ + +/*------------------------------------------------- + metadata_find_entry - find a metadata entry +-------------------------------------------------*/ + +static chd_error metadata_find_entry(chd_file *chd, uint32_t metatag, uint32_t metaindex, metadata_entry *metaentry) +{ + /* start at the beginning */ + metaentry->offset = chd->header.metaoffset; + metaentry->prev = 0; + + /* loop until we run out of options */ + while (metaentry->offset != 0) + { + uint8_t raw_meta_header[METADATA_HEADER_SIZE]; + + /* read the raw header */ + if (!seek_and_read(chd, metaentry->offset, raw_meta_header, sizeof(raw_meta_header))) + break; + + /* extract the data */ + metaentry->metatag = get_bigendian_uint32_t(&raw_meta_header[0]); + metaentry->length = get_bigendian_uint32_t(&raw_meta_header[4]); + metaentry->next = get_bigendian_uint64_t(&raw_meta_header[8]); + + /* flags are encoded in the high byte of length */ + metaentry->flags = metaentry->length >> 24; + metaentry->length &= 0x00ffffff; + + /* if we got a match, proceed */ + if (metatag == CHDMETATAG_WILDCARD || metaentry->metatag == metatag) + if (metaindex-- == 0) + return CHDERR_NONE; + + /* no match, fetch the next link */ + metaentry->prev = metaentry->offset; + metaentry->offset = metaentry->next; + } + + /* if we get here, we didn't find it */ + return CHDERR_METADATA_NOT_FOUND; +} + +/*************************************************************************** + CORE FILE +***************************************************************************/ + +/*------------------------------------------------- + core_stdio_fopen - core_file wrapper over fopen +-------------------------------------------------*/ +static void *core_stdio_fopen(char const *path) { + return filestream_open(path, + RETRO_VFS_FILE_ACCESS_READ, + RETRO_VFS_FILE_ACCESS_HINT_NONE); +} + +/*------------------------------------------------- + core_stdio_fsize - core_file function for + getting file size with stdio +-------------------------------------------------*/ +static uint64_t core_stdio_fsize(void *file) { + RFILE *fp = (RFILE*)file; + int64_t p, rv; + + p = filestream_tell(fp); + filestream_seek(fp, 0, SEEK_END); + rv = filestream_tell(fp); + filestream_seek(fp, p, SEEK_SET); + return (uint64_t)rv; +} + +/*------------------------------------------------- + core_stdio_fread - core_file wrapper over fread +-------------------------------------------------*/ +static size_t core_stdio_fread(void *ptr, size_t size, size_t nmemb, void *file) { + return (size_t)filestream_read((RFILE*)file, ptr, size * nmemb) / (size ? size : 1); +} + +/*------------------------------------------------- + core_stdio_fclose - core_file wrapper over fclose +-------------------------------------------------*/ +static int core_stdio_fclose(void *file) { + return filestream_close((RFILE*)file); +} + +/*------------------------------------------------- + core_stdio_fclose_nonowner - don't call fclose because + we don't own the underlying file. +-------------------------------------------------*/ +static int core_stdio_fclose_nonowner(void *file) { + (void)file; + return 0; +} + +/*------------------------------------------------- + core_stdio_fseek - core_file wrapper over fclose +-------------------------------------------------*/ +static int core_stdio_fseek(void* file, int64_t offset, int whence) { + return (filestream_seek((RFILE*)file, offset, whence) < 0) ? -1 : 0; +} + +/*------------------------------------------------- + core_legacy_fsize - legacy core_file wrapper +-------------------------------------------------*/ +static uint64_t core_legacy_fsize(void *file) { + core_file* const core = (core_file*)file; + return core->fsize(core); +} + +/*------------------------------------------------- + core_legacy_fread - legacy core_file wrapper +-------------------------------------------------*/ +static size_t core_legacy_fread(void *ptr, size_t size, size_t nmemb, void *file) { + core_file* const core = (core_file*)file; + return core->fread(ptr, size, nmemb, core); +} + +/*------------------------------------------------- + core_legacy_fclose - legacy core_file wrapper +-------------------------------------------------*/ +static int core_legacy_fclose(void *file) { + core_file* const core = (core_file*)file; + return core->fclose(core); +} + +/*------------------------------------------------- + core_legacy_fseek - legacy core_file wrapper +-------------------------------------------------*/ +static int core_legacy_fseek(void* file, int64_t offset, int whence) { + core_file* const core = (core_file*)file; + return core->fseek(core, offset, whence); +} diff --git a/libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_cdfl.c b/libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_cdfl.c new file mode 100644 index 000000000..2c6ece9d7 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_cdfl.c @@ -0,0 +1,100 @@ +#include "../include/libchdr/codec_cdfl.h" + +#include +#include +#include + +#include "../include/libchdr/cdrom.h" + +static uint32_t cdfl_codec_blocksize(uint32_t bytes) +{ + /* for CDs it seems that CD_MAX_SECTOR_DATA is the right target */ + uint32_t blocksize = bytes / 4; + while (blocksize > CD_MAX_SECTOR_DATA) + blocksize /= 2; + return blocksize; +} + +chd_error cdfl_codec_init(void *codec, uint32_t hunkbytes) +{ +#if WANT_SUBCODE + chd_error ret; +#endif + cdfl_codec_data *cdfl = (cdfl_codec_data*)codec; + + /* make sure the CHD's hunk size is an even multiple of the frame size */ + if (hunkbytes % CD_FRAME_SIZE != 0) + return CHDERR_CODEC_ERROR; + + cdfl->buffer = (uint8_t*)malloc(sizeof(uint8_t) * hunkbytes); + if (cdfl->buffer == NULL) + return CHDERR_OUT_OF_MEMORY; + + /* determine whether we want native or swapped samples */ + cdfl->swap_endian = flac_decoder_detect_native_endian(); + +#if WANT_SUBCODE + /* init zlib inflater */ + ret = zlib_codec_init(&cdfl->subcode_decompressor, (hunkbytes / CD_FRAME_SIZE) * CD_MAX_SECTOR_DATA); + if (ret != CHDERR_NONE) + return ret; +#endif + + /* flac decoder init */ + if (flac_decoder_init(&cdfl->decoder)) + return CHDERR_OUT_OF_MEMORY; + + return CHDERR_NONE; +} + +void cdfl_codec_free(void *codec) +{ + cdfl_codec_data *cdfl = (cdfl_codec_data*)codec; + flac_decoder_free(&cdfl->decoder); +#if WANT_SUBCODE + zlib_codec_free(&cdfl->subcode_decompressor); +#endif + if (cdfl->buffer) + free(cdfl->buffer); +} + +chd_error cdfl_codec_decompress(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen) +{ + uint32_t framenum; + uint8_t *buffer; +#if WANT_SUBCODE + uint32_t offset; + chd_error ret; +#endif + cdfl_codec_data *cdfl = (cdfl_codec_data*)codec; + + /* reset and decode */ + uint32_t frames = destlen / CD_FRAME_SIZE; + + if (!flac_decoder_reset(&cdfl->decoder, 44100, 2, cdfl_codec_blocksize(frames * CD_MAX_SECTOR_DATA), src, complen)) + return CHDERR_DECOMPRESSION_ERROR; + buffer = &cdfl->buffer[0]; + if (!flac_decoder_decode_interleaved(&cdfl->decoder, (int16_t *)(buffer), frames * CD_MAX_SECTOR_DATA/4, cdfl->swap_endian)) + return CHDERR_DECOMPRESSION_ERROR; + +#if WANT_SUBCODE + /* inflate the subcode data */ + offset = flac_decoder_finish(&cdfl->decoder); + ret = zlib_codec_decompress(&cdfl->subcode_decompressor, src + offset, complen - offset, &cdfl->buffer[frames * CD_MAX_SECTOR_DATA], frames * CD_MAX_SUBCODE_DATA); + if (ret != CHDERR_NONE) + return ret; +#else + flac_decoder_finish(&cdfl->decoder); +#endif + + /* reassemble the data */ + for (framenum = 0; framenum < frames; framenum++) + { + memcpy(&dest[framenum * CD_FRAME_SIZE], &cdfl->buffer[framenum * CD_MAX_SECTOR_DATA], CD_MAX_SECTOR_DATA); +#if WANT_SUBCODE + memcpy(&dest[framenum * CD_FRAME_SIZE + CD_MAX_SECTOR_DATA], &cdfl->buffer[frames * CD_MAX_SECTOR_DATA + framenum * CD_MAX_SUBCODE_DATA], CD_MAX_SUBCODE_DATA); +#endif + } + + return CHDERR_NONE; +} diff --git a/libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_cdlz.c b/libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_cdlz.c new file mode 100644 index 000000000..c975974ad --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_cdlz.c @@ -0,0 +1,57 @@ +#include "../include/libchdr/codec_cdlz.h" + +#include +#include +#include + +#include "../include/libchdr/cdrom.h" + +chd_error cdlz_codec_init(void* codec, uint32_t hunkbytes) +{ + chd_error ret; + cdlz_codec_data* cdlz = (cdlz_codec_data*) codec; + + /* allocate buffer */ + cdlz->buffer = (uint8_t*)malloc(sizeof(uint8_t) * hunkbytes); + if (cdlz->buffer == NULL) + return CHDERR_OUT_OF_MEMORY; + + /* make sure the CHD's hunk size is an even multiple of the frame size */ + ret = lzma_codec_init(&cdlz->base_decompressor, (hunkbytes / CD_FRAME_SIZE) * CD_MAX_SECTOR_DATA); + if (ret != CHDERR_NONE) + return ret; + +#if WANT_SUBCODE + ret = zlib_codec_init(&cdlz->subcode_decompressor, (hunkbytes / CD_FRAME_SIZE) * CD_MAX_SUBCODE_DATA); + if (ret != CHDERR_NONE) + return ret; +#endif + + if (hunkbytes % CD_FRAME_SIZE != 0) + return CHDERR_CODEC_ERROR; + + return CHDERR_NONE; +} + +void cdlz_codec_free(void* codec) +{ + cdlz_codec_data* cdlz = (cdlz_codec_data*) codec; + free(cdlz->buffer); + lzma_codec_free(&cdlz->base_decompressor); +#if WANT_SUBCODE + zlib_codec_free(&cdlz->subcode_decompressor); +#endif +} + +chd_error cdlz_codec_decompress(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen) +{ + cdlz_codec_data* cdlz = (cdlz_codec_data*)codec; + + return cd_codec_decompress(cdlz->buffer, + &cdlz->base_decompressor, lzma_codec_decompress, +#if WANT_SUBCODE + &cdlz->subcode_decompressor, zlib_codec_decompress, +#endif + src, complen, dest, destlen + ); +} diff --git a/libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_cdzl.c b/libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_cdzl.c new file mode 100644 index 000000000..2c8164e69 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_cdzl.c @@ -0,0 +1,56 @@ +#include "../include/libchdr/codec_cdzl.h" + +#include +#include +#include + +#include "../include/libchdr/cdrom.h" + +chd_error cdzl_codec_init(void *codec, uint32_t hunkbytes) +{ + chd_error ret; + cdzl_codec_data* cdzl = (cdzl_codec_data*)codec; + + /* make sure the CHD's hunk size is an even multiple of the frame size */ + if (hunkbytes % CD_FRAME_SIZE != 0) + return CHDERR_CODEC_ERROR; + + cdzl->buffer = (uint8_t*)malloc(sizeof(uint8_t) * hunkbytes); + if (cdzl->buffer == NULL) + return CHDERR_OUT_OF_MEMORY; + + ret = zlib_codec_init(&cdzl->base_decompressor, (hunkbytes / CD_FRAME_SIZE) * CD_MAX_SECTOR_DATA); + if (ret != CHDERR_NONE) + return ret; + +#if WANT_SUBCODE + ret = zlib_codec_init(&cdzl->subcode_decompressor, (hunkbytes / CD_FRAME_SIZE) * CD_MAX_SUBCODE_DATA); + if (ret != CHDERR_NONE) + return ret; +#endif + + return CHDERR_NONE; +} + +void cdzl_codec_free(void *codec) +{ + cdzl_codec_data* cdzl = (cdzl_codec_data*)codec; + zlib_codec_free(&cdzl->base_decompressor); +#if WANT_SUBCODE + zlib_codec_free(&cdzl->subcode_decompressor); +#endif + free(cdzl->buffer); +} + +chd_error cdzl_codec_decompress(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen) +{ + cdzl_codec_data* cdzl = (cdzl_codec_data*)codec; + + return cd_codec_decompress(cdzl->buffer, + &cdzl->base_decompressor, zlib_codec_decompress, +#if WANT_SUBCODE + &cdzl->subcode_decompressor, zlib_codec_decompress, +#endif + src, complen, dest, destlen + ); +} diff --git a/libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_cdzs.c b/libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_cdzs.c new file mode 100644 index 000000000..503082720 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_cdzs.c @@ -0,0 +1,57 @@ +#include "../include/libchdr/codec_cdzs.h" + +#include +#include +#include + +#include "../include/libchdr/cdrom.h" + +chd_error cdzs_codec_init(void* codec, uint32_t hunkbytes) +{ + chd_error ret; + cdzs_codec_data* cdzs = (cdzs_codec_data*) codec; + + /* allocate buffer */ + cdzs->buffer = (uint8_t*)malloc(sizeof(uint8_t) * hunkbytes); + if (cdzs->buffer == NULL) + return CHDERR_OUT_OF_MEMORY; + + /* make sure the CHD's hunk size is an even multiple of the frame size */ + ret = zstd_codec_init(&cdzs->base_decompressor, (hunkbytes / CD_FRAME_SIZE) * CD_MAX_SECTOR_DATA); + if (ret != CHDERR_NONE) + return ret; + +#if WANT_SUBCODE + ret = zstd_codec_init(&cdzs->subcode_decompressor, (hunkbytes / CD_FRAME_SIZE) * CD_MAX_SUBCODE_DATA); + if (ret != CHDERR_NONE) + return ret; +#endif + + if (hunkbytes % CD_FRAME_SIZE != 0) + return CHDERR_CODEC_ERROR; + + return CHDERR_NONE; +} + +void cdzs_codec_free(void* codec) +{ + cdzs_codec_data* cdzs = (cdzs_codec_data*) codec; + free(cdzs->buffer); + zstd_codec_free(&cdzs->base_decompressor); +#if WANT_SUBCODE + zstd_codec_free(&cdzs->subcode_decompressor); +#endif +} + +chd_error cdzs_codec_decompress(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen) +{ + cdzs_codec_data* cdzs = (cdzs_codec_data*)codec; + + return cd_codec_decompress(cdzs->buffer, + &cdzs->base_decompressor, zstd_codec_decompress, +#if WANT_SUBCODE + &cdzs->subcode_decompressor, zstd_codec_decompress, +#endif + src, complen, dest, destlen + ); +} diff --git a/libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_flac.c b/libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_flac.c new file mode 100644 index 000000000..61752cb2e --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_flac.c @@ -0,0 +1,65 @@ +#include "../include/libchdr/codec_flac.h" + +#include +#include +#include + +/*------------------------------------------------------ + * flac_codec_blocksize - return the optimal block size + *------------------------------------------------------ + */ + +static uint32_t flac_codec_blocksize(uint32_t bytes) +{ + /* determine FLAC block size, which must be 16-65535 + * clamp to 2k since that's supposed to be the sweet spot */ + uint32_t blocksize = bytes / 4; + while (blocksize > 2048) + blocksize /= 2; + return blocksize; +} + +chd_error flac_codec_init(void *codec, uint32_t hunkbytes) +{ + flac_codec_data *flac = (flac_codec_data*)codec; + + /* make sure the CHD's hunk size is an even multiple of the sample size */ + if (hunkbytes % 4 != 0) + return CHDERR_CODEC_ERROR; + + /* determine whether we want native or swapped samples */ + flac->native_endian = flac_decoder_detect_native_endian(); + + /* flac decoder init */ + if (flac_decoder_init(&flac->decoder)) + return CHDERR_OUT_OF_MEMORY; + + return CHDERR_NONE; +} + +void flac_codec_free(void *codec) +{ + flac_codec_data *flac = (flac_codec_data*)codec; + flac_decoder_free(&flac->decoder); +} + +chd_error flac_codec_decompress(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen) +{ + flac_codec_data *flac = (flac_codec_data*)codec; + int swap_endian; + + if (src[0] == 'L') + swap_endian = !flac->native_endian; + else if (src[0] == 'B') + swap_endian = flac->native_endian; + else + return CHDERR_DECOMPRESSION_ERROR; + + if (!flac_decoder_reset(&flac->decoder, 44100, 2, flac_codec_blocksize(destlen), src + 1, complen - 1)) + return CHDERR_DECOMPRESSION_ERROR; + if (!flac_decoder_decode_interleaved(&flac->decoder, (int16_t *)(dest), destlen/4, swap_endian)) + return CHDERR_DECOMPRESSION_ERROR; + flac_decoder_finish(&flac->decoder); + + return CHDERR_NONE; +} diff --git a/libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_huff.c b/libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_huff.c new file mode 100644 index 000000000..c5dc34fb5 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_huff.c @@ -0,0 +1,46 @@ +#include "../include/libchdr/codec_huff.h" + +#include +#include +#include + +#include "../include/libchdr/huffman.h" + +chd_error huff_codec_init(void* codec, uint32_t hunkbytes) +{ + huff_codec_data* huff_codec = (huff_codec_data*) codec; + (void)hunkbytes; + huff_codec->decoder = create_huffman_decoder(256, 16); + return CHDERR_NONE; +} + +void huff_codec_free(void *codec) +{ + huff_codec_data* huff_codec = (huff_codec_data*) codec; + delete_huffman_decoder(huff_codec->decoder); +} + +chd_error huff_codec_decompress(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen) +{ + huff_codec_data* huff_codec = (huff_codec_data*) codec; + struct bitstream* bitbuf = create_bitstream(src, complen); + uint32_t cur; + chd_error result; + + /* first import the tree */ + enum huffman_error err = huffman_import_tree_huffman(huff_codec->decoder, bitbuf); + if (err != HUFFERR_NONE) + { + free(bitbuf); + return CHDERR_DECOMPRESSION_ERROR; + } + + /* then decode the data */ + for (cur = 0; cur < destlen; cur++) + dest[cur] = huffman_decode_one(huff_codec->decoder, bitbuf); + bitstream_flush(bitbuf); + result = bitstream_overflow(bitbuf) ? CHDERR_DECOMPRESSION_ERROR : CHDERR_NONE; + + free(bitbuf); + return result; +} diff --git a/libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_lzma.c b/libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_lzma.c new file mode 100644 index 000000000..3646f3a88 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_lzma.c @@ -0,0 +1,266 @@ +#include "../include/libchdr/codec_lzma.h" + +#include +#include +#include + +/*************************************************************************** + * LZMA ALLOCATOR HELPER + *************************************************************************** + */ + +static void *lzma_fast_alloc(void *p, size_t size); +static void lzma_fast_free(void *p, void *address); + +/*------------------------------------------------- + * lzma_allocator_init + *------------------------------------------------- + */ + +static void lzma_allocator_init(void* p) +{ + lzma_allocator *codec = (lzma_allocator *)(p); + + /* reset pointer list */ + memset(codec->allocptr, 0, sizeof(codec->allocptr)); + memset(codec->allocptr2, 0, sizeof(codec->allocptr2)); + codec->Alloc = lzma_fast_alloc; + codec->Free = lzma_fast_free; +} + +/*------------------------------------------------- + * lzma_allocator_free + *------------------------------------------------- + */ + +static void lzma_allocator_free(void* p ) +{ + int i; + lzma_allocator *codec = (lzma_allocator *)(p); + + /* free our memory */ + for (i = 0 ; i < MAX_LZMA_ALLOCS ; i++) + { + if (codec->allocptr[i] != NULL) + free(codec->allocptr[i]); + } +} + +/*------------------------------------------------- + * lzma_fast_alloc - fast malloc for lzma, which + * allocates and frees memory frequently + *------------------------------------------------- + */ + +/* Huge alignment values for possible SIMD optimization by compiler (NEON, SSE, AVX) */ +#define LZMA_MIN_ALIGNMENT_BITS 512 +#define LZMA_MIN_ALIGNMENT_BYTES (LZMA_MIN_ALIGNMENT_BITS / 8) + +static void *lzma_fast_alloc(void *p, size_t size) +{ + int scan; + uint32_t *addr = NULL; + lzma_allocator *codec = (lzma_allocator *)(p); + uintptr_t vaddr = 0; + + /* compute the size, rounding to the nearest 1k */ + size = (size + 0x3ff) & ~0x3ff; + + /* reuse a hunk if we can */ + for (scan = 0; scan < MAX_LZMA_ALLOCS; scan++) + { + uint32_t *ptr = codec->allocptr[scan]; + if (ptr != NULL && size == *ptr) + { + /* set the low bit of the size so we don't match next time */ + *ptr |= 1; + + /* return aligned address of the block */ + return codec->allocptr2[scan]; + } + } + + /* alloc a new one and put it into the list */ + addr = (uint32_t *)malloc(size + sizeof(uint32_t) + LZMA_MIN_ALIGNMENT_BYTES); + if (addr==NULL) + return NULL; + for (scan = 0; scan < MAX_LZMA_ALLOCS; scan++) + { + if (codec->allocptr[scan] == NULL) + { + /* store block address */ + codec->allocptr[scan] = addr; + + /* compute aligned address, store it */ + vaddr = (uintptr_t)addr; + vaddr = (vaddr + sizeof(uint32_t) + (LZMA_MIN_ALIGNMENT_BYTES-1)) & (~(LZMA_MIN_ALIGNMENT_BYTES-1)); + codec->allocptr2[scan] = (uint32_t*)vaddr; + break; + } + } + + /* set the low bit of the size so we don't match next time */ + *addr = size | 1; + + /* return aligned address */ + return (void*)vaddr; +} + +/*------------------------------------------------- + * lzma_fast_free - fast free for lzma, which + * allocates and frees memory frequently + *------------------------------------------------- + */ + +static void lzma_fast_free(void *p, void *address) +{ + int scan; + uint32_t *ptr = NULL; + lzma_allocator *codec = NULL; + + if (address == NULL) + return; + + codec = (lzma_allocator *)(p); + + /* find the hunk */ + ptr = (uint32_t *)address; + for (scan = 0; scan < MAX_LZMA_ALLOCS; scan++) + { + if (ptr == codec->allocptr2[scan]) + { + /* clear the low bit of the size to allow matches */ + *codec->allocptr[scan] &= ~1; + return; + } + } +} + +/*************************************************************************** + * LZMA DECOMPRESSOR + *************************************************************************** + */ + +/*------------------------------------------------- + * lzma_compute_aligned_dictionary_size + * Based on LzmaEncProps_Normalize, LzmaEnc_SetProps, LzmaEnc_WriteProperties. + *------------------------------------------------- + */ + +static uint32_t lzma_compute_aligned_dictionary_size(uint32_t hunkbytes) +{ + const unsigned int level = 9; + const uint32_t reduceSize = hunkbytes; + + uint32_t dictSize, alignedDictSize; + + /* LzmaEncProps_Normalize */ + dictSize = level <= 4 ? + (uint32_t)1 << (level * 2 + 16) : + level <= sizeof(size_t) / 2 + 4 ? + (uint32_t)1 << (level + 20) : + (uint32_t)1 << (sizeof(size_t) / 2 + 24); + + if (dictSize > reduceSize) + { + const uint32_t kReduceMin = (uint32_t)1 << 12; + const uint32_t max = MIN(kReduceMin, reduceSize); + + dictSize = MAX(max, dictSize); + } + + /* LzmaEnc_SetProps */ + dictSize = MIN((uint32_t)15 << 28, dictSize); /* kLzmaMaxHistorySize */ + + /* LzmaEnc_WriteProperties */ + /* we write aligned dictionary value to properties for lzma decoder */ + if (dictSize >= ((uint32_t)1 << 21)) + { + const uint32_t kDictMask = ((uint32_t)1 << 20) - 1; + + alignedDictSize = (dictSize + kDictMask) & ~kDictMask; + alignedDictSize = MIN(dictSize, alignedDictSize); + } + else + { + unsigned int i = 11 * 2; + + do + { + alignedDictSize = (uint32_t)(2 + (i & 1)) << (i >> 1); + i++; + } + while (alignedDictSize < dictSize); + } + + return alignedDictSize; +} + +/*------------------------------------------------- + * lzma_codec_init - constructor + *------------------------------------------------- + */ + +chd_error lzma_codec_init(void* codec, uint32_t hunkbytes) +{ + lzma_codec_data* lzma_codec = (lzma_codec_data*) codec; + lzma_allocator* alloc = &lzma_codec->allocator; + const uint32_t alignedDictSize = lzma_compute_aligned_dictionary_size(hunkbytes); + + unsigned int i; + Byte decoder_props[LZMA_PROPS_SIZE]; + + decoder_props[0] = 93; + for (i = 0; i < LZMA_PROPS_SIZE - 1; ++i) + decoder_props[1 + i] = (alignedDictSize >> (8 * i)) & 0xFF; + + lzma_allocator_init(alloc); + + /* construct the decoder */ + LzmaDec_Construct(&lzma_codec->decoder); + + /* do memory allocations */ + if (LzmaDec_Allocate(&lzma_codec->decoder, decoder_props, LZMA_PROPS_SIZE, (ISzAlloc*)alloc) != SZ_OK) + return CHDERR_DECOMPRESSION_ERROR; + + /* Okay */ + return CHDERR_NONE; +} + +/*------------------------------------------------- + * lzma_codec_free + *------------------------------------------------- + */ + +void lzma_codec_free(void* codec) +{ + lzma_codec_data* lzma_codec = (lzma_codec_data*) codec; + + /* free memory */ + LzmaDec_Free(&lzma_codec->decoder, (ISzAlloc*)&lzma_codec->allocator); + lzma_allocator_free(&lzma_codec->allocator); +} + +/*------------------------------------------------- + * decompress - decompress data using the LZMA + * codec + *------------------------------------------------- + */ + +chd_error lzma_codec_decompress(void* codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen) +{ + ELzmaStatus status; + SRes res; + SizeT consumedlen, decodedlen; + /* initialize */ + lzma_codec_data* lzma_codec = (lzma_codec_data*) codec; + LzmaDec_Init(&lzma_codec->decoder); + + /* decode */ + consumedlen = complen; + decodedlen = destlen; + res = LzmaDec_DecodeToBuf(&lzma_codec->decoder, dest, &decodedlen, src, &consumedlen, LZMA_FINISH_END, &status); + if ((res != SZ_OK && res != LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK) || consumedlen != complen || decodedlen != destlen) + return CHDERR_DECOMPRESSION_ERROR; + return CHDERR_NONE; +} diff --git a/libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_zlib.c b/libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_zlib.c new file mode 100644 index 000000000..6fc8f1c68 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_zlib.c @@ -0,0 +1,180 @@ +#include "../include/libchdr/codec_zlib.h" + +#include +#include +#include + +static voidpf zlib_fast_alloc(voidpf opaque, zlib_alloc_size items, zlib_alloc_size size); +static void zlib_fast_free(voidpf opaque, voidpf address); +static void zlib_allocator_free(voidpf opaque); + +/*------------------------------------------------- + zlib_codec_init - initialize the ZLIB codec +-------------------------------------------------*/ + +chd_error zlib_codec_init(void *codec, uint32_t hunkbytes) +{ + int zerr; + chd_error err; + zlib_codec_data *data = (zlib_codec_data*)codec; + + (void)hunkbytes; + + /* clear the buffers */ + memset(data, 0, sizeof(zlib_codec_data)); + + /* init the inflater first */ + data->inflater.next_in = (Bytef *)data; /* bogus, but that's ok */ + data->inflater.avail_in = 0; + data->inflater.zalloc = zlib_fast_alloc; + data->inflater.zfree = zlib_fast_free; + data->inflater.opaque = &data->allocator; + zerr = inflateInit2(&data->inflater, -MAX_WBITS); + + /* convert errors */ + if (zerr == Z_MEM_ERROR) + err = CHDERR_OUT_OF_MEMORY; + else if (zerr != Z_OK) + err = CHDERR_CODEC_ERROR; + else + err = CHDERR_NONE; + + return err; +} + +/*------------------------------------------------- + zlib_codec_free - free data for the ZLIB + codec +-------------------------------------------------*/ + +void zlib_codec_free(void *codec) +{ + zlib_codec_data *data = (zlib_codec_data *)codec; + + /* deinit the streams */ + if (data != NULL) + { + inflateEnd(&data->inflater); + + /* free our fast memory */ + zlib_allocator_free(&data->allocator); + } +} + +/*------------------------------------------------- + zlib_codec_decompress - decompress data using + the ZLIB codec +-------------------------------------------------*/ + +chd_error zlib_codec_decompress(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen) +{ + zlib_codec_data *data = (zlib_codec_data *)codec; + int zerr; + + /* reset the decompressor */ + data->inflater.next_in = (Bytef *)src; + data->inflater.avail_in = complen; + data->inflater.total_in = 0; + data->inflater.next_out = (Bytef *)dest; + data->inflater.avail_out = destlen; + data->inflater.total_out = 0; + zerr = inflateReset(&data->inflater); + if (zerr != Z_OK) + return CHDERR_DECOMPRESSION_ERROR; + + /* do it */ + zerr = inflate(&data->inflater, Z_FINISH); + if (data->inflater.total_out != destlen) + return CHDERR_DECOMPRESSION_ERROR; + + return CHDERR_NONE; +} + +/*------------------------------------------------- + zlib_fast_alloc - fast malloc for ZLIB, which + allocates and frees memory frequently +-------------------------------------------------*/ + +/* Huge alignment values for possible SIMD optimization by compiler (NEON, SSE, AVX) */ +#define ZLIB_MIN_ALIGNMENT_BITS 512 +#define ZLIB_MIN_ALIGNMENT_BYTES (ZLIB_MIN_ALIGNMENT_BITS / 8) + +static voidpf zlib_fast_alloc(voidpf opaque, zlib_alloc_size items, zlib_alloc_size size) +{ + zlib_allocator *alloc = (zlib_allocator *)opaque; + uintptr_t paddr = 0; + uint32_t *ptr; + int i; + + /* compute the size, rounding to the nearest 1k */ + size = (size * items + 0x3ff) & ~0x3ff; + + /* reuse a hunk if we can */ + for (i = 0; i < MAX_ZLIB_ALLOCS; i++) + { + ptr = alloc->allocptr[i]; + if (ptr && size == *ptr) + { + /* set the low bit of the size so we don't match next time */ + *ptr |= 1; + + /* return aligned block address */ + return (voidpf)(alloc->allocptr2[i]); + } + } + + /* alloc a new one */ + ptr = (uint32_t *)malloc(size + sizeof(uint32_t) + ZLIB_MIN_ALIGNMENT_BYTES); + if (!ptr) + return NULL; + + /* put it into the list */ + for (i = 0; i < MAX_ZLIB_ALLOCS; i++) + if (!alloc->allocptr[i]) + { + alloc->allocptr[i] = ptr; + paddr = (((uintptr_t)ptr) + sizeof(uint32_t) + (ZLIB_MIN_ALIGNMENT_BYTES-1)) & (~(ZLIB_MIN_ALIGNMENT_BYTES-1)); + alloc->allocptr2[i] = (uint32_t*)paddr; + break; + } + + /* set the low bit of the size so we don't match next time */ + *ptr = size | 1; + + /* return aligned block address */ + return (voidpf)paddr; +} + +/*------------------------------------------------- + zlib_fast_free - fast free for ZLIB, which + allocates and frees memory frequently +-------------------------------------------------*/ + +static void zlib_fast_free(voidpf opaque, voidpf address) +{ + zlib_allocator *alloc = (zlib_allocator *)opaque; + uint32_t *ptr = (uint32_t *)address; + int i; + + /* find the hunk */ + for (i = 0; i < MAX_ZLIB_ALLOCS; i++) + if (ptr == alloc->allocptr2[i]) + { + /* clear the low bit of the size to allow matches */ + *(alloc->allocptr[i]) &= ~1; + return; + } +} + +/*------------------------------------------------- + zlib_allocator_free +-------------------------------------------------*/ +static void zlib_allocator_free(voidpf opaque) +{ + zlib_allocator *alloc = (zlib_allocator *)opaque; + int i; + + for (i = 0; i < MAX_ZLIB_ALLOCS; i++) + if (alloc->allocptr[i]) + free(alloc->allocptr[i]); +} diff --git a/libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_zstd.c b/libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_zstd.c new file mode 100644 index 000000000..9ba38e731 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/src/libchdr_codec_zstd.c @@ -0,0 +1,91 @@ +#include "../include/libchdr/codec_zstd.h" + +#include +#include +#include + +/*------------------------------------------------- + * zstd_codec_init - constructor + *------------------------------------------------- + */ + +chd_error zstd_codec_init(void* codec, uint32_t hunkbytes) +{ + zstd_codec_data* zstd_codec = (zstd_codec_data*) codec; + + (void)hunkbytes; + zstd_codec->dstream = ZSTD_createDStream(); + if (!zstd_codec->dstream) { +#if 0 + printf("NO DSTREAM CREATED!\n"); +#endif + return CHDERR_DECOMPRESSION_ERROR; + } + return CHDERR_NONE; +} + +/*------------------------------------------------- + * zstd_codec_free + *------------------------------------------------- + */ + +void zstd_codec_free(void* codec) +{ + zstd_codec_data* zstd_codec = (zstd_codec_data*) codec; + + ZSTD_freeDStream(zstd_codec->dstream); +} + +/*------------------------------------------------- + * decompress - decompress data using the ZSTD + * codec + *------------------------------------------------- + */ +chd_error zstd_codec_decompress(void* codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen) +{ + ZSTD_inBuffer input; + ZSTD_outBuffer output; + + /* initialize */ + zstd_codec_data* zstd_codec = (zstd_codec_data*) codec; + + /* reset decompressor */ + size_t zstd_res = ZSTD_initDStream(zstd_codec->dstream); + + if (ZSTD_isError(zstd_res)) + { +#if 0 + printf("INITI DSTREAM FAILED!\n"); +#endif + return CHDERR_DECOMPRESSION_ERROR; + } + + input.src = src; + input.size = complen; + input.pos = 0; + + output.dst = dest; + output.size = destlen; + output.pos = 0; + + while ((input.pos < input.size) && (output.pos < output.size)) + { + zstd_res = ZSTD_decompressStream(zstd_codec->dstream, &output, &input); + if (ZSTD_isError(zstd_res)) + { +#if 0 + printf("DECOMPRESSION ERROR IN LOOP\n"); +#endif + return CHDERR_DECOMPRESSION_ERROR; + } + } + if (output.pos != output.size) + { +#if 0 + printf("OUTPUT DOESN'T MATCH!\n"); +#endif + return CHDERR_DECOMPRESSION_ERROR; + } + return CHDERR_NONE; + +} diff --git a/libretrodroid/src/main/cpp/libchdr/src/libchdr_flac.c b/libretrodroid/src/main/cpp/libchdr/src/libchdr_flac.c new file mode 100644 index 000000000..d6e787a11 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/src/libchdr_flac.c @@ -0,0 +1,328 @@ +/* license:BSD-3-Clause + * copyright-holders:Aaron Giles +*************************************************************************** + + flac.c + + FLAC compression wrappers + +***************************************************************************/ + +#include + +#include "../include/libchdr/flac.h" +#include "../include/libchdr/macros.h" +#define DR_FLAC_IMPLEMENTATION +#include "../include/dr_libs/dr_flac.h" + +/*************************************************************************** + * FLAC DECODER + *************************************************************************** + */ + +static size_t flac_decoder_read_callback(void *userdata, void *buffer, size_t bytes); +static drflac_bool32 flac_decoder_seek_callback(void *userdata, int offset, drflac_seek_origin origin); +static drflac_bool32 flac_decoder_tell_callback(void *userdata, drflac_int64 *cursor); +static void flac_decoder_metadata_callback(void *userdata, drflac_metadata *metadata); +static void flac_decoder_write_callback(void *userdata, void *buffer, size_t bytes); + + +/* getters (valid after reset) */ +static uint32_t sample_rate(flac_decoder *decoder) { return decoder->sample_rate; } +static uint8_t channels(flac_decoder *decoder) { return decoder->channels; } +static uint8_t bits_per_sample(flac_decoder *decoder) { return decoder->bits_per_sample; } + +/*------------------------------------------------- + * flac_decoder - constructor + *------------------------------------------------- + */ + +int flac_decoder_init(flac_decoder *decoder) +{ + decoder->decoder = NULL; + decoder->sample_rate = 0; + decoder->channels = 0; + decoder->bits_per_sample = 0; + decoder->compressed_offset = 0; + decoder->compressed_start = NULL; + decoder->compressed_length = 0; + decoder->compressed2_start = NULL; + decoder->compressed2_length = 0; + decoder->uncompressed_offset = 0; + decoder->uncompressed_length = 0; + decoder->uncompressed_swap = 0; + return 0; +} + +/*------------------------------------------------- + * flac_decoder - destructor + *------------------------------------------------- + */ + +void flac_decoder_free(flac_decoder* decoder) +{ + if ((decoder != NULL) && (decoder->decoder != NULL)) { + drflac_close((drflac*)decoder->decoder); + decoder->decoder = NULL; + } +} + +/*------------------------------------------------- + * reset - reset state with the original + * parameters + *------------------------------------------------- + */ + +static int flac_decoder_internal_reset(flac_decoder* decoder) +{ + decoder->compressed_offset = 0; + flac_decoder_free(decoder); + decoder->decoder = drflac_open_with_metadata( + flac_decoder_read_callback, flac_decoder_seek_callback, + flac_decoder_tell_callback, flac_decoder_metadata_callback, + decoder, NULL); + return (decoder->decoder != NULL); +} + +/*------------------------------------------------- + * reset - reset state with new memory parameters + * and a custom-generated header + *------------------------------------------------- + */ + +int flac_decoder_reset(flac_decoder* decoder, uint32_t sample_rate, uint8_t num_channels, uint32_t block_size, const void *buffer, uint32_t length) +{ + /* modify the template header with our parameters */ + static const uint8_t s_header_template[0x2a] = + { + 0x66, 0x4C, 0x61, 0x43, /* +00: 'fLaC' stream header */ + 0x80, /* +04: metadata block type 0 (STREAMINFO), */ + /* flagged as last block */ + 0x00, 0x00, 0x22, /* +05: metadata block length = 0x22 */ + 0x00, 0x00, /* +08: minimum block size */ + 0x00, 0x00, /* +0A: maximum block size */ + 0x00, 0x00, 0x00, /* +0C: minimum frame size (0 == unknown) */ + 0x00, 0x00, 0x00, /* +0F: maximum frame size (0 == unknown) */ + 0x0A, 0xC4, 0x42, 0xF0, 0x00, 0x00, 0x00, 0x00, /* +12: sample rate (0x0ac44 == 44100), */ + /* numchannels (2), sample bits (16), */ + /* samples in stream (0 == unknown) */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* +1A: MD5 signature (0 == none) */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 /* +2A: start of stream data */ + }; + memcpy(decoder->custom_header, s_header_template, sizeof(s_header_template)); + decoder->custom_header[0x08] = decoder->custom_header[0x0a] = (block_size*num_channels) >> 8; + decoder->custom_header[0x09] = decoder->custom_header[0x0b] = (block_size*num_channels) & 0xff; + decoder->custom_header[0x12] = sample_rate >> 12; + decoder->custom_header[0x13] = sample_rate >> 4; + decoder->custom_header[0x14] = (sample_rate << 4) | ((num_channels - 1) << 1); + + /* configure the header ahead of the provided buffer */ + decoder->compressed_start = (const uint8_t *)(decoder->custom_header); + decoder->compressed_length = sizeof(decoder->custom_header); + decoder->compressed2_start = (const uint8_t *)(buffer); + decoder->compressed2_length = length; + return flac_decoder_internal_reset(decoder); +} + +/*------------------------------------------------- + * decode_interleaved - decode to an interleaved + * sound stream + *------------------------------------------------- + */ + +int flac_decoder_decode_interleaved(flac_decoder* decoder, int16_t *samples, uint32_t num_frames, int swap_endian) +{ + int16_t buffer[2352 / sizeof(int16_t)]; /* 2352 is the number of bytes per CD audio sector */ + uint32_t buf_frames = ARRAY_LENGTH(buffer) / channels(decoder); + + /* configure the uncompressed buffer */ + memset(decoder->uncompressed_start, 0, sizeof(decoder->uncompressed_start)); + decoder->uncompressed_start[0] = samples; + decoder->uncompressed_offset = 0; + decoder->uncompressed_length = num_frames; + decoder->uncompressed_swap = swap_endian; + + /* loop until we get everything we want */ + while (decoder->uncompressed_offset < decoder->uncompressed_length) { + uint32_t frames_to_do = MIN(num_frames, buf_frames); + if (!drflac_read_pcm_frames_s16((drflac*)decoder->decoder, frames_to_do, buffer)) + return 0; + flac_decoder_write_callback(decoder, buffer, frames_to_do*sizeof(*buffer)*channels(decoder)); + num_frames -= frames_to_do; + } + return 1; +} + +/*------------------------------------------------- + * finish - finish up the decode + *------------------------------------------------- + */ + +uint32_t flac_decoder_finish(flac_decoder* decoder) +{ + /* get the final decoding position and move forward */ + drflac *flac = (drflac*)decoder->decoder; + uint64_t position = decoder->compressed_offset; + + /* ugh... there's no function to obtain bytes used in drflac :-/ */ + position -= DRFLAC_CACHE_L2_LINES_REMAINING(&flac->bs) * sizeof(drflac_cache_t); + position -= DRFLAC_CACHE_L1_BITS_REMAINING(&flac->bs) / 8; + position -= flac->bs.unalignedByteCount; + + /* adjust position if we provided the header */ + if (position == 0) + return 0; + if (decoder->compressed_start == (const uint8_t *)(decoder->custom_header)) + position -= decoder->compressed_length; + + flac_decoder_free(decoder); + return position; +} + +/*------------------------------------------------- + * detect_native_endian - detect system endianness + *------------------------------------------------- + */ + +int flac_decoder_detect_native_endian(void) +{ + uint16_t native_endian = 0; + *(uint8_t *)(&native_endian) = 1; + return (native_endian & 1); +} + +/*------------------------------------------------- + * read_callback - handle reads from the input + * stream + *------------------------------------------------- + */ + +static size_t flac_decoder_read_callback(void *userdata, void *buffer, size_t bytes) +{ + flac_decoder *decoder = (flac_decoder*)userdata; + uint8_t *dst = (uint8_t*)buffer; + + /* copy from primary buffer first */ + uint32_t outputpos = 0; + if (outputpos < bytes && decoder->compressed_offset < decoder->compressed_length) + { + uint32_t bytes_to_copy = MIN(bytes - outputpos, decoder->compressed_length - decoder->compressed_offset); + memcpy(&dst[outputpos], decoder->compressed_start + decoder->compressed_offset, bytes_to_copy); + outputpos += bytes_to_copy; + decoder->compressed_offset += bytes_to_copy; + } + + /* once we're out of that, copy from the secondary buffer */ + if (outputpos < bytes && decoder->compressed_offset < decoder->compressed_length + decoder->compressed2_length) + { + uint32_t bytes_to_copy = MIN(bytes - outputpos, decoder->compressed2_length - (decoder->compressed_offset - decoder->compressed_length)); + memcpy(&dst[outputpos], decoder->compressed2_start + decoder->compressed_offset - decoder->compressed_length, bytes_to_copy); + outputpos += bytes_to_copy; + decoder->compressed_offset += bytes_to_copy; + } + + return outputpos; +} + +/*------------------------------------------------- + * metadata_callback - handle STREAMINFO metadata + *------------------------------------------------- + */ + +static void flac_decoder_metadata_callback(void *userdata, drflac_metadata *metadata) +{ + flac_decoder *decoder = (flac_decoder*)userdata; + + /* ignore all but STREAMINFO metadata */ + if (metadata->type != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO) + return; + + /* parse out the data we care about */ + decoder->sample_rate = metadata->data.streaminfo.sampleRate; + decoder->bits_per_sample = metadata->data.streaminfo.bitsPerSample; + decoder->channels = metadata->data.streaminfo.channels; +} + +/*------------------------------------------------- + * write_callback - handle writes to the output + * stream + *------------------------------------------------- + */ + +static void flac_decoder_write_callback(void *userdata, void *buffer, size_t bytes) +{ + int sampnum, chan; + int shift, blocksize; + flac_decoder * decoder = (flac_decoder *)userdata; + int16_t *sampbuf = (int16_t *)buffer; + int sampch = channels(decoder); + uint32_t offset = decoder->uncompressed_offset; + uint16_t usample; + + /* interleaved case */ + shift = decoder->uncompressed_swap ? 8 : 0; + blocksize = bytes / (sampch * sizeof(sampbuf[0])); + if (decoder->uncompressed_start[1] == NULL) + { + int16_t *dest = decoder->uncompressed_start[0] + offset * sampch; + for (sampnum = 0; sampnum < blocksize && offset < decoder->uncompressed_length; sampnum++, offset++) + for (chan = 0; chan < sampch; chan++) { + usample = (uint16_t)*sampbuf++; + *dest++ = (int16_t)((usample << shift) | (usample >> shift)); + } + } + + /* non-interleaved case */ + else + { + for (sampnum = 0; sampnum < blocksize && offset < decoder->uncompressed_length; sampnum++, offset++) + for (chan = 0; chan < sampch; chan++) { + usample = (uint16_t)*sampbuf++; + if (decoder->uncompressed_start[chan] != NULL) + decoder->uncompressed_start[chan][offset] = (int16_t) ((usample << shift) | (usample >> shift)); + } + } + decoder->uncompressed_offset = offset; +} + + +/*------------------------------------------------- + * seek_callback - handle seeks on the output + * stream + *------------------------------------------------- + */ + +static drflac_bool32 flac_decoder_seek_callback(void *userdata, int offset, drflac_seek_origin origin) +{ + flac_decoder * decoder = (flac_decoder *)userdata; + uint32_t length = decoder->compressed_length + decoder->compressed2_length; + + if (origin == DRFLAC_SEEK_SET) { + uint32_t pos = offset; + if (pos <= length) { + decoder->compressed_offset = pos; + return DRFLAC_TRUE; + } + } else if (origin == DRFLAC_SEEK_CUR) { + uint32_t pos = decoder->compressed_offset + offset; + if (pos <= length) { + decoder->compressed_offset = pos; + return DRFLAC_TRUE; + } + } + return DRFLAC_FALSE; +} + + +/*------------------------------------------------- + * tell_callback - handle seeks on the output + * stream + *------------------------------------------------- + */ + +static drflac_bool32 flac_decoder_tell_callback(void *userdata, drflac_int64 *cursor) +{ + flac_decoder * decoder = (flac_decoder *)userdata; + *cursor = decoder->compressed_offset; + return 1; +} diff --git a/libretrodroid/src/main/cpp/libchdr/src/libchdr_huffman.c b/libretrodroid/src/main/cpp/libchdr/src/libchdr_huffman.c new file mode 100644 index 000000000..a940ca21a --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/src/libchdr_huffman.c @@ -0,0 +1,569 @@ +/* license:BSD-3-Clause + * copyright-holders:Aaron Giles +**************************************************************************** + + huffman.c + + Static Huffman compression and decompression helpers. + +**************************************************************************** + + Maximum codelength is officially (alphabetsize - 1). This would be 255 bits + (since we use 1 byte values). However, it is also dependent upon the number + of samples used, as follows: + + 2 bits -> 3..4 samples + 3 bits -> 5..7 samples + 4 bits -> 8..12 samples + 5 bits -> 13..20 samples + 6 bits -> 21..33 samples + 7 bits -> 34..54 samples + 8 bits -> 55..88 samples + 9 bits -> 89..143 samples + 10 bits -> 144..232 samples + 11 bits -> 233..376 samples + 12 bits -> 377..609 samples + 13 bits -> 610..986 samples + 14 bits -> 987..1596 samples + 15 bits -> 1597..2583 samples + 16 bits -> 2584..4180 samples -> note that a 4k data size guarantees codelength <= 16 bits + 17 bits -> 4181..6764 samples + 18 bits -> 6765..10945 samples + 19 bits -> 10946..17710 samples + 20 bits -> 17711..28656 samples + 21 bits -> 28657..46367 samples + 22 bits -> 46368..75024 samples + 23 bits -> 75025..121392 samples + 24 bits -> 121393..196417 samples + 25 bits -> 196418..317810 samples + 26 bits -> 317811..514228 samples + 27 bits -> 514229..832039 samples + 28 bits -> 832040..1346268 samples + 29 bits -> 1346269..2178308 samples + 30 bits -> 2178309..3524577 samples + 31 bits -> 3524578..5702886 samples + 32 bits -> 5702887..9227464 samples + + Looking at it differently, here is where powers of 2 fall into these buckets: + + 256 samples -> 11 bits max + 512 samples -> 12 bits max + 1k samples -> 14 bits max + 2k samples -> 15 bits max + 4k samples -> 16 bits max + 8k samples -> 18 bits max + 16k samples -> 19 bits max + 32k samples -> 21 bits max + 64k samples -> 22 bits max + 128k samples -> 24 bits max + 256k samples -> 25 bits max + 512k samples -> 27 bits max + 1M samples -> 28 bits max + 2M samples -> 29 bits max + 4M samples -> 31 bits max + 8M samples -> 32 bits max + +**************************************************************************** + + Delta-RLE encoding works as follows: + + Starting value is assumed to be 0. All data is encoded as a delta + from the previous value, such that final[i] = final[i - 1] + delta. + Long runs of 0s are RLE-encoded as follows: + + 0x100 = repeat count of 8 + 0x101 = repeat count of 9 + 0x102 = repeat count of 10 + 0x103 = repeat count of 11 + 0x104 = repeat count of 12 + 0x105 = repeat count of 13 + 0x106 = repeat count of 14 + 0x107 = repeat count of 15 + 0x108 = repeat count of 16 + 0x109 = repeat count of 32 + 0x10a = repeat count of 64 + 0x10b = repeat count of 128 + 0x10c = repeat count of 256 + 0x10d = repeat count of 512 + 0x10e = repeat count of 1024 + 0x10f = repeat count of 2048 + + Note that repeat counts are reset at the end of a row, so if a 0 run + extends to the end of a row, a large repeat count may be used. + + The reason for starting the run counts at 8 is that 0 is expected to + be the most common symbol, and is typically encoded in 1 or 2 bits. + +***************************************************************************/ + +#include +#include +#include + +#include "../include/libchdr/huffman.h" +#include "../include/libchdr/macros.h" + +/*************************************************************************** + * MACROS + *************************************************************************** + */ + +#define MAKE_LOOKUP(code,bits) (((code) << 5) | ((bits) & 0x1f)) + +/*************************************************************************** + * IMPLEMENTATION + *************************************************************************** + */ + +/*------------------------------------------------- + * huffman_context_base - create an encoding/ + * decoding context + *------------------------------------------------- + */ + +struct huffman_decoder* create_huffman_decoder(int numcodes, int maxbits) +{ + struct huffman_decoder* decoder = NULL; + + /* limit to 24 bits */ + if (maxbits > 24) + return NULL; + + decoder = (struct huffman_decoder*)malloc(sizeof(struct huffman_decoder)); + decoder->numcodes = numcodes; + decoder->maxbits = maxbits; + decoder->lookup = (lookup_value*)malloc(sizeof(lookup_value) * (1 << maxbits)); + decoder->huffnode = (struct node_t*)malloc(sizeof(struct node_t) * numcodes); + decoder->datahisto = NULL; + decoder->prevdata = 0; + decoder->rleremaining = 0; + return decoder; +} + +void delete_huffman_decoder(struct huffman_decoder* decoder) +{ + if (decoder != NULL) + { + if (decoder->lookup != NULL) + free(decoder->lookup); + if (decoder->huffnode != NULL) + free(decoder->huffnode); + free(decoder); + } +} + +/*------------------------------------------------- + * decode_one - decode a single code from the + * huffman stream + *------------------------------------------------- + */ + +uint32_t huffman_decode_one(struct huffman_decoder* decoder, struct bitstream* bitbuf) +{ + /* peek ahead to get maxbits worth of data */ + uint32_t bits = bitstream_peek(bitbuf, decoder->maxbits); + + /* look it up, then remove the actual number of bits for this code */ + lookup_value lookup = decoder->lookup[bits]; + bitstream_remove(bitbuf, lookup & 0x1f); + + /* return the value */ + return lookup >> 5; +} + +/*------------------------------------------------- + * import_tree_rle - import an RLE-encoded + * huffman tree from a source data stream + *------------------------------------------------- + */ + +enum huffman_error huffman_import_tree_rle(struct huffman_decoder* decoder, struct bitstream* bitbuf) +{ + int numbits; + uint32_t curnode; + enum huffman_error error; + + /* bits per entry depends on the maxbits */ + if (decoder->maxbits >= 16) + numbits = 5; + else if (decoder->maxbits >= 8) + numbits = 4; + else + numbits = 3; + + /* loop until we read all the nodes */ + for (curnode = 0; curnode < decoder->numcodes; ) + { + /* a non-one value is just raw */ + int nodebits = bitstream_read(bitbuf, numbits); + if (nodebits != 1) + decoder->huffnode[curnode++].numbits = nodebits; + + /* a one value is an escape code */ + else + { + /* a double 1 is just a single 1 */ + nodebits = bitstream_read(bitbuf, numbits); + if (nodebits == 1) + decoder->huffnode[curnode++].numbits = nodebits; + + /* otherwise, we need one for value for the repeat count */ + else + { + int repcount = bitstream_read(bitbuf, numbits) + 3; + if (repcount + curnode > decoder->numcodes) + return HUFFERR_INVALID_DATA; + while (repcount--) + decoder->huffnode[curnode++].numbits = nodebits; + } + } + } + + /* make sure we ended up with the right number */ + if (curnode != decoder->numcodes) + return HUFFERR_INVALID_DATA; + + /* assign canonical codes for all nodes based on their code lengths */ + error = huffman_assign_canonical_codes(decoder); + if (error != HUFFERR_NONE) + return error; + + /* build the lookup table */ + error = huffman_build_lookup_table(decoder); + if (error != HUFFERR_NONE) + return error; + + /* determine final input length and report errors */ + return bitstream_overflow(bitbuf) ? HUFFERR_INPUT_BUFFER_TOO_SMALL : HUFFERR_NONE; +} + + +/*------------------------------------------------- + * import_tree_huffman - import a huffman-encoded + * huffman tree from a source data stream + *------------------------------------------------- + */ + +enum huffman_error huffman_import_tree_huffman(struct huffman_decoder* decoder, struct bitstream* bitbuf) +{ + int start; + int last = 0; + int count = 0; + int index; + uint32_t curcode; + uint8_t rlefullbits = 0; + uint32_t temp; + enum huffman_error error; + /* start by parsing the lengths for the small tree */ + struct huffman_decoder* smallhuff = create_huffman_decoder(24, 6); + smallhuff->huffnode[0].numbits = bitstream_read(bitbuf, 3); + start = bitstream_read(bitbuf, 3) + 1; + for (index = 1; index < 24; index++) + { + if (index < start || count == 7) + smallhuff->huffnode[index].numbits = 0; + else + { + count = bitstream_read(bitbuf, 3); + smallhuff->huffnode[index].numbits = (count == 7) ? 0 : count; + } + } + + /* then regenerate the tree */ + error = huffman_assign_canonical_codes(smallhuff); + if (error != HUFFERR_NONE) + { + delete_huffman_decoder(smallhuff); + return error; + } + error = huffman_build_lookup_table(smallhuff); + if (error != HUFFERR_NONE) + { + delete_huffman_decoder(smallhuff); + return error; + } + + /* determine the maximum length of an RLE count */ + temp = decoder->numcodes - 9; + while (temp != 0) + temp >>= 1, rlefullbits++; + + /* now process the rest of the data */ + for (curcode = 0; curcode < decoder->numcodes; ) + { + int value = huffman_decode_one(smallhuff, bitbuf); + if (value != 0) + decoder->huffnode[curcode++].numbits = last = value - 1; + else + { + int count = bitstream_read(bitbuf, 3) + 2; + if (count == 7+2) + count += bitstream_read(bitbuf, rlefullbits); + for ( ; count != 0 && curcode < decoder->numcodes; count--) + decoder->huffnode[curcode++].numbits = last; + } + } + + /* make sure we free the local huffman decoder */ + delete_huffman_decoder(smallhuff); + + /* make sure we ended up with the right number */ + if (curcode != decoder->numcodes) + return HUFFERR_INVALID_DATA; + + /* assign canonical codes for all nodes based on their code lengths */ + error = huffman_assign_canonical_codes(decoder); + if (error != HUFFERR_NONE) + return error; + + /* build the lookup table */ + error = huffman_build_lookup_table(decoder); + if (error != HUFFERR_NONE) + return error; + + /* determine final input length and report errors */ + return bitstream_overflow(bitbuf) ? HUFFERR_INPUT_BUFFER_TOO_SMALL : HUFFERR_NONE; +} + +/*------------------------------------------------- + * compute_tree_from_histo - common backend for + * computing a tree based on the data histogram + *------------------------------------------------- + */ + +enum huffman_error huffman_compute_tree_from_histo(struct huffman_decoder* decoder) +{ + uint32_t i; + uint32_t lowerweight; + uint32_t upperweight; + /* compute the number of data items in the histogram */ + uint32_t sdatacount = 0; + for (i = 0; i < decoder->numcodes; i++) + sdatacount += decoder->datahisto[i]; + + /* binary search to achieve the optimum encoding */ + lowerweight = 0; + upperweight = sdatacount * 2; + while (1) + { + /* build a tree using the current weight */ + uint32_t curweight = (upperweight + lowerweight) / 2; + int curmaxbits = huffman_build_tree(decoder, sdatacount, curweight); + + /* apply binary search here */ + if (curmaxbits <= decoder->maxbits) + { + lowerweight = curweight; + + /* early out if it worked with the raw weights, or if we're done searching */ + if (curweight == sdatacount || (upperweight - lowerweight) <= 1) + break; + } + else + upperweight = curweight; + } + + /* assign canonical codes for all nodes based on their code lengths */ + return huffman_assign_canonical_codes(decoder); +} + +/*************************************************************************** + * INTERNAL FUNCTIONS + *************************************************************************** + */ + +/*------------------------------------------------- + * tree_node_compare - compare two tree nodes + * by weight + *------------------------------------------------- + */ + +static int huffman_tree_node_compare(const void *item1, const void *item2) +{ + const struct node_t *node1 = *(const struct node_t **)item1; + const struct node_t *node2 = *(const struct node_t **)item2; + if (node2->weight != node1->weight) + return node2->weight - node1->weight; +#if 0 + if (node2->bits - node1->bits == 0) + fprintf(stderr, "identical node sort keys, should not happen!\n"); +#endif + return (int)node1->bits - (int)node2->bits; +} + +/*------------------------------------------------- + * build_tree - build a huffman tree based on the + * data distribution + *------------------------------------------------- + */ + +int huffman_build_tree(struct huffman_decoder* decoder, uint32_t totaldata, uint32_t totalweight) +{ + uint32_t curcode; + int nextalloc; + int listitems = 0; + int maxbits = 0; + /* make a list of all non-zero nodes */ + struct node_t** list = (struct node_t**)malloc(sizeof(struct node_t*) * decoder->numcodes * 2); + memset(decoder->huffnode, 0, decoder->numcodes * sizeof(decoder->huffnode[0])); + for (curcode = 0; curcode < decoder->numcodes; curcode++) + if (decoder->datahisto[curcode] != 0) + { + list[listitems++] = &decoder->huffnode[curcode]; + decoder->huffnode[curcode].count = decoder->datahisto[curcode]; + decoder->huffnode[curcode].bits = curcode; + + /* scale the weight by the current effective length, ensuring we don't go to 0 */ + decoder->huffnode[curcode].weight = ((uint64_t)decoder->datahisto[curcode]) * ((uint64_t)totalweight) / ((uint64_t)totaldata); + if (decoder->huffnode[curcode].weight == 0) + decoder->huffnode[curcode].weight = 1; + } + +#if 0 + fprintf(stderr, "Pre-sort:\n"); + for (int i = 0; i < listitems; i++) { + fprintf(stderr, "weight: %d code: %d\n", list[i]->m_weight, list[i]->m_bits); + } +#endif + + /* sort the list by weight, largest weight first */ + qsort(&list[0], listitems, sizeof(list[0]), huffman_tree_node_compare); + +#if 0 + fprintf(stderr, "Post-sort:\n"); + for (int i = 0; i < listitems; i++) { + fprintf(stderr, "weight: %d code: %d\n", list[i]->m_weight, list[i]->m_bits); + } + fprintf(stderr, "===================\n"); +#endif + + /* now build the tree */ + nextalloc = decoder->numcodes; + while (listitems > 1) + { + int curitem; + /* remove lowest two items */ + struct node_t* node1 = &(*list[--listitems]); + struct node_t* node0 = &(*list[--listitems]); + + /* create new node */ + struct node_t* newnode = &decoder->huffnode[nextalloc++]; + newnode->parent = NULL; + node0->parent = node1->parent = newnode; + newnode->weight = node0->weight + node1->weight; + + /* insert into list at appropriate location */ + for (curitem = 0; curitem < listitems; curitem++) + if (newnode->weight > list[curitem]->weight) + { + memmove(&list[curitem+1], &list[curitem], (listitems - curitem) * sizeof(list[0])); + break; + } + list[curitem] = newnode; + listitems++; + } + + /* compute the number of bits in each code, and fill in another histogram */ + for (curcode = 0; curcode < decoder->numcodes; curcode++) + { + struct node_t *curnode; + struct node_t* node = &decoder->huffnode[curcode]; + node->numbits = 0; + node->bits = 0; + + /* if we have a non-zero weight, compute the number of bits */ + if (node->weight > 0) + { + /* determine the number of bits for this node */ + for (curnode = node; curnode->parent != NULL; curnode = curnode->parent) + node->numbits++; + if (node->numbits == 0) + node->numbits = 1; + + /* keep track of the max */ + maxbits = MAX(maxbits, ((int)node->numbits)); + } + } + return maxbits; +} + +/*------------------------------------------------- + * assign_canonical_codes - assign canonical codes + * to all the nodes based on the number of bits + * in each + *------------------------------------------------- + */ + +enum huffman_error huffman_assign_canonical_codes(struct huffman_decoder* decoder) +{ + uint32_t curcode; + int codelen; + uint32_t curstart = 0; + /* build up a histogram of bit lengths */ + uint32_t bithisto[33] = { 0 }; + for (curcode = 0; curcode < decoder->numcodes; curcode++) + { + struct node_t* node = &decoder->huffnode[curcode]; + if (node->numbits > decoder->maxbits) + return HUFFERR_INTERNAL_INCONSISTENCY; + if (node->numbits <= 32) + bithisto[node->numbits]++; + } + + /* for each code length, determine the starting code number */ + for (codelen = 32; codelen > 0; codelen--) + { + uint32_t nextstart = (curstart + bithisto[codelen]) >> 1; + if (codelen != 1 && nextstart * 2 != (curstart + bithisto[codelen])) + return HUFFERR_INTERNAL_INCONSISTENCY; + bithisto[codelen] = curstart; + curstart = nextstart; + } + + /* now assign canonical codes */ + for (curcode = 0; curcode < decoder->numcodes; curcode++) + { + struct node_t* node = &decoder->huffnode[curcode]; + if (node->numbits > 0) + node->bits = bithisto[node->numbits]++; + } + return HUFFERR_NONE; +} + +/*------------------------------------------------- + * build_lookup_table - build a lookup table for + * fast decoding + *------------------------------------------------- + */ + +enum huffman_error huffman_build_lookup_table(struct huffman_decoder* decoder) +{ + const lookup_value* lookupend = &decoder->lookup[(1u << decoder->maxbits)]; + uint32_t curcode; + /* iterate over all codes */ + for (curcode = 0; curcode < decoder->numcodes; curcode++) + { + /* process all nodes which have non-zero bits */ + struct node_t* node = &decoder->huffnode[curcode]; + if (node->numbits > 0) + { + int shift; + lookup_value *dest; + lookup_value *destend; + + /* set up the entry */ + lookup_value value = MAKE_LOOKUP(curcode, node->numbits); + + /* fill all matching entries */ + shift = decoder->maxbits - node->numbits; + dest = &decoder->lookup[node->bits << shift]; + destend = &decoder->lookup[((node->bits + 1) << shift) - 1]; + if (dest >= lookupend || destend >= lookupend || destend < dest) + return HUFFERR_INTERNAL_INCONSISTENCY; + while (dest <= destend) + *dest++ = value; + } + } + + return HUFFERR_NONE; +} diff --git a/libretrodroid/src/main/cpp/libchdr/src/link.T b/libretrodroid/src/main/cpp/libchdr/src/link.T new file mode 100644 index 000000000..ea37716b7 --- /dev/null +++ b/libretrodroid/src/main/cpp/libchdr/src/link.T @@ -0,0 +1,5 @@ +{ + global: chd_*; + local: *; +}; + diff --git a/libretrodroid/src/main/cpp/libretro/libretro-common b/libretrodroid/src/main/cpp/libretro/libretro-common new file mode 160000 index 000000000..b0c348ea5 --- /dev/null +++ b/libretrodroid/src/main/cpp/libretro/libretro-common @@ -0,0 +1 @@ +Subproject commit b0c348ea5543c4d7fb0bc479258aa6988b20c0c9 diff --git a/libretrodroid/src/main/cpp/libretrodroid.cpp b/libretrodroid/src/main/cpp/libretrodroid.cpp new file mode 100644 index 000000000..e98cb127c --- /dev/null +++ b/libretrodroid/src/main/cpp/libretrodroid.cpp @@ -0,0 +1,730 @@ +/* + * Copyright (C) 2019 Filippo Scognamiglio + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include + +#include + +#include +#include +#include +#include + +#include "libretrodroid.h" +#include "utils/libretrodroidexception.h" +#include "log.h" +#include "core.h" +#include "audio.h" +#include "video.h" +#include "renderers/renderer.h" +#include "fpssync.h" +#include "input.h" +#include "rumble.h" +#include "shadermanager.h" +#include "utils/javautils.h" +#include "environment.h" +#include "netpacket.h" +#include "renderers/es3/framebufferrenderer.h" +#include "renderers/es2/imagerendereres2.h" +#include "renderers/es3/imagerendereres3.h" +#include "utils/utils.h" +#include "utils/rect.h" +#include "errorcodes.h" +#include "vfs/vfs.h" + +namespace libretrodroid { + +uintptr_t LibretroDroid::callback_get_current_framebuffer() { + return LibretroDroid::getInstance().handleGetCurrentFrameBuffer(); +} + +void LibretroDroid::callback_hw_video_refresh( + const void *data, + unsigned width, + unsigned height, + size_t pitch +) { + LOGD("hw video refresh callback called %i %i", width, height); + LibretroDroid::getInstance().handleVideoRefresh(data, width, height, pitch); +} + +void LibretroDroid::callback_audio_sample(int16_t left, int16_t right) { + LOGE("callback audio sample (left, right) has been called"); +} + +size_t LibretroDroid::callback_set_audio_sample_batch(const int16_t *data, size_t frames) { + return LibretroDroid::getInstance().handleAudioCallback(data, frames); +} + +void LibretroDroid::callback_retro_set_input_poll() { + // Do nothing in here... +} + +int16_t LibretroDroid::callback_set_input_state( + unsigned int port, + unsigned int device, + unsigned int index, + unsigned int id +) { + return LibretroDroid::getInstance().handleSetInputState(port, device, index, id); +} + +void LibretroDroid::updateAudioSampleRateMultiplier() { + if (audio) { + audio->setPlaybackSpeed(frameSpeed); + } +} + +// TODO... Do we really need this? +void LibretroDroid::resetGlobalVariables() { + core = nullptr; + audio = nullptr; + video = nullptr; + fpsSync = nullptr; + input = nullptr; + rumble = nullptr; +} + +int LibretroDroid::availableDisks() { + return Environment::getInstance().getRetroDiskControlCallback() != nullptr + ? Environment::getInstance().getRetroDiskControlCallback()->get_num_images() + : 0; +} + +int LibretroDroid::currentDisk() { + return Environment::getInstance().getRetroDiskControlCallback() != nullptr + ? Environment::getInstance().getRetroDiskControlCallback()->get_image_index() + : 0; +} + +void LibretroDroid::changeDisk(unsigned int index) { + if (Environment::getInstance().getRetroDiskControlCallback() == nullptr) { + LOGE("Cannot swap disk. This platform does not support it."); + return; + } + + if (index < 0 || index >= Environment::getInstance().getRetroDiskControlCallback()->get_num_images()) { + LOGE("Requested image index is not valid."); + return; + } + + if (Environment::getInstance().getRetroDiskControlCallback()->get_image_index() != index) { + Environment::getInstance().getRetroDiskControlCallback()->set_eject_state(true); + Environment::getInstance().getRetroDiskControlCallback()->set_image_index((unsigned) index); + Environment::getInstance().getRetroDiskControlCallback()->set_eject_state(false); + } +} + +void LibretroDroid::updateVariable(const Variable& variable) { + Environment::getInstance().updateVariable(variable.key, variable.value); +} + +std::vector LibretroDroid::getVariables() { + return Environment::getInstance().getVariables(); +} + +std::vector> LibretroDroid::getControllers() { + return Environment::getInstance().getControllers(); +} + +void LibretroDroid::setControllerType(unsigned int port, unsigned int type) { + core->retro_set_controller_port_device(port, type); +} + +bool LibretroDroid::netpacketHasCore() { + return NetpacketBridge::getInstance().hasCoreInterface(); +} + +bool LibretroDroid::netpacketStartHost(int listenPort) { + std::lock_guard lock(coreLock); + return NetpacketBridge::getInstance().startHost(listenPort); +} + +bool LibretroDroid::netpacketStartClient(const std::string& host, int port) { + std::lock_guard lock(coreLock); + return NetpacketBridge::getInstance().startClient(host, port); +} + +void LibretroDroid::netpacketStop() { + std::lock_guard lock(coreLock); + NetpacketBridge::getInstance().stop(); +} + +bool LibretroDroid::netpacketIsActive() { + return NetpacketBridge::getInstance().isActive(); +} + +int LibretroDroid::netpacketPeerCount() { + return NetpacketBridge::getInstance().peerCount(); +} + +bool LibretroDroid::unserializeState(int8_t *data, size_t size) { + std::lock_guard lock(coreLock); + + return core->retro_unserialize(data, size); +} + +JNIEXPORT jboolean JNICALL LibretroDroid::unserializeSRAM(int8_t* data, size_t size) { + std::lock_guard lock(coreLock); + + size_t sramSize = core->retro_get_memory_size(RETRO_MEMORY_SAVE_RAM); + void *sramState = core->retro_get_memory_data(RETRO_MEMORY_SAVE_RAM); + + if (sramState == nullptr) { + LOGE("Cannot load SRAM: nullptr in retro_get_memory_data"); + return false; + } + + if (size > sramSize) { + LOGE("Cannot load SRAM: size mismatch"); + return false; + } + + memcpy(sramState, data, size); + + return true; +} + +size_t LibretroDroid::coreMemorySize(unsigned id) { + if (!core) return 0; + return core->retro_get_memory_size(id); +} + +void* LibretroDroid::coreMemoryData(unsigned id) { + if (!core) return nullptr; + return core->retro_get_memory_data(id); +} + +std::string LibretroDroid::coreLibraryName() { + if (!core) return std::string(); + struct retro_system_info info {}; + core->retro_get_system_info(&info); + return info.library_name != nullptr ? std::string(info.library_name) : std::string(); +} + +std::pair LibretroDroid::serializeSRAM() { + std::lock_guard lock(coreLock); + + size_t size = core->retro_get_memory_size(RETRO_MEMORY_SAVE_RAM); + auto* data = new int8_t[size]; + memcpy(data, (int8_t*) core->retro_get_memory_data(RETRO_MEMORY_SAVE_RAM), size); + + return std::pair(data, size); +} + +void LibretroDroid::onSurfaceChanged(unsigned int width, unsigned int height) { + LOGD("Performing libretrodroid onSurfaceChanged"); + video->updateScreenSize(width, height); +} + +void LibretroDroid::onSurfaceCreated() { + LOGD("Performing libretrodroid onSurfaceCreated"); + + struct retro_system_av_info system_av_info {}; + core->retro_get_system_av_info(&system_av_info); + + video = nullptr; + + unsigned fbWidth = system_av_info.geometry.base_width; + unsigned fbHeight = system_av_info.geometry.base_height; + if (fbWidth == 0) fbWidth = system_av_info.geometry.max_width; + if (fbHeight == 0) fbHeight = system_av_info.geometry.max_height; + if (fbWidth == 0) fbWidth = 640; + if (fbHeight == 0) fbHeight = 528; + if (fbWidth > 4096) fbWidth = 4096; + if (fbHeight > 4096) fbHeight = 4096; + LOGI( + "Video init geometry base=%ux%u max=%ux%u using=%ux%u hw=%d depth=%d stencil=%d", + system_av_info.geometry.base_width, + system_av_info.geometry.base_height, + system_av_info.geometry.max_width, + system_av_info.geometry.max_height, + fbWidth, + fbHeight, + Environment::getInstance().isUseHwAcceleration() ? 1 : 0, + Environment::getInstance().isUseDepth() ? 1 : 0, + Environment::getInstance().isUseStencil() ? 1 : 0 + ); + + Video::RenderingOptions renderingOptions { + Environment::getInstance().isUseHwAcceleration(), + fbWidth, + fbHeight, + Environment::getInstance().isUseDepth(), + Environment::getInstance().isUseStencil(), + openglESVersion, + Environment::getInstance().getPixelFormat() + }; + + auto newVideo = new Video( + renderingOptions, + fragmentShaderConfig, + Environment::getInstance().isBottomLeftOrigin(), + Environment::getInstance().getScreenRotation(), + skipDuplicateFrames, + immersiveModeEnabled, + viewportRect, + immersiveModeConfig, + viewportAlignment + ); + + video = std::unique_ptr