mirror of
https://github.com/spice2x/spice2x.github.io.git
synced 2026-11-29 10:48:56 -08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8c864f69b5 | ||
|
|
5bb526c4ba | ||
|
|
3e3db7a411 | ||
|
|
37f947b57f | ||
|
|
63bfef7c69 | ||
|
|
c83496776e | ||
|
|
fdc7adff7f | ||
|
|
cf5d87d4d5 | ||
|
|
175245333d | ||
|
|
9c8f7f551d | ||
|
|
0684872013 | ||
|
|
ed0ccdd6e3 | ||
|
|
7aba7da3b6 | ||
|
|
197d76755b | ||
|
|
2b6e76730b | ||
|
|
4042b77065 | ||
|
|
4c77a3f148 | ||
|
|
603fbfc69d | ||
|
|
5e4afecd90 | ||
|
|
531e7a54b3 | ||
|
|
f11b9d0189 | ||
|
|
112b1aecb0 | ||
|
|
de466db29f | ||
|
|
08e99dea4a | ||
|
|
00e904539e | ||
|
|
eaab4698eb | ||
|
|
a48eccab93 | ||
|
|
81c913726d | ||
|
|
0169fe1e31 | ||
|
|
357e6c86f1 | ||
|
|
67963389ef | ||
|
|
4009bb8a84 | ||
|
|
8fb6d94000 | ||
|
|
8d3685415d | ||
|
|
50b38b856f | ||
|
|
dad88caf01 | ||
|
|
699659d4bf | ||
|
|
21e7d24ed3 | ||
|
|
1cdb7be810 | ||
|
|
09314f1fd3 | ||
|
|
e7b90271ca | ||
|
|
95f10ed733 | ||
|
|
d51de976b1 | ||
|
|
8acd433ec6 | ||
|
|
b9c8afbbc1 | ||
|
|
7d5f528e1a | ||
|
|
2dc3c0cbe4 | ||
|
|
4c2a70bab6 | ||
|
|
46f76597fc |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
name: Bug report (NOT for troubleshooting or asking for help)
|
||||
about: 'File a bug in spice2x'
|
||||
title: ''
|
||||
labels: bug
|
||||
assignees: ''
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
on: [push, pull_request]
|
||||
on:
|
||||
push:
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
name: Continuous Integration
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
@@ -29,4 +32,33 @@ jobs:
|
||||
with:
|
||||
name: spice2x-ci-${{ env.COMMIT_SHORT_SHA }}
|
||||
path: src/spice2x/bin
|
||||
if-no-files-found: error
|
||||
if-no-files-found: error
|
||||
|
||||
msvc-ci:
|
||||
name: Build (MSVC ${{ matrix.arch }}-bit)
|
||||
# windows-latest ships Visual Studio 2026; pin to the VS 2022 image, which is
|
||||
# the toolset spice2x is actually developed against
|
||||
runs-on: windows-2022
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- arch: 32
|
||||
platform: Win32
|
||||
target: spicetools_spice spicetools_cfg
|
||||
- arch: 64
|
||||
platform: x64
|
||||
target: spicetools_spice64
|
||||
defaults:
|
||||
run:
|
||||
working-directory: ./src/spice2x
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- name: Configure
|
||||
run: >
|
||||
cmake -S . -B cmake-build-msvc-${{ matrix.arch }}
|
||||
-A ${{ matrix.platform }}
|
||||
- name: Compile
|
||||
run: >
|
||||
cmake --build cmake-build-msvc-${{ matrix.arch }}
|
||||
--config Release --target ${{ matrix.target }}
|
||||
+2
-1
@@ -22,6 +22,7 @@ To contribute, fork the repo (just the main branch), make changes in your fork,
|
||||
* Any additions to built-in patches (modifications / removals are OK if we have a good reason).
|
||||
* Changes to the software license terms.
|
||||
* Localization / translation for UI text. It becomes too difficult to manage by the maintainers.
|
||||
* Bundling third party DLL binary; e.g., Discord Social SDK, PC light control integration, and so on. These should be built as hook DLLs instead, optionally with [Spice SDK](https://github.com/spice2x/spice2x.github.io/wiki/Spice-SDK).
|
||||
|
||||
### Avoiding regressions
|
||||
|
||||
@@ -104,5 +105,5 @@ if (conditional)
|
||||
* We don't use GSL.
|
||||
* Don't throw exceptions.
|
||||
* Stick to smart pointers. For interfacing with C Win32 API and raw buffers, use `unique_plain_ptr`.
|
||||
* Writing in C is also completely acceptable.
|
||||
* Writing in C is also completely acceptable but prefer to use RAII patterns.
|
||||
* Other than that, there are no strict rules for code formatting, but please attempt to emulate the style around the code you are modifying.
|
||||
@@ -56,6 +56,10 @@ We explicitly do **NOT** have a Discord server for dicussions - we try to do eve
|
||||
|
||||
Please see [CONTRIBUTING page](https://github.com/spice2x/spice2x.github.io/blob/main/CONTRIBUTING.md) for a full list of guidelines when submitting code.
|
||||
|
||||
### AI-Use Policy
|
||||
|
||||
Use AI tools at your discretion, but remember that a human will review every issue and pull request. Please ensure submissions are accurate, relevant, and worth the reviewer’s time.
|
||||
|
||||
## Additional information
|
||||
|
||||
Please read [README.md](https://github.com/spice2x/spice2x.github.io/blob/main/src/spice2x/README.md) inside `src/spice2x`.
|
||||
@@ -254,6 +254,7 @@ add_subdirectory(external/discord-rpc EXCLUDE_FROM_ALL)
|
||||
add_subdirectory(external/hash-library EXCLUDE_FROM_ALL)
|
||||
add_subdirectory(external/imgui EXCLUDE_FROM_ALL)
|
||||
add_subdirectory(external/minhook EXCLUDE_FROM_ALL)
|
||||
add_subdirectory(external/wslay EXCLUDE_FROM_ALL)
|
||||
add_subdirectory(external/cpu_features EXCLUDE_FROM_ALL)
|
||||
|
||||
# libjpeg-turbo, prebuilt into the deps image. The WinXP toolchains have their own
|
||||
@@ -519,6 +520,7 @@ set(SOURCE_FILES ${SOURCE_FILES}
|
||||
games/scotto/io.cpp
|
||||
games/drs/drs.cpp
|
||||
games/drs/io.cpp
|
||||
games/drs/motion_cam.cpp
|
||||
games/drs/rgb_cam.cpp
|
||||
games/we/we.cpp
|
||||
games/we/io.cpp
|
||||
@@ -530,6 +532,7 @@ set(SOURCE_FILES ${SOURCE_FILES}
|
||||
games/otoca/p4io.cpp
|
||||
games/silentscope/silentscope.cpp
|
||||
games/silentscope/io.cpp
|
||||
games/silentscope/projector.cpp
|
||||
games/pcm/pcm.cpp
|
||||
games/pcm/io.cpp
|
||||
games/onpara/onpara.cpp
|
||||
@@ -538,6 +541,7 @@ set(SOURCE_FILES ${SOURCE_FILES}
|
||||
games/onpara/touchpanel.cpp
|
||||
games/bc/bc.cpp
|
||||
games/bc/io.cpp
|
||||
games/bc/bi2x_hook.cpp
|
||||
games/ccj/ccj.cpp
|
||||
games/ccj/io.cpp
|
||||
games/ccj/bi2x_hook.cpp
|
||||
@@ -551,6 +555,13 @@ set(SOURCE_FILES ${SOURCE_FILES}
|
||||
games/pc/pc.cpp
|
||||
games/pc/io.cpp
|
||||
games/pc/bi2x_hook.cpp
|
||||
games/udn/udn.cpp
|
||||
games/udn/io.cpp
|
||||
games/udn/bi2x_hook.cpp
|
||||
games/cardconnect/cardconnect.cpp
|
||||
games/cardconnect/io.cpp
|
||||
games/cardconnect/bi2x_hook.cpp
|
||||
games/cardconnect/printer.cpp
|
||||
|
||||
# hooks
|
||||
hooks/audio/acm.cpp
|
||||
@@ -602,6 +613,7 @@ set(SOURCE_FILES ${SOURCE_FILES}
|
||||
hooks/graphics/backends/d3d9/d3d9_texture.cpp
|
||||
hooks/graphics/backends/d3d11/d3d11_backend.cpp
|
||||
hooks/graphics/backends/d3d11/d3d11_swapchain.cpp
|
||||
hooks/graphics/backends/d3d11/d3d11_swapchain_udn.cpp
|
||||
hooks/graphics/backends/d3d11/d3d11_factory.cpp
|
||||
hooks/graphics/backends/d3d11/d3d11_vtable_capture.cpp
|
||||
hooks/graphics/backends/d3d11/d3d11_screenshot.cpp
|
||||
@@ -613,6 +625,8 @@ set(SOURCE_FILES ${SOURCE_FILES}
|
||||
hooks/networkhook.cpp
|
||||
hooks/icmphook_net.cpp
|
||||
hooks/icmphook_iphlpapi.cpp
|
||||
hooks/nicspoof.cpp
|
||||
hooks/nicspoof_tunnel.cpp
|
||||
hooks/powrprof.cpp
|
||||
#hooks/rom.cpp
|
||||
hooks/setupapihook.cpp
|
||||
@@ -714,6 +728,8 @@ set(SOURCE_FILES ${SOURCE_FILES}
|
||||
reader/crypt.cpp
|
||||
|
||||
# sdk
|
||||
sdk/d3d9.cpp
|
||||
sdk/modules.cpp
|
||||
sdk/sdk.cpp
|
||||
|
||||
# stubs
|
||||
@@ -797,7 +813,7 @@ endfunction()
|
||||
add_library(spicetools_spice_objs OBJECT ${SOURCE_FILES})
|
||||
target_link_libraries(spicetools_spice_objs
|
||||
PUBLIC d3d9 ws2_32 version comctl32 shlwapi iphlpapi hid secur32 setupapi psapi winmm winhttp
|
||||
PRIVATE fmt::fmt-header-only discord-rpc imgui hash-library minhook imm32 dwmapi CpuFeatures::cpu_features spice_jpeg spice_x264)
|
||||
PRIVATE fmt::fmt-header-only discord-rpc imgui hash-library minhook wslay imm32 dwmapi CpuFeatures::cpu_features spice_jpeg spice_x264)
|
||||
target_link_libraries(spicetools_spice_objs PUBLIC winscard)
|
||||
|
||||
if(NOT MSVC)
|
||||
@@ -837,7 +853,7 @@ set(RESOURCE_FILES build/manifest.manifest build/manifest.rc build/icon.rc cfg/W
|
||||
add_executable(spicetools_spice_linux ${SOURCE_FILES} ${RESOURCE_FILES})
|
||||
target_link_libraries(spicetools_spice_linux
|
||||
PUBLIC d3d9 ws2_32 version comctl32 shlwapi iphlpapi hid secur32 setupapi psapi winmm winhttp
|
||||
PRIVATE fmt::fmt-header-only discord-rpc imgui hash-library minhook imm32 dwmapi CpuFeatures::cpu_features spice_jpeg spice_x264)
|
||||
PRIVATE fmt::fmt-header-only discord-rpc imgui hash-library minhook wslay imm32 dwmapi CpuFeatures::cpu_features spice_jpeg spice_x264)
|
||||
set_target_properties(spicetools_spice_linux PROPERTIES PREFIX "")
|
||||
set_target_properties(spicetools_spice_linux PROPERTIES OUTPUT_NAME "spice_linux")
|
||||
target_compile_definitions(spicetools_spice_linux PRIVATE NO_SCARD=1 PRIVATE SPICE_LINUX=1)
|
||||
@@ -855,7 +871,7 @@ add_executable(spicetools_spice64 ${SOURCE_FILES} ${RESOURCE_FILES})
|
||||
# do NOT link against: mf, mfplat, mfreadwrite; otherwise unity games will break
|
||||
target_link_libraries(spicetools_spice64
|
||||
PUBLIC d3d9 ws2_32 version comctl32 shlwapi iphlpapi hid secur32 setupapi psapi winmm winhttp mfuuid strmiids dxva2
|
||||
PRIVATE fmt::fmt-header-only discord-rpc imgui hash-library minhook imm32 dwmapi CpuFeatures::cpu_features spice_jpeg spice_x264)
|
||||
PRIVATE fmt::fmt-header-only discord-rpc imgui hash-library minhook wslay imm32 dwmapi CpuFeatures::cpu_features spice_jpeg spice_x264)
|
||||
target_link_libraries(spicetools_spice64 PUBLIC winscard)
|
||||
set_target_properties(spicetools_spice64 PROPERTIES PREFIX "")
|
||||
set_target_properties(spicetools_spice64 PROPERTIES OUTPUT_NAME "spice64")
|
||||
@@ -878,7 +894,7 @@ add_executable(spicetools_spice64_linux ${SOURCE_FILES} ${RESOURCE_FILES})
|
||||
# do NOT link against: mf, mfplat, mfreadwrite; otherwise unity games will break
|
||||
target_link_libraries(spicetools_spice64_linux
|
||||
PUBLIC d3d9 ws2_32 version comctl32 shlwapi iphlpapi hid secur32 setupapi psapi winmm winhttp mfuuid strmiids dxva2
|
||||
PRIVATE fmt::fmt-header-only discord-rpc imgui hash-library minhook imm32 dwmapi CpuFeatures::cpu_features spice_jpeg spice_x264)
|
||||
PRIVATE fmt::fmt-header-only discord-rpc imgui hash-library minhook wslay imm32 dwmapi CpuFeatures::cpu_features spice_jpeg spice_x264)
|
||||
set_target_properties(spicetools_spice64_linux PROPERTIES PREFIX "")
|
||||
set_target_properties(spicetools_spice64_linux PROPERTIES OUTPUT_NAME "spice64_linux")
|
||||
target_compile_definitions(spicetools_spice64_linux PRIVATE SPICE64=1)
|
||||
@@ -900,7 +916,7 @@ add_executable(spicetools_cfg WIN32 ${SOURCE_FILES} ${RESOURCE_FILES})
|
||||
# the configurator serves neither the API nor the video stream, so it needs no codecs
|
||||
target_link_libraries(spicetools_cfg
|
||||
PUBLIC d3d9 ws2_32 version comctl32 shlwapi iphlpapi hid secur32 setupapi psapi winmm winhttp strmiids
|
||||
PRIVATE fmt::fmt-header-only discord-rpc imgui hash-library minhook imm32 dwmapi CpuFeatures::cpu_features)
|
||||
PRIVATE fmt::fmt-header-only discord-rpc imgui hash-library minhook wslay imm32 dwmapi CpuFeatures::cpu_features)
|
||||
target_link_libraries(spicetools_cfg PUBLIC winscard)
|
||||
set_target_properties(spicetools_cfg PROPERTIES PREFIX "")
|
||||
set_target_properties(spicetools_cfg PROPERTIES OUTPUT_NAME "spicecfg")
|
||||
@@ -918,7 +934,7 @@ set(RESOURCE_FILES cfg/manifest.manifest cfg/manifest.rc cfg/icon.rc cfg/Win32D.
|
||||
add_executable(spicetools_cfg_linux WIN32 ${SOURCE_FILES} ${RESOURCE_FILES})
|
||||
target_link_libraries(spicetools_cfg_linux
|
||||
PUBLIC d3d9 ws2_32 version comctl32 shlwapi iphlpapi hid secur32 setupapi psapi winmm winhttp strmiids
|
||||
PRIVATE fmt::fmt-header-only discord-rpc imgui hash-library minhook imm32 dwmapi CpuFeatures::cpu_features)
|
||||
PRIVATE fmt::fmt-header-only discord-rpc imgui hash-library minhook wslay imm32 dwmapi CpuFeatures::cpu_features)
|
||||
set_target_properties(spicetools_cfg_linux PROPERTIES PREFIX "")
|
||||
set_target_properties(spicetools_cfg_linux PROPERTIES OUTPUT_NAME "spicecfg_linux")
|
||||
target_compile_definitions(spicetools_cfg_linux PRIVATE SPICETOOLS_SPICECFG_STANDALONE=1)
|
||||
@@ -1042,8 +1058,16 @@ if(NOT MSVC)
|
||||
endif()
|
||||
|
||||
# sdk_sample_v0_cpp.dll (64 bit)
|
||||
set(SOURCE_FILES sdk/sample/v0/cpp/v0_cpp.cpp)
|
||||
set(SOURCE_FILES
|
||||
sdk/sample/v0/cpp/v0_cpp.cpp
|
||||
sdk/sample/v0/cpp/v0_cpp_imgui.cpp
|
||||
external/imgui/imgui.cpp
|
||||
external/imgui/imgui_draw.cpp
|
||||
external/imgui/imgui_tables.cpp
|
||||
external/imgui/imgui_widgets.cpp
|
||||
external/imgui/backends/imgui_impl_dx9.cpp)
|
||||
add_library(spicetools_sdk_sample_v0_cpp_64 SHARED ${SOURCE_FILES} ${RESOURCE_FILES} sdk/sample/v0/cpp/v0_cpp.def)
|
||||
target_link_libraries(spicetools_sdk_sample_v0_cpp_64 PRIVATE imm32)
|
||||
set_target_properties(spicetools_sdk_sample_v0_cpp_64 PROPERTIES PREFIX "")
|
||||
set_target_properties(spicetools_sdk_sample_v0_cpp_64 PROPERTIES OUTPUT_NAME "sdk_sample_v0_cpp")
|
||||
|
||||
|
||||
+31
-3
@@ -127,7 +127,30 @@ doesn't matter since the TCP protocol doesn't allow for out of order data,
|
||||
however this may change when/if support for UDP is being introduced. The only
|
||||
restriction is that the ID has to be a valid 64-bit unsigned integer.
|
||||
|
||||
#### Capture
|
||||
- get_screens()
|
||||
- returns the screen numbers the game has registered for capture
|
||||
- get_jpg(screen: uint, quality: uint, divide: uint)
|
||||
- returns the timestamp, width, height and base64 encoded JPEG of one screen
|
||||
- all parameters are optional and default to screen 0, quality 70, divide 1
|
||||
- divide shrinks the image by that factor before encoding
|
||||
- get_streams()
|
||||
- returns a dict describing the HTTP video stream, or no data at all when
|
||||
`-apistream` is not enabled and there is nothing to describe
|
||||
- `port` is the stream server port
|
||||
- `formats` lists the wire formats this build serves, each with a `name`
|
||||
(`h264` or `mjpeg`) and the `path` to request them on
|
||||
- `screens` lists every capturable screen with its `width`, `height`, and
|
||||
`busy`
|
||||
|
||||
#### Card
|
||||
- get_cards()
|
||||
- returns the current card ID and source for each active card reader
|
||||
- each entry contains `index`, `card_id`, and `source`
|
||||
- `source` is `file` or `override`
|
||||
- file entries also contain `file_name`, without the full configured path
|
||||
- `-card0` and `-card1` overrides do not contain `file_name`
|
||||
- this function only works when an API password is configured
|
||||
- insert(index: uint, card_id: hex)
|
||||
- inserts a card which gets read by the emulated card readers for the game
|
||||
- index has to be either 0 (for P1) or 1 (for P2)
|
||||
@@ -298,6 +321,10 @@ stream over plain HTTP. Enable it with `-apistream`. It listens on the API port
|
||||
plus two, in the same way the WebSocket server uses the API port plus one, so
|
||||
`-api 1337` puts the stream on 1339. This means `-api` has to be enabled too.
|
||||
|
||||
Rather than working the port out, clients should ask the JSON API for it with
|
||||
`capture.get_streams()`, which also reports which of the formats below this
|
||||
build serves, the size of each screen and whether one is already taken.
|
||||
|
||||
Two formats are served:
|
||||
|
||||
http://host:1339/stream.mjpg JPEG frames, multipart/x-mixed-replace
|
||||
@@ -323,9 +350,10 @@ The stream is view only. Touch and other input still go through the JSON API,
|
||||
so a companion app needs both. There is no authentication on the stream port -
|
||||
anyone who can reach it can watch the screen.
|
||||
|
||||
WinXP builds have no video stream. Neither encoder is compiled in, so every
|
||||
endpoint returns 404, and the JSON API's JPEG screen capture is unavailable for
|
||||
the same reason.
|
||||
WinXP builds have no video stream. Neither encoder is compiled in, so nothing
|
||||
listens on the stream port even with `-apistream`, `capture.get_streams()`
|
||||
returns no data, and the JSON API's JPEG screen capture is unavailable for the
|
||||
same reason.
|
||||
|
||||
## Native wrapper libraries
|
||||
Spicetools provides wrapper libraries in: Arduino, C++, Dart, and Python.
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#include "bmpu.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include "acio/icca/icca.h"
|
||||
#include "avs/game.h"
|
||||
#include "cfg/api.h"
|
||||
@@ -9,6 +11,7 @@
|
||||
#include "games/ftt/io.h"
|
||||
#include "games/museca/io.h"
|
||||
#include "games/silentscope/io.h"
|
||||
#include "hooks/graphics/graphics.h"
|
||||
#include "launcher/launcher.h"
|
||||
#include "misc/eamuse.h"
|
||||
|
||||
@@ -530,15 +533,38 @@ static bool __cdecl ac_io_bmpu_update_control_status_buffer() {
|
||||
STATUS_BUFFER[4] |= 0x20;
|
||||
}
|
||||
|
||||
// joy stick raw input
|
||||
// gun position, sent big endian; the game keeps the top 12 bits of each pair
|
||||
auto &analogs = games::silentscope::get_analogs();
|
||||
auto &gun_x = analogs.at(games::silentscope::Analogs::GUN_X);
|
||||
auto &gun_y = analogs.at(games::silentscope::Analogs::GUN_Y);
|
||||
unsigned short joy_x = 0x7FFF;
|
||||
unsigned short joy_y = 0x7FFF;
|
||||
if (analogs.at(games::silentscope::Analogs::GUN_X).isSet()) {
|
||||
joy_x = (unsigned short) (Analogs::getState(RI_MGR, analogs.at(games::silentscope::Analogs::GUN_X)) * USHRT_MAX);
|
||||
}
|
||||
if (analogs.at(games::silentscope::Analogs::GUN_Y).isSet()) {
|
||||
joy_y = (unsigned short) (Analogs::getState(RI_MGR, analogs.at(games::silentscope::Analogs::GUN_Y)) * USHRT_MAX);
|
||||
|
||||
if (gun_x.isSet() || gun_y.isSet()) {
|
||||
if (gun_x.isSet()) {
|
||||
joy_x = (unsigned short) (Analogs::getState(RI_MGR, gun_x) * USHRT_MAX);
|
||||
}
|
||||
if (gun_y.isSet()) {
|
||||
joy_y = (unsigned short) (Analogs::getState(RI_MGR, gun_y) * USHRT_MAX);
|
||||
}
|
||||
} else {
|
||||
|
||||
// the gun reports where it is aimed, which a relative pointer cannot express - the
|
||||
// calibration screen asks for the screen centre and two corners, so read the cursor
|
||||
POINT cursor {};
|
||||
RECT client {};
|
||||
POINT origin {};
|
||||
if (NDD_MAIN_WINDOW != nullptr &&
|
||||
GetCursorPos(&cursor) &&
|
||||
GetClientRect(NDD_MAIN_WINDOW, &client) &&
|
||||
ClientToScreen(NDD_MAIN_WINDOW, &origin) &&
|
||||
client.right > 1 && client.bottom > 1)
|
||||
{
|
||||
const LONG x = std::clamp(cursor.x - origin.x, 0L, client.right - 1);
|
||||
const LONG y = std::clamp(cursor.y - origin.y, 0L, client.bottom - 1);
|
||||
joy_x = (unsigned short) (x * USHRT_MAX / (client.right - 1));
|
||||
joy_y = (unsigned short) (y * USHRT_MAX / (client.bottom - 1));
|
||||
}
|
||||
}
|
||||
|
||||
// invert X axis
|
||||
|
||||
@@ -118,11 +118,11 @@ static inline void update_card(int unit_id) {
|
||||
const bool card_presented = eamuse_card_insert_consume(icca_get_active_count(), unit_id);
|
||||
const bool key_pressed = (kb_insert_press && !kb_insert_press_old[unit_id]);
|
||||
|
||||
// beatstream and nostalgia have logic that requires ac_io_icca_get_uid_felica to return the
|
||||
// beatstream, nostalgia and Dance Evolution have logic that requires ac_io_icca_get_uid_felica to return the
|
||||
// exact same card number multiple times in a row in order for the card number to be read...
|
||||
// for whatever reason setting this to 3-4 doesn't work the very first time the game boots up
|
||||
// so we use 10 just to be safe
|
||||
const bool need_felica_retries = avs::game::is_model({"NBT", "PAN"});
|
||||
const bool need_felica_retries = avs::game::is_model({"KDM", "NBT", "PAN"});
|
||||
if (need_felica_retries && (card_presented || key_pressed)) {
|
||||
unit->felica_retries = 10;
|
||||
}
|
||||
|
||||
@@ -46,17 +46,14 @@ MessageData *ACIODeviceEmu::create_msg(uint8_t addr, uint16_t code, uint8_t pid,
|
||||
}
|
||||
|
||||
// allocate data
|
||||
auto data_raw = new uint8_t[MSG_HEADER_SIZE + data_size];
|
||||
auto msg = new MessageData {};
|
||||
|
||||
// set header
|
||||
auto msg = (MessageData *) &data_raw[0];
|
||||
set_header(msg, addr, code, pid, (uint8_t) data_size);
|
||||
|
||||
// set data
|
||||
if (data) {
|
||||
memcpy(data_raw + MSG_HEADER_SIZE, data, data_size);
|
||||
} else {
|
||||
memset(data_raw + MSG_HEADER_SIZE, 0, data_size);
|
||||
memcpy(msg->cmd.raw, data, data_size);
|
||||
}
|
||||
|
||||
// return prepared message
|
||||
|
||||
@@ -14,15 +14,20 @@ bool acioemu::ACIOHandle::open(LPCWSTR lpFileName) {
|
||||
return false;
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
log_info("acioemu", "Opened {} (ACIO)", ws2s(com_port));
|
||||
|
||||
// ACIO device
|
||||
acio_emu.add_device(new acioemu::ICCADevice(false, true, icca_node_count));
|
||||
if (!initialized) {
|
||||
acio_emu.add_device(new acioemu::ICCADevice(false, true, icca_node_count));
|
||||
initialized = true;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
int acioemu::ACIOHandle::read(LPVOID lpBuffer, DWORD nNumberOfBytesToRead) {
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
auto buffer = reinterpret_cast<uint8_t *>(lpBuffer);
|
||||
|
||||
// read from emu
|
||||
@@ -42,6 +47,7 @@ int acioemu::ACIOHandle::read(LPVOID lpBuffer, DWORD nNumberOfBytesToRead) {
|
||||
}
|
||||
|
||||
int acioemu::ACIOHandle::write(LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite) {
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
auto buffer = reinterpret_cast<const uint8_t *>(lpBuffer);
|
||||
|
||||
// write to emu
|
||||
@@ -64,6 +70,7 @@ int acioemu::ACIOHandle::device_io(
|
||||
}
|
||||
|
||||
size_t acioemu::ACIOHandle::bytes_available() {
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
return acio_emu.bytes_available();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <mutex>
|
||||
|
||||
#include "acioemu/acioemu.h"
|
||||
#include "hooks/devicehook.h"
|
||||
|
||||
@@ -12,6 +14,8 @@ namespace acioemu {
|
||||
uint8_t icca_node_count;
|
||||
|
||||
acioemu::ACIOEmu acio_emu;
|
||||
std::mutex mutex;
|
||||
bool initialized = false;
|
||||
|
||||
public:
|
||||
ACIOHandle(LPCWSTR lpCOMPort, uint8_t iccaNodeCount = 2);
|
||||
|
||||
@@ -46,9 +46,9 @@ ICCADevice::ICCADevice(bool flip_order, bool keypad_thread, uint8_t node_count)
|
||||
|
||||
// keypad thread for faster polling
|
||||
if (keypad_thread) {
|
||||
this->keypad_thread = new std::thread([this]() {
|
||||
this->keypad_thread = std::jthread([this](std::stop_token stop_token) {
|
||||
timeutils::PreciseSleepTimer timer;
|
||||
while (this->cards) {
|
||||
while (!stop_token.stop_requested()) {
|
||||
for (int unit = 0; unit < this->node_count; unit++) {
|
||||
this->update_keypad(unit, false);
|
||||
}
|
||||
@@ -61,11 +61,15 @@ ICCADevice::ICCADevice(bool flip_order, bool keypad_thread, uint8_t node_count)
|
||||
ICCADevice::~ICCADevice() {
|
||||
|
||||
// stop thread
|
||||
delete keypad_thread;
|
||||
if (keypad_thread.joinable()) {
|
||||
keypad_thread.request_stop();
|
||||
keypad_thread.join();
|
||||
}
|
||||
|
||||
// delete cards in array
|
||||
for (int i = 0; i < node_count; i++) {
|
||||
delete cards[i];
|
||||
delete[] cards[i];
|
||||
delete[] keypad_last[i];
|
||||
}
|
||||
|
||||
// delete the rest
|
||||
@@ -107,7 +111,7 @@ bool ICCADevice::parse_msg(MessageData *msg_in,
|
||||
if (avs::game::is_model({"LDJ", "TBS", "UJK", "XIF"}) ||
|
||||
games::sdvx::is_valkyrie_model()) {
|
||||
this->set_version(msg, 0x3, 0, 1, 7, 0, "ICCA");
|
||||
} else if (avs::game::is_model("VFG")) {
|
||||
} else if (avs::game::is_model({"VFG", "TCS"})) {
|
||||
this->set_version(msg, 0x3, 0, 1, 7, 0, "ICCB");
|
||||
} else {
|
||||
this->set_version(msg, 0x3, 0, 1, 6, 0, "ICCA");
|
||||
@@ -160,7 +164,7 @@ bool ICCADevice::parse_msg(MessageData *msg_in,
|
||||
break;
|
||||
case 0x12: // EJECT
|
||||
if (this->cards[unit] != nullptr) {
|
||||
delete this->cards[unit];
|
||||
delete[] this->cards[unit];
|
||||
}
|
||||
this->cards[unit] = nullptr;
|
||||
this->hold[unit] = false;
|
||||
@@ -267,7 +271,7 @@ bool ICCADevice::parse_msg(MessageData *msg_in,
|
||||
memcpy(msg->cmd.raw, this->cards[unit], 8);
|
||||
|
||||
// delete card
|
||||
delete this->cards[unit];
|
||||
delete[] this->cards[unit];
|
||||
this->cards[unit] = nullptr;
|
||||
this->hold[unit] = false;
|
||||
}
|
||||
@@ -326,7 +330,9 @@ bool ICCADevice::parse_msg(MessageData *msg_in,
|
||||
}
|
||||
//log_info("icca", "counter[{}] = {}", unit, this->counter[unit]);
|
||||
|
||||
auto msg = this->create_msg_status(msg_in, this->counter[unit]);
|
||||
// Card Connect waits for a successful reply without retrying this command.
|
||||
auto msg = this->create_msg_status(
|
||||
msg_in, avs::game::is_model("TCS") ? 0 : this->counter[unit]);
|
||||
write_msg(msg, response_buffer);
|
||||
delete msg;
|
||||
break;
|
||||
@@ -363,7 +369,7 @@ void ICCADevice::update_card(int unit) {
|
||||
|
||||
if (difftime(t_now, this->cards_time[unit]) >= 10.f) {
|
||||
if (this->cards[unit] != nullptr) {
|
||||
delete this->cards[unit];
|
||||
delete[] this->cards[unit];
|
||||
}
|
||||
this->cards[unit] = nullptr;
|
||||
this->hold[unit] = false;
|
||||
|
||||
@@ -17,7 +17,7 @@ namespace acioemu {
|
||||
private:
|
||||
bool type_new;
|
||||
bool flip_order;
|
||||
std::thread *keypad_thread;
|
||||
std::jthread keypad_thread;
|
||||
std::mutex keypad_mutex;
|
||||
uint8_t **cards;
|
||||
time_t *cards_time;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#include "capture_pump.h"
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
|
||||
#include "hooks/graphics/graphics.h"
|
||||
@@ -11,8 +12,8 @@ namespace api::capture_pump {
|
||||
|
||||
std::array<std::mutex, GRAPHICS_CAPTURE_SCREEN_NO> CONSUMER_M;
|
||||
|
||||
std::mutex CLAIMED_M;
|
||||
std::array<bool, GRAPHICS_CAPTURE_SCREEN_NO> CLAIMED {};
|
||||
// read once per capture from the present thread, so it stays lock free
|
||||
std::atomic<bool> CLAIMED[GRAPHICS_CAPTURE_SCREEN_NO] {};
|
||||
|
||||
bool valid_screen(int screen) {
|
||||
return 0 <= screen && screen < static_cast<int>(GRAPHICS_CAPTURE_SCREEN_NO);
|
||||
@@ -37,14 +38,7 @@ namespace api::capture_pump {
|
||||
return false;
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(CLAIMED_M);
|
||||
|
||||
if (CLAIMED[screen]) {
|
||||
return false;
|
||||
}
|
||||
|
||||
CLAIMED[screen] = true;
|
||||
return true;
|
||||
return !CLAIMED[screen].exchange(true);
|
||||
}
|
||||
|
||||
void release_screen(int screen) {
|
||||
@@ -52,7 +46,14 @@ namespace api::capture_pump {
|
||||
return;
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(CLAIMED_M);
|
||||
CLAIMED[screen] = false;
|
||||
}
|
||||
|
||||
bool screen_claimed(int screen) {
|
||||
if (!valid_screen(screen)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return CLAIMED[screen];
|
||||
}
|
||||
}
|
||||
@@ -21,4 +21,7 @@ namespace api::capture_pump {
|
||||
// a screen carries one stream at a time; false when another connection already holds it
|
||||
bool claim_screen(int screen);
|
||||
void release_screen(int screen);
|
||||
|
||||
// true while a video stream client holds this screen
|
||||
bool screen_claimed(int screen);
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
#include "client.h"
|
||||
#include "cfg/configurator.h"
|
||||
#include "external/rapidjson/document.h"
|
||||
#include "external/rapidjson/error/en.h"
|
||||
#include "util/crypt.h"
|
||||
#include "util/logging.h"
|
||||
#include "util/utils.h"
|
||||
@@ -92,6 +93,7 @@ Controller::Controller(unsigned short port, std::string password, bool pretty)
|
||||
// bind socket to address
|
||||
if (bind(this->server, (sockaddr *) &server_address, sizeof(sockaddr)) == -1) {
|
||||
log_warning("api", "could not bind socket on port {}: {}", port, get_last_error_string());
|
||||
closesocket(this->server);
|
||||
this->server = INVALID_SOCKET;
|
||||
if (!cfg::CONFIGURATOR_STANDALONE) {
|
||||
log_fatal("api", "failed to start server");
|
||||
@@ -102,6 +104,7 @@ Controller::Controller(unsigned short port, std::string password, bool pretty)
|
||||
// set socket to listen
|
||||
if (listen(this->server, server_backlog) == -1) {
|
||||
log_warning("api", "could not listen to socket on port {}: {}", port, get_last_error_string());
|
||||
closesocket(this->server);
|
||||
this->server = INVALID_SOCKET;
|
||||
if (!cfg::CONFIGURATOR_STANDALONE) {
|
||||
log_fatal("api", "failed to start server");
|
||||
@@ -312,6 +315,8 @@ bool Controller::process_request(ClientState *state, const char *in, size_t in_s
|
||||
|
||||
// check for parse error
|
||||
if (document.HasParseError()) {
|
||||
log_warning("api", "Request JSON parse error: {} (byte offset {}, decrypted request length {} bytes)",
|
||||
GetParseError_En(document.GetParseError()), document.GetErrorOffset(), in_size);
|
||||
|
||||
// return empty response and close connection
|
||||
out->push_back(0);
|
||||
@@ -337,9 +342,11 @@ bool Controller::process_request(ClientState *state, const char *in, size_t in_s
|
||||
if (module->name == request.module) {
|
||||
module_found = true;
|
||||
|
||||
// check password force
|
||||
if (module->password_force && this->password.empty() && request.function != "session_refresh") {
|
||||
Value err("Module requires the password to be set.");
|
||||
// check password requirement
|
||||
if (module->requires_password(request.function)
|
||||
&& this->password.empty()
|
||||
&& request.function != "session_refresh") {
|
||||
Value err("Function requires the password to be set.");
|
||||
response.add_error(err);
|
||||
break;
|
||||
}
|
||||
@@ -441,7 +448,9 @@ void Controller::free_socket() {
|
||||
this->server = INVALID_SOCKET;
|
||||
}
|
||||
|
||||
this->websocket->free_socket();
|
||||
if (this->websocket) {
|
||||
this->websocket->free_socket();
|
||||
}
|
||||
|
||||
for (auto &s : this->serial) {
|
||||
s->free_port();
|
||||
|
||||
@@ -41,21 +41,21 @@ namespace api {
|
||||
bool pretty;
|
||||
|
||||
// server
|
||||
WebSocketController *websocket;
|
||||
WebSocketController *websocket = nullptr;
|
||||
std::vector<SerialController *> serial;
|
||||
std::vector<std::thread> server_workers;
|
||||
std::vector<std::thread> server_handlers;
|
||||
std::mutex server_handlers_m;
|
||||
std::vector<api::ClientState *> client_states;
|
||||
std::mutex client_states_m;
|
||||
SOCKET server;
|
||||
SOCKET server = INVALID_SOCKET;
|
||||
void server_worker();
|
||||
void connection_handler(ClientState client_state);
|
||||
|
||||
public:
|
||||
|
||||
// state
|
||||
bool server_running;
|
||||
bool server_running = false;
|
||||
|
||||
// constructor / destructor
|
||||
Controller(unsigned short port, std::string password, bool pretty);
|
||||
|
||||
@@ -118,7 +118,13 @@ namespace api {
|
||||
param.i_height = height;
|
||||
param.i_fps_num = this->fps;
|
||||
param.i_fps_den = 1;
|
||||
param.i_threads = 1;
|
||||
|
||||
// sliced threading, which zerolatency already selected, so a frame is split
|
||||
// across workers rather than held back to be reordered. deliberately not the
|
||||
// automatic count: this shares a machine with the game it is capturing, and
|
||||
// taking every core to encode would win back frames at the game's expense
|
||||
param.i_threads = 4;
|
||||
|
||||
param.b_annexb = 1;
|
||||
// SPS/PPS ahead of every IDR, so a client can start decoding cold
|
||||
param.b_repeat_headers = 1;
|
||||
|
||||
@@ -16,6 +16,14 @@ namespace api {
|
||||
this->password_force = password_force;
|
||||
}
|
||||
|
||||
void Module::require_password(const std::string &function) {
|
||||
this->password_force_functions.emplace(function);
|
||||
}
|
||||
|
||||
bool Module::requires_password(const std::string &function) const {
|
||||
return this->password_force || this->password_force_functions.contains(function);
|
||||
}
|
||||
|
||||
void Module::handle(Request &req, Response &res) {
|
||||
|
||||
// log module access
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <sstream>
|
||||
#include <unordered_set>
|
||||
#include <external/robin_hood.h>
|
||||
|
||||
#include "response.h"
|
||||
@@ -26,6 +27,13 @@ namespace api {
|
||||
// default constructor
|
||||
explicit Module(std::string name, bool password_force=false);
|
||||
|
||||
void require_password(const std::string &function);
|
||||
|
||||
private:
|
||||
|
||||
// functions which expose sensitive data or actions
|
||||
std::unordered_set<std::string> password_force_functions;
|
||||
|
||||
public:
|
||||
|
||||
// virtual deconstructor
|
||||
@@ -35,6 +43,8 @@ namespace api {
|
||||
std::string name;
|
||||
bool password_force;
|
||||
|
||||
bool requires_password(const std::string &function) const;
|
||||
|
||||
// the magic
|
||||
void handle(Request &req, Response &res);
|
||||
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
#include "capture.h"
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <unordered_map>
|
||||
#include "api/capture_pump.h"
|
||||
#include "api/stream_format.h"
|
||||
#include "api/stream_server.h"
|
||||
#include "external/rapidjson/document.h"
|
||||
#include "hooks/graphics/graphics.h"
|
||||
#include "hooks/graphics/jpeg_encoder.h"
|
||||
@@ -71,6 +74,7 @@ namespace api::modules {
|
||||
Capture::Capture() : Module("capture") {
|
||||
functions["get_screens"] = std::bind(&Capture::get_screens, this, _1, _2);
|
||||
functions["get_jpg"] = std::bind(&Capture::get_jpg, this, _1, _2);
|
||||
functions["get_streams"] = std::bind(&Capture::get_streams, this, _1, _2);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -141,4 +145,98 @@ namespace api::modules {
|
||||
CAPTURE_BUFFER.clear();
|
||||
try_cached_response(screen, res);
|
||||
}
|
||||
|
||||
/**
|
||||
* get_streams()
|
||||
*/
|
||||
void Capture::get_streams(Request &req, Response &res) {
|
||||
|
||||
auto &alloc = res.doc()->GetAllocator();
|
||||
|
||||
// nothing is listening without -apistream, so there is no stream to describe
|
||||
const unsigned short port = stream_server_port();
|
||||
if (port == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
Value formats(kArrayType);
|
||||
for (const auto &[name, path] : stream_formats()) {
|
||||
Value entry(kObjectType);
|
||||
entry.AddMember("name", Value(name.c_str(), alloc), alloc);
|
||||
entry.AddMember("path", Value(path.c_str(), alloc), alloc);
|
||||
formats.PushBack(entry, alloc);
|
||||
}
|
||||
|
||||
std::vector<int> screen_numbers;
|
||||
graphics_screens_get(screen_numbers);
|
||||
|
||||
// measuring a screen nobody has captured yet waits for the game to present, which can
|
||||
// take as long as the whole request is allowed, so only one screen is measured per
|
||||
// call and the rest are reported null until a later one settles them. which screen
|
||||
// gets the attempt rotates, otherwise one that never presents would take every
|
||||
// request and the screens behind it would stay unmeasured forever
|
||||
int probe_screen = -1;
|
||||
{
|
||||
std::vector<int> unmeasured;
|
||||
for (const auto screen : screen_numbers) {
|
||||
if (screen < static_cast<int>(GRAPHICS_CAPTURE_SCREEN_NO)
|
||||
&& !graphics_capture_last_size(screen, nullptr, nullptr)
|
||||
&& !capture_pump::screen_claimed(screen)) {
|
||||
unmeasured.push_back(screen);
|
||||
}
|
||||
}
|
||||
|
||||
if (!unmeasured.empty()) {
|
||||
static std::atomic<unsigned> probe_cursor { 0 };
|
||||
probe_screen = unmeasured[probe_cursor.fetch_add(1) % unmeasured.size()];
|
||||
}
|
||||
}
|
||||
|
||||
Value screens(kArrayType);
|
||||
for (const auto screen : screen_numbers) {
|
||||
if (screen >= static_cast<int>(GRAPHICS_CAPTURE_SCREEN_NO)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
int width = 0;
|
||||
int height = 0;
|
||||
bool known = graphics_capture_last_size(screen, &width, &height);
|
||||
|
||||
// a probe holds the screen for as long as it waits, so a second caller arriving
|
||||
// during one would queue behind it and then take a wait of its own; let it report
|
||||
// the screen as unmeasured instead and pick the size up once the first is done
|
||||
static std::atomic<bool> probe_running { false };
|
||||
if (!known && screen == probe_screen && !probe_running.exchange(true)) {
|
||||
std::shared_ptr<uint8_t[]> pixels;
|
||||
known = capture_pump::capture_direct(
|
||||
screen, pixels, 1, nullptr, &width, &height);
|
||||
probe_running = false;
|
||||
}
|
||||
|
||||
// a screen of unknown size cannot be described, and a client told about it could
|
||||
// not size its decoder anyway; leaving it out until it has been measured beats
|
||||
// handing over an entry that has to be treated as absent
|
||||
if (!known) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Value entry(kObjectType);
|
||||
entry.AddMember("screen", screen, alloc);
|
||||
entry.AddMember("width", width, alloc);
|
||||
entry.AddMember("height", height, alloc);
|
||||
|
||||
// a screen carries one viewer at a time, so this is what decides whether a client
|
||||
// can connect at all; still racy by the time it does, only more honest than not
|
||||
entry.AddMember("busy", capture_pump::screen_claimed(screen), alloc);
|
||||
|
||||
screens.PushBack(entry, alloc);
|
||||
}
|
||||
|
||||
Value info(kObjectType);
|
||||
info.AddMember("port", port, alloc);
|
||||
info.AddMember("formats", formats, alloc);
|
||||
info.AddMember("screens", screens, alloc);
|
||||
|
||||
res.add_data(info);
|
||||
}
|
||||
}
|
||||
@@ -19,5 +19,6 @@ namespace api::modules {
|
||||
// function definitions
|
||||
void get_screens(Request &req, Response &res);
|
||||
void get_jpg(Request &req, Response &res);
|
||||
void get_streams(Request &req, Response &res);
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "card.h"
|
||||
#include <fstream>
|
||||
#include <functional>
|
||||
#include "external/rapidjson/document.h"
|
||||
#include "util/logging.h"
|
||||
@@ -11,8 +12,71 @@ using namespace rapidjson;
|
||||
|
||||
namespace api::modules {
|
||||
|
||||
static bool normalize_card_id(const std::string &value, std::string &card_id) {
|
||||
if (value.size() != 16) {
|
||||
return false;
|
||||
}
|
||||
|
||||
uint8_t card_bin[8] {};
|
||||
if (!hex2bin(value.c_str(), card_bin)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
card_id = bin2hex(card_bin, std::size(card_bin));
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool read_card_id(const std::filesystem::path &path, std::string &card_id) {
|
||||
std::ifstream file(path);
|
||||
char buffer[16] {};
|
||||
if (!file.read(buffer, std::size(buffer))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return normalize_card_id(std::string(buffer, std::size(buffer)), card_id);
|
||||
}
|
||||
|
||||
Card::Card() : Module("card") {
|
||||
functions["get_cards"] = std::bind(&Card::get_cards, this, _1, _2);
|
||||
functions["insert"] = std::bind(&Card::insert, this, _1, _2);
|
||||
require_password("get_cards");
|
||||
}
|
||||
|
||||
/**
|
||||
* get_cards()
|
||||
*/
|
||||
void Card::get_cards(Request &req, Response &res) {
|
||||
auto &alloc = res.doc()->GetAllocator();
|
||||
|
||||
for (int index = 0; index < eamuse_get_game_keypads(); index++) {
|
||||
std::string card_id;
|
||||
std::string filename;
|
||||
const auto card_override = eamuse_get_card_override(index);
|
||||
const bool has_override = !card_override.empty();
|
||||
|
||||
if (has_override) {
|
||||
if (!normalize_card_id(card_override, card_id)) {
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
const auto path = eamuse_get_card_path(index);
|
||||
if (!read_card_id(path, card_id)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const auto filename_u8 = path.filename().u8string();
|
||||
filename.assign(filename_u8.begin(), filename_u8.end());
|
||||
}
|
||||
|
||||
Value card(kObjectType);
|
||||
card.AddMember("index", index, alloc);
|
||||
card.AddMember("card_id", Value(card_id.c_str(), alloc), alloc);
|
||||
card.AddMember("source", Value(has_override ? "override" : "file", alloc), alloc);
|
||||
if (!has_override) {
|
||||
card.AddMember("file_name", Value(filename.c_str(), alloc), alloc);
|
||||
}
|
||||
res.add_data(card);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -12,6 +12,7 @@ namespace api::modules {
|
||||
private:
|
||||
|
||||
// function definitions
|
||||
void get_cards(Request &req, Response &res);
|
||||
void insert(Request &req, Response &res);
|
||||
};
|
||||
}
|
||||
@@ -61,7 +61,7 @@ namespace api::modules {
|
||||
return error_type(res, "amount", "int");
|
||||
|
||||
// add to coin stock
|
||||
eamuse_coin_set_stock(eamuse_coin_get_stock() + std::max(0, req.params[0].GetInt()));
|
||||
eamuse_coin_add(std::max(0, req.params[0].GetInt()));
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
@@ -11,6 +11,7 @@ part "src/exceptions.dart";
|
||||
part "src/rc4.dart";
|
||||
part "src/wrappers/analogs.dart";
|
||||
part "src/wrappers/buttons.dart";
|
||||
part "src/wrappers/capture.dart";
|
||||
part "src/wrappers/card.dart";
|
||||
part "src/wrappers/coin.dart";
|
||||
part "src/wrappers/control.dart";
|
||||
|
||||
@@ -4,8 +4,8 @@ part of spiceapi;
|
||||
class Connection {
|
||||
|
||||
// settings
|
||||
static const _TIMEOUT = Duration(seconds: 2);
|
||||
static const _BUFFER_SIZE = 1024 * 8;
|
||||
static const _TIMEOUT = Duration(seconds: 3);
|
||||
static const _BUFFER_SIZE = 1024 * 1024 * 8;
|
||||
|
||||
// state
|
||||
final String host, pass;
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
part of spiceapi;
|
||||
|
||||
class CaptureData {
|
||||
int timestamp;
|
||||
int width, height;
|
||||
Uint8List data;
|
||||
}
|
||||
|
||||
var _base64DecoderInstance = Base64Decoder();
|
||||
|
||||
Future<List> captureGetScreens(Connection con) {
|
||||
var req = Request("capture", "get_screens");
|
||||
return con.request(req).then((res) {
|
||||
return res.getData();
|
||||
});
|
||||
}
|
||||
|
||||
Future<CaptureData> captureGetJPG(Connection con, {
|
||||
int screen = 0,
|
||||
int quality = 70,
|
||||
int divide = 1,
|
||||
}) {
|
||||
var req = Request("capture", "get_jpg");
|
||||
req.addParam(screen);
|
||||
req.addParam(quality);
|
||||
req.addParam(divide);
|
||||
return con.request(req).then((res) {
|
||||
var captureData = CaptureData();
|
||||
var data = res.getData();
|
||||
if (data.length > 0) captureData.timestamp = data[0];
|
||||
if (data.length > 1) captureData.width = data[1];
|
||||
if (data.length > 2) captureData.height = data[2];
|
||||
if (data.length > 3) {
|
||||
captureData.data = _base64DecoderInstance.convert(data[3]);
|
||||
}
|
||||
return captureData;
|
||||
});
|
||||
}
|
||||
|
||||
/// Describes the HTTP video stream, or null when this spice2x serves none.
|
||||
Future<Map> captureGetStreams(Connection con) {
|
||||
var req = Request("capture", "get_streams");
|
||||
return con.request(req).then((res) {
|
||||
var data = res.getData();
|
||||
return data.length > 0 ? data[0] : null;
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,32 @@
|
||||
part of spiceapi;
|
||||
|
||||
class CardInfo {
|
||||
final int index;
|
||||
final String cardID;
|
||||
final String source;
|
||||
final String? fileName;
|
||||
|
||||
CardInfo(this.index, this.cardID, this.source, this.fileName);
|
||||
}
|
||||
|
||||
Future<List<CardInfo>> cardGetCards(Connection con) {
|
||||
var req = Request("card", "get_cards");
|
||||
return con.request(req).then((res) {
|
||||
List<CardInfo> cards = [];
|
||||
for (var value in res.getData()) {
|
||||
cards.add(
|
||||
CardInfo(
|
||||
value["index"],
|
||||
value["card_id"],
|
||||
value["source"],
|
||||
value["file_name"],
|
||||
),
|
||||
);
|
||||
}
|
||||
return cards;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> cardInsert(Connection con, int unit, String cardID) {
|
||||
var req = Request("card", "insert");
|
||||
req.addParam(unit);
|
||||
|
||||
@@ -17,7 +17,7 @@ Future<List> captureGetScreens(Connection con) {
|
||||
|
||||
Future<CaptureData> captureGetJPG(Connection con, {
|
||||
int screen = 0,
|
||||
int quality = 60,
|
||||
int quality = 70,
|
||||
int divide = 1,
|
||||
}) {
|
||||
var req = Request("capture", "get_jpg");
|
||||
@@ -36,3 +36,12 @@ Future<CaptureData> captureGetJPG(Connection con, {
|
||||
return captureData;
|
||||
});
|
||||
}
|
||||
|
||||
/// Describes the HTTP video stream, or null when this spice2x serves none.
|
||||
Future<Map> captureGetStreams(Connection con) {
|
||||
var req = Request("capture", "get_streams");
|
||||
return con.request(req).then((res) {
|
||||
var data = res.getData();
|
||||
return data.length > 0 ? data[0] : null;
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,32 @@
|
||||
part of spiceapi;
|
||||
|
||||
class CardInfo {
|
||||
final int index;
|
||||
final String cardID;
|
||||
final String source;
|
||||
final String? fileName;
|
||||
|
||||
CardInfo(this.index, this.cardID, this.source, this.fileName);
|
||||
}
|
||||
|
||||
Future<List<CardInfo>> cardGetCards(Connection con) {
|
||||
var req = Request("card", "get_cards");
|
||||
return con.request(req).then((res) {
|
||||
List<CardInfo> cards = [];
|
||||
for (var value in res.getData()) {
|
||||
cards.add(
|
||||
CardInfo(
|
||||
value["index"],
|
||||
value["card_id"],
|
||||
value["source"],
|
||||
value["file_name"],
|
||||
),
|
||||
);
|
||||
}
|
||||
return cards;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> cardInsert(Connection con, int unit, String cardID) {
|
||||
var req = Request("card", "insert");
|
||||
req.addParam(unit);
|
||||
|
||||
@@ -2,6 +2,7 @@ from .connection import Connection
|
||||
from .request import Request
|
||||
from .analogs import *
|
||||
from .buttons import *
|
||||
from .capture import *
|
||||
from .card import *
|
||||
from .coin import *
|
||||
from .control import *
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import base64
|
||||
|
||||
from .connection import Connection
|
||||
from .request import Request
|
||||
|
||||
|
||||
def capture_get_screens(con: Connection):
|
||||
res = con.request(Request("capture", "get_screens"))
|
||||
return res.get_data()
|
||||
|
||||
|
||||
def capture_get_jpg(con: Connection, screen: int = 0, quality: int = 70, divide: int = 1):
|
||||
req = Request("capture", "get_jpg")
|
||||
req.add_param(screen)
|
||||
req.add_param(quality)
|
||||
req.add_param(divide)
|
||||
data = con.request(req).get_data()
|
||||
|
||||
if len(data) < 4:
|
||||
return None
|
||||
|
||||
return {
|
||||
"timestamp": data[0],
|
||||
"width": data[1],
|
||||
"height": data[2],
|
||||
"data": base64.b64decode(data[3]),
|
||||
}
|
||||
|
||||
|
||||
def capture_get_streams(con: Connection):
|
||||
"""Describes the HTTP video stream, or None when this spice2x serves none."""
|
||||
data = con.request(Request("capture", "get_streams")).get_data()
|
||||
return data[0] if data else None
|
||||
@@ -2,6 +2,10 @@ from .connection import Connection
|
||||
from .request import Request
|
||||
|
||||
|
||||
def card_get_cards(con: Connection):
|
||||
return con.request(Request("card", "get_cards")).get_data()
|
||||
|
||||
|
||||
def card_insert(con: Connection, unit: int, card_id: str):
|
||||
req = Request("card", "insert")
|
||||
req.add_param(unit)
|
||||
|
||||
@@ -67,4 +67,18 @@ namespace api {
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::vector<std::pair<std::string, std::string>> stream_formats() {
|
||||
std::vector<std::pair<std::string, std::string>> formats;
|
||||
|
||||
#ifdef SPICE_JPEG
|
||||
formats.emplace_back("mjpeg", "/stream.mjpg");
|
||||
#endif
|
||||
|
||||
#ifdef SPICE_H264
|
||||
formats.emplace_back("h264", "/stream.h264");
|
||||
#endif
|
||||
|
||||
return formats;
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "capture_pump.h"
|
||||
|
||||
@@ -35,4 +37,7 @@ namespace api {
|
||||
// null when the path does not name a format this build supports
|
||||
std::unique_ptr<StreamWriter> make_stream_writer(
|
||||
const std::string &path, int quality, int fps);
|
||||
|
||||
// name and path of every format compiled into this build, for clients to pick from
|
||||
std::vector<std::pair<std::string, std::string>> stream_formats();
|
||||
}
|
||||
@@ -14,6 +14,7 @@
|
||||
|
||||
#include "capture_pump.h"
|
||||
#include "hooks/graphics/graphics.h"
|
||||
#include "overlay/notifications.h"
|
||||
#include "stream_format.h"
|
||||
#include "util/logging.h"
|
||||
#include "util/utils.h"
|
||||
@@ -178,6 +179,13 @@ namespace api {
|
||||
// carry it too, or the client sees an opaque failure instead of the status.
|
||||
constexpr const char *cors_header = "Access-Control-Allow-Origin: *\r\n";
|
||||
|
||||
// the port is unauthenticated, so a scanner hammering a busy/missing screen could
|
||||
// otherwise flood the overlay; throttle failure toasts per distinct cause. kept under
|
||||
// a second so it only swallows that, not a legitimate reconnect - substream itself
|
||||
// switches screens with a 300ms gap, and only backs off to a full second once a
|
||||
// retry has actually failed
|
||||
constexpr double notification_throttle_seconds = 0.5;
|
||||
|
||||
void send_error(SOCKET socket, const char *status) {
|
||||
const std::string response =
|
||||
std::string("HTTP/1.0 ") + status + "\r\n"
|
||||
@@ -187,11 +195,25 @@ namespace api {
|
||||
"\r\n";
|
||||
send_all(socket, response);
|
||||
}
|
||||
|
||||
std::atomic<unsigned short> LISTENING_PORT { 0 };
|
||||
}
|
||||
|
||||
unsigned short stream_server_port() {
|
||||
return LISTENING_PORT.load();
|
||||
}
|
||||
|
||||
StreamServer::StreamServer(unsigned short port)
|
||||
: port(port)
|
||||
{
|
||||
// WinXP builds compile in neither encoder, so there would be nothing to serve and
|
||||
// every request would 404; taking the port instead only invites confused clients
|
||||
if (stream_formats().empty()) {
|
||||
log_warning("api::stream",
|
||||
"this build has no video encoders, the video stream is unavailable");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this->open_listener()) {
|
||||
// the stream was asked for explicitly, so say plainly that it is not there
|
||||
log_warning("api::stream",
|
||||
@@ -204,6 +226,8 @@ namespace api {
|
||||
this->accept_worker();
|
||||
});
|
||||
|
||||
LISTENING_PORT = this->port;
|
||||
|
||||
// deliberately not logging a full URL; local IPs would leak into shared logs
|
||||
log_info("api::stream", "video stream is listening on port: {}", this->port);
|
||||
log_warning("api::stream",
|
||||
@@ -261,6 +285,7 @@ namespace api {
|
||||
StreamServer::~StreamServer() {
|
||||
|
||||
this->running = false;
|
||||
LISTENING_PORT = 0;
|
||||
|
||||
if (this->listener != INVALID_SOCKET) {
|
||||
closesocket(this->listener);
|
||||
@@ -334,6 +359,11 @@ namespace api {
|
||||
|
||||
if (slot < 0) {
|
||||
log_warning("api::stream", "client limit of {} hit", client_limit);
|
||||
overlay::notifications::add_throttled(
|
||||
overlay::notifications::Severity::Warning,
|
||||
"api::stream.client_limit",
|
||||
notification_throttle_seconds,
|
||||
fmt::format("Video stream refused: client limit reached ({})", address));
|
||||
send_error(client, "503 Service Unavailable");
|
||||
closesocket(client);
|
||||
continue;
|
||||
@@ -410,16 +440,32 @@ namespace api {
|
||||
if (!streamable(screen)) {
|
||||
log_warning("api::stream",
|
||||
"screen {} is not available, refusing {}", screen, address);
|
||||
overlay::notifications::add_throttled(
|
||||
overlay::notifications::Severity::Warning,
|
||||
fmt::format("api::stream.screen_unavailable.{}", screen),
|
||||
notification_throttle_seconds,
|
||||
fmt::format("Video stream refused: screen {} not available ({})",
|
||||
screen, address));
|
||||
send_error(socket, "404 Not Found");
|
||||
} else if (!capture_pump::claim_screen(screen)) {
|
||||
log_warning("api::stream",
|
||||
"screen {} is already being streamed, refusing {}",
|
||||
screen, address);
|
||||
overlay::notifications::add_throttled(
|
||||
overlay::notifications::Severity::Warning,
|
||||
fmt::format("api::stream.screen_claimed.{}", screen),
|
||||
notification_throttle_seconds,
|
||||
fmt::format("Video stream refused: screen {} already streaming ({})",
|
||||
screen, address));
|
||||
send_error(socket, "503 Service Unavailable");
|
||||
} else {
|
||||
log_info("api::stream",
|
||||
"client connected: {} ({}, screen={}, fps={}, quality={})",
|
||||
address, request.path, screen, fps, quality);
|
||||
overlay::notifications::add(
|
||||
overlay::notifications::Severity::Success,
|
||||
fmt::format("Video stream client connected ({}, screen {})",
|
||||
address, screen));
|
||||
|
||||
const std::string header =
|
||||
"HTTP/1.0 200 OK\r\n"
|
||||
@@ -460,6 +506,9 @@ namespace api {
|
||||
|
||||
capture_pump::release_screen(screen);
|
||||
log_info("api::stream", "client disconnected: {}", address);
|
||||
overlay::notifications::add(
|
||||
overlay::notifications::Severity::Info,
|
||||
fmt::format("Video stream client disconnected ({})", address));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,9 @@
|
||||
|
||||
namespace api {
|
||||
|
||||
// 0 while no stream server is listening, so the API can tell clients not to look for one
|
||||
unsigned short stream_server_port();
|
||||
|
||||
class StreamServer {
|
||||
public:
|
||||
|
||||
|
||||
+547
-173
@@ -1,205 +1,579 @@
|
||||
#define HEADSOCKET_IMPLEMENTATION
|
||||
#include "external/headsocket.h"
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
|
||||
#include "websocket.h"
|
||||
#include "util/utils.h"
|
||||
#include "util/rc4.h"
|
||||
#include "util/logging.h"
|
||||
#include "overlay/notifications.h"
|
||||
#include "controller.h"
|
||||
|
||||
using namespace headsocket;
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cctype>
|
||||
#include <chrono>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include "external/wslay/msvc_compat.h"
|
||||
#include <wslay/wslay.h>
|
||||
|
||||
#include "controller.h"
|
||||
#include "external/hash-library/sha1.h"
|
||||
#include "overlay/notifications.h"
|
||||
#include "util/crypt.h"
|
||||
#include "util/logging.h"
|
||||
|
||||
namespace api {
|
||||
|
||||
namespace {
|
||||
|
||||
// how long a single handshake read may stall before the connection is dropped;
|
||||
// headsocket reads the request a byte at a time, so this is an idle timeout between
|
||||
// bytes rather than a deadline for the whole handshake
|
||||
constexpr int handshake_timeout_ms = 5000;
|
||||
constexpr int server_backlog = 4;
|
||||
constexpr size_t client_limit = 8;
|
||||
|
||||
void set_recv_timeout(connection &conn, int milliseconds) {
|
||||
DWORD timeout = static_cast<DWORD>(milliseconds);
|
||||
setsockopt(conn.impl()->socket, SOL_SOCKET, SO_RCVTIMEO,
|
||||
// a peer that connects and then says nothing must not hold a slot forever
|
||||
constexpr int handshake_timeout_ms = 5000;
|
||||
constexpr size_t request_size_limit = 8 * 1024;
|
||||
constexpr uint64_t message_size_limit = 64 * 1024;
|
||||
|
||||
// how long a quiet connection waits before the loop rechecks whether we are stopping
|
||||
constexpr int idle_poll_ms = 500;
|
||||
|
||||
// RFC 6455 appends this to the client key before hashing
|
||||
constexpr const char *websocket_guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
||||
|
||||
constexpr double notification_throttle_seconds = 0.5;
|
||||
|
||||
std::string trim(const std::string &text) {
|
||||
const auto begin = text.find_first_not_of(" \t");
|
||||
if (begin == std::string::npos) {
|
||||
return "";
|
||||
}
|
||||
return text.substr(begin, text.find_last_not_of(" \t") - begin + 1);
|
||||
}
|
||||
|
||||
std::string to_lower(std::string text) {
|
||||
std::transform(text.begin(), text.end(), text.begin(), [](unsigned char c) {
|
||||
return static_cast<char>(std::tolower(c));
|
||||
});
|
||||
return text;
|
||||
}
|
||||
|
||||
bool contains_token(const std::string &value, const std::string &expected) {
|
||||
size_t pos = 0;
|
||||
while (pos < value.size()) {
|
||||
const size_t end = value.find(',', pos);
|
||||
if (to_lower(trim(value.substr(pos, end - pos))) == expected) {
|
||||
return true;
|
||||
}
|
||||
if (end == std::string::npos) {
|
||||
break;
|
||||
}
|
||||
pos = end + 1;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool valid_websocket_key(const std::string &key) {
|
||||
if (key.size() != 24 || key[22] != '=' || key[23] != '=') {
|
||||
return false;
|
||||
}
|
||||
|
||||
const std::string alphabet =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
for (size_t i = 0; i < 22; i++) {
|
||||
if (alphabet.find(key[i]) == std::string::npos) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool send_all(SOCKET socket, const std::string &text) {
|
||||
size_t remaining = text.size();
|
||||
const char *cursor = text.data();
|
||||
|
||||
while (remaining > 0) {
|
||||
const int sent = send(socket, cursor, static_cast<int>(remaining), 0);
|
||||
if (sent <= 0) {
|
||||
return false;
|
||||
}
|
||||
cursor += sent;
|
||||
remaining -= static_cast<size_t>(sent);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void set_recv_timeout(SOCKET socket, int milliseconds) {
|
||||
const DWORD timeout = static_cast<DWORD>(milliseconds);
|
||||
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO,
|
||||
reinterpret_cast<const char *>(&timeout), sizeof(timeout));
|
||||
}
|
||||
|
||||
std::string accept_key(const std::string &client_key) {
|
||||
SHA1 sha1;
|
||||
sha1.add(client_key.data(), client_key.size());
|
||||
sha1.add(websocket_guid, strlen(websocket_guid));
|
||||
|
||||
unsigned char digest[SHA1::HashBytes] {};
|
||||
sha1.getHash(digest);
|
||||
|
||||
return crypt::base64_encode(digest, sizeof(digest));
|
||||
}
|
||||
|
||||
bool handshake(SOCKET socket) {
|
||||
std::string request;
|
||||
char byte = 0;
|
||||
bool complete = false;
|
||||
|
||||
while (request.size() < request_size_limit) {
|
||||
const int read = recv(socket, &byte, 1, 0);
|
||||
if (read <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
request.push_back(byte);
|
||||
if (request.size() >= 4
|
||||
&& request.compare(request.size() - 4, 4, "\r\n\r\n") == 0) {
|
||||
complete = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
std::string key;
|
||||
std::string version;
|
||||
bool connection_upgrade = false;
|
||||
bool upgrade = false;
|
||||
const size_t request_line_end = request.find("\r\n");
|
||||
const std::string request_line = request.substr(0, request_line_end);
|
||||
const size_t target_end = request_line.find(' ', 4);
|
||||
const bool valid_request_line = request_line_end != std::string::npos
|
||||
&& request_line.compare(0, 4, "GET ") == 0
|
||||
&& target_end != std::string::npos
|
||||
&& target_end > 4
|
||||
&& target_end == request_line.rfind(' ')
|
||||
&& request_line.substr(target_end + 1) == "HTTP/1.1";
|
||||
size_t pos = request_line_end;
|
||||
|
||||
while (pos != std::string::npos) {
|
||||
const size_t end = request.find("\r\n", pos + 2);
|
||||
if (end == std::string::npos || end == pos + 2) {
|
||||
break;
|
||||
}
|
||||
|
||||
const std::string line = request.substr(pos + 2, end - pos - 2);
|
||||
const size_t colon = line.find(':');
|
||||
if (colon != std::string::npos) {
|
||||
const std::string name = to_lower(trim(line.substr(0, colon)));
|
||||
const std::string value = trim(line.substr(colon + 1));
|
||||
|
||||
if (name == "sec-websocket-key") {
|
||||
key = value;
|
||||
} else if (name == "sec-websocket-version") {
|
||||
version = value;
|
||||
} else if (name == "connection") {
|
||||
connection_upgrade = connection_upgrade
|
||||
|| contains_token(value, "upgrade");
|
||||
} else if (name == "upgrade") {
|
||||
upgrade = upgrade || contains_token(value, "websocket");
|
||||
}
|
||||
}
|
||||
|
||||
pos = end;
|
||||
}
|
||||
|
||||
if (!complete || !valid_request_line || !connection_upgrade || !upgrade
|
||||
|| version != "13" || !valid_websocket_key(key)) {
|
||||
send_all(socket,
|
||||
"HTTP/1.1 400 Bad Request\r\n"
|
||||
"Connection: close\r\n"
|
||||
"Content-Length: 0\r\n"
|
||||
"\r\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
// deliberately echoes back no extension or subprotocol: naming one the client did
|
||||
// not offer is a handshake failure, and none of them are wanted here
|
||||
return send_all(socket,
|
||||
"HTTP/1.1 101 Switching Protocols\r\n"
|
||||
"Upgrade: websocket\r\n"
|
||||
"Connection: Upgrade\r\n"
|
||||
"Sec-WebSocket-Accept: " + accept_key(key) + "\r\n"
|
||||
"\r\n");
|
||||
}
|
||||
|
||||
// everything one connection needs; wslay hands this back to the callbacks
|
||||
struct Session {
|
||||
SOCKET socket = INVALID_SOCKET;
|
||||
Controller *controller = nullptr;
|
||||
ClientState *state = nullptr;
|
||||
bool failed = false;
|
||||
};
|
||||
|
||||
ssize_t recv_callback(wslay_event_context_ptr ctx, uint8_t *buffer, size_t length,
|
||||
int flags, void *user_data) {
|
||||
|
||||
(void) flags;
|
||||
|
||||
auto *session = static_cast<Session *>(user_data);
|
||||
const int read = recv(session->socket, reinterpret_cast<char *>(buffer),
|
||||
static_cast<int>(length), 0);
|
||||
|
||||
if (read > 0) {
|
||||
return read;
|
||||
}
|
||||
|
||||
// the socket is non-blocking, so an empty one has to read as "nothing yet"
|
||||
// rather than as a dead peer
|
||||
if (read < 0 && WSAGetLastError() == WSAEWOULDBLOCK) {
|
||||
wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK);
|
||||
return -1;
|
||||
}
|
||||
|
||||
wslay_event_set_error(ctx,
|
||||
read == 0 ? WSLAY_ERR_NO_MORE_MSG : WSLAY_ERR_CALLBACK_FAILURE);
|
||||
return -1;
|
||||
}
|
||||
|
||||
ssize_t send_callback(wslay_event_context_ptr ctx, const uint8_t *data, size_t length,
|
||||
int flags, void *user_data) {
|
||||
|
||||
(void) flags;
|
||||
|
||||
auto *session = static_cast<Session *>(user_data);
|
||||
const int sent = send(session->socket, reinterpret_cast<const char *>(data),
|
||||
static_cast<int>(length), 0);
|
||||
|
||||
if (sent > 0) {
|
||||
return sent;
|
||||
}
|
||||
|
||||
if (sent < 0 && WSAGetLastError() == WSAEWOULDBLOCK) {
|
||||
wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK);
|
||||
return -1;
|
||||
}
|
||||
|
||||
wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
|
||||
return -1;
|
||||
}
|
||||
|
||||
void on_msg_recv(wslay_event_context_ptr ctx,
|
||||
const struct wslay_event_on_msg_recv_arg *arg, void *user_data) {
|
||||
|
||||
auto *session = static_cast<Session *>(user_data);
|
||||
|
||||
// pings and closes are wslay's business, it answers them itself
|
||||
if (wslay_is_ctrl_frame(arg->opcode)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (arg->opcode != WSLAY_BINARY_FRAME) {
|
||||
log_warning("api::websocket", "ignoring a non-binary message");
|
||||
return;
|
||||
}
|
||||
|
||||
std::vector<char> in(arg->msg, arg->msg + arg->msg_length);
|
||||
std::vector<char> out;
|
||||
|
||||
if (session->state->cipher) {
|
||||
session->state->cipher->crypt(
|
||||
reinterpret_cast<uint8_t *>(in.data()), in.size());
|
||||
}
|
||||
|
||||
session->controller->process_request(session->state, &in, &out);
|
||||
|
||||
if (session->state->cipher) {
|
||||
session->state->cipher->crypt(
|
||||
reinterpret_cast<uint8_t *>(out.data()), out.size());
|
||||
}
|
||||
|
||||
wslay_event_msg reply {};
|
||||
reply.opcode = WSLAY_BINARY_FRAME;
|
||||
reply.msg = reinterpret_cast<const uint8_t *>(out.data());
|
||||
reply.msg_length = out.size();
|
||||
|
||||
if (wslay_event_queue_msg(ctx, &reply) != 0) {
|
||||
session->failed = true;
|
||||
return;
|
||||
}
|
||||
|
||||
Controller::process_password_change(session->state);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Client class declaration
|
||||
*/
|
||||
class WebSocketClient : public web_socket_client {
|
||||
|
||||
// required class header
|
||||
HEADSOCKET_CLIENT(WebSocketClient, web_socket_client);
|
||||
|
||||
private:
|
||||
ClientState *state = nullptr;
|
||||
|
||||
protected:
|
||||
bool async_received_data(const data_block &db, uint8_t *ptr, size_t length) override;
|
||||
|
||||
void on_accept() override;
|
||||
void on_disconnect() override;
|
||||
};
|
||||
|
||||
/*
|
||||
* Server class declaration
|
||||
*/
|
||||
class WebSocketServer : public web_socket_server<WebSocketClient> {
|
||||
HEADSOCKET_SERVER(WebSocketServer, web_socket_server);
|
||||
public:
|
||||
WebSocketController *websocket;
|
||||
|
||||
protected:
|
||||
bool handshake(connection &conn) override {
|
||||
|
||||
// headsocket runs the handshake on its single accept thread with a blocking
|
||||
// recv, so a peer that connects and then says nothing would park that thread and
|
||||
// leave every later connection sitting unaccepted in the backlog
|
||||
set_recv_timeout(conn, handshake_timeout_ms);
|
||||
const bool accepted = base_t::handshake(conn);
|
||||
|
||||
// from here the client thread owns the socket and wants to block on reads
|
||||
set_recv_timeout(conn, 0);
|
||||
|
||||
return accepted;
|
||||
}
|
||||
};
|
||||
|
||||
void api::WebSocketServer::init() {}
|
||||
|
||||
/*
|
||||
* Controller state so we don't have to import headsocket stuff in our header
|
||||
*/
|
||||
struct WebSocketControllerState {
|
||||
std::shared_ptr<WebSocketServer> server;
|
||||
struct Client {
|
||||
std::thread thread;
|
||||
SOCKET socket = INVALID_SOCKET;
|
||||
bool active = false;
|
||||
};
|
||||
|
||||
Controller *controller = nullptr;
|
||||
unsigned short port = 0;
|
||||
SOCKET listener = INVALID_SOCKET;
|
||||
bool wsa_started = false;
|
||||
std::atomic_bool running { false };
|
||||
std::thread acceptor;
|
||||
std::mutex clients_m;
|
||||
std::array<Client, client_limit> clients;
|
||||
|
||||
bool open_listener();
|
||||
void accept_worker();
|
||||
void client_worker(int slot, SOCKET socket, std::string address);
|
||||
void stop();
|
||||
};
|
||||
|
||||
bool WebSocketControllerState::open_listener() {
|
||||
WSADATA wsa_data;
|
||||
const int error = WSAStartup(MAKEWORD(2, 2), &wsa_data);
|
||||
if (error != 0) {
|
||||
log_warning("api::websocket", "WSAStartup() returned {}", error);
|
||||
return false;
|
||||
}
|
||||
this->wsa_started = true;
|
||||
|
||||
this->listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
||||
if (this->listener == INVALID_SOCKET) {
|
||||
log_warning("api::websocket", "socket() returned {}", WSAGetLastError());
|
||||
return false;
|
||||
}
|
||||
|
||||
sockaddr_in address {};
|
||||
address.sin_family = AF_INET;
|
||||
address.sin_addr.s_addr = INADDR_ANY;
|
||||
address.sin_port = htons(this->port);
|
||||
|
||||
if (bind(this->listener, reinterpret_cast<sockaddr *>(&address), sizeof(address))
|
||||
== SOCKET_ERROR) {
|
||||
log_warning("api::websocket", "bind() returned {}", WSAGetLastError());
|
||||
return false;
|
||||
}
|
||||
|
||||
if (listen(this->listener, server_backlog) == SOCKET_ERROR) {
|
||||
log_warning("api::websocket", "listen() returned {}", WSAGetLastError());
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void WebSocketControllerState::accept_worker() {
|
||||
|
||||
while (this->running) {
|
||||
sockaddr_in client_address {};
|
||||
int client_address_size = sizeof(sockaddr_in);
|
||||
|
||||
const SOCKET client = accept(
|
||||
this->listener, reinterpret_cast<sockaddr *>(&client_address),
|
||||
&client_address_size);
|
||||
|
||||
if (client == INVALID_SOCKET) {
|
||||
// on shutdown the listener is closed under us; otherwise do not spin
|
||||
if (this->running) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!this->running) {
|
||||
closesocket(client);
|
||||
break;
|
||||
}
|
||||
|
||||
// formatted by hand rather than with inet_ntop, which needs a newer Windows than
|
||||
// the XP toolchain targets, or inet_ntoa, which answers from a shared buffer
|
||||
const uint32_t raw = ntohl(client_address.sin_addr.s_addr);
|
||||
const std::string address = fmt::format("{}.{}.{}.{}",
|
||||
(raw >> 24) & 0xff, (raw >> 16) & 0xff, (raw >> 8) & 0xff, raw & 0xff);
|
||||
|
||||
int slot = -1;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(this->clients_m);
|
||||
for (size_t i = 0; i < this->clients.size(); i++) {
|
||||
if (!this->clients[i].active) {
|
||||
this->clients[i].active = true;
|
||||
this->clients[i].socket = client;
|
||||
slot = static_cast<int>(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (slot < 0) {
|
||||
log_warning("api::websocket", "client limit of {} hit", client_limit);
|
||||
overlay::notifications::add_throttled(
|
||||
overlay::notifications::Severity::Warning,
|
||||
"api::websocket.client_limit",
|
||||
notification_throttle_seconds,
|
||||
fmt::format("API websocket refused: client limit reached ({})", address));
|
||||
closesocket(client);
|
||||
continue;
|
||||
}
|
||||
|
||||
// this thread is the only one that touches the thread objects, so the slot's
|
||||
// previous occupant gets reaped here rather than being detached
|
||||
if (this->clients[slot].thread.joinable()) {
|
||||
this->clients[slot].thread.join();
|
||||
}
|
||||
|
||||
// the handshake runs on the client thread on purpose: doing it here would put
|
||||
// every later connection behind whatever this one is waiting for
|
||||
this->clients[slot].thread = std::thread([this, slot, client, address] {
|
||||
this->client_worker(slot, client, address);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void WebSocketControllerState::client_worker(int slot, SOCKET socket, std::string address) {
|
||||
|
||||
// wslay writes a frame header and its payload as separate sends, so leaving Nagle on
|
||||
// holds the payload back until the peer acknowledges the header, costing a delayed
|
||||
// ack per message; requests here are small and latency sensitive
|
||||
int nodelay = 1;
|
||||
setsockopt(socket, IPPROTO_TCP, TCP_NODELAY,
|
||||
reinterpret_cast<const char *>(&nodelay), sizeof(nodelay));
|
||||
|
||||
set_recv_timeout(socket, handshake_timeout_ms);
|
||||
|
||||
if (handshake(socket)) {
|
||||
// wslay reads until the socket would block, so leaving it blocking would make
|
||||
// every reply wait out a receive timeout before the send got a turn
|
||||
u_long non_blocking = 1;
|
||||
ioctlsocket(socket, FIONBIO, &non_blocking);
|
||||
|
||||
Session session;
|
||||
session.socket = socket;
|
||||
session.controller = this->controller;
|
||||
session.state = new ClientState();
|
||||
this->controller->init_state(session.state);
|
||||
|
||||
log_info("api::websocket", "client connected: {}", address);
|
||||
overlay::notifications::add(
|
||||
overlay::notifications::Severity::Success,
|
||||
fmt::format("API websocket client connected ({})", address));
|
||||
|
||||
wslay_event_callbacks callbacks {};
|
||||
callbacks.recv_callback = recv_callback;
|
||||
callbacks.send_callback = send_callback;
|
||||
callbacks.on_msg_recv_callback = on_msg_recv;
|
||||
|
||||
wslay_event_context_ptr ctx = nullptr;
|
||||
if (wslay_event_context_server_init(&ctx, &callbacks, &session) == 0) {
|
||||
wslay_event_config_set_max_recv_msg_length(ctx, message_size_limit);
|
||||
while (this->running && !session.failed
|
||||
&& (wslay_event_want_read(ctx) || wslay_event_want_write(ctx))) {
|
||||
|
||||
fd_set read_set;
|
||||
fd_set write_set;
|
||||
FD_ZERO(&read_set);
|
||||
FD_ZERO(&write_set);
|
||||
|
||||
if (wslay_event_want_read(ctx)) {
|
||||
FD_SET(socket, &read_set);
|
||||
}
|
||||
if (wslay_event_want_write(ctx)) {
|
||||
FD_SET(socket, &write_set);
|
||||
}
|
||||
|
||||
// bounded so a silent connection still notices us shutting down
|
||||
timeval timeout {};
|
||||
timeout.tv_usec = idle_poll_ms * 1000;
|
||||
|
||||
if (select(0, &read_set, &write_set, nullptr, &timeout) < 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (FD_ISSET(socket, &read_set) && wslay_event_recv(ctx) != 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
// unconditional, so a reply queued by the read above goes out now
|
||||
if (wslay_event_send(ctx) != 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
wslay_event_context_free(ctx);
|
||||
}
|
||||
|
||||
Controller::free_state(session.state);
|
||||
delete session.state;
|
||||
|
||||
log_info("api::websocket", "client disconnected: {}", address);
|
||||
overlay::notifications::add(
|
||||
overlay::notifications::Severity::Info,
|
||||
fmt::format("API websocket client disconnected ({})", address));
|
||||
}
|
||||
|
||||
closesocket(socket);
|
||||
|
||||
std::lock_guard<std::mutex> lock(this->clients_m);
|
||||
this->clients[slot].socket = INVALID_SOCKET;
|
||||
this->clients[slot].active = false;
|
||||
}
|
||||
|
||||
void WebSocketControllerState::stop() {
|
||||
this->running = false;
|
||||
|
||||
if (this->listener != INVALID_SOCKET) {
|
||||
closesocket(this->listener);
|
||||
this->listener = INVALID_SOCKET;
|
||||
}
|
||||
|
||||
// drops the client threads out of their blocking send/recv
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(this->clients_m);
|
||||
for (auto &client : this->clients) {
|
||||
if (client.socket != INVALID_SOCKET) {
|
||||
::shutdown(client.socket, SD_BOTH);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (this->acceptor.joinable()) {
|
||||
this->acceptor.join();
|
||||
}
|
||||
|
||||
// joining is what guarantees no client thread outlives this object
|
||||
for (auto &client : this->clients) {
|
||||
if (client.thread.joinable()) {
|
||||
client.thread.join();
|
||||
}
|
||||
}
|
||||
|
||||
if (this->wsa_started) {
|
||||
WSACleanup();
|
||||
this->wsa_started = false;
|
||||
}
|
||||
}
|
||||
|
||||
WebSocketController::WebSocketController(Controller *controller, uint16_t port) {
|
||||
this->controller = controller;
|
||||
|
||||
// create state
|
||||
this->state = new WebSocketControllerState();
|
||||
this->state->controller = controller;
|
||||
this->state->port = port;
|
||||
|
||||
// start server
|
||||
this->state->server = WebSocketServer::create(port);
|
||||
this->state->server->websocket = this;
|
||||
if (this->state->server->is_running()) {
|
||||
log_info("api::websocket", "server listening on port: {}", port);
|
||||
} else {
|
||||
if (!this->state->open_listener()) {
|
||||
log_warning("api::websocket", "server failed to listen on port: {}", port);
|
||||
return;
|
||||
}
|
||||
|
||||
this->state->running = true;
|
||||
this->state->acceptor = std::thread([this] {
|
||||
this->state->accept_worker();
|
||||
});
|
||||
|
||||
log_info("api::websocket", "server listening on port: {}", port);
|
||||
}
|
||||
|
||||
WebSocketController::~WebSocketController() {
|
||||
|
||||
// stop server
|
||||
this->state->server->stop();
|
||||
|
||||
// delete state
|
||||
this->state->stop();
|
||||
delete this->state;
|
||||
this->state = nullptr;
|
||||
}
|
||||
|
||||
void WebSocketController::free_socket() {
|
||||
this->state->server->stop();
|
||||
}
|
||||
|
||||
void WebSocketClient::on_accept() {
|
||||
web_socket_client::on_accept();
|
||||
|
||||
// get pointer to server
|
||||
auto srv = reinterpret_cast<WebSocketServer *>(server().get());
|
||||
if (!srv || !srv->websocket) {
|
||||
log_fatal("api::websocket", "on_accept has no server");
|
||||
}
|
||||
|
||||
// check for init
|
||||
state = new ClientState();
|
||||
srv->websocket->controller->init_state(state);
|
||||
|
||||
// log connection
|
||||
log_info("api::websocket", "client connected");
|
||||
overlay::notifications::add(
|
||||
overlay::notifications::Severity::Success,
|
||||
"API websocket client connected");
|
||||
}
|
||||
|
||||
void WebSocketClient::on_disconnect() {
|
||||
|
||||
// log disconnection
|
||||
log_info("api::websocket", "client disconnected");
|
||||
overlay::notifications::add(
|
||||
overlay::notifications::Severity::Info,
|
||||
"API websocket client disconnected");
|
||||
|
||||
// get pointer to server
|
||||
auto srv = reinterpret_cast<WebSocketServer *>(server().get());
|
||||
if (!srv || !srv->websocket) {
|
||||
log_fatal("api::websocket", "on_disconnect has no server");
|
||||
}
|
||||
|
||||
// clean up state
|
||||
srv->websocket->controller->free_state(state);
|
||||
delete state;
|
||||
state = nullptr;
|
||||
|
||||
// call super
|
||||
web_socket_client::on_disconnect();
|
||||
}
|
||||
|
||||
/*
|
||||
* This is where business actually happens, gets called on every datablock receive
|
||||
*/
|
||||
bool WebSocketClient::async_received_data(const data_block &db, uint8_t *ptr, size_t length) {
|
||||
|
||||
// get pointer to server
|
||||
auto srv = reinterpret_cast<WebSocketServer *>(server().get());
|
||||
if (!srv || !srv->websocket) {
|
||||
log_fatal("api::websocket", "received datablock without server");
|
||||
}
|
||||
|
||||
// check state
|
||||
if (!state) {
|
||||
log_fatal("api::websocket", "client with no state received datablock");
|
||||
}
|
||||
|
||||
// check datablock type
|
||||
switch (db.op) {
|
||||
case opcode::binary: {
|
||||
|
||||
// allocate buffers
|
||||
std::vector<char> in(ptr, ptr + length);
|
||||
std::vector<char> out;
|
||||
|
||||
// crypt in-data
|
||||
if (state->cipher) {
|
||||
state->cipher->crypt(reinterpret_cast<uint8_t *>(in.data()), in.size());
|
||||
}
|
||||
|
||||
// process request
|
||||
srv->websocket->controller->process_request(state, &in, &out);
|
||||
|
||||
// crypt out-data
|
||||
if (state->cipher) {
|
||||
state->cipher->crypt(reinterpret_cast<uint8_t *>(out.data()), out.size());
|
||||
}
|
||||
|
||||
// send answer
|
||||
push(out.data(), out.size());
|
||||
|
||||
// check for password change
|
||||
srv->websocket->controller->process_password_change(state);
|
||||
|
||||
break;
|
||||
}
|
||||
default:
|
||||
log_warning("api::websocket", "datablock received with non-binary type");
|
||||
break;
|
||||
}
|
||||
|
||||
// always consume the datablock, nomnom
|
||||
return true;
|
||||
this->state->stop();
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,14 @@
|
||||
#include "core.h"
|
||||
|
||||
#include <climits>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#include "avs/game.h"
|
||||
#include "external/robin_hood.h"
|
||||
#include "games/popn/popn.h"
|
||||
#include "launcher/logger.h"
|
||||
@@ -1181,6 +1184,18 @@ namespace avs {
|
||||
return;
|
||||
}
|
||||
|
||||
#ifdef SPICE64
|
||||
// nabla increased heap size a few months into service (June 2026?)
|
||||
if (dll_name == "soundvoltex.dll" &&
|
||||
avs::game::is_ext(2025121501, INT_MAX)) {
|
||||
auto old_size = HEAP_SIZE;
|
||||
HEAP_SIZE = 0x18000000;
|
||||
DEFAULT_HEAP_SIZE_SET = true;
|
||||
log_info("avs-core", "updated heap size: {} -> {} (nabla)", old_size, avs::core::HEAP_SIZE);
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
|
||||
// hack, both hello! popn and popn hc using popn.dll
|
||||
if (games::popn::is_pikapika_model()) {
|
||||
auto old_size = HEAP_SIZE;
|
||||
|
||||
@@ -573,6 +573,13 @@ static inline void easrv_init_messages() {
|
||||
"\x5b\x99\xa1\x15\x78\x16\x84\xe0\x67\x2c\x75\xf7\xc0\x38\xd5\x20\xf7\x81\xae\x1f\x77\x02\xdf\x0c"
|
||||
"\x60\x68\x2e\x26\xe5\xbb\xb7\xb4\x41\x72\xc4\xa4\x43\x2a\xc8\x81\xd3\x8a\x1f\xe8\x94\x39\x7e\xf6"
|
||||
"\x69\x56\x9e\xaf\x06\x10\xfd\x47\x69\xb8\x14\xe6\x48\x36\xd6\x25\x18\x0c\x2b\x3d\x69");
|
||||
if (avs::game::is_model("UDN")) {
|
||||
// Only UDN needs an ASCII location/name for the Unity score-screen marshaler.
|
||||
// These 12 encoded bytes replace the name with "SPICE2 LOCAL";
|
||||
// its terminator, the other fields and the response length stay unchanged.
|
||||
EA_FACILITY_GET.replace(311, 12,
|
||||
"\xf2\x20\xcc\x9a\xe3\x32\x78\x80\x9a\xba\xcd\xc3");
|
||||
}
|
||||
EA_PCBEVENT_PUT = std::string(
|
||||
"\x17\x7e\x7c\x0e\x1a\x15\x41\x0b\xae\xd5\xa0\xf5\x2c\xa1\xb9\xd2\x53\xca\xd2\x0d\x81\x34\xdb\x94\x79\xd0"
|
||||
"\xc8\x9d\xb5\xfb\xef\x97");
|
||||
|
||||
+7
-6
@@ -25,10 +25,11 @@ ENV PATH="$PATH:/opt/llvm-mingw-xp/bin"
|
||||
RUN curl -fsSL "https://github.com/mon/windows-dll-compat-checker/releases/download/v1.3/windows_dll_compat_checker-linux-x86_64.tar.xz" \
|
||||
| tar -xJ -C /usr/local/bin
|
||||
|
||||
# libjpeg-turbo for JPEG encoding. Only the mingw-w64 toolchains get it;
|
||||
# the WinXP targets build without JPEG support entirely.
|
||||
RUN su user -c "yay --noconfirm -S mingw-w64-libjpeg-turbo"
|
||||
# Stock makepkg.conf builds serially; this makes the AUR compiles below parallel.
|
||||
RUN printf '%s\n' 'MAKEFLAGS="-j$(nproc)"' > /home/user/.makepkg.conf \
|
||||
&& chown user: /home/user/.makepkg.conf
|
||||
|
||||
# x264 for the API H.264 video stream. Only the mingw-w64 toolchains need it;
|
||||
# the WinXP targets build without the stream encoder.
|
||||
RUN su user -c "yay --noconfirm -S mingw-w64-x264"
|
||||
# libjpeg-turbo for JPEG encoding, x264 for the API H.264 video stream. Only the
|
||||
# mingw-w64 toolchains get these; the WinXP targets build without JPEG support
|
||||
# and without the stream encoder.
|
||||
RUN su user -c "yay --noconfirm -S mingw-w64-libjpeg-turbo mingw-w64-x264"
|
||||
Vendored
-2192
File diff suppressed because it is too large.
Load diff
Vendored
+7
-3
@@ -50,6 +50,7 @@ static const BYTE UID_CMD[5] = { 0xFFu, 0xCAu, 0x00u, 0x00u, 0x00u };
|
||||
enum scard_atr_protocol {
|
||||
SCARD_ATR_PROTOCOL_ISO14443_PART3 = 0x03,
|
||||
SCARD_ATR_PROTOCOL_ISO15693_PART3 = 0x0B,
|
||||
SCARD_ATR_PROTOCOL_ISO15693_PART4 = 0x0C,
|
||||
SCARD_ATR_PROTOCOL_FELICA_212K = 0x11,
|
||||
SCARD_ATR_PROTOCOL_FELICA_424K = 0x12,
|
||||
};
|
||||
@@ -121,11 +122,14 @@ void scard_update(SCARDCONTEXT hContext, LPCTSTR readerName, uint8_t unit_no) {
|
||||
BYTE cardProtocol = atr[12];
|
||||
BOOL shouldReverseUid = false;
|
||||
bool is_felica = false;
|
||||
if (cardProtocol == SCARD_ATR_PROTOCOL_ISO15693_PART3) {
|
||||
if (cardProtocol == SCARD_ATR_PROTOCOL_ISO14443_PART3) {
|
||||
log_info("scard", "card protocol: ISO14443_PART3");
|
||||
} else if (cardProtocol == SCARD_ATR_PROTOCOL_ISO15693_PART3) {
|
||||
log_info("scard", "card protocol: ISO15693_PART3");
|
||||
shouldReverseUid = true;
|
||||
} else if (cardProtocol == SCARD_ATR_PROTOCOL_ISO14443_PART3) {
|
||||
log_info("scard", "card protocol: ISO14443_PART3");
|
||||
} else if (cardProtocol == SCARD_ATR_PROTOCOL_ISO15693_PART4) {
|
||||
log_info("scard", "card protocol: ISO15693_PART4");
|
||||
shouldReverseUid = true;
|
||||
} else if (cardProtocol == SCARD_ATR_PROTOCOL_FELICA_212K) {
|
||||
log_info("scard", "card protocol: FELICA_212K");
|
||||
is_felica = true;
|
||||
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
cmake_minimum_required(VERSION 3.12)
|
||||
project(wslay C)
|
||||
|
||||
set(WSLAY_HEADERS
|
||||
msvc_compat.h
|
||||
wslay_event.h
|
||||
wslay_frame.h
|
||||
wslay_macro.h
|
||||
wslay_net.h
|
||||
wslay_queue.h
|
||||
includes/wslay/wslay.h
|
||||
includes/wslay/wslayver.h
|
||||
)
|
||||
set(WSLAY_SOURCES
|
||||
wslay_event.c
|
||||
wslay_frame.c
|
||||
wslay_net.c
|
||||
wslay_queue.c
|
||||
)
|
||||
|
||||
add_library(wslay STATIC ${WSLAY_HEADERS} ${WSLAY_SOURCES})
|
||||
|
||||
# config.h here is checked in rather than generated, see the note in it
|
||||
target_compile_definitions(wslay PRIVATE HAVE_CONFIG_H)
|
||||
target_include_directories(wslay PRIVATE ${PROJECT_SOURCE_DIR})
|
||||
target_include_directories(wslay PUBLIC ${PROJECT_SOURCE_DIR}/includes)
|
||||
|
||||
if(MSVC)
|
||||
target_compile_options(wslay PRIVATE "/FI${PROJECT_SOURCE_DIR}/msvc_compat.h")
|
||||
else()
|
||||
# upstream code, and not ours to keep warning clean
|
||||
target_compile_options(wslay PRIVATE -w)
|
||||
endif()
|
||||
Vendored
+22
@@ -0,0 +1,22 @@
|
||||
The MIT License
|
||||
|
||||
Copyright (c) 2011, 2012, 2015 Tatsuhiro Tsujikawa
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
/* Hand written stand-in for the autotools/CMake generated config.h. Spice only
|
||||
builds this for Windows on x86, so the probes have single known answers. */
|
||||
#ifndef CONFIG_H
|
||||
#define CONFIG_H
|
||||
|
||||
#define HAVE_WINSOCK2_H
|
||||
/* x86 and x86_64 are little endian, so WORDS_BIGENDIAN stays undefined */
|
||||
|
||||
#endif /* CONFIG_H */
|
||||
+841
@@ -0,0 +1,841 @@
|
||||
/*
|
||||
* Wslay - The WebSocket Library
|
||||
*
|
||||
* Copyright (c) 2011, 2012 Tatsuhiro Tsujikawa
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
#ifndef WSLAY_H
|
||||
#define WSLAY_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
/*
|
||||
* wslay/wslayver.h is generated from wslay/wslayver.h.in by
|
||||
* configure. The projects which do not use autotools can set
|
||||
* WSLAY_VERSION macro from outside to avoid to generating wslayver.h
|
||||
*/
|
||||
#ifndef WSLAY_VERSION
|
||||
# include <wslay/wslayver.h>
|
||||
#endif /* WSLAY_VERSION */
|
||||
|
||||
enum wslay_error {
|
||||
WSLAY_ERR_WANT_READ = -100,
|
||||
WSLAY_ERR_WANT_WRITE = -101,
|
||||
WSLAY_ERR_PROTO = -200,
|
||||
WSLAY_ERR_INVALID_ARGUMENT = -300,
|
||||
WSLAY_ERR_INVALID_CALLBACK = -301,
|
||||
WSLAY_ERR_NO_MORE_MSG = -302,
|
||||
WSLAY_ERR_CALLBACK_FAILURE = -400,
|
||||
WSLAY_ERR_WOULDBLOCK = -401,
|
||||
WSLAY_ERR_NOMEM = -500
|
||||
};
|
||||
|
||||
/*
|
||||
* Status codes defined in RFC6455
|
||||
*/
|
||||
enum wslay_status_code {
|
||||
WSLAY_CODE_NORMAL_CLOSURE = 1000,
|
||||
WSLAY_CODE_GOING_AWAY = 1001,
|
||||
WSLAY_CODE_PROTOCOL_ERROR = 1002,
|
||||
WSLAY_CODE_UNSUPPORTED_DATA = 1003,
|
||||
WSLAY_CODE_NO_STATUS_RCVD = 1005,
|
||||
WSLAY_CODE_ABNORMAL_CLOSURE = 1006,
|
||||
WSLAY_CODE_INVALID_FRAME_PAYLOAD_DATA = 1007,
|
||||
WSLAY_CODE_POLICY_VIOLATION = 1008,
|
||||
WSLAY_CODE_MESSAGE_TOO_BIG = 1009,
|
||||
WSLAY_CODE_MANDATORY_EXT = 1010,
|
||||
WSLAY_CODE_INTERNAL_SERVER_ERROR = 1011,
|
||||
WSLAY_CODE_TLS_HANDSHAKE = 1015
|
||||
};
|
||||
|
||||
enum wslay_io_flags {
|
||||
/*
|
||||
* There is more data to send.
|
||||
*/
|
||||
WSLAY_MSG_MORE = 1
|
||||
};
|
||||
|
||||
/*
|
||||
* Callback function used by wslay_frame_send() function when it needs
|
||||
* to send data. The implementation of this function must send at most
|
||||
* len bytes of data in data. flags is the bitwise OR of zero or more
|
||||
* of the following flag:
|
||||
*
|
||||
* WSLAY_MSG_MORE
|
||||
* There is more data to send
|
||||
*
|
||||
* It provides some hints to tune performance and behaviour. user_data
|
||||
* is one given in wslay_frame_context_init() function. The
|
||||
* implementation of this function must return the number of bytes
|
||||
* sent. If there is an error, return -1. The return value 0 is also
|
||||
* treated an error by the library.
|
||||
*/
|
||||
typedef ssize_t (*wslay_frame_send_callback)(const uint8_t *data, size_t len,
|
||||
int flags, void *user_data);
|
||||
/*
|
||||
* Callback function used by wslay_frame_recv() function when it needs
|
||||
* more data. The implementation of this function must fill at most
|
||||
* len bytes of data into buf. The memory area of buf is allocated by
|
||||
* library and not be freed by the application code. flags is always 0
|
||||
* in this version. user_data is one given in
|
||||
* wslay_frame_context_init() function. The implementation of this
|
||||
* function must return the number of bytes filled. If there is an
|
||||
* error, return -1. The return value 0 is also treated an error by
|
||||
* the library.
|
||||
*/
|
||||
typedef ssize_t (*wslay_frame_recv_callback)(uint8_t *buf, size_t len,
|
||||
int flags, void *user_data);
|
||||
/*
|
||||
* Callback function used by wslay_frame_send() function when it needs
|
||||
* new mask key. The implementation of this function must write
|
||||
* exactly len bytes of mask key to buf. user_data is one given in
|
||||
* wslay_frame_context_init() function. The implementation of this
|
||||
* function return 0 on success. If there is an error, return -1.
|
||||
*/
|
||||
typedef int (*wslay_frame_genmask_callback)(uint8_t *buf, size_t len,
|
||||
void *user_data);
|
||||
|
||||
struct wslay_frame_callbacks {
|
||||
wslay_frame_send_callback send_callback;
|
||||
wslay_frame_recv_callback recv_callback;
|
||||
wslay_frame_genmask_callback genmask_callback;
|
||||
};
|
||||
|
||||
/*
|
||||
* The opcode defined in RFC6455.
|
||||
*/
|
||||
enum wslay_opcode {
|
||||
WSLAY_CONTINUATION_FRAME = 0x0u,
|
||||
WSLAY_TEXT_FRAME = 0x1u,
|
||||
WSLAY_BINARY_FRAME = 0x2u,
|
||||
WSLAY_CONNECTION_CLOSE = 0x8u,
|
||||
WSLAY_PING = 0x9u,
|
||||
WSLAY_PONG = 0xau
|
||||
};
|
||||
|
||||
/*
|
||||
* Macro that returns 1 if opcode is control frame opcode, otherwise
|
||||
* returns 0.
|
||||
*/
|
||||
#define wslay_is_ctrl_frame(opcode) ((opcode >> 3) & 1)
|
||||
|
||||
/*
|
||||
* Macros that represent and return reserved bits: RSV1, RSV2, RSV3.
|
||||
* These macros assume that rsv is constructed by ((RSV1 << 2) |
|
||||
* (RSV2 << 1) | RSV3)
|
||||
*/
|
||||
#define WSLAY_RSV_NONE ((uint8_t)0)
|
||||
#define WSLAY_RSV1_BIT (((uint8_t)1) << 2)
|
||||
#define WSLAY_RSV2_BIT (((uint8_t)1) << 1)
|
||||
#define WSLAY_RSV3_BIT (((uint8_t)1) << 0)
|
||||
|
||||
#define wslay_get_rsv1(rsv) ((rsv >> 2) & 1)
|
||||
#define wslay_get_rsv2(rsv) ((rsv >> 1) & 1)
|
||||
#define wslay_get_rsv3(rsv) (rsv & 1)
|
||||
|
||||
struct wslay_frame_iocb {
|
||||
/* 1 for fragmented final frame, 0 for otherwise */
|
||||
uint8_t fin;
|
||||
/*
|
||||
* reserved 3 bits. rsv = ((RSV1 << 2) | (RSV << 1) | RSV3).
|
||||
* RFC6455 requires 0 unless extensions are negotiated.
|
||||
*/
|
||||
uint8_t rsv;
|
||||
/* 4 bit opcode */
|
||||
uint8_t opcode;
|
||||
/* payload length [0, 2**63-1] */
|
||||
uint64_t payload_length;
|
||||
/* 1 for masked frame, 0 for unmasked */
|
||||
uint8_t mask;
|
||||
/* part of payload data */
|
||||
const uint8_t *data;
|
||||
/* bytes of data defined above */
|
||||
size_t data_length;
|
||||
};
|
||||
|
||||
struct wslay_frame_context;
|
||||
typedef struct wslay_frame_context *wslay_frame_context_ptr;
|
||||
|
||||
/*
|
||||
* Initializes ctx using given callbacks and user_data. This function
|
||||
* allocates memory for struct wslay_frame_context and stores the
|
||||
* result to *ctx. The callback functions specified in callbacks are
|
||||
* copied to ctx. user_data is stored in ctx and it will be passed to
|
||||
* callback functions. When the user code finished using ctx, it must
|
||||
* call wslay_frame_context_free to deallocate memory.
|
||||
*/
|
||||
int wslay_frame_context_init(wslay_frame_context_ptr *ctx,
|
||||
const struct wslay_frame_callbacks *callbacks,
|
||||
void *user_data);
|
||||
|
||||
/*
|
||||
* Deallocates memory pointed by ctx.
|
||||
*/
|
||||
void wslay_frame_context_free(wslay_frame_context_ptr ctx);
|
||||
|
||||
/*
|
||||
* Send WebSocket frame specified in iocb. ctx must be initialized
|
||||
* using wslay_frame_context_init() function. iocb->fin must be 1 if
|
||||
* this is a fin frame, otherwise 0. iocb->rsv is reserved bits.
|
||||
* iocb->opcode must be the opcode of this frame. iocb->mask must be
|
||||
* 1 if this is masked frame, otherwise 0. iocb->payload_length is
|
||||
* the payload_length of this frame. iocb->data must point to the
|
||||
* payload data to be sent. iocb->data_length must be the length of
|
||||
* the data. This function calls send_callback function if it needs
|
||||
* to send bytes. This function calls gen_mask_callback function if
|
||||
* it needs new mask key. This function returns the number of payload
|
||||
* bytes sent. Please note that it does not include any number of
|
||||
* header bytes. If it cannot send any single bytes of payload, it
|
||||
* returns WSLAY_ERR_WANT_WRITE. If the library detects error in iocb,
|
||||
* this function returns WSLAY_ERR_INVALID_ARGUMENT. If callback
|
||||
* functions report a failure, this function returns
|
||||
* WSLAY_ERR_INVALID_CALLBACK. This function does not always send all
|
||||
* given data in iocb. If there are remaining data to be sent, adjust
|
||||
* data and data_length in iocb accordingly and call this function
|
||||
* again.
|
||||
*/
|
||||
ssize_t wslay_frame_send(wslay_frame_context_ptr ctx,
|
||||
struct wslay_frame_iocb *iocb);
|
||||
|
||||
/*
|
||||
* Write WebSocket frame specified in iocb to buf of length
|
||||
* buflen. ctx must be initialized using wslay_frame_context_init()
|
||||
* function. iocb->fin must be 1 if this is a fin frame, otherwise 0.
|
||||
* iocb->rsv is reserved bits. iocb->opcode must be the opcode of
|
||||
* this frame. iocb->mask must be 1 if this is masked frame,
|
||||
* otherwise 0. iocb->payload_length is the payload_length of this
|
||||
* frame. iocb->data must point to the payload data to be
|
||||
* sent. iocb->data_length must be the length of the data. Unlike
|
||||
* wslay_frame_send, this function does not call send_callback
|
||||
* function. This function calls gen_mask_callback function if it
|
||||
* needs new mask key. This function returns the number of bytes
|
||||
* written to a buffer. Unlike wslay_frame_send, it includes the
|
||||
* number of header bytes. Instead, the number of payload bytes
|
||||
* written is assigned to *pwpayloadlen if this function succeeds. If
|
||||
* there is not enough space left in a buffer, it returns 0. If the
|
||||
* library detects error in iocb, this function returns
|
||||
* WSLAY_ERR_INVALID_ARGUMENT. If callback functions report a
|
||||
* failure, this function returns WSLAY_ERR_INVALID_CALLBACK. This
|
||||
* function does not always send all given data in iocb. If there are
|
||||
* remaining data to be sent, adjust data and data_length in iocb
|
||||
* accordingly and call this function again.
|
||||
*/
|
||||
ssize_t wslay_frame_write(wslay_frame_context_ptr ctx,
|
||||
struct wslay_frame_iocb *iocb, uint8_t *buf,
|
||||
size_t buflen, size_t *pwpayloadlen);
|
||||
|
||||
/*
|
||||
* Receives WebSocket frame and stores it in iocb. This function
|
||||
* returns the number of payload bytes received. This does not
|
||||
* include header bytes. In this case, iocb will be populated as
|
||||
* follows: iocb->fin is 1 if received frame is fin frame, otherwise
|
||||
* 0. iocb->rsv is reserved bits of received frame. iocb->opcode is
|
||||
* opcode of received frame. iocb->mask is 1 if received frame is
|
||||
* masked, otherwise 0. iocb->payload_length is the payload length of
|
||||
* received frame. iocb->data is pointed to the buffer containing
|
||||
* received payload data. This buffer is allocated by the library and
|
||||
* must be read-only. iocb->data_length is the number of payload
|
||||
* bytes recieved. This function calls recv_callback if it needs to
|
||||
* receive additional bytes. If it cannot receive any single bytes of
|
||||
* payload, it returns WSLAY_ERR_WANT_READ. If the library detects
|
||||
* protocol violation in a received frame, this function returns
|
||||
* WSLAY_ERR_PROTO. If callback functions report a failure, this
|
||||
* function returns WSLAY_ERR_INVALID_CALLBACK. This function does
|
||||
* not always receive whole frame in a single call. If there are
|
||||
* remaining data to be received, call this function again. This
|
||||
* function ensures frame alignment.
|
||||
*/
|
||||
ssize_t wslay_frame_recv(wslay_frame_context_ptr ctx,
|
||||
struct wslay_frame_iocb *iocb);
|
||||
|
||||
struct wslay_event_context;
|
||||
/* Pointer to the event-based API context */
|
||||
typedef struct wslay_event_context *wslay_event_context_ptr;
|
||||
|
||||
struct wslay_event_on_msg_recv_arg {
|
||||
/* reserved bits: rsv = (RSV1 << 2) | (RSV2 << 1) | RSV3 */
|
||||
uint8_t rsv;
|
||||
/* opcode */
|
||||
uint8_t opcode;
|
||||
/* received message */
|
||||
const uint8_t *msg;
|
||||
/* message length */
|
||||
size_t msg_length;
|
||||
/*
|
||||
* Status code iff opcode == WSLAY_CONNECTION_CLOSE. If no status
|
||||
* code is included in the close control frame, it is set to 0.
|
||||
*/
|
||||
uint16_t status_code;
|
||||
};
|
||||
|
||||
/*
|
||||
* Callback function invoked by wslay_event_recv() when a message is
|
||||
* completely received.
|
||||
*/
|
||||
typedef void (*wslay_event_on_msg_recv_callback)(
|
||||
wslay_event_context_ptr ctx, const struct wslay_event_on_msg_recv_arg *arg,
|
||||
void *user_data);
|
||||
|
||||
struct wslay_event_on_frame_recv_start_arg {
|
||||
/* fin bit; 1 for final frame, or 0. */
|
||||
uint8_t fin;
|
||||
/* reserved bits: rsv = (RSV1 << 2) | (RSV2 << 1) | RSV3 */
|
||||
uint8_t rsv;
|
||||
/* opcode of the frame */
|
||||
uint8_t opcode;
|
||||
/* payload length of ths frame */
|
||||
uint64_t payload_length;
|
||||
};
|
||||
|
||||
/*
|
||||
* Callback function invoked by wslay_event_recv() when a new frame
|
||||
* starts to be received. This callback function is only invoked once
|
||||
* for each frame.
|
||||
*/
|
||||
typedef void (*wslay_event_on_frame_recv_start_callback)(
|
||||
wslay_event_context_ptr ctx,
|
||||
const struct wslay_event_on_frame_recv_start_arg *arg, void *user_data);
|
||||
|
||||
struct wslay_event_on_frame_recv_chunk_arg {
|
||||
/* chunk of payload data */
|
||||
const uint8_t *data;
|
||||
/* length of data */
|
||||
size_t data_length;
|
||||
};
|
||||
|
||||
/*
|
||||
* Callback function invoked by wslay_event_recv() when a chunk of
|
||||
* frame payload is received.
|
||||
*/
|
||||
typedef void (*wslay_event_on_frame_recv_chunk_callback)(
|
||||
wslay_event_context_ptr ctx,
|
||||
const struct wslay_event_on_frame_recv_chunk_arg *arg, void *user_data);
|
||||
|
||||
/*
|
||||
* Callback function invoked by wslay_event_recv() when a frame is
|
||||
* completely received.
|
||||
*/
|
||||
typedef void (*wslay_event_on_frame_recv_end_callback)(
|
||||
wslay_event_context_ptr ctx, void *user_data);
|
||||
|
||||
/*
|
||||
* Callback function invoked by wslay_event_recv() when it wants to
|
||||
* receive more data from peer. The implementation of this callback
|
||||
* function must read data at most len bytes from peer and store them
|
||||
* in buf and return the number of bytes read. flags is always 0 in
|
||||
* this version.
|
||||
*
|
||||
* If there is an error, return -1 and set error code
|
||||
* WSLAY_ERR_CALLBACK_FAILURE using wslay_event_set_error(). Wslay
|
||||
* event-based API on the whole assumes non-blocking I/O. If the cause
|
||||
* of error is EAGAIN or EWOULDBLOCK, set WSLAY_ERR_WOULDBLOCK
|
||||
* instead. This is important because it tells wslay_event_recv() to
|
||||
* stop receiving further data and return.
|
||||
*/
|
||||
typedef ssize_t (*wslay_event_recv_callback)(wslay_event_context_ptr ctx,
|
||||
uint8_t *buf, size_t len,
|
||||
int flags, void *user_data);
|
||||
|
||||
/*
|
||||
* Callback function invoked by wslay_event_send() when it wants to
|
||||
* send more data to peer. The implementation of this callback
|
||||
* function must send data at most len bytes to peer and return the
|
||||
* number of bytes sent. flags is the bitwise OR of zero or more of
|
||||
* the following flag:
|
||||
*
|
||||
* WSLAY_MSG_MORE
|
||||
* There is more data to send
|
||||
*
|
||||
* It provides some hints to tune performance and behaviour.
|
||||
*
|
||||
* If there is an error, return -1 and set error code
|
||||
* WSLAY_ERR_CALLBACK_FAILURE using wslay_event_set_error(). Wslay
|
||||
* event-based API on the whole assumes non-blocking I/O. If the cause
|
||||
* of error is EAGAIN or EWOULDBLOCK, set WSLAY_ERR_WOULDBLOCK
|
||||
* instead. This is important because it tells wslay_event_send() to
|
||||
* stop sending data and return.
|
||||
*/
|
||||
typedef ssize_t (*wslay_event_send_callback)(wslay_event_context_ptr ctx,
|
||||
const uint8_t *data, size_t len,
|
||||
int flags, void *user_data);
|
||||
|
||||
/*
|
||||
* Callback function invoked by wslay_event_send() when it wants new
|
||||
* mask key. As described in RFC6455, only the traffic from WebSocket
|
||||
* client is masked, so this callback function is only needed if an
|
||||
* event-based API is initialized for WebSocket client use.
|
||||
*/
|
||||
typedef int (*wslay_event_genmask_callback)(wslay_event_context_ptr ctx,
|
||||
uint8_t *buf, size_t len,
|
||||
void *user_data);
|
||||
|
||||
struct wslay_event_callbacks {
|
||||
wslay_event_recv_callback recv_callback;
|
||||
wslay_event_send_callback send_callback;
|
||||
wslay_event_genmask_callback genmask_callback;
|
||||
wslay_event_on_frame_recv_start_callback on_frame_recv_start_callback;
|
||||
wslay_event_on_frame_recv_chunk_callback on_frame_recv_chunk_callback;
|
||||
wslay_event_on_frame_recv_end_callback on_frame_recv_end_callback;
|
||||
wslay_event_on_msg_recv_callback on_msg_recv_callback;
|
||||
};
|
||||
|
||||
/*
|
||||
* Initializes ctx as WebSocket Server. user_data is an arbitrary
|
||||
* pointer, which is directly passed to each callback functions as
|
||||
* user_data argument.
|
||||
*
|
||||
* On success, returns 0. On error, returns one of following negative
|
||||
* values:
|
||||
*
|
||||
* WSLAY_ERR_NOMEM
|
||||
* Out of memory.
|
||||
*/
|
||||
int wslay_event_context_server_init(
|
||||
wslay_event_context_ptr *ctx, const struct wslay_event_callbacks *callbacks,
|
||||
void *user_data);
|
||||
|
||||
/*
|
||||
* Initializes ctx as WebSocket client. user_data is an arbitrary
|
||||
* pointer, which is directly passed to each callback functions as
|
||||
* user_data argument.
|
||||
*
|
||||
* On success, returns 0. On error, returns one of following negative
|
||||
* values:
|
||||
*
|
||||
* WSLAY_ERR_NOMEM
|
||||
* Out of memory.
|
||||
*/
|
||||
int wslay_event_context_client_init(
|
||||
wslay_event_context_ptr *ctx, const struct wslay_event_callbacks *callbacks,
|
||||
void *user_data);
|
||||
|
||||
/*
|
||||
* Releases allocated resources for ctx.
|
||||
*/
|
||||
void wslay_event_context_free(wslay_event_context_ptr ctx);
|
||||
|
||||
/*
|
||||
* Sets a bit mask of allowed reserved bits.
|
||||
* Currently only permitted values are WSLAY_RSV1_BIT to allow PMCE
|
||||
* extension (see RFC-7692) or WSLAY_RSV_NONE to disable.
|
||||
*
|
||||
* Default: WSLAY_RSV_NONE
|
||||
*/
|
||||
void wslay_event_config_set_allowed_rsv_bits(wslay_event_context_ptr ctx,
|
||||
uint8_t rsv);
|
||||
|
||||
/*
|
||||
* Enables or disables buffering of an entire message for non-control
|
||||
* frames. If val is 0, buffering is enabled. Otherwise, buffering is
|
||||
* disabled. If wslay_event_on_msg_recv_callback is invoked when
|
||||
* buffering is disabled, the msg_length member of struct
|
||||
* wslay_event_on_msg_recv_arg is set to 0.
|
||||
*
|
||||
* The control frames are always buffered regardless of this function call.
|
||||
*
|
||||
* This function must not be used after the first invocation of
|
||||
* wslay_event_recv() function.
|
||||
*/
|
||||
void wslay_event_config_set_no_buffering(wslay_event_context_ptr ctx, int val);
|
||||
|
||||
/*
|
||||
* Sets maximum length of a message that can be received. The length
|
||||
* of message is checked by wslay_event_recv() function. If the length
|
||||
* of a message is larger than this value, reading operation is
|
||||
* disabled (same effect with wslay_event_shutdown_read() call) and
|
||||
* close control frame with WSLAY_CODE_MESSAGE_TOO_BIG is queued. If
|
||||
* buffering for non-control frames is disabled, the library checks
|
||||
* each frame payload length and does not check length of entire
|
||||
* message.
|
||||
*
|
||||
* The default value is (1u << 31)-1.
|
||||
*/
|
||||
void wslay_event_config_set_max_recv_msg_length(wslay_event_context_ptr ctx,
|
||||
uint64_t val);
|
||||
|
||||
/*
|
||||
* Sets callbacks to ctx. The callbacks previously set by this function
|
||||
* or wslay_event_context_server_init() or
|
||||
* wslay_event_context_client_init() are replaced with callbacks.
|
||||
*/
|
||||
void wslay_event_config_set_callbacks(
|
||||
wslay_event_context_ptr ctx, const struct wslay_event_callbacks *callbacks);
|
||||
|
||||
/*
|
||||
* Receives messages from peer. When receiving
|
||||
* messages, it uses wslay_event_recv_callback function. Single call
|
||||
* of this function receives multiple messages until
|
||||
* wslay_event_recv_callback function sets error code
|
||||
* WSLAY_ERR_WOULDBLOCK.
|
||||
*
|
||||
* When close control frame is received, this function automatically
|
||||
* queues close control frame. Also this function calls
|
||||
* wslay_event_set_read_enabled() with second argument 0 to disable
|
||||
* further read from peer.
|
||||
*
|
||||
* When ping control frame is received, this function automatically
|
||||
* queues pong control frame.
|
||||
*
|
||||
* In case of a fatal errror which leads to negative return code, this
|
||||
* function calls wslay_event_set_read_enabled() with second argument
|
||||
* 0 to disable further read from peer.
|
||||
*
|
||||
* wslay_event_recv() returns 0 if it succeeds, or one of the
|
||||
* following negative error codes:
|
||||
*
|
||||
* WSLAY_ERR_CALLBACK_FAILURE
|
||||
* User defined callback function is failed.
|
||||
*
|
||||
* WSLAY_ERR_NOMEM
|
||||
* Out of memory.
|
||||
*
|
||||
* When negative error code is returned, application must not make any
|
||||
* further call of wslay_event_recv() and must close WebSocket
|
||||
* connection.
|
||||
*/
|
||||
int wslay_event_recv(wslay_event_context_ptr ctx);
|
||||
|
||||
/*
|
||||
* Sends queued messages to peer. When sending a
|
||||
* message, it uses wslay_event_send_callback function. Single call of
|
||||
* wslay_event_send() sends multiple messages until
|
||||
* wslay_event_send_callback sets error code WSLAY_ERR_WOULDBLOCK.
|
||||
*
|
||||
* If ctx is initialized for WebSocket client use, wslay_event_send()
|
||||
* uses wslay_event_genmask_callback to get new mask key.
|
||||
*
|
||||
* When a message queued using wslay_event_queue_fragmented_msg() is
|
||||
* sent, wslay_event_send() invokes
|
||||
* wslay_event_fragmented_msg_callback for that message.
|
||||
*
|
||||
* After close control frame is sent, this function calls
|
||||
* wslay_event_set_write_enabled() with second argument 0 to disable
|
||||
* further transmission to peer.
|
||||
*
|
||||
* If there are any pending messages, wslay_event_want_write() returns
|
||||
* 1, otherwise returns 0.
|
||||
*
|
||||
* In case of a fatal errror which leads to negative return code, this
|
||||
* function calls wslay_event_set_write_enabled() with second argument
|
||||
* 0 to disable further transmission to peer.
|
||||
*
|
||||
* wslay_event_send() returns 0 if it succeeds, or one of the
|
||||
* following negative error codes:
|
||||
*
|
||||
* WSLAY_ERR_CALLBACK_FAILURE
|
||||
* User defined callback function is failed.
|
||||
*
|
||||
* WSLAY_ERR_NOMEM
|
||||
* Out of memory.
|
||||
*
|
||||
* When negative error code is returned, application must not make any
|
||||
* further call of wslay_event_send() and must close WebSocket
|
||||
* connection.
|
||||
*/
|
||||
int wslay_event_send(wslay_event_context_ptr ctx);
|
||||
|
||||
/*
|
||||
* Writes queued messages to a buffer. Unlike wslay_event_send(), this
|
||||
* function writes messages into the given buffer. It does not use
|
||||
* wslay_event_send_callback function. Single call of
|
||||
* wslay_event_write() writes multiple messages until there is not
|
||||
* enough space left in a buffer.
|
||||
*
|
||||
* If ctx is initialized for WebSocket client use, wslay_event_write()
|
||||
* uses wslay_event_genmask_callback to get new mask key.
|
||||
*
|
||||
* buf is a pointer to buffer and its capacity is given in buflen. It
|
||||
* should have at least 14 bytes.
|
||||
*
|
||||
* When a message queued using wslay_event_queue_fragmented_msg() is
|
||||
* sent, wslay_event_write() invokes
|
||||
* wslay_event_fragmented_msg_callback for that message.
|
||||
*
|
||||
* After close control frame is sent, this function calls
|
||||
* wslay_event_set_write_enabled() with second argument 0 to disable
|
||||
* further transmission to peer.
|
||||
*
|
||||
* If there are any pending messages, wslay_event_want_write() returns
|
||||
* 1, otherwise returns 0.
|
||||
*
|
||||
* In case of a fatal errror which leads to negative return code, this
|
||||
* function calls wslay_event_set_write_enabled() with second argument
|
||||
* 0 to disable further transmission to peer.
|
||||
*
|
||||
* wslay_event_write() returns the number of bytes written to a buffer
|
||||
* if it succeeds, or one of the following negative error codes:
|
||||
*
|
||||
* WSLAY_ERR_CALLBACK_FAILURE
|
||||
* User defined callback function is failed.
|
||||
*
|
||||
* WSLAY_ERR_NOMEM
|
||||
* Out of memory.
|
||||
*
|
||||
* When negative error code is returned, application must not make any
|
||||
* further call of wslay_event_write() and must close WebSocket
|
||||
* connection.
|
||||
*/
|
||||
ssize_t wslay_event_write(wslay_event_context_ptr ctx, uint8_t *buf,
|
||||
size_t buflen);
|
||||
|
||||
struct wslay_event_msg {
|
||||
uint8_t opcode;
|
||||
const uint8_t *msg;
|
||||
size_t msg_length;
|
||||
};
|
||||
|
||||
/*
|
||||
* Queues message specified in arg.
|
||||
*
|
||||
* This function supports both control and non-control messages and
|
||||
* the given message is sent without fragmentation. If fragmentation
|
||||
* is needed, use wslay_event_queue_fragmented_msg() function instead.
|
||||
*
|
||||
* This function just queues a message and does not send
|
||||
* it. wslay_event_send() function call sends these queued messages.
|
||||
*
|
||||
* wslay_event_queue_msg() returns 0 if it succeeds, or returns the
|
||||
* following negative error codes:
|
||||
*
|
||||
* WSLAY_ERR_NO_MORE_MSG
|
||||
* Could not queue given message. The one of possible reason is that
|
||||
* close control frame has been queued/sent and no further queueing
|
||||
* message is not allowed.
|
||||
*
|
||||
* WSLAY_ERR_INVALID_ARGUMENT
|
||||
* The given message is invalid.
|
||||
*
|
||||
* WSLAY_ERR_NOMEM
|
||||
* Out of memory.
|
||||
*/
|
||||
int wslay_event_queue_msg(wslay_event_context_ptr ctx,
|
||||
const struct wslay_event_msg *arg);
|
||||
|
||||
/*
|
||||
* Extended version of wslay_event_queue_msg which allows to set reserved bits.
|
||||
*/
|
||||
int wslay_event_queue_msg_ex(wslay_event_context_ptr ctx,
|
||||
const struct wslay_event_msg *arg, uint8_t rsv);
|
||||
|
||||
/*
|
||||
* Specify "source" to generate message.
|
||||
*/
|
||||
union wslay_event_msg_source {
|
||||
int fd;
|
||||
void *data;
|
||||
};
|
||||
|
||||
/*
|
||||
* Callback function called by wslay_event_send() to read message data
|
||||
* from source. The implementation of
|
||||
* wslay_event_fragmented_msg_callback must store at most len bytes of
|
||||
* data to buf and return the number of stored bytes. If all data is
|
||||
* read (i.e., EOF), set *eof to 1. If no data can be generated at the
|
||||
* moment, return 0. If there is an error, return -1 and set error
|
||||
* code WSLAY_ERR_CALLBACK_FAILURE using wslay_event_set_error().
|
||||
*/
|
||||
typedef ssize_t (*wslay_event_fragmented_msg_callback)(
|
||||
wslay_event_context_ptr ctx, uint8_t *buf, size_t len,
|
||||
const union wslay_event_msg_source *source, int *eof, void *user_data);
|
||||
|
||||
struct wslay_event_fragmented_msg {
|
||||
/* opcode */
|
||||
uint8_t opcode;
|
||||
/* "source" to generate message data */
|
||||
union wslay_event_msg_source source;
|
||||
/* Callback function to read message data from source. */
|
||||
wslay_event_fragmented_msg_callback read_callback;
|
||||
};
|
||||
|
||||
/*
|
||||
* Queues a fragmented message specified in arg.
|
||||
*
|
||||
* This function supports non-control messages only. For control frames,
|
||||
* use wslay_event_queue_msg() or wslay_event_queue_close().
|
||||
*
|
||||
* This function just queues a message and does not send
|
||||
* it. wslay_event_send() function call sends these queued messages.
|
||||
*
|
||||
* wslay_event_queue_fragmented_msg() returns 0 if it succeeds, or
|
||||
* returns the following negative error codes:
|
||||
*
|
||||
* WSLAY_ERR_NO_MORE_MSG
|
||||
* Could not queue given message. The one of possible reason is that
|
||||
* close control frame has been queued/sent and no further queueing
|
||||
* message is not allowed.
|
||||
*
|
||||
* WSLAY_ERR_INVALID_ARGUMENT
|
||||
* The given message is invalid.
|
||||
*
|
||||
* WSLAY_ERR_NOMEM
|
||||
* Out of memory.
|
||||
*/
|
||||
int wslay_event_queue_fragmented_msg(
|
||||
wslay_event_context_ptr ctx, const struct wslay_event_fragmented_msg *arg);
|
||||
|
||||
/*
|
||||
* Extended version of wslay_event_queue_fragmented_msg which allows to set
|
||||
* reserved bits.
|
||||
*/
|
||||
int wslay_event_queue_fragmented_msg_ex(
|
||||
wslay_event_context_ptr ctx, const struct wslay_event_fragmented_msg *arg,
|
||||
uint8_t rsv);
|
||||
|
||||
/*
|
||||
* Queues close control frame. This function is provided just for
|
||||
* convenience. wslay_event_queue_msg() can queue a close control
|
||||
* frame as well. status_code is the status code of close control
|
||||
* frame. reason is the close reason encoded in UTF-8. reason_length
|
||||
* is the length of reason in bytes. reason_length must be less than
|
||||
* 123 bytes.
|
||||
*
|
||||
* If status_code is 0, reason and reason_length is not used and close
|
||||
* control frame with zero-length payload will be queued.
|
||||
*
|
||||
* This function just queues a message and does not send
|
||||
* it. wslay_event_send() function call sends these queued messages.
|
||||
*
|
||||
* wslay_event_queue_close() returns 0 if it succeeds, or returns the
|
||||
* following negative error codes:
|
||||
*
|
||||
* WSLAY_ERR_NO_MORE_MSG
|
||||
* Could not queue given message. The one of possible reason is that
|
||||
* close control frame has been queued/sent and no further queueing
|
||||
* message is not allowed.
|
||||
*
|
||||
* WSLAY_ERR_INVALID_ARGUMENT
|
||||
* The given message is invalid.
|
||||
*
|
||||
* WSLAY_ERR_NOMEM
|
||||
* Out of memory.
|
||||
*/
|
||||
int wslay_event_queue_close(wslay_event_context_ptr ctx, uint16_t status_code,
|
||||
const uint8_t *reason, size_t reason_length);
|
||||
|
||||
/*
|
||||
* Sets error code to tell the library there is an error. This
|
||||
* function is typically used in user defined callback functions. See
|
||||
* the description of callback function to know which error code
|
||||
* should be used.
|
||||
*/
|
||||
void wslay_event_set_error(wslay_event_context_ptr ctx, int val);
|
||||
|
||||
/*
|
||||
* Query whehter the library want to read more data from peer.
|
||||
*
|
||||
* wslay_event_want_read() returns 1 if the library want to read more
|
||||
* data from peer, or returns 0.
|
||||
*/
|
||||
int wslay_event_want_read(wslay_event_context_ptr ctx);
|
||||
|
||||
/*
|
||||
* Query whehter the library want to send more data to peer.
|
||||
*
|
||||
* wslay_event_want_write() returns 1 if the library want to send more
|
||||
* data to peer, or returns 0.
|
||||
*/
|
||||
int wslay_event_want_write(wslay_event_context_ptr ctx);
|
||||
|
||||
/*
|
||||
* Prevents the event-based API context from reading any further data
|
||||
* from peer.
|
||||
*
|
||||
* This function may be used with wslay_event_queue_close() if the
|
||||
* application detects error in the data received and wants to fail
|
||||
* WebSocket connection.
|
||||
*/
|
||||
void wslay_event_shutdown_read(wslay_event_context_ptr ctx);
|
||||
|
||||
/*
|
||||
* Prevents the event-based API context from sending any further data
|
||||
* to peer.
|
||||
*/
|
||||
void wslay_event_shutdown_write(wslay_event_context_ptr ctx);
|
||||
|
||||
/*
|
||||
* Returns 1 if the event-based API context allows read operation, or
|
||||
* return 0.
|
||||
*
|
||||
* After wslay_event_shutdown_read() is called,
|
||||
* wslay_event_get_read_enabled() returns 0.
|
||||
*/
|
||||
int wslay_event_get_read_enabled(wslay_event_context_ptr ctx);
|
||||
|
||||
/*
|
||||
* Returns 1 if the event-based API context allows write operation, or
|
||||
* return 0.
|
||||
*
|
||||
* After wslay_event_shutdown_write() is called,
|
||||
* wslay_event_get_write_enabled() returns 0.
|
||||
*/
|
||||
int wslay_event_get_write_enabled(wslay_event_context_ptr ctx);
|
||||
|
||||
/*
|
||||
* Returns 1 if a close control frame has been received from peer, or
|
||||
* returns 0.
|
||||
*/
|
||||
int wslay_event_get_close_received(wslay_event_context_ptr ctx);
|
||||
|
||||
/*
|
||||
* Returns 1 if a close control frame has been sent to peer, or
|
||||
* returns 0.
|
||||
*/
|
||||
int wslay_event_get_close_sent(wslay_event_context_ptr ctx);
|
||||
|
||||
/*
|
||||
* Returns status code received in close control frame. If no close
|
||||
* control frame has not been received, returns
|
||||
* WSLAY_CODE_ABNORMAL_CLOSURE. If received close control frame has no
|
||||
* status code, returns WSLAY_CODE_NO_STATUS_RCVD.
|
||||
*/
|
||||
uint16_t wslay_event_get_status_code_received(wslay_event_context_ptr ctx);
|
||||
|
||||
/*
|
||||
* Returns status code sent in close control frame. If no close
|
||||
* control frame has not been sent, returns
|
||||
* WSLAY_CODE_ABNORMAL_CLOSURE. If sent close control frame has no
|
||||
* status code, returns WSLAY_CODE_NO_STATUS_RCVD.
|
||||
*/
|
||||
uint16_t wslay_event_get_status_code_sent(wslay_event_context_ptr ctx);
|
||||
|
||||
/*
|
||||
* Returns the number of queued messages.
|
||||
*/
|
||||
size_t wslay_event_get_queued_msg_count(wslay_event_context_ptr ctx);
|
||||
|
||||
/*
|
||||
* Returns the sum of queued message length. It only counts the
|
||||
* message length queued using wslay_event_queue_msg() or
|
||||
* wslay_event_queue_close().
|
||||
*/
|
||||
size_t wslay_event_get_queued_msg_length(wslay_event_context_ptr ctx);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* WSLAY_H */
|
||||
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Wslay - The WebSocket Library
|
||||
*
|
||||
* Copyright (c) 2011, 2012 Tatsuhiro Tsujikawa
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
#ifndef WSLAYVER_H
|
||||
#define WSLAYVER_H
|
||||
|
||||
/* normally substituted by the build system; pinned to the vendored release */
|
||||
#define WSLAY_VERSION "1.1.1"
|
||||
|
||||
#endif /* WSLAYVER_H */
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#include <BaseTsd.h>
|
||||
#ifndef _SSIZE_T_DEFINED
|
||||
#define _SSIZE_T_DEFINED
|
||||
typedef SSIZE_T ssize_t;
|
||||
#endif
|
||||
#endif
|
||||
+1082
File diff suppressed because it is too large.
Load diff
+138
@@ -0,0 +1,138 @@
|
||||
/*
|
||||
* Wslay - The WebSocket Library
|
||||
*
|
||||
* Copyright (c) 2011, 2012 Tatsuhiro Tsujikawa
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
#ifndef WSLAY_EVENT_H
|
||||
#define WSLAY_EVENT_H
|
||||
|
||||
#ifdef HAVE_CONFIG_H
|
||||
# include <config.h>
|
||||
#endif /* HAVE_CONFIG_H */
|
||||
|
||||
#include <wslay/wslay.h>
|
||||
|
||||
#include "wslay_queue.h"
|
||||
|
||||
struct wslay_event_byte_chunk {
|
||||
struct wslay_queue_entry qe;
|
||||
uint8_t *data;
|
||||
size_t data_length;
|
||||
};
|
||||
|
||||
struct wslay_event_imsg {
|
||||
uint8_t fin;
|
||||
uint8_t rsv;
|
||||
uint8_t opcode;
|
||||
uint32_t utf8state;
|
||||
struct wslay_queue chunks;
|
||||
size_t msg_length;
|
||||
};
|
||||
|
||||
enum wslay_event_msg_type { WSLAY_NON_FRAGMENTED, WSLAY_FRAGMENTED };
|
||||
|
||||
struct wslay_event_omsg {
|
||||
struct wslay_queue_entry qe;
|
||||
uint8_t fin;
|
||||
uint8_t opcode;
|
||||
uint8_t rsv;
|
||||
enum wslay_event_msg_type type;
|
||||
|
||||
uint8_t *data;
|
||||
size_t data_length;
|
||||
|
||||
union wslay_event_msg_source source;
|
||||
wslay_event_fragmented_msg_callback read_callback;
|
||||
};
|
||||
|
||||
struct wslay_event_frame_user_data {
|
||||
wslay_event_context_ptr ctx;
|
||||
void *user_data;
|
||||
};
|
||||
|
||||
enum wslay_event_close_status {
|
||||
WSLAY_CLOSE_RECEIVED = 1 << 0,
|
||||
WSLAY_CLOSE_QUEUED = 1 << 1,
|
||||
WSLAY_CLOSE_SENT = 1 << 2
|
||||
};
|
||||
|
||||
enum wslay_event_config { WSLAY_CONFIG_NO_BUFFERING = 1 << 0 };
|
||||
|
||||
struct wslay_event_context {
|
||||
/* config status, bitwise OR of enum wslay_event_config values*/
|
||||
uint32_t config;
|
||||
/* maximum message length that can be received */
|
||||
uint64_t max_recv_msg_length;
|
||||
/* 1 if initialized for server, otherwise 0 */
|
||||
uint8_t server;
|
||||
/* bitwise OR of enum wslay_event_close_status values */
|
||||
uint8_t close_status;
|
||||
/* status code in received close control frame */
|
||||
uint16_t status_code_recv;
|
||||
/* status code in sent close control frame */
|
||||
uint16_t status_code_sent;
|
||||
wslay_frame_context_ptr frame_ctx;
|
||||
/* 1 if reading is enabled, otherwise 0. Upon receiving close
|
||||
control frame this value set to 0. If any errors in read
|
||||
operation will also set this value to 0. */
|
||||
uint8_t read_enabled;
|
||||
/* 1 if writing is enabled, otherwise 0 Upon completing sending
|
||||
close control frame, this value set to 0. If any errors in write
|
||||
opration will also set this value to 0. */
|
||||
uint8_t write_enabled;
|
||||
/* imsg buffer to allow interleaved control frame between
|
||||
non-control frames. */
|
||||
struct wslay_event_imsg imsgs[2];
|
||||
/* Pointer to imsgs to indicate current used buffer. */
|
||||
struct wslay_event_imsg *imsg;
|
||||
/* payload length of frame currently being received. */
|
||||
uint64_t ipayloadlen;
|
||||
/* next byte offset of payload currently being received. */
|
||||
uint64_t ipayloadoff;
|
||||
/* error value set by user callback */
|
||||
int error;
|
||||
/* Pointer to the message currently being sent. NULL if no message
|
||||
is currently sent. */
|
||||
struct wslay_event_omsg *omsg;
|
||||
/* Queue for non-control frames */
|
||||
struct wslay_queue /*<wslay_omsg*>*/ send_queue;
|
||||
/* Queue for control frames */
|
||||
struct wslay_queue /*<wslay_omsg*>*/ send_ctrl_queue;
|
||||
/* Size of send_queue + size of send_ctrl_queue */
|
||||
size_t queued_msg_count;
|
||||
/* The sum of message length in send_queue */
|
||||
size_t queued_msg_length;
|
||||
/* Buffer used for fragmented messages */
|
||||
uint8_t obuf[4096];
|
||||
uint8_t *obuflimit;
|
||||
uint8_t *obufmark;
|
||||
/* payload length of frame currently being sent. */
|
||||
uint64_t opayloadlen;
|
||||
/* next byte offset of payload currently being sent. */
|
||||
uint64_t opayloadoff;
|
||||
struct wslay_event_callbacks callbacks;
|
||||
struct wslay_event_frame_user_data frame_user_data;
|
||||
void *user_data;
|
||||
uint8_t allowed_rsv_bits;
|
||||
};
|
||||
|
||||
#endif /* WSLAY_EVENT_H */
|
||||
+438
@@ -0,0 +1,438 @@
|
||||
/*
|
||||
* Wslay - The WebSocket Library
|
||||
*
|
||||
* Copyright (c) 2011, 2012 Tatsuhiro Tsujikawa
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
#include "wslay_frame.h"
|
||||
|
||||
#include <stddef.h>
|
||||
#include <string.h>
|
||||
#include <assert.h>
|
||||
|
||||
#include "wslay_net.h"
|
||||
|
||||
#define wslay_min(A, B) (((A) < (B)) ? (A) : (B))
|
||||
|
||||
int wslay_frame_context_init(wslay_frame_context_ptr *ctx,
|
||||
const struct wslay_frame_callbacks *callbacks,
|
||||
void *user_data) {
|
||||
*ctx = malloc(sizeof(struct wslay_frame_context));
|
||||
if (*ctx == NULL) {
|
||||
return -1;
|
||||
}
|
||||
memset(*ctx, 0, sizeof(struct wslay_frame_context));
|
||||
(*ctx)->istate = RECV_HEADER1;
|
||||
(*ctx)->ireqread = 2;
|
||||
(*ctx)->ostate = PREP_HEADER;
|
||||
(*ctx)->user_data = user_data;
|
||||
(*ctx)->ibufmark = (*ctx)->ibuflimit = (*ctx)->ibuf;
|
||||
(*ctx)->callbacks = *callbacks;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void wslay_frame_context_free(wslay_frame_context_ptr ctx) { free(ctx); }
|
||||
|
||||
ssize_t wslay_frame_send(wslay_frame_context_ptr ctx,
|
||||
struct wslay_frame_iocb *iocb) {
|
||||
if (iocb->data_length > iocb->payload_length) {
|
||||
return WSLAY_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
if (ctx->ostate == PREP_HEADER) {
|
||||
uint8_t *hdptr = ctx->oheader;
|
||||
memset(ctx->oheader, 0, sizeof(ctx->oheader));
|
||||
*hdptr |= (uint8_t)((uint8_t)(iocb->fin << 7) & 0x80u);
|
||||
*hdptr |= (uint8_t)((uint8_t)(iocb->rsv << 4) & 0x70u);
|
||||
/* Suppress stubborn gcc-10 warning */
|
||||
*hdptr |= (uint8_t)((uint8_t)(iocb->opcode << 0) & 0xfu);
|
||||
++hdptr;
|
||||
*hdptr |= (uint8_t)((uint8_t)(iocb->mask << 7) & 0x80u);
|
||||
if (wslay_is_ctrl_frame(iocb->opcode) && iocb->payload_length > 125) {
|
||||
return WSLAY_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
if (iocb->payload_length < 126) {
|
||||
*hdptr |= (uint8_t)iocb->payload_length;
|
||||
++hdptr;
|
||||
} else if (iocb->payload_length < (1 << 16)) {
|
||||
uint16_t len = htons((uint16_t)iocb->payload_length);
|
||||
*hdptr |= 126;
|
||||
++hdptr;
|
||||
memcpy(hdptr, &len, 2);
|
||||
hdptr += 2;
|
||||
} else if (iocb->payload_length < (1ull << 63)) {
|
||||
uint64_t len = hton64(iocb->payload_length);
|
||||
*hdptr |= 127;
|
||||
++hdptr;
|
||||
memcpy(hdptr, &len, 8);
|
||||
hdptr += 8;
|
||||
} else {
|
||||
/* Too large payload length */
|
||||
return WSLAY_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
if (iocb->mask) {
|
||||
if (ctx->callbacks.genmask_callback(ctx->omaskkey, 4, ctx->user_data) !=
|
||||
0) {
|
||||
return WSLAY_ERR_INVALID_CALLBACK;
|
||||
} else {
|
||||
ctx->omask = 1;
|
||||
memcpy(hdptr, ctx->omaskkey, 4);
|
||||
hdptr += 4;
|
||||
}
|
||||
}
|
||||
ctx->ostate = SEND_HEADER;
|
||||
ctx->oheadermark = ctx->oheader;
|
||||
ctx->oheaderlimit = hdptr;
|
||||
ctx->opayloadlen = iocb->payload_length;
|
||||
ctx->opayloadoff = 0;
|
||||
}
|
||||
if (ctx->ostate == SEND_HEADER) {
|
||||
ptrdiff_t len = ctx->oheaderlimit - ctx->oheadermark;
|
||||
ssize_t r;
|
||||
int flags = 0;
|
||||
if (iocb->data_length > 0) {
|
||||
flags |= WSLAY_MSG_MORE;
|
||||
}
|
||||
r = ctx->callbacks.send_callback(ctx->oheadermark, (size_t)len, flags,
|
||||
ctx->user_data);
|
||||
if (r > 0) {
|
||||
if (r > len) {
|
||||
return WSLAY_ERR_INVALID_CALLBACK;
|
||||
} else {
|
||||
ctx->oheadermark += r;
|
||||
if (ctx->oheadermark == ctx->oheaderlimit) {
|
||||
ctx->ostate = SEND_PAYLOAD;
|
||||
} else {
|
||||
return WSLAY_ERR_WANT_WRITE;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return WSLAY_ERR_WANT_WRITE;
|
||||
}
|
||||
}
|
||||
if (ctx->ostate == SEND_PAYLOAD) {
|
||||
size_t totallen = 0;
|
||||
if (iocb->data_length > 0) {
|
||||
if (ctx->omask) {
|
||||
uint8_t temp[4096];
|
||||
const uint8_t *datamark = iocb->data,
|
||||
*datalimit = iocb->data + iocb->data_length;
|
||||
while (datamark < datalimit) {
|
||||
size_t datalen = (size_t)(datalimit - datamark);
|
||||
const uint8_t *writelimit =
|
||||
datamark + wslay_min(sizeof(temp), datalen);
|
||||
size_t writelen = (size_t)(writelimit - datamark);
|
||||
ssize_t r;
|
||||
size_t i;
|
||||
for (i = 0; i < writelen; ++i) {
|
||||
temp[i] = datamark[i] ^ ctx->omaskkey[(ctx->opayloadoff + i) % 4];
|
||||
}
|
||||
r = ctx->callbacks.send_callback(temp, writelen, 0, ctx->user_data);
|
||||
if (r > 0) {
|
||||
if ((size_t)r > writelen) {
|
||||
return WSLAY_ERR_INVALID_CALLBACK;
|
||||
} else {
|
||||
datamark += r;
|
||||
ctx->opayloadoff += (uint64_t)r;
|
||||
totallen += (size_t)r;
|
||||
}
|
||||
} else {
|
||||
if (totallen > 0) {
|
||||
break;
|
||||
} else {
|
||||
return WSLAY_ERR_WANT_WRITE;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
ssize_t r;
|
||||
r = ctx->callbacks.send_callback(iocb->data, iocb->data_length, 0,
|
||||
ctx->user_data);
|
||||
if (r > 0) {
|
||||
if ((size_t)r > iocb->data_length) {
|
||||
return WSLAY_ERR_INVALID_CALLBACK;
|
||||
} else {
|
||||
ctx->opayloadoff += (uint64_t)r;
|
||||
totallen = (size_t)r;
|
||||
}
|
||||
} else {
|
||||
return WSLAY_ERR_WANT_WRITE;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ctx->opayloadoff == ctx->opayloadlen) {
|
||||
ctx->ostate = PREP_HEADER;
|
||||
}
|
||||
return (ssize_t)totallen;
|
||||
}
|
||||
return WSLAY_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
|
||||
ssize_t wslay_frame_write(wslay_frame_context_ptr ctx,
|
||||
struct wslay_frame_iocb *iocb, uint8_t *buf,
|
||||
size_t buflen, size_t *pwpayloadlen) {
|
||||
uint8_t *buf_last = buf;
|
||||
size_t i;
|
||||
size_t hdlen;
|
||||
|
||||
*pwpayloadlen = 0;
|
||||
|
||||
if (iocb->data_length > iocb->payload_length) {
|
||||
return WSLAY_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
|
||||
switch (ctx->ostate) {
|
||||
case PREP_HEADER:
|
||||
case PREP_HEADER_NOBUF:
|
||||
hdlen = 2;
|
||||
if (iocb->payload_length < 126) {
|
||||
/* nothing to do */
|
||||
} else if (iocb->payload_length < (1 << 16)) {
|
||||
hdlen += 2;
|
||||
} else if (iocb->payload_length < (1ull << 63)) {
|
||||
hdlen += 8;
|
||||
}
|
||||
if (iocb->mask) {
|
||||
hdlen += 4;
|
||||
}
|
||||
|
||||
if (buflen < hdlen) {
|
||||
ctx->ostate = PREP_HEADER_NOBUF;
|
||||
return 0;
|
||||
}
|
||||
|
||||
memset(buf_last, 0, hdlen);
|
||||
*buf_last |= (uint8_t)((uint8_t)(iocb->fin << 7) & 0x80u);
|
||||
*buf_last |= (uint8_t)((uint8_t)(iocb->rsv << 4) & 0x70u);
|
||||
/* Suppress stubborn gcc-10 warning */
|
||||
*buf_last |= (uint8_t)((uint8_t)(iocb->opcode << 0) & 0xfu);
|
||||
++buf_last;
|
||||
*buf_last |= (uint8_t)((uint8_t)(iocb->mask << 7) & 0x80u);
|
||||
if (wslay_is_ctrl_frame(iocb->opcode) && iocb->payload_length > 125) {
|
||||
return WSLAY_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
if (iocb->payload_length < 126) {
|
||||
*buf_last |= (uint8_t)iocb->payload_length;
|
||||
++buf_last;
|
||||
} else if (iocb->payload_length < (1 << 16)) {
|
||||
uint16_t len = htons((uint16_t)iocb->payload_length);
|
||||
*buf_last |= 126;
|
||||
++buf_last;
|
||||
memcpy(buf_last, &len, 2);
|
||||
buf_last += 2;
|
||||
} else if (iocb->payload_length < (1ull << 63)) {
|
||||
uint64_t len = hton64(iocb->payload_length);
|
||||
*buf_last |= 127;
|
||||
++buf_last;
|
||||
memcpy(buf_last, &len, 8);
|
||||
buf_last += 8;
|
||||
} else {
|
||||
/* Too large payload length */
|
||||
return WSLAY_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
if (iocb->mask) {
|
||||
if (ctx->callbacks.genmask_callback(ctx->omaskkey, 4, ctx->user_data) !=
|
||||
0) {
|
||||
return WSLAY_ERR_INVALID_CALLBACK;
|
||||
} else {
|
||||
ctx->omask = 1;
|
||||
memcpy(buf_last, ctx->omaskkey, 4);
|
||||
buf_last += 4;
|
||||
}
|
||||
}
|
||||
ctx->ostate = SEND_PAYLOAD;
|
||||
ctx->opayloadlen = iocb->payload_length;
|
||||
ctx->opayloadoff = 0;
|
||||
|
||||
buflen -= (size_t)(buf_last - buf);
|
||||
/* fall through */
|
||||
case SEND_PAYLOAD:
|
||||
if (iocb->data_length > 0) {
|
||||
size_t writelen = wslay_min(buflen, iocb->data_length);
|
||||
|
||||
if (ctx->omask) {
|
||||
for (i = 0; i < writelen; ++i) {
|
||||
*buf_last++ =
|
||||
iocb->data[i] ^ ctx->omaskkey[(ctx->opayloadoff + i) % 4];
|
||||
}
|
||||
} else {
|
||||
memcpy(buf_last, iocb->data, writelen);
|
||||
buf_last += writelen;
|
||||
}
|
||||
|
||||
ctx->opayloadoff += writelen;
|
||||
*pwpayloadlen = writelen;
|
||||
}
|
||||
|
||||
if (ctx->opayloadoff == ctx->opayloadlen) {
|
||||
ctx->ostate = PREP_HEADER;
|
||||
}
|
||||
|
||||
return buf_last - buf;
|
||||
default:
|
||||
return WSLAY_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
}
|
||||
|
||||
static void wslay_shift_ibuf(wslay_frame_context_ptr ctx) {
|
||||
ptrdiff_t len = ctx->ibuflimit - ctx->ibufmark;
|
||||
memmove(ctx->ibuf, ctx->ibufmark, (size_t)len);
|
||||
ctx->ibuflimit = ctx->ibuf + len;
|
||||
ctx->ibufmark = ctx->ibuf;
|
||||
}
|
||||
|
||||
static ssize_t wslay_recv(wslay_frame_context_ptr ctx) {
|
||||
ssize_t r;
|
||||
if (ctx->ibufmark != ctx->ibuf) {
|
||||
wslay_shift_ibuf(ctx);
|
||||
}
|
||||
r = ctx->callbacks.recv_callback(
|
||||
ctx->ibuflimit, (size_t)(ctx->ibuf + sizeof(ctx->ibuf) - ctx->ibuflimit),
|
||||
0, ctx->user_data);
|
||||
if (r > 0) {
|
||||
ctx->ibuflimit += r;
|
||||
} else {
|
||||
r = WSLAY_ERR_WANT_READ;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
#define WSLAY_AVAIL_IBUF(ctx) ((size_t)(ctx->ibuflimit - ctx->ibufmark))
|
||||
|
||||
ssize_t wslay_frame_recv(wslay_frame_context_ptr ctx,
|
||||
struct wslay_frame_iocb *iocb) {
|
||||
ssize_t r;
|
||||
if (ctx->istate == RECV_HEADER1) {
|
||||
uint8_t fin, opcode, rsv, payloadlen;
|
||||
if (WSLAY_AVAIL_IBUF(ctx) < ctx->ireqread) {
|
||||
if ((r = wslay_recv(ctx)) <= 0) {
|
||||
return r;
|
||||
}
|
||||
}
|
||||
if (WSLAY_AVAIL_IBUF(ctx) < ctx->ireqread) {
|
||||
return WSLAY_ERR_WANT_READ;
|
||||
}
|
||||
fin = (ctx->ibufmark[0] >> 7) & 1;
|
||||
rsv = (ctx->ibufmark[0] >> 4) & 7;
|
||||
opcode = ctx->ibufmark[0] & 0xfu;
|
||||
ctx->iom.opcode = opcode;
|
||||
ctx->iom.fin = fin;
|
||||
ctx->iom.rsv = rsv;
|
||||
++ctx->ibufmark;
|
||||
ctx->imask = (ctx->ibufmark[0] >> 7) & 1;
|
||||
payloadlen = ctx->ibufmark[0] & 0x7fu;
|
||||
++ctx->ibufmark;
|
||||
if (wslay_is_ctrl_frame(opcode) && (payloadlen > 125 || !fin)) {
|
||||
return WSLAY_ERR_PROTO;
|
||||
}
|
||||
if (payloadlen == 126) {
|
||||
ctx->istate = RECV_EXT_PAYLOADLEN;
|
||||
ctx->ireqread = 2;
|
||||
} else if (payloadlen == 127) {
|
||||
ctx->istate = RECV_EXT_PAYLOADLEN;
|
||||
ctx->ireqread = 8;
|
||||
} else {
|
||||
ctx->ipayloadlen = payloadlen;
|
||||
ctx->ipayloadoff = 0;
|
||||
if (ctx->imask) {
|
||||
ctx->istate = RECV_MASKKEY;
|
||||
ctx->ireqread = 4;
|
||||
} else {
|
||||
ctx->istate = RECV_PAYLOAD;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ctx->istate == RECV_EXT_PAYLOADLEN) {
|
||||
if (WSLAY_AVAIL_IBUF(ctx) < ctx->ireqread) {
|
||||
if ((r = wslay_recv(ctx)) <= 0) {
|
||||
return r;
|
||||
}
|
||||
if (WSLAY_AVAIL_IBUF(ctx) < ctx->ireqread) {
|
||||
return WSLAY_ERR_WANT_READ;
|
||||
}
|
||||
}
|
||||
ctx->ipayloadlen = 0;
|
||||
ctx->ipayloadoff = 0;
|
||||
memcpy((uint8_t *)&ctx->ipayloadlen + (8 - ctx->ireqread), ctx->ibufmark,
|
||||
ctx->ireqread);
|
||||
ctx->ipayloadlen = ntoh64(ctx->ipayloadlen);
|
||||
ctx->ibufmark += ctx->ireqread;
|
||||
if (ctx->ireqread == 8) {
|
||||
if (ctx->ipayloadlen < (1 << 16) || ctx->ipayloadlen & (1ull << 63)) {
|
||||
return WSLAY_ERR_PROTO;
|
||||
}
|
||||
} else if (ctx->ipayloadlen < 126) {
|
||||
return WSLAY_ERR_PROTO;
|
||||
}
|
||||
if (ctx->imask) {
|
||||
ctx->istate = RECV_MASKKEY;
|
||||
ctx->ireqread = 4;
|
||||
} else {
|
||||
ctx->istate = RECV_PAYLOAD;
|
||||
}
|
||||
}
|
||||
if (ctx->istate == RECV_MASKKEY) {
|
||||
if (WSLAY_AVAIL_IBUF(ctx) < ctx->ireqread) {
|
||||
if ((r = wslay_recv(ctx)) <= 0) {
|
||||
return r;
|
||||
}
|
||||
if (WSLAY_AVAIL_IBUF(ctx) < ctx->ireqread) {
|
||||
return WSLAY_ERR_WANT_READ;
|
||||
}
|
||||
}
|
||||
memcpy(ctx->imaskkey, ctx->ibufmark, 4);
|
||||
ctx->ibufmark += 4;
|
||||
ctx->istate = RECV_PAYLOAD;
|
||||
}
|
||||
if (ctx->istate == RECV_PAYLOAD) {
|
||||
uint8_t *readlimit, *readmark;
|
||||
uint64_t rempayloadlen = ctx->ipayloadlen - ctx->ipayloadoff;
|
||||
if (WSLAY_AVAIL_IBUF(ctx) == 0 && rempayloadlen > 0) {
|
||||
if ((r = wslay_recv(ctx)) <= 0) {
|
||||
return r;
|
||||
}
|
||||
}
|
||||
readmark = ctx->ibufmark;
|
||||
readlimit = WSLAY_AVAIL_IBUF(ctx) < rempayloadlen
|
||||
? ctx->ibuflimit
|
||||
: ctx->ibufmark + rempayloadlen;
|
||||
if (ctx->imask) {
|
||||
for (; ctx->ibufmark != readlimit; ++ctx->ibufmark, ++ctx->ipayloadoff) {
|
||||
ctx->ibufmark[0] ^= ctx->imaskkey[ctx->ipayloadoff % 4];
|
||||
}
|
||||
} else {
|
||||
ctx->ibufmark = readlimit;
|
||||
ctx->ipayloadoff += (uint64_t)(readlimit - readmark);
|
||||
}
|
||||
iocb->fin = ctx->iom.fin;
|
||||
iocb->rsv = ctx->iom.rsv;
|
||||
iocb->opcode = ctx->iom.opcode;
|
||||
iocb->payload_length = ctx->ipayloadlen;
|
||||
iocb->mask = ctx->imask;
|
||||
iocb->data = readmark;
|
||||
iocb->data_length = (size_t)(ctx->ibufmark - readmark);
|
||||
if (ctx->ipayloadlen == ctx->ipayloadoff) {
|
||||
ctx->istate = RECV_HEADER1;
|
||||
ctx->ireqread = 2;
|
||||
}
|
||||
return (ssize_t)iocb->data_length;
|
||||
}
|
||||
return WSLAY_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* Wslay - The WebSocket Library
|
||||
*
|
||||
* Copyright (c) 2011, 2012 Tatsuhiro Tsujikawa
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
#ifndef WSLAY_FRAME_H
|
||||
#define WSLAY_FRAME_H
|
||||
|
||||
#ifdef HAVE_CONFIG_H
|
||||
# include <config.h>
|
||||
#endif /* HAVE_CONFIG_H */
|
||||
|
||||
#include <wslay/wslay.h>
|
||||
|
||||
enum wslay_frame_state {
|
||||
PREP_HEADER,
|
||||
PREP_HEADER_NOBUF,
|
||||
SEND_HEADER,
|
||||
SEND_PAYLOAD,
|
||||
RECV_HEADER1,
|
||||
RECV_PAYLOADLEN,
|
||||
RECV_EXT_PAYLOADLEN,
|
||||
RECV_MASKKEY,
|
||||
RECV_PAYLOAD
|
||||
};
|
||||
|
||||
struct wslay_frame_opcode_memo {
|
||||
uint8_t fin;
|
||||
uint8_t opcode;
|
||||
uint8_t rsv;
|
||||
};
|
||||
|
||||
struct wslay_frame_context {
|
||||
uint8_t ibuf[4096];
|
||||
uint8_t *ibufmark;
|
||||
uint8_t *ibuflimit;
|
||||
struct wslay_frame_opcode_memo iom;
|
||||
uint64_t ipayloadlen;
|
||||
uint64_t ipayloadoff;
|
||||
uint8_t imask;
|
||||
uint8_t imaskkey[4];
|
||||
enum wslay_frame_state istate;
|
||||
size_t ireqread;
|
||||
|
||||
uint8_t oheader[14];
|
||||
uint8_t *oheadermark;
|
||||
uint8_t *oheaderlimit;
|
||||
uint64_t opayloadlen;
|
||||
uint64_t opayloadoff;
|
||||
uint8_t omask;
|
||||
uint8_t omaskkey[4];
|
||||
enum wslay_frame_state ostate;
|
||||
|
||||
struct wslay_frame_callbacks callbacks;
|
||||
void *user_data;
|
||||
};
|
||||
|
||||
#endif /* WSLAY_FRAME_H */
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Wslay - The WebSocket Library
|
||||
*
|
||||
* Copyright (c) 2020 Tatsuhiro Tsujikawa
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
#ifndef WSLAY_MACRO_H
|
||||
#define WSLAY_MACRO_H
|
||||
|
||||
#ifdef HAVE_CONFIG_H
|
||||
# include "config.h"
|
||||
#endif /* HAVE_CONFIG_H */
|
||||
|
||||
#include <wslay/wslay.h>
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
#define wslay_struct_of(ptr, type, member) \
|
||||
((type *)(void *)((char *)(ptr)-offsetof(type, member)))
|
||||
|
||||
#endif /* WSLAY_MACRO_H */
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Wslay - The WebSocket Library
|
||||
*
|
||||
* Copyright (c) 2011, 2012 Tatsuhiro Tsujikawa
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
#include "wslay_net.h"
|
||||
|
||||
#ifndef WORDS_BIGENDIAN
|
||||
|
||||
uint64_t wslay_byteswap64(uint64_t x) {
|
||||
uint64_t u = ntohl(x & 0xffffffffllu);
|
||||
uint64_t l = ntohl((uint32_t)(x >> 32));
|
||||
return (u << 32) | l;
|
||||
}
|
||||
|
||||
#endif /* !WORDS_BIGENDIAN */
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
* Wslay - The WebSocket Library
|
||||
*
|
||||
* Copyright (c) 2011, 2012 Tatsuhiro Tsujikawa
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
#ifndef WSLAY_NET_H
|
||||
#define WSLAY_NET_H
|
||||
|
||||
#ifdef HAVE_CONFIG_H
|
||||
# include <config.h>
|
||||
#endif /* HAVE_CONFIG_H */
|
||||
|
||||
#include <wslay/wslay.h>
|
||||
|
||||
#ifdef HAVE_ARPA_INET_H
|
||||
# include <arpa/inet.h>
|
||||
#endif /* HAVE_ARPA_INET_H */
|
||||
#ifdef HAVE_NETINET_IN_H
|
||||
# include <netinet/in.h>
|
||||
#endif /* HAVE_NETINET_IN_H */
|
||||
/* For Mingw build */
|
||||
#ifdef HAVE_WINSOCK2_H
|
||||
# include <winsock2.h>
|
||||
#endif /* HAVE_WINSOCK2_H */
|
||||
|
||||
#ifdef WORDS_BIGENDIAN
|
||||
# define ntoh64(x) (x)
|
||||
# define hton64(x) (x)
|
||||
#else /* !WORDS_BIGENDIAN */
|
||||
uint64_t wslay_byteswap64(uint64_t x);
|
||||
# define ntoh64(x) wslay_byteswap64(x)
|
||||
# define hton64(x) wslay_byteswap64(x)
|
||||
#endif /* !WORDS_BIGENDIAN */
|
||||
|
||||
#endif /* WSLAY_NET_H */
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* Wslay - The WebSocket Library
|
||||
*
|
||||
* Copyright (c) 2011, 2012 Tatsuhiro Tsujikawa
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
#include "wslay_queue.h"
|
||||
|
||||
#include <string.h>
|
||||
#include <assert.h>
|
||||
|
||||
#include "wslay_macro.h"
|
||||
|
||||
void wslay_queue_init(struct wslay_queue *queue) {
|
||||
queue->top = NULL;
|
||||
queue->tail = &queue->top;
|
||||
}
|
||||
|
||||
void wslay_queue_deinit(struct wslay_queue *queue) { (void)queue; }
|
||||
|
||||
void wslay_queue_push(struct wslay_queue *queue,
|
||||
struct wslay_queue_entry *ent) {
|
||||
ent->next = NULL;
|
||||
*queue->tail = ent;
|
||||
queue->tail = &ent->next;
|
||||
}
|
||||
|
||||
void wslay_queue_push_front(struct wslay_queue *queue,
|
||||
struct wslay_queue_entry *ent) {
|
||||
ent->next = queue->top;
|
||||
queue->top = ent;
|
||||
|
||||
if (ent->next == NULL) {
|
||||
queue->tail = &ent->next;
|
||||
}
|
||||
}
|
||||
|
||||
void wslay_queue_pop(struct wslay_queue *queue) {
|
||||
assert(queue->top);
|
||||
queue->top = queue->top->next;
|
||||
if (queue->top == NULL) {
|
||||
queue->tail = &queue->top;
|
||||
}
|
||||
}
|
||||
|
||||
struct wslay_queue_entry *wslay_queue_top(struct wslay_queue *queue) {
|
||||
assert(queue->top);
|
||||
return queue->top;
|
||||
}
|
||||
|
||||
struct wslay_queue_entry *wslay_queue_tail(struct wslay_queue *queue) {
|
||||
assert(queue->top);
|
||||
return wslay_struct_of(queue->tail, struct wslay_queue_entry, next);
|
||||
}
|
||||
|
||||
int wslay_queue_empty(struct wslay_queue *queue) {
|
||||
assert(queue->top || queue->tail == &queue->top);
|
||||
return queue->top == NULL;
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* Wslay - The WebSocket Library
|
||||
*
|
||||
* Copyright (c) 2011, 2012 Tatsuhiro Tsujikawa
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
#ifndef WSLAY_QUEUE_H
|
||||
#define WSLAY_QUEUE_H
|
||||
|
||||
#ifdef HAVE_CONFIG_H
|
||||
# include "config.h"
|
||||
#endif /* HAVE_CONFIG_H */
|
||||
|
||||
#include <wslay/wslay.h>
|
||||
|
||||
struct wslay_queue_entry {
|
||||
struct wslay_queue_entry *next;
|
||||
};
|
||||
|
||||
struct wslay_queue {
|
||||
struct wslay_queue_entry *top;
|
||||
struct wslay_queue_entry **tail;
|
||||
};
|
||||
|
||||
void wslay_queue_init(struct wslay_queue *queue);
|
||||
void wslay_queue_deinit(struct wslay_queue *queue);
|
||||
void wslay_queue_push(struct wslay_queue *queue, struct wslay_queue_entry *ent);
|
||||
void wslay_queue_push_front(struct wslay_queue *queue,
|
||||
struct wslay_queue_entry *ent);
|
||||
void wslay_queue_pop(struct wslay_queue *queue);
|
||||
struct wslay_queue_entry *wslay_queue_top(struct wslay_queue *queue);
|
||||
struct wslay_queue_entry *wslay_queue_tail(struct wslay_queue *queue);
|
||||
int wslay_queue_empty(struct wslay_queue *queue);
|
||||
|
||||
#endif /* WSLAY_QUEUE_H */
|
||||
+28
-14
@@ -1,25 +1,30 @@
|
||||
#include "bc.h"
|
||||
|
||||
#include <format>
|
||||
#include "hooks/setupapihook.h"
|
||||
#include "util/fileutils.h"
|
||||
#include "util/libutils.h"
|
||||
#include "acio2emu/handle.h"
|
||||
#include "acioemu/handle.h"
|
||||
#include "hooks/graphics/graphics.h"
|
||||
#include "util/detour.h"
|
||||
#include "util/unity_player.h"
|
||||
#include "node.h"
|
||||
#include "bi2x_hook.h"
|
||||
|
||||
namespace games::bc {
|
||||
|
||||
static decltype(ShowCursor) *ShowCursor_orig = nullptr;
|
||||
|
||||
static int WINAPI ShowCursor_hook(BOOL bShow) {
|
||||
// log_misc("bsac", "ShowCursor {}", bShow);
|
||||
return 1;
|
||||
}
|
||||
std::string BC_INJECT_ARGS = "";
|
||||
|
||||
void BCGame::attach() {
|
||||
Game::attach();
|
||||
|
||||
// create required directories
|
||||
fileutils::dir_create_recursive("dev/raw/log");
|
||||
|
||||
// preload libraries
|
||||
libutils::load_library("libaio.dll");
|
||||
libutils::load_library("libaio-iob2_video.dll");
|
||||
|
||||
setupapihook_init(libutils::load_library("libaio.dll"));
|
||||
|
||||
SETUPAPI_SETTINGS settings {};
|
||||
@@ -32,15 +37,24 @@ namespace games::bc {
|
||||
auto iob = new acio2emu::IOBHandle(L"COM3");
|
||||
iob->register_node(std::make_unique<TBSNode>());
|
||||
|
||||
if (GRAPHICS_SHOW_CURSOR) {
|
||||
detour::trampoline_try(
|
||||
"user32.dll", "ShowCursor",
|
||||
(void*)ShowCursor_hook, (void**)&ShowCursor_orig);
|
||||
}
|
||||
#if SPICE64
|
||||
// insert BI2X hooks
|
||||
bi2x_hook_init();
|
||||
#endif
|
||||
|
||||
devicehook_init();
|
||||
devicehook_init_trampoline();
|
||||
devicehook_add(iob);
|
||||
devicehook_add(new acioemu::ACIOHandle(L"COM1"));
|
||||
|
||||
if (GRAPHICS_SHOW_CURSOR) {
|
||||
unity_utils::force_show_cursor(true);
|
||||
}
|
||||
|
||||
unity_utils::set_args(
|
||||
std::format("{} {}{}",
|
||||
GetCommandLineA(),
|
||||
BC_INJECT_ARGS,
|
||||
unity_utils::get_unity_player_args()));
|
||||
}
|
||||
|
||||
void BCGame::detach() {
|
||||
@@ -48,4 +62,4 @@ namespace games::bc {
|
||||
|
||||
devicehook_dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include "games/game.h"
|
||||
|
||||
namespace games::bc {
|
||||
extern std::string BC_INJECT_ARGS;
|
||||
|
||||
class BCGame : public games::Game {
|
||||
public:
|
||||
BCGame() : Game("Busou Shinki: Armored Princess Battle Conductor") {}
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
#include "bi2x_hook.h"
|
||||
|
||||
#if SPICE64
|
||||
|
||||
#include <cstdint>
|
||||
#include <iterator>
|
||||
|
||||
#include "util/detour.h"
|
||||
#include "util/logging.h"
|
||||
#include "rawinput/rawinput.h"
|
||||
#include "games/io.h"
|
||||
#include "io.h"
|
||||
#include "util/tapeled.h"
|
||||
|
||||
namespace games::bc {
|
||||
|
||||
struct AIO_IOB2_BI2X_TBS;
|
||||
|
||||
/*
|
||||
* typedefs
|
||||
*/
|
||||
|
||||
typedef void (__fastcall *aioIob2Bi2xTBS_GetDeviceStatus_t)(
|
||||
AIO_IOB2_BI2X_TBS *i_pNodeCtl, void *o_DevStatus);
|
||||
typedef void (__fastcall *aioIob2Bi2xTBS_SetButton0Lamp_t)(
|
||||
AIO_IOB2_BI2X_TBS *i_pNodeCtl, bool i_bOn);
|
||||
typedef void (__fastcall *aioIob2Bi2xTBS_SetIrLed_t)(
|
||||
AIO_IOB2_BI2X_TBS *i_pNodeCtl, bool i_bOn);
|
||||
typedef void (__fastcall *aioIob2Bi2xTBS_SetIccrLed_t)(
|
||||
AIO_IOB2_BI2X_TBS *i_pNodeCtl, uint32_t i_RGB);
|
||||
typedef void (__fastcall *aioIob2Bi2xTBS_SetStickLed_t)(
|
||||
AIO_IOB2_BI2X_TBS *i_pNodeCtl, uint32_t i_RGB);
|
||||
typedef void (__fastcall *aioIob2Bi2xTBS_SetTapeLedData_t)(
|
||||
AIO_IOB2_BI2X_TBS *i_pNodeCtl, uint32_t i_TapeLed, uint8_t *i_pData);
|
||||
|
||||
static aioIob2Bi2xTBS_GetDeviceStatus_t aioIob2Bi2xTBS_GetDeviceStatus_orig = nullptr;
|
||||
static aioIob2Bi2xTBS_SetButton0Lamp_t aioIob2Bi2xTBS_SetButton0Lamp_orig = nullptr;
|
||||
static aioIob2Bi2xTBS_SetIrLed_t aioIob2Bi2xTBS_SetIrLed_orig = nullptr;
|
||||
static aioIob2Bi2xTBS_SetIccrLed_t aioIob2Bi2xTBS_SetIccrLed_orig = nullptr;
|
||||
static aioIob2Bi2xTBS_SetStickLed_t aioIob2Bi2xTBS_SetStickLed_orig = nullptr;
|
||||
static aioIob2Bi2xTBS_SetTapeLedData_t aioIob2Bi2xTBS_SetTapeLedData_orig = nullptr;
|
||||
|
||||
/*
|
||||
* hooks
|
||||
*/
|
||||
|
||||
static void write_light_rgb(
|
||||
Lights::bc_lights_t r, Lights::bc_lights_t g, Lights::bc_lights_t b, uint32_t color) {
|
||||
|
||||
auto &lights = get_lights();
|
||||
GameAPI::Lights::writeLight(RI_MGR, lights.at(r), ((color >> 16) & 0xFF) / 255.f);
|
||||
GameAPI::Lights::writeLight(RI_MGR, lights.at(g), ((color >> 8) & 0xFF) / 255.f);
|
||||
GameAPI::Lights::writeLight(RI_MGR, lights.at(b), (color & 0xFF) / 255.f);
|
||||
}
|
||||
|
||||
static void __fastcall aioIob2Bi2xTBS_GetDeviceStatus(
|
||||
AIO_IOB2_BI2X_TBS *i_pNodeCtl, void *o_DevStatus) {
|
||||
|
||||
RI_MGR->devices_flush_output();
|
||||
|
||||
if (aioIob2Bi2xTBS_GetDeviceStatus_orig) {
|
||||
aioIob2Bi2xTBS_GetDeviceStatus_orig(i_pNodeCtl, o_DevStatus);
|
||||
}
|
||||
}
|
||||
|
||||
static void __fastcall aioIob2Bi2xTBS_SetButton0Lamp(
|
||||
AIO_IOB2_BI2X_TBS *i_pNodeCtl, bool i_bOn) {
|
||||
|
||||
auto &lights = get_lights();
|
||||
GameAPI::Lights::writeLight(RI_MGR, lights.at(Lights::Button), (i_bOn ? 1.f : 0.f));
|
||||
|
||||
if (aioIob2Bi2xTBS_SetButton0Lamp_orig) {
|
||||
aioIob2Bi2xTBS_SetButton0Lamp_orig(i_pNodeCtl, i_bOn);
|
||||
}
|
||||
}
|
||||
|
||||
static void __fastcall aioIob2Bi2xTBS_SetIrLed(
|
||||
AIO_IOB2_BI2X_TBS *i_pNodeCtl, bool i_bOn) {
|
||||
|
||||
auto &lights = get_lights();
|
||||
GameAPI::Lights::writeLight(RI_MGR, lights.at(Lights::IrLed), (i_bOn ? 1.f : 0.f));
|
||||
|
||||
if (aioIob2Bi2xTBS_SetIrLed_orig) {
|
||||
aioIob2Bi2xTBS_SetIrLed_orig(i_pNodeCtl, i_bOn);
|
||||
}
|
||||
}
|
||||
|
||||
static void __fastcall aioIob2Bi2xTBS_SetIccrLed(
|
||||
AIO_IOB2_BI2X_TBS *i_pNodeCtl, uint32_t i_RGB) {
|
||||
|
||||
write_light_rgb(Lights::CardReader_R, Lights::CardReader_G, Lights::CardReader_B, i_RGB);
|
||||
|
||||
if (aioIob2Bi2xTBS_SetIccrLed_orig) {
|
||||
aioIob2Bi2xTBS_SetIccrLed_orig(i_pNodeCtl, i_RGB);
|
||||
}
|
||||
}
|
||||
|
||||
static void __fastcall aioIob2Bi2xTBS_SetStickLed(
|
||||
AIO_IOB2_BI2X_TBS *i_pNodeCtl, uint32_t i_RGB) {
|
||||
|
||||
write_light_rgb(Lights::Joystick_R, Lights::Joystick_G, Lights::Joystick_B, i_RGB);
|
||||
|
||||
if (aioIob2Bi2xTBS_SetStickLed_orig) {
|
||||
aioIob2Bi2xTBS_SetStickLed_orig(i_pNodeCtl, i_RGB);
|
||||
}
|
||||
}
|
||||
|
||||
static void __fastcall aioIob2Bi2xTBS_SetTapeLedData(
|
||||
AIO_IOB2_BI2X_TBS *i_pNodeCtl, uint32_t i_TapeLed, uint8_t *i_pData) {
|
||||
|
||||
static struct TapeLedMapping {
|
||||
size_t data_size;
|
||||
int r, g, b;
|
||||
|
||||
TapeLedMapping(size_t data_size, int r, int g, int b)
|
||||
: data_size(data_size), r(r), g(g), b(b) {}
|
||||
} mapping[] = {
|
||||
{ 48, Lights::TitlePanel_R, Lights::TitlePanel_G, Lights::TitlePanel_B },
|
||||
{ 49, Lights::SidePanel_R, Lights::SidePanel_G, Lights::SidePanel_B },
|
||||
};
|
||||
|
||||
if (tapeledutils::is_enabled() && i_TapeLed < std::size(mapping)) {
|
||||
auto &map = mapping[i_TapeLed];
|
||||
const auto rgb = tapeledutils::pick_color_from_led_tape(i_pData, map.data_size);
|
||||
|
||||
auto &lights = get_lights();
|
||||
GameAPI::Lights::writeLight(RI_MGR, lights.at(map.r), rgb.r);
|
||||
GameAPI::Lights::writeLight(RI_MGR, lights.at(map.g), rgb.g);
|
||||
GameAPI::Lights::writeLight(RI_MGR, lights.at(map.b), rgb.b);
|
||||
}
|
||||
|
||||
if (aioIob2Bi2xTBS_SetTapeLedData_orig) {
|
||||
aioIob2Bi2xTBS_SetTapeLedData_orig(i_pNodeCtl, i_TapeLed, i_pData);
|
||||
}
|
||||
}
|
||||
|
||||
void bi2x_hook_init() {
|
||||
static bool initialized = false;
|
||||
if (initialized) {
|
||||
return;
|
||||
} else {
|
||||
initialized = true;
|
||||
}
|
||||
|
||||
log_info("bc_bi2x_hook", "init");
|
||||
|
||||
const auto libaioIob2VideoDll = "libaio-iob2_video.dll";
|
||||
detour::trampoline_try(libaioIob2VideoDll, "aioIob2Bi2xTBS_GetDeviceStatus",
|
||||
aioIob2Bi2xTBS_GetDeviceStatus, &aioIob2Bi2xTBS_GetDeviceStatus_orig);
|
||||
detour::trampoline_try(libaioIob2VideoDll, "aioIob2Bi2xTBS_SetButton0Lamp",
|
||||
aioIob2Bi2xTBS_SetButton0Lamp, &aioIob2Bi2xTBS_SetButton0Lamp_orig);
|
||||
detour::trampoline_try(libaioIob2VideoDll, "aioIob2Bi2xTBS_SetIrLed",
|
||||
aioIob2Bi2xTBS_SetIrLed, &aioIob2Bi2xTBS_SetIrLed_orig);
|
||||
detour::trampoline_try(libaioIob2VideoDll, "aioIob2Bi2xTBS_SetIccrLed",
|
||||
aioIob2Bi2xTBS_SetIccrLed, &aioIob2Bi2xTBS_SetIccrLed_orig);
|
||||
detour::trampoline_try(libaioIob2VideoDll, "aioIob2Bi2xTBS_SetStickLed",
|
||||
aioIob2Bi2xTBS_SetStickLed, &aioIob2Bi2xTBS_SetStickLed_orig);
|
||||
detour::trampoline_try(libaioIob2VideoDll, "aioIob2Bi2xTBS_SetTapeLedData",
|
||||
aioIob2Bi2xTBS_SetTapeLedData, &aioIob2Bi2xTBS_SetTapeLedData_orig);
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
#if SPICE64
|
||||
|
||||
namespace games::bc {
|
||||
void bi2x_hook_init();
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -47,4 +47,32 @@ std::vector<Analog> &games::bc::get_analogs() {
|
||||
}
|
||||
|
||||
return analogs;
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<Light> &games::bc::get_lights() {
|
||||
static std::vector<Light> lights;
|
||||
|
||||
if (lights.empty()) {
|
||||
lights = GameAPI::Lights::getLights("Busou Shinki: Armored Princess Battle Conductor");
|
||||
|
||||
GameAPI::Lights::sortLights(
|
||||
&lights,
|
||||
"Title Panel R",
|
||||
"Title Panel G",
|
||||
"Title Panel B",
|
||||
"Side Panel R",
|
||||
"Side Panel G",
|
||||
"Side Panel B",
|
||||
"Card Reader R",
|
||||
"Card Reader G",
|
||||
"Card Reader B",
|
||||
"Joystick R",
|
||||
"Joystick G",
|
||||
"Joystick B",
|
||||
"Button",
|
||||
"IR LED"
|
||||
);
|
||||
}
|
||||
|
||||
return lights;
|
||||
}
|
||||
@@ -30,7 +30,27 @@ namespace games::bc {
|
||||
};
|
||||
}
|
||||
|
||||
namespace Lights {
|
||||
typedef enum {
|
||||
TitlePanel_R,
|
||||
TitlePanel_G,
|
||||
TitlePanel_B,
|
||||
SidePanel_R,
|
||||
SidePanel_G,
|
||||
SidePanel_B,
|
||||
CardReader_R,
|
||||
CardReader_G,
|
||||
CardReader_B,
|
||||
Joystick_R,
|
||||
Joystick_G,
|
||||
Joystick_B,
|
||||
Button,
|
||||
IrLed,
|
||||
} bc_lights_t;
|
||||
}
|
||||
|
||||
std::vector<Button> &get_buttons();
|
||||
std::string get_buttons_help();
|
||||
std::vector<Analog> &get_analogs();
|
||||
std::vector<Light> &get_lights();
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
#include "bi2x_hook.h"
|
||||
|
||||
#if SPICE64
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
|
||||
#include "io.h"
|
||||
#include "misc/eamuse.h"
|
||||
#include "rawinput/rawinput.h"
|
||||
#include "util/detour.h"
|
||||
#include "util/logging.h"
|
||||
#include "util/tapeled.h"
|
||||
|
||||
namespace games::cardconnect {
|
||||
|
||||
struct AIO_SCI_COMM {
|
||||
uint8_t data[0xf8];
|
||||
};
|
||||
|
||||
struct AIO_NMGR_IOB2 {
|
||||
uint8_t data[0x9f8];
|
||||
};
|
||||
|
||||
struct AIO_IOB2_BI2X_TCS {
|
||||
uint8_t data[0x350];
|
||||
};
|
||||
|
||||
struct AIO_IOB2_BI2X_WRFIRM {
|
||||
uint8_t data[0x20f48];
|
||||
};
|
||||
|
||||
#pragma pack(push, 1)
|
||||
struct AIO_IOB2_BI2X_TCS__INPUT {
|
||||
uint8_t DevIoCounter;
|
||||
uint8_t bTest;
|
||||
uint8_t bService;
|
||||
uint8_t bCoinSw;
|
||||
uint8_t bCoinJam;
|
||||
uint8_t CoinCount;
|
||||
};
|
||||
|
||||
struct AIO_IOB2_BI2X_TCS__DEVSTATUS {
|
||||
uint8_t InputCounter;
|
||||
uint8_t OutputCounter;
|
||||
uint8_t TapeLedCounter;
|
||||
AIO_IOB2_BI2X_TCS__INPUT Input;
|
||||
uint8_t reserved[17];
|
||||
};
|
||||
#pragma pack(pop)
|
||||
|
||||
// The supplied native DLL copies 26 bytes, even though the managed wrapper requests 27.
|
||||
static_assert(sizeof(AIO_IOB2_BI2X_TCS__DEVSTATUS) == 26);
|
||||
static_assert(offsetof(AIO_IOB2_BI2X_TCS__DEVSTATUS, Input) == 3);
|
||||
static_assert(offsetof(AIO_IOB2_BI2X_TCS__INPUT, bTest) == 1);
|
||||
static_assert(offsetof(AIO_IOB2_BI2X_TCS__INPUT, bService) == 2);
|
||||
static_assert(offsetof(AIO_IOB2_BI2X_TCS__INPUT, bCoinSw) == 3);
|
||||
static_assert(offsetof(AIO_IOB2_BI2X_TCS__INPUT, CoinCount) == 5);
|
||||
|
||||
static AIO_IOB2_BI2X_TCS *(__fastcall *aioIob2Bi2xTCS_Create_orig)(
|
||||
AIO_NMGR_IOB2 *, uint32_t) = nullptr;
|
||||
static uint32_t (__fastcall *aioIob2Bi2xTCS_GetDeviceStatus_orig)(
|
||||
AIO_IOB2_BI2X_TCS *, AIO_IOB2_BI2X_TCS__DEVSTATUS *, uint32_t) = nullptr;
|
||||
static void (__fastcall *aioIob2Bi2xTCS_IoReset_orig)(
|
||||
AIO_IOB2_BI2X_TCS *, uint32_t) = nullptr;
|
||||
static void (__fastcall *aioIob2Bi2xTCS_SetWatchDogTimer_orig)(
|
||||
AIO_IOB2_BI2X_TCS *, uint8_t) = nullptr;
|
||||
static void (__fastcall *aioIob2Bi2xTCS_ControlCoinBlocker_orig)(
|
||||
AIO_IOB2_BI2X_TCS *, uint32_t, bool) = nullptr;
|
||||
static void (__fastcall *aioIob2Bi2xTCS_AddCounter_orig)(
|
||||
AIO_IOB2_BI2X_TCS *, uint32_t, uint32_t) = nullptr;
|
||||
static void (__fastcall *aioIob2Bi2xTCS_SetPhotoLight_orig)(
|
||||
AIO_IOB2_BI2X_TCS *, bool) = nullptr;
|
||||
static void (__fastcall *aioIob2Bi2xTCS_SetIccrLed_orig)(
|
||||
AIO_IOB2_BI2X_TCS *, uint32_t) = nullptr;
|
||||
static void (__fastcall *aioIob2Bi2xTCS_SetTapeLedData_orig)(
|
||||
AIO_IOB2_BI2X_TCS *, uint32_t, uint8_t *) = nullptr;
|
||||
|
||||
static AIO_SCI_COMM *(__fastcall *aioIob2Bi2x_OpenSciUsbCdc_orig)(uint32_t) = nullptr;
|
||||
static AIO_IOB2_BI2X_WRFIRM *(__fastcall *aioIob2Bi2x_CreateWriteFirmContext_orig)(
|
||||
uint32_t, uint32_t) = nullptr;
|
||||
static void (__fastcall *aioIob2Bi2x_DestroyWriteFirmContext_orig)(
|
||||
AIO_IOB2_BI2X_WRFIRM *) = nullptr;
|
||||
static int32_t (__fastcall *aioIob2Bi2x_WriteFirmGetState_orig)(
|
||||
AIO_IOB2_BI2X_WRFIRM *) = nullptr;
|
||||
static AIO_NMGR_IOB2 *(__fastcall *aioNMgrIob2_Create_orig)(
|
||||
AIO_SCI_COMM *, uint32_t) = nullptr;
|
||||
static void (__fastcall *aioNMgrIob_BeginManage_orig)(AIO_NMGR_IOB2 *) = nullptr;
|
||||
|
||||
static void (__fastcall *aioNodeMgr_Destroy_orig)(AIO_NMGR_IOB2 *) = nullptr;
|
||||
static int32_t (__fastcall *aioNodeMgr_GetState_orig)(AIO_NMGR_IOB2 *) = nullptr;
|
||||
static bool (__fastcall *aioNodeMgr_IsReady_orig)(AIO_NMGR_IOB2 *, int32_t) = nullptr;
|
||||
static void (__fastcall *aioNodeCtl_Destroy_orig)(AIO_IOB2_BI2X_TCS *) = nullptr;
|
||||
static int32_t (__fastcall *aioNodeCtl_GetState_orig)(AIO_IOB2_BI2X_TCS *) = nullptr;
|
||||
static bool (__fastcall *aioNodeCtl_IsReady_orig)(AIO_IOB2_BI2X_TCS *, int32_t) = nullptr;
|
||||
static void (__fastcall *aioSci_Destroy_orig)(AIO_SCI_COMM *) = nullptr;
|
||||
|
||||
static std::unique_ptr<AIO_SCI_COMM> aio_sci;
|
||||
static std::unique_ptr<AIO_NMGR_IOB2> aio_manager;
|
||||
static std::unique_ptr<AIO_IOB2_BI2X_TCS> aio_board;
|
||||
static std::unique_ptr<AIO_IOB2_BI2X_WRFIRM> aio_firmware;
|
||||
static uint8_t input_counter = 0;
|
||||
static bool coin_pressed = false;
|
||||
|
||||
static void write_light(size_t index, float value) {
|
||||
auto &lights = get_lights();
|
||||
GameAPI::Lights::writeLight(RI_MGR, lights[index], value);
|
||||
}
|
||||
|
||||
static AIO_IOB2_BI2X_TCS *__fastcall aioIob2Bi2xTCS_Create(
|
||||
AIO_NMGR_IOB2 *manager, uint32_t device_id) {
|
||||
if (!aio_manager || manager != aio_manager.get()) {
|
||||
return aioIob2Bi2xTCS_Create_orig(manager, device_id);
|
||||
}
|
||||
if (!aio_board) {
|
||||
aio_board = std::make_unique<AIO_IOB2_BI2X_TCS>();
|
||||
input_counter = 0;
|
||||
coin_pressed = false;
|
||||
log_info("cardconnect::bi2x", "created emulated BI2X-TCS board");
|
||||
}
|
||||
return aio_board.get();
|
||||
}
|
||||
|
||||
static uint32_t __fastcall aioIob2Bi2xTCS_GetDeviceStatus(
|
||||
AIO_IOB2_BI2X_TCS *board, AIO_IOB2_BI2X_TCS__DEVSTATUS *status,
|
||||
uint32_t status_size) {
|
||||
if (!aio_board || board != aio_board.get()) {
|
||||
return aioIob2Bi2xTCS_GetDeviceStatus_orig(board, status, status_size);
|
||||
}
|
||||
if (!status && status_size > 0) {
|
||||
log_warning("cardconnect::bi2x", "GetDeviceStatus called with a null output buffer");
|
||||
return 0;
|
||||
}
|
||||
|
||||
auto &buttons = get_buttons();
|
||||
const bool coin = GameAPI::Buttons::getState(RI_MGR, buttons[Buttons::CoinMech]);
|
||||
if (coin && !coin_pressed) {
|
||||
eamuse_coin_insert();
|
||||
}
|
||||
coin_pressed = coin;
|
||||
|
||||
AIO_IOB2_BI2X_TCS__DEVSTATUS current {};
|
||||
current.InputCounter = ++input_counter;
|
||||
current.Input.DevIoCounter = input_counter;
|
||||
current.Input.bTest = GameAPI::Buttons::getState(RI_MGR, buttons[Buttons::Test]) ? 1 : 0;
|
||||
current.Input.bService = GameAPI::Buttons::getState(RI_MGR, buttons[Buttons::Service]) ? 1 : 0;
|
||||
current.Input.bCoinSw = coin ? 1 : 0;
|
||||
current.Input.CoinCount = static_cast<uint8_t>(eamuse_coin_get_stock());
|
||||
|
||||
RI_MGR->devices_flush_output();
|
||||
|
||||
const auto copy_size = std::min<uint32_t>(status_size, sizeof(current));
|
||||
if (copy_size > 0) {
|
||||
std::memcpy(status, ¤t, copy_size);
|
||||
}
|
||||
return copy_size;
|
||||
}
|
||||
|
||||
static void __fastcall aioIob2Bi2xTCS_IoReset(AIO_IOB2_BI2X_TCS *board, uint32_t bits) {
|
||||
if (!aio_board || board != aio_board.get()) {
|
||||
return aioIob2Bi2xTCS_IoReset_orig(board, bits);
|
||||
}
|
||||
}
|
||||
|
||||
static void __fastcall aioIob2Bi2xTCS_SetWatchDogTimer(
|
||||
AIO_IOB2_BI2X_TCS *board, uint8_t count) {
|
||||
if (!aio_board || board != aio_board.get()) {
|
||||
return aioIob2Bi2xTCS_SetWatchDogTimer_orig(board, count);
|
||||
}
|
||||
}
|
||||
|
||||
static void __fastcall aioIob2Bi2xTCS_ControlCoinBlocker(
|
||||
AIO_IOB2_BI2X_TCS *board, uint32_t slot, bool open) {
|
||||
if (!aio_board || board != aio_board.get()) {
|
||||
return aioIob2Bi2xTCS_ControlCoinBlocker_orig(board, slot, open);
|
||||
}
|
||||
if (slot != 0) {
|
||||
log_warning("cardconnect::bi2x", "unknown coin blocker slot {}", slot);
|
||||
return;
|
||||
}
|
||||
eamuse_coin_set_block(!open);
|
||||
}
|
||||
|
||||
static void __fastcall aioIob2Bi2xTCS_AddCounter(
|
||||
AIO_IOB2_BI2X_TCS *board, uint32_t counter, uint32_t count) {
|
||||
if (!aio_board || board != aio_board.get()) {
|
||||
return aioIob2Bi2xTCS_AddCounter_orig(board, counter, count);
|
||||
}
|
||||
// This drives the physical bookkeeping meter, not the input coin counter.
|
||||
}
|
||||
|
||||
static void __fastcall aioIob2Bi2xTCS_SetPhotoLight(AIO_IOB2_BI2X_TCS *board, bool on) {
|
||||
if (!aio_board || board != aio_board.get()) {
|
||||
return aioIob2Bi2xTCS_SetPhotoLight_orig(board, on);
|
||||
}
|
||||
write_light(Lights::PhotoLight, on ? 1.f : 0.f);
|
||||
}
|
||||
|
||||
static void __fastcall aioIob2Bi2xTCS_SetIccrLed(AIO_IOB2_BI2X_TCS *board, uint32_t rgb) {
|
||||
if (!aio_board || board != aio_board.get()) {
|
||||
return aioIob2Bi2xTCS_SetIccrLed_orig(board, rgb);
|
||||
}
|
||||
write_light(Lights::CardReaderR, ((rgb >> 16) & 0xff) / 255.f);
|
||||
write_light(Lights::CardReaderG, ((rgb >> 8) & 0xff) / 255.f);
|
||||
write_light(Lights::CardReaderB, (rgb & 0xff) / 255.f);
|
||||
}
|
||||
|
||||
static void __fastcall aioIob2Bi2xTCS_SetTapeLedData(
|
||||
AIO_IOB2_BI2X_TCS *board, uint32_t tape, uint8_t *data) {
|
||||
if (!aio_board || board != aio_board.get()) {
|
||||
return aioIob2Bi2xTCS_SetTapeLedData_orig(board, tape, data);
|
||||
}
|
||||
if (!data || tape >= 2) {
|
||||
log_warning("cardconnect::bi2x", "invalid tape LED data for channel {}", tape);
|
||||
return;
|
||||
}
|
||||
if (tapeledutils::is_enabled()) {
|
||||
const auto color = tapeledutils::pick_color_from_led_tape(data, 15);
|
||||
const auto first = tape == 0 ? Lights::SideLeftR : Lights::SideRightR;
|
||||
write_light(first, color.r);
|
||||
write_light(first + 1, color.g);
|
||||
write_light(first + 2, color.b);
|
||||
}
|
||||
}
|
||||
|
||||
static AIO_SCI_COMM *__fastcall aioIob2Bi2x_OpenSciUsbCdc(uint32_t serial_number) {
|
||||
if (!aio_sci) {
|
||||
aio_sci = std::make_unique<AIO_SCI_COMM>();
|
||||
}
|
||||
return aio_sci.get();
|
||||
}
|
||||
|
||||
static AIO_IOB2_BI2X_WRFIRM *__fastcall aioIob2Bi2x_CreateWriteFirmContext(
|
||||
uint32_t serial_number, uint32_t iob_mask) {
|
||||
if (!aio_firmware) {
|
||||
aio_firmware = std::make_unique<AIO_IOB2_BI2X_WRFIRM>();
|
||||
}
|
||||
return aio_firmware.get();
|
||||
}
|
||||
|
||||
static void __fastcall aioIob2Bi2x_DestroyWriteFirmContext(AIO_IOB2_BI2X_WRFIRM *context) {
|
||||
if (!aio_firmware || context != aio_firmware.get()) {
|
||||
return aioIob2Bi2x_DestroyWriteFirmContext_orig(context);
|
||||
}
|
||||
aio_firmware.reset();
|
||||
}
|
||||
|
||||
static int32_t __fastcall aioIob2Bi2x_WriteFirmGetState(AIO_IOB2_BI2X_WRFIRM *context) {
|
||||
if (!aio_firmware || context != aio_firmware.get()) {
|
||||
return aioIob2Bi2x_WriteFirmGetState_orig(context);
|
||||
}
|
||||
return 8;
|
||||
}
|
||||
|
||||
static AIO_NMGR_IOB2 *__fastcall aioNMgrIob2_Create(AIO_SCI_COMM *sci, uint32_t mode) {
|
||||
if (!aio_sci || sci != aio_sci.get()) {
|
||||
return aioNMgrIob2_Create_orig(sci, mode);
|
||||
}
|
||||
if (!aio_manager) {
|
||||
aio_manager = std::make_unique<AIO_NMGR_IOB2>();
|
||||
}
|
||||
return aio_manager.get();
|
||||
}
|
||||
|
||||
static void __fastcall aioNMgrIob_BeginManage(AIO_NMGR_IOB2 *manager) {
|
||||
if (!aio_manager || manager != aio_manager.get()) {
|
||||
return aioNMgrIob_BeginManage_orig(manager);
|
||||
}
|
||||
}
|
||||
|
||||
static void __fastcall aioNodeMgr_Destroy(AIO_NMGR_IOB2 *manager) {
|
||||
if (!aio_manager || manager != aio_manager.get()) {
|
||||
return aioNodeMgr_Destroy_orig(manager);
|
||||
}
|
||||
aio_manager.reset();
|
||||
}
|
||||
|
||||
static int32_t __fastcall aioNodeMgr_GetState(AIO_NMGR_IOB2 *manager) {
|
||||
if (!aio_manager || manager != aio_manager.get()) {
|
||||
return aioNodeMgr_GetState_orig(manager);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static bool __fastcall aioNodeMgr_IsReady(AIO_NMGR_IOB2 *manager, int32_t state) {
|
||||
if (!aio_manager || manager != aio_manager.get()) {
|
||||
return aioNodeMgr_IsReady_orig(manager, state);
|
||||
}
|
||||
return state >= 1;
|
||||
}
|
||||
|
||||
static void __fastcall aioNodeCtl_Destroy(AIO_IOB2_BI2X_TCS *board) {
|
||||
if (!aio_board || board != aio_board.get()) {
|
||||
return aioNodeCtl_Destroy_orig(board);
|
||||
}
|
||||
aio_board.reset();
|
||||
}
|
||||
|
||||
static int32_t __fastcall aioNodeCtl_GetState(AIO_IOB2_BI2X_TCS *board) {
|
||||
if (!aio_board || board != aio_board.get()) {
|
||||
return aioNodeCtl_GetState_orig(board);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static bool __fastcall aioNodeCtl_IsReady(AIO_IOB2_BI2X_TCS *board, int32_t state) {
|
||||
if (!aio_board || board != aio_board.get()) {
|
||||
return aioNodeCtl_IsReady_orig(board, state);
|
||||
}
|
||||
return state >= 1;
|
||||
}
|
||||
|
||||
static void __fastcall aioSci_Destroy(AIO_SCI_COMM *sci) {
|
||||
if (!aio_sci || sci != aio_sci.get()) {
|
||||
return aioSci_Destroy_orig(sci);
|
||||
}
|
||||
aio_sci.reset();
|
||||
}
|
||||
|
||||
void bi2x_hook_init() {
|
||||
log_info("cardconnect::bi2x", "initializing native BI2X-TCS hooks");
|
||||
|
||||
const auto video = "libaio-iob2_video.dll";
|
||||
detour::trampoline(video, "aioIob2Bi2xTCS_Create",
|
||||
aioIob2Bi2xTCS_Create, &aioIob2Bi2xTCS_Create_orig);
|
||||
detour::trampoline(video, "aioIob2Bi2xTCS_GetDeviceStatus",
|
||||
aioIob2Bi2xTCS_GetDeviceStatus, &aioIob2Bi2xTCS_GetDeviceStatus_orig);
|
||||
detour::trampoline(video, "aioIob2Bi2xTCS_IoReset",
|
||||
aioIob2Bi2xTCS_IoReset, &aioIob2Bi2xTCS_IoReset_orig);
|
||||
detour::trampoline(video, "aioIob2Bi2xTCS_SetWatchDogTimer",
|
||||
aioIob2Bi2xTCS_SetWatchDogTimer, &aioIob2Bi2xTCS_SetWatchDogTimer_orig);
|
||||
detour::trampoline(video, "aioIob2Bi2xTCS_ControlCoinBlocker",
|
||||
aioIob2Bi2xTCS_ControlCoinBlocker, &aioIob2Bi2xTCS_ControlCoinBlocker_orig);
|
||||
detour::trampoline(video, "aioIob2Bi2xTCS_AddCounter",
|
||||
aioIob2Bi2xTCS_AddCounter, &aioIob2Bi2xTCS_AddCounter_orig);
|
||||
detour::trampoline(video, "aioIob2Bi2xTCS_SetPhotoLight",
|
||||
aioIob2Bi2xTCS_SetPhotoLight, &aioIob2Bi2xTCS_SetPhotoLight_orig);
|
||||
detour::trampoline(video, "aioIob2Bi2xTCS_SetIccrLed",
|
||||
aioIob2Bi2xTCS_SetIccrLed, &aioIob2Bi2xTCS_SetIccrLed_orig);
|
||||
detour::trampoline(video, "aioIob2Bi2xTCS_SetTapeLedData",
|
||||
aioIob2Bi2xTCS_SetTapeLedData, &aioIob2Bi2xTCS_SetTapeLedData_orig);
|
||||
|
||||
const auto iob = "libaio-iob.dll";
|
||||
detour::trampoline(iob, "aioIob2Bi2x_OpenSciUsbCdc",
|
||||
aioIob2Bi2x_OpenSciUsbCdc, &aioIob2Bi2x_OpenSciUsbCdc_orig);
|
||||
detour::trampoline(iob, "aioIob2Bi2x_CreateWriteFirmContext",
|
||||
aioIob2Bi2x_CreateWriteFirmContext, &aioIob2Bi2x_CreateWriteFirmContext_orig);
|
||||
detour::trampoline(iob, "aioIob2Bi2x_DestroyWriteFirmContext",
|
||||
aioIob2Bi2x_DestroyWriteFirmContext, &aioIob2Bi2x_DestroyWriteFirmContext_orig);
|
||||
detour::trampoline(iob, "aioIob2Bi2x_WriteFirmGetState",
|
||||
aioIob2Bi2x_WriteFirmGetState, &aioIob2Bi2x_WriteFirmGetState_orig);
|
||||
detour::trampoline(iob, "aioNMgrIob2_Create",
|
||||
aioNMgrIob2_Create, &aioNMgrIob2_Create_orig);
|
||||
detour::trampoline(iob, "aioNMgrIob_BeginManage",
|
||||
aioNMgrIob_BeginManage, &aioNMgrIob_BeginManage_orig);
|
||||
|
||||
const auto aio = "libaio.dll";
|
||||
detour::trampoline(aio, "aioNodeMgr_Destroy", aioNodeMgr_Destroy, &aioNodeMgr_Destroy_orig);
|
||||
detour::trampoline(aio, "aioNodeMgr_GetState", aioNodeMgr_GetState, &aioNodeMgr_GetState_orig);
|
||||
detour::trampoline(aio, "aioNodeMgr_IsReady", aioNodeMgr_IsReady, &aioNodeMgr_IsReady_orig);
|
||||
detour::trampoline(aio, "aioNodeCtl_Destroy", aioNodeCtl_Destroy, &aioNodeCtl_Destroy_orig);
|
||||
detour::trampoline(aio, "aioNodeCtl_GetState", aioNodeCtl_GetState, &aioNodeCtl_GetState_orig);
|
||||
detour::trampoline(aio, "aioNodeCtl_IsReady", aioNodeCtl_IsReady, &aioNodeCtl_IsReady_orig);
|
||||
detour::trampoline(aio, "aioSci_Destroy", aioSci_Destroy, &aioSci_Destroy_orig);
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,5 @@
|
||||
#pragma once
|
||||
|
||||
namespace games::cardconnect {
|
||||
void bi2x_hook_init();
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
#include "cardconnect.h"
|
||||
|
||||
#include <format>
|
||||
|
||||
#include "acioemu/handle.h"
|
||||
#include "bi2x_hook.h"
|
||||
#include "printer.h"
|
||||
#include "hooks/graphics/graphics.h"
|
||||
#include "util/execexe.h"
|
||||
#include "util/fileutils.h"
|
||||
#include "util/libutils.h"
|
||||
#include "util/logging.h"
|
||||
#include "util/unity_player.h"
|
||||
|
||||
namespace games::cardconnect {
|
||||
std::string CARDCONNECT_INJECT_ARGS = "";
|
||||
|
||||
static const std::wstring reader_port = L"\\\\.\\COM2";
|
||||
|
||||
void CardConnectGame::attach() {
|
||||
Game::attach();
|
||||
|
||||
fileutils::dir_create_recursive_log("cardconnect", "dev/raw/log");
|
||||
if (!fileutils::bin_write("dev/raw/log/output_log.txt", nullptr, 0)) {
|
||||
log_warning("cardconnect", "failed to create Unity output log");
|
||||
}
|
||||
|
||||
auto *reader = new acioemu::ACIOHandle(reader_port.c_str(), 1);
|
||||
devicehook_init_trampoline();
|
||||
devicehook_add(reader);
|
||||
|
||||
execexe::init();
|
||||
execexe::init_port_hook(reader_port, reader);
|
||||
|
||||
#if SPICE64
|
||||
libutils::load_library("libaio.dll");
|
||||
libutils::load_library("libaio-iob.dll");
|
||||
libutils::load_library("libaio-iob2_video.dll");
|
||||
bi2x_hook_init();
|
||||
printer_attach();
|
||||
#endif
|
||||
|
||||
if (GRAPHICS_SHOW_CURSOR) {
|
||||
unity_utils::force_show_cursor(true);
|
||||
}
|
||||
|
||||
unity_utils::set_args(
|
||||
std::format("{} {}{}",
|
||||
GetCommandLineA(),
|
||||
CARDCONNECT_INJECT_ARGS,
|
||||
unity_utils::get_unity_player_args()));
|
||||
}
|
||||
|
||||
void CardConnectGame::detach() {
|
||||
Game::detach();
|
||||
devicehook_dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
#pragma once
|
||||
|
||||
#include "games/game.h"
|
||||
|
||||
namespace games::cardconnect {
|
||||
extern std::string CARDCONNECT_INJECT_ARGS;
|
||||
|
||||
class CardConnectGame : public games::Game {
|
||||
public:
|
||||
CardConnectGame() : Game("Card Connect") {}
|
||||
|
||||
virtual void attach() override;
|
||||
virtual void detach() override;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
#include "io.h"
|
||||
|
||||
std::vector<Button> &games::cardconnect::get_buttons() {
|
||||
static std::vector<Button> buttons;
|
||||
|
||||
if (buttons.empty()) {
|
||||
buttons = GameAPI::Buttons::getButtons("Card Connect");
|
||||
GameAPI::Buttons::sortButtons(
|
||||
&buttons,
|
||||
"Test",
|
||||
"Service",
|
||||
"Coin Mech"
|
||||
);
|
||||
}
|
||||
|
||||
return buttons;
|
||||
}
|
||||
|
||||
std::vector<Light> &games::cardconnect::get_lights() {
|
||||
static std::vector<Light> lights;
|
||||
|
||||
if (lights.empty()) {
|
||||
lights = GameAPI::Lights::getLights("Card Connect");
|
||||
GameAPI::Lights::sortLights(
|
||||
&lights,
|
||||
"Photo Light",
|
||||
"Card Reader R",
|
||||
"Card Reader G",
|
||||
"Card Reader B",
|
||||
"Side Left R",
|
||||
"Side Left G",
|
||||
"Side Left B",
|
||||
"Side Right R",
|
||||
"Side Right G",
|
||||
"Side Right B"
|
||||
);
|
||||
}
|
||||
|
||||
return lights;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
#pragma once
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include "cfg/api.h"
|
||||
|
||||
namespace games::cardconnect {
|
||||
namespace Buttons {
|
||||
enum {
|
||||
Test,
|
||||
Service,
|
||||
CoinMech,
|
||||
};
|
||||
}
|
||||
|
||||
namespace Lights {
|
||||
enum {
|
||||
PhotoLight,
|
||||
CardReaderR,
|
||||
CardReaderG,
|
||||
CardReaderB,
|
||||
SideLeftR,
|
||||
SideLeftG,
|
||||
SideLeftB,
|
||||
SideRightR,
|
||||
SideRightG,
|
||||
SideRightB,
|
||||
};
|
||||
}
|
||||
|
||||
std::vector<Button> &get_buttons();
|
||||
std::vector<Light> &get_lights();
|
||||
}
|
||||
@@ -0,0 +1,617 @@
|
||||
#include "printer.h"
|
||||
|
||||
#if SPICE64
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
|
||||
#include "games/shared/printer.h"
|
||||
#include "util/detour.h"
|
||||
#include "util/libutils.h"
|
||||
#include "util/logging.h"
|
||||
|
||||
namespace games::cardconnect {
|
||||
|
||||
// Settings and native protocol values.
|
||||
bool PRINTER_DISABLED = false;
|
||||
bool PRINTER_SIMULATE_DELAY = false;
|
||||
|
||||
static constexpr uint16_t READY = 0;
|
||||
static constexpr uint16_t INVALID_PARAMETER = 1006;
|
||||
static constexpr uint16_t BUSY = 1500;
|
||||
static constexpr uint16_t PRINTING = 2100;
|
||||
static constexpr uint16_t OUTPUT_ERROR = 2504;
|
||||
|
||||
enum PrinterInfoTag : uint16_t {
|
||||
INFO_PAPER = 0,
|
||||
INFO_FIRMWARE = 3,
|
||||
INFO_PRINT_COUNT = 4,
|
||||
INFO_HOLO_REMAINING = 6,
|
||||
INFO_MEMORY = 16,
|
||||
INFO_FRONT_MODE = 19,
|
||||
INFO_BACK_MODE = 20,
|
||||
INFO_IR_CORRECTION = 22,
|
||||
};
|
||||
|
||||
enum PrinterMode : uint8_t {
|
||||
MODE_YMC_MAT = 2,
|
||||
MODE_YMC_LAM = 3,
|
||||
MODE_YMC_MAT_HOLO = 5,
|
||||
MODE_YMC_LAM_HOLO = 6,
|
||||
MODE_IR_R_YMAC_MAT = 8,
|
||||
MODE_IR_R_YMAC_LAM = 9,
|
||||
MODE_R_YMAC_MAT = 10,
|
||||
MODE_R_YMAC_LAM = 11,
|
||||
MODE_YMC_GROSS = 18,
|
||||
MODE_YMC_GROSS_HOLO = 21,
|
||||
MODE_IR_R_YMAC_GROSS = 24,
|
||||
MODE_R_YMAC_GROSS = 25,
|
||||
};
|
||||
|
||||
static constexpr uint16_t FORMAT_RGB = 3;
|
||||
static constexpr uint16_t FORMAT_BGR = 4;
|
||||
static constexpr uint16_t COLOR_COMPONENTS = 3;
|
||||
static constexpr uint16_t COLOR_DEPTH = 8;
|
||||
static constexpr uint16_t CARD_WIDTH = 662;
|
||||
static constexpr uint16_t CARD_HEIGHT = 1024;
|
||||
static constexpr uint32_t RIBBON_REMAINING = 4096;
|
||||
static constexpr auto PRINT_TIME = std::chrono::seconds(5);
|
||||
|
||||
static constexpr std::optional<std::chrono::seconds> get_mode_delay(uint8_t mode) {
|
||||
// Printer::GetPrintTime adds 10s for holo and 8s per finished side.
|
||||
if (mode == MODE_YMC_GROSS || mode == MODE_IR_R_YMAC_GROSS || mode == MODE_R_YMAC_GROSS) {
|
||||
return std::chrono::seconds(0);
|
||||
}
|
||||
if (mode == MODE_YMC_MAT || mode == MODE_YMC_LAM ||
|
||||
mode == MODE_IR_R_YMAC_MAT || mode == MODE_IR_R_YMAC_LAM ||
|
||||
mode == MODE_R_YMAC_MAT || mode == MODE_R_YMAC_LAM) {
|
||||
return std::chrono::seconds(8);
|
||||
}
|
||||
if (mode == MODE_YMC_GROSS_HOLO) {
|
||||
return std::chrono::seconds(10);
|
||||
}
|
||||
if (mode == MODE_YMC_MAT_HOLO || mode == MODE_YMC_LAM_HOLO) {
|
||||
return std::chrono::seconds(18);
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// Native reply layouts.
|
||||
#pragma pack(push, 1)
|
||||
struct FirmwareRecord {
|
||||
std::array<uint8_t, 34> reserved;
|
||||
uint8_t major;
|
||||
uint8_t minor;
|
||||
std::array<uint8_t, 2> reserved_tail;
|
||||
};
|
||||
|
||||
struct FirmwareReply {
|
||||
uint8_t count;
|
||||
std::array<FirmwareRecord, 4> records;
|
||||
};
|
||||
|
||||
struct PrintCountReply {
|
||||
uint32_t total_count;
|
||||
std::array<uint8_t, 16> reserved;
|
||||
uint32_t ribbon_remaining;
|
||||
std::array<uint8_t, 8> reserved_tail;
|
||||
};
|
||||
|
||||
struct HoloRemainingReply {
|
||||
uint32_t remaining;
|
||||
std::array<uint8_t, 28> reserved;
|
||||
};
|
||||
|
||||
struct MemoryReply {
|
||||
uint16_t reserved;
|
||||
uint16_t remaining;
|
||||
uint16_t completed;
|
||||
uint16_t copies;
|
||||
std::array<uint8_t, 10> reserved_tail;
|
||||
};
|
||||
|
||||
struct PrintIDReply {
|
||||
uint16_t remaining;
|
||||
std::array<uint8_t, 4> reserved;
|
||||
uint16_t status;
|
||||
};
|
||||
#pragma pack(pop)
|
||||
|
||||
static_assert(sizeof(FirmwareRecord) == 38);
|
||||
static_assert(offsetof(FirmwareRecord, major) == 34);
|
||||
static_assert(offsetof(FirmwareRecord, minor) == 35);
|
||||
static_assert(sizeof(FirmwareReply) == 153);
|
||||
static_assert(offsetof(FirmwareReply, records) == 1);
|
||||
|
||||
static_assert(sizeof(PrintCountReply) == 32);
|
||||
static_assert(offsetof(PrintCountReply, ribbon_remaining) == 20);
|
||||
static_assert(sizeof(HoloRemainingReply) == 32);
|
||||
|
||||
static_assert(sizeof(MemoryReply) == 18);
|
||||
static_assert(offsetof(MemoryReply, remaining) == 2);
|
||||
static_assert(offsetof(MemoryReply, completed) == 4);
|
||||
static_assert(offsetof(MemoryReply, copies) == 6);
|
||||
|
||||
static_assert(sizeof(PrintIDReply) == 8);
|
||||
static_assert(offsetof(PrintIDReply, status) == 6);
|
||||
|
||||
// One printer, shared by the game's threads.
|
||||
struct PrintJob {
|
||||
uint16_t id = 0;
|
||||
uint16_t copies = 1;
|
||||
uint16_t remaining = 0;
|
||||
|
||||
uint16_t width = 0;
|
||||
uint16_t height = 0;
|
||||
uint16_t format = FORMAT_RGB;
|
||||
std::array<std::vector<uint8_t>, 2> sides;
|
||||
|
||||
uint16_t error = READY;
|
||||
bool receiving = false;
|
||||
// Submitted jobs stay busy while waiting for this baseline.
|
||||
bool awaiting_counter_baseline = false;
|
||||
std::array<std::chrono::seconds, 2> mode_delays {};
|
||||
std::chrono::seconds print_time = PRINT_TIME;
|
||||
std::chrono::steady_clock::time_point next_copy;
|
||||
};
|
||||
|
||||
static std::mutex printer_mutex;
|
||||
static PrintJob job;
|
||||
static uint16_t next_page_id = 0;
|
||||
static uint32_t total_count = 0;
|
||||
static uint32_t cutter_offset = 0;
|
||||
|
||||
// Write the result; non-ready codes return FALSE.
|
||||
static BOOL set_result(uint16_t *result, uint16_t code = READY) {
|
||||
if (!result) {
|
||||
log_warning("cardconnect::printer", "missing result buffer");
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
*result = code;
|
||||
return code == READY;
|
||||
}
|
||||
|
||||
static BOOL invalid_parameter(uint16_t *result, const char *operation) {
|
||||
log_warning("cardconnect::printer", "{}: invalid parameter or job state", operation);
|
||||
return set_result(result, INVALID_PARAMETER);
|
||||
}
|
||||
|
||||
// Caller holds printer_mutex. The baseline gates completion.
|
||||
static void update_printing() {
|
||||
if (job.awaiting_counter_baseline) {
|
||||
return;
|
||||
}
|
||||
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
while (job.remaining && now >= job.next_copy) {
|
||||
++total_count;
|
||||
--job.remaining;
|
||||
job.next_copy += job.print_time;
|
||||
log_info("cardconnect::printer", "job {}: total count={}, remaining={}",
|
||||
job.id, total_count, job.remaining);
|
||||
}
|
||||
}
|
||||
|
||||
// Caller holds printer_mutex.
|
||||
static uint16_t poll_status() {
|
||||
update_printing();
|
||||
if (job.error) {
|
||||
return job.error;
|
||||
}
|
||||
return job.remaining ? PRINTING : READY;
|
||||
}
|
||||
|
||||
// Driver lifetime.
|
||||
static void __stdcall chcusb_MakeThread(uint16_t count) {
|
||||
log_info("cardconnect::printer", "initializing printer with {} thread slots", count);
|
||||
}
|
||||
|
||||
static BOOL __stdcall chcusb_open(uint16_t *result) {
|
||||
return set_result(result);
|
||||
}
|
||||
|
||||
static void __stdcall chcusb_close() {
|
||||
// Closing a worker must not cancel a submitted job.
|
||||
std::lock_guard lock(printer_mutex);
|
||||
if (job.receiving) {
|
||||
log_warning("cardconnect::printer", "discarding incomplete print job {}", job.id);
|
||||
job = {};
|
||||
}
|
||||
}
|
||||
|
||||
static BOOL __stdcall chcusb_ReleaseThread(uint16_t *result) {
|
||||
std::lock_guard lock(printer_mutex);
|
||||
job = {};
|
||||
return set_result(result);
|
||||
}
|
||||
|
||||
// Status and printer information.
|
||||
static BOOL __stdcall chcusb_status(uint16_t *result) {
|
||||
std::lock_guard lock(printer_mutex);
|
||||
return set_result(result, poll_status());
|
||||
}
|
||||
|
||||
static BOOL __stdcall chcusb_getPrinterInfo(uint16_t tag, void *buffer, uint16_t *length) {
|
||||
std::lock_guard lock(printer_mutex);
|
||||
update_printing();
|
||||
|
||||
// Build the requested reply.
|
||||
std::array<uint8_t, sizeof(FirmwareReply)> data {};
|
||||
uint16_t size;
|
||||
switch (tag) {
|
||||
case INFO_FIRMWARE: {
|
||||
FirmwareReply reply {};
|
||||
reply.count = static_cast<uint8_t>(reply.records.size());
|
||||
for (auto &record : reply.records) {
|
||||
record.major = 1;
|
||||
}
|
||||
size = sizeof(reply);
|
||||
std::memcpy(data.data(), &reply, size);
|
||||
break;
|
||||
}
|
||||
case INFO_PRINT_COUNT: {
|
||||
PrintCountReply reply {};
|
||||
reply.total_count = total_count;
|
||||
reply.ribbon_remaining = RIBBON_REMAINING;
|
||||
size = sizeof(reply);
|
||||
std::memcpy(data.data(), &reply, size);
|
||||
break;
|
||||
}
|
||||
case INFO_HOLO_REMAINING: {
|
||||
HoloRemainingReply reply {};
|
||||
reply.remaining = RIBBON_REMAINING;
|
||||
size = sizeof(reply);
|
||||
std::memcpy(data.data(), &reply, size);
|
||||
break;
|
||||
}
|
||||
case INFO_MEMORY: {
|
||||
MemoryReply reply {};
|
||||
reply.remaining = job.remaining;
|
||||
reply.completed = static_cast<uint16_t>(job.copies - job.remaining);
|
||||
reply.copies = job.copies;
|
||||
size = sizeof(reply);
|
||||
std::memcpy(data.data(), &reply, size);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
log_warning("cardconnect::printer", "unsupported printer info tag {}", tag);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
// Check capacity before writing.
|
||||
if (!buffer || !length || *length < size) {
|
||||
log_warning("cardconnect::printer", "invalid buffer for printer info tag {}", tag);
|
||||
if (length) {
|
||||
*length = size;
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
std::memcpy(buffer, data.data(), size);
|
||||
*length = size;
|
||||
|
||||
// CoMain needs its post-cleanup baseline before any copy finishes.
|
||||
if (tag == INFO_PRINT_COUNT && job.awaiting_counter_baseline) {
|
||||
job.awaiting_counter_baseline = false;
|
||||
job.next_copy = std::chrono::steady_clock::now() + job.print_time;
|
||||
log_info("cardconnect::printer",
|
||||
"job {}: counter baseline={}, starting print timer ({}s per copy)",
|
||||
job.id, total_count, job.print_time.count());
|
||||
}
|
||||
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
// Paper and coating settings do not alter saved RGB data.
|
||||
static BOOL __stdcall chcusb_setPrinterInfo(
|
||||
uint16_t tag, const void *buffer, uint16_t *length, uint16_t *result) {
|
||||
uint16_t expected = 0;
|
||||
switch (tag) {
|
||||
case INFO_PAPER:
|
||||
expected = 10;
|
||||
break;
|
||||
case INFO_FRONT_MODE:
|
||||
case INFO_BACK_MODE:
|
||||
case INFO_IR_CORRECTION:
|
||||
// The managed caller sends one byte, not two.
|
||||
expected = 1;
|
||||
break;
|
||||
}
|
||||
|
||||
if (!expected || !buffer || !length || *length != expected) {
|
||||
log_warning("cardconnect::printer",
|
||||
"setPrinterInfo: tag={}, length={}, expected={}, buffer={}, length pointer={}",
|
||||
tag, length ? *length : 0, expected, buffer != nullptr, length != nullptr);
|
||||
return invalid_parameter(result, "setPrinterInfo");
|
||||
}
|
||||
|
||||
if (PRINTER_SIMULATE_DELAY && (tag == INFO_FRONT_MODE || tag == INFO_BACK_MODE)) {
|
||||
const auto mode = *static_cast<const uint8_t *>(buffer);
|
||||
const auto delay = get_mode_delay(mode);
|
||||
if (!delay) {
|
||||
log_warning("cardconnect::printer", "cannot estimate delay for print mode {}", mode);
|
||||
return invalid_parameter(result, "setPrinterInfo print mode");
|
||||
}
|
||||
if (!result) {
|
||||
return set_result(result);
|
||||
}
|
||||
|
||||
std::lock_guard lock(printer_mutex);
|
||||
if (tag == INFO_FRONT_MODE) {
|
||||
job.mode_delays[0] = *delay;
|
||||
} else {
|
||||
job.mode_delays[1] = *delay;
|
||||
}
|
||||
}
|
||||
|
||||
return set_result(result);
|
||||
}
|
||||
|
||||
// Configure the next job.
|
||||
static BOOL __stdcall chcusb_imageformat(
|
||||
uint16_t format, uint16_t components, uint16_t depth,
|
||||
uint16_t width, uint16_t height, uint16_t *result) {
|
||||
std::lock_guard lock(printer_mutex);
|
||||
update_printing();
|
||||
|
||||
if ((format != FORMAT_RGB && format != FORMAT_BGR) ||
|
||||
components != COLOR_COMPONENTS || depth != COLOR_DEPTH ||
|
||||
width != CARD_WIDTH || height != CARD_HEIGHT || job.receiving || job.remaining) {
|
||||
return invalid_parameter(result, "imageformat");
|
||||
}
|
||||
|
||||
job.width = width;
|
||||
job.height = height;
|
||||
job.format = format;
|
||||
return set_result(result);
|
||||
}
|
||||
|
||||
static BOOL __stdcall chcusb_copies(uint16_t copies, uint16_t *result) {
|
||||
std::lock_guard lock(printer_mutex);
|
||||
update_printing();
|
||||
|
||||
if (!copies || job.receiving || job.remaining) {
|
||||
return invalid_parameter(result, "copies");
|
||||
}
|
||||
|
||||
job.copies = copies;
|
||||
return set_result(result);
|
||||
}
|
||||
|
||||
// Receive front and back image data.
|
||||
static BOOL __stdcall chcusb_startpage(uint16_t mode, uint16_t *page_id, uint16_t *result) {
|
||||
std::lock_guard lock(printer_mutex);
|
||||
update_printing();
|
||||
|
||||
if (job.receiving || job.remaining) {
|
||||
log_warning("cardconnect::printer", "startpage while printer is busy");
|
||||
return set_result(result, BUSY);
|
||||
}
|
||||
if (mode != 0 || !page_id || !result || !job.width || !job.height) {
|
||||
return invalid_parameter(result, "startpage");
|
||||
}
|
||||
|
||||
// Keep zero reserved for "no job".
|
||||
if (++next_page_id == 0) {
|
||||
++next_page_id;
|
||||
}
|
||||
|
||||
job.id = next_page_id;
|
||||
job.print_time = PRINT_TIME;
|
||||
if (PRINTER_SIMULATE_DELAY) {
|
||||
job.print_time = std::chrono::seconds(73) + job.mode_delays[0] + job.mode_delays[1];
|
||||
}
|
||||
job.error = READY;
|
||||
job.receiving = true;
|
||||
job.sides = {};
|
||||
*page_id = job.id;
|
||||
log_info("cardconnect::printer", "receiving job {} ({} copies)", job.id, job.copies);
|
||||
return set_result(result);
|
||||
}
|
||||
|
||||
static BOOL __stdcall chcusb_write(
|
||||
const uint8_t *data, uint32_t *size, uint16_t *result) {
|
||||
std::lock_guard lock(printer_mutex);
|
||||
const size_t expected = static_cast<size_t>(job.width) * job.height * COLOR_COMPONENTS;
|
||||
|
||||
if (!job.receiving || !data || !size || !result || !*size) {
|
||||
return invalid_parameter(result, "write");
|
||||
}
|
||||
|
||||
// Fill the front before accepting the back.
|
||||
auto &side = job.sides[job.sides[0].size() == expected ? 1 : 0];
|
||||
if (*size > expected - side.size()) {
|
||||
return invalid_parameter(result, "write size");
|
||||
}
|
||||
side.insert(side.end(), data, data + *size);
|
||||
return set_result(result);
|
||||
}
|
||||
|
||||
// Accept coating masks without saving them.
|
||||
static BOOL __stdcall discard_mask(
|
||||
const uint8_t *data, uint32_t *size, uint16_t *result) {
|
||||
std::lock_guard lock(printer_mutex);
|
||||
if (!job.receiving || !data || !size ||
|
||||
*size != static_cast<uint32_t>(job.width) * job.height) {
|
||||
return invalid_parameter(result, "mask write");
|
||||
}
|
||||
return set_result(result);
|
||||
}
|
||||
|
||||
static BOOL __stdcall chcusb_endpage(uint16_t *result) {
|
||||
std::lock_guard lock(printer_mutex);
|
||||
const size_t expected = static_cast<size_t>(job.width) * job.height * COLOR_COMPONENTS;
|
||||
|
||||
// Both sides must be complete.
|
||||
if (!result || !job.receiving ||
|
||||
job.sides[0].size() != expected || job.sides[1].size() != expected) {
|
||||
return invalid_parameter(result, "endpage");
|
||||
}
|
||||
|
||||
// Image files use RGB channel order.
|
||||
if (job.format == FORMAT_BGR) {
|
||||
for (auto &side : job.sides) {
|
||||
for (size_t i = 0; i < side.size(); i += COLOR_COMPONENTS) {
|
||||
std::swap(side[i], side[i + 2]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Save every copy before reporting success.
|
||||
job.receiving = false;
|
||||
for (uint16_t i = 0; i < job.copies; ++i) {
|
||||
if (!games::shared::printer_write_images({
|
||||
{job.sides[0].data(), job.width, job.height, COLOR_COMPONENTS, "_front"},
|
||||
{job.sides[1].data(), job.width, job.height, COLOR_COMPONENTS, "_back"}})) {
|
||||
job.error = OUTPUT_ERROR;
|
||||
job.sides = {};
|
||||
log_warning("cardconnect::printer", "failed to save job {}", job.id);
|
||||
return set_result(result, job.error);
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for the game's counter baseline.
|
||||
job.sides = {};
|
||||
job.remaining = job.copies;
|
||||
job.awaiting_counter_baseline = true;
|
||||
log_info("cardconnect::printer", "submitted job {}, waiting for counter baseline", job.id);
|
||||
return set_result(result);
|
||||
}
|
||||
|
||||
// Job progress and cancellation.
|
||||
static BOOL __stdcall chcusb_getPrintIDStatus(
|
||||
uint16_t page_id, void *buffer, uint16_t *result) {
|
||||
std::lock_guard lock(printer_mutex);
|
||||
const auto status = poll_status();
|
||||
|
||||
if (!buffer || page_id != job.id) {
|
||||
return invalid_parameter(result, "getPrintIDStatus");
|
||||
}
|
||||
|
||||
PrintIDReply reply {};
|
||||
reply.remaining = job.remaining;
|
||||
reply.status = status;
|
||||
std::memcpy(buffer, &reply, sizeof(reply));
|
||||
return set_result(result);
|
||||
}
|
||||
|
||||
static BOOL __stdcall chcusb_cancelCopies(uint16_t page_id, uint16_t *result) {
|
||||
std::lock_guard lock(printer_mutex);
|
||||
if (page_id != job.id) {
|
||||
return invalid_parameter(result, "cancelCopies");
|
||||
}
|
||||
|
||||
update_printing();
|
||||
job.remaining = 0;
|
||||
job.receiving = false;
|
||||
job.awaiting_counter_baseline = false;
|
||||
job.sides = {};
|
||||
return set_result(result);
|
||||
}
|
||||
|
||||
static BOOL __stdcall chcusb_resetPrinter(uint16_t *result) {
|
||||
std::lock_guard lock(printer_mutex);
|
||||
update_printing();
|
||||
job = {};
|
||||
return set_result(result);
|
||||
}
|
||||
|
||||
// Physical-printer controls.
|
||||
static BOOL __stdcall chcusb_setIcctable(
|
||||
[[maybe_unused]] const char *input_profile,
|
||||
[[maybe_unused]] const char *output_profile,
|
||||
[[maybe_unused]] uint16_t rendering_intents,
|
||||
[[maybe_unused]] const void *input_tone_r,
|
||||
[[maybe_unused]] const void *input_tone_g,
|
||||
[[maybe_unused]] const void *input_tone_b,
|
||||
[[maybe_unused]] const void *output_tone_r,
|
||||
[[maybe_unused]] const void *output_tone_g,
|
||||
[[maybe_unused]] const void *output_tone_b,
|
||||
uint16_t *result) {
|
||||
// Keep the original RGB colors.
|
||||
return set_result(result);
|
||||
}
|
||||
|
||||
static void __stdcall chcusb_setCutterOffset(uint32_t offset, uint16_t *result) {
|
||||
std::lock_guard lock(printer_mutex);
|
||||
cutter_offset = offset;
|
||||
set_result(result);
|
||||
}
|
||||
|
||||
static BOOL __stdcall chcusb_getCutterOffset(uint32_t *offset, uint16_t *result) {
|
||||
std::lock_guard lock(printer_mutex);
|
||||
if (!offset) {
|
||||
return invalid_parameter(result, "getCutterOffset");
|
||||
}
|
||||
*offset = cutter_offset;
|
||||
return set_result(result);
|
||||
}
|
||||
|
||||
static BOOL __stdcall chcusb_getErrorLog(uint16_t index, void *buffer, uint16_t *result) {
|
||||
if (!buffer || index != 0) {
|
||||
return invalid_parameter(result, "getErrorLog");
|
||||
}
|
||||
std::memset(buffer, 0, 16);
|
||||
return set_result(result);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
static void hook(const char *name, T function) {
|
||||
T original = nullptr;
|
||||
detour::trampoline("C320Dusb.dll", name, function, &original);
|
||||
}
|
||||
|
||||
void printer_attach() {
|
||||
if (PRINTER_DISABLED) {
|
||||
return;
|
||||
}
|
||||
|
||||
log_info("cardconnect::printer", "enabling C320D printer emulation");
|
||||
games::shared::printer_init_output({"_front", "_back"});
|
||||
libutils::load_library("game\\tcs_data\\Plugins\\C320Dusb.dll");
|
||||
|
||||
// Connections and status.
|
||||
hook("chcusb_MakeThread", chcusb_MakeThread);
|
||||
hook("chcusb_open", chcusb_open);
|
||||
hook("chcusb_close", chcusb_close);
|
||||
hook("chcusb_ReleaseThread", chcusb_ReleaseThread);
|
||||
hook("chcusb_status", chcusb_status);
|
||||
hook("chcusb_getPrinterInfo", chcusb_getPrinterInfo);
|
||||
hook("chcusb_setPrinterInfo", chcusb_setPrinterInfo);
|
||||
|
||||
// Job setup and image transfer.
|
||||
hook("chcusb_imageformat", chcusb_imageformat);
|
||||
hook("chcusb_copies", chcusb_copies);
|
||||
hook("chcusb_startpage", chcusb_startpage);
|
||||
hook("chcusb_write", chcusb_write);
|
||||
hook("chcusb_writeLaminate", discard_mask);
|
||||
hook("chcusb_writeHolo", discard_mask);
|
||||
hook("chcusb_writeIred", discard_mask);
|
||||
hook("chcusb_endpage", chcusb_endpage);
|
||||
|
||||
// Completion and device controls.
|
||||
hook("chcusb_getPrintIDStatus", chcusb_getPrintIDStatus);
|
||||
hook("chcusb_cancelCopies", chcusb_cancelCopies);
|
||||
hook("chcusb_resetPrinter", chcusb_resetPrinter);
|
||||
hook("chcusb_setIcctable", chcusb_setIcctable);
|
||||
hook("chcusb_setCutterOffset", chcusb_setCutterOffset);
|
||||
hook("chcusb_getCutterOffset", chcusb_getCutterOffset);
|
||||
hook("chcusb_getErrorLog", chcusb_getErrorLog);
|
||||
}
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
namespace games::cardconnect {
|
||||
bool PRINTER_DISABLED = false;
|
||||
bool PRINTER_SIMULATE_DELAY = false;
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
namespace games::cardconnect {
|
||||
extern bool PRINTER_DISABLED;
|
||||
extern bool PRINTER_SIMULATE_DELAY;
|
||||
void printer_attach();
|
||||
}
|
||||
@@ -9,6 +9,8 @@
|
||||
#include "util/logging.h"
|
||||
#include "util/precise_timer.h"
|
||||
#include "util/memutils.h"
|
||||
#include "io.h"
|
||||
#include "motion_cam.h"
|
||||
#include "rgb_cam.h"
|
||||
|
||||
#pragma pack(push)
|
||||
@@ -276,48 +278,50 @@ namespace games::drs {
|
||||
void DRSGame::attach() {
|
||||
Game::attach();
|
||||
|
||||
// TouchSDK hooks
|
||||
detour::iat("??0TouchSDK@@QEAA@XZ",
|
||||
(void *) &TouchSDK_Constructor, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?SendData@TouchSDK@@QEAA_NU_DeviceInfo@@QEAEH1HH@Z",
|
||||
(void *) &TouchSDK_SendData, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?SetSignalInit@TouchSDK@@QEAA_NU_DeviceInfo@@H@Z",
|
||||
(void *) &TouchSDK_SetSignalInit, avs::game::DLL_INSTANCE);
|
||||
detour::iat("??1TouchSDK@@QEAA@XZ",
|
||||
(void *) &TouchSDK_Destructor, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?GetYLedTotal@TouchSDK@@QEAAHU_DeviceInfo@@H@Z",
|
||||
(void *) &TouchSDK_GetYLedTotal, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?GetXLedTotal@TouchSDK@@QEAAHU_DeviceInfo@@H@Z",
|
||||
(void *) &TouchSDK_GetXLedTotal, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?DisableTouch@TouchSDK@@QEAA_NU_DeviceInfo@@H@Z",
|
||||
(void *) &TouchSDK_DisableTouch, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?DisableDrag@TouchSDK@@QEAA_NU_DeviceInfo@@H@Z",
|
||||
(void *) &TouchSDK_DisableDrag, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?DisableWheel@TouchSDK@@QEAA_NU_DeviceInfo@@H@Z",
|
||||
(void *) &TouchSDK_DisableWheel, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?DisableRightClick@TouchSDK@@QEAA_NU_DeviceInfo@@H@Z",
|
||||
(void *) &TouchSDK_DisableRightClick, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?SetMultiTouchMode@TouchSDK@@QEAA_NU_DeviceInfo@@H@Z",
|
||||
(void *) &TouchSDK_SetMultiTouchMode, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?EnableTouchWidthData@TouchSDK@@QEAA_NU_DeviceInfo@@H@Z",
|
||||
(void *) &TouchSDK_EnableTouchWidthData, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?EnableRawData@TouchSDK@@QEAA_NU_DeviceInfo@@H@Z",
|
||||
(void *) &TouchSDK_EnableRawData, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?SetAllEnable@TouchSDK@@QEAA_NU_DeviceInfo@@_NH@Z",
|
||||
(void *) &TouchSDK_SetAllEnable, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?GetTouchDeviceCount@TouchSDK@@QEAAHXZ",
|
||||
(void *) &TouchSDK_GetTouchDeviceCount, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?GetTouchSDKVersion@TouchSDK@@QEAAIXZ",
|
||||
(void *) &TouchSDK_GetTouchSDKVersion, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?InitTouch@TouchSDK@@QEAAHPEAU_DeviceInfo@@HP6AXU2@PEBU_TouchPointData@@HHPEBX@ZP6AX1_N3@ZPEAX@Z",
|
||||
(void *) &TouchSDK_InitTouch, avs::game::DLL_INSTANCE);
|
||||
|
||||
if (!DISABLE_TOUCH) {
|
||||
// TouchSDK hooks
|
||||
detour::iat("??0TouchSDK@@QEAA@XZ",
|
||||
(void *) &TouchSDK_Constructor, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?SendData@TouchSDK@@QEAA_NU_DeviceInfo@@QEAEH1HH@Z",
|
||||
(void *) &TouchSDK_SendData, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?SetSignalInit@TouchSDK@@QEAA_NU_DeviceInfo@@H@Z",
|
||||
(void *) &TouchSDK_SetSignalInit, avs::game::DLL_INSTANCE);
|
||||
detour::iat("??1TouchSDK@@QEAA@XZ",
|
||||
(void *) &TouchSDK_Destructor, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?GetYLedTotal@TouchSDK@@QEAAHU_DeviceInfo@@H@Z",
|
||||
(void *) &TouchSDK_GetYLedTotal, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?GetXLedTotal@TouchSDK@@QEAAHU_DeviceInfo@@H@Z",
|
||||
(void *) &TouchSDK_GetXLedTotal, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?DisableTouch@TouchSDK@@QEAA_NU_DeviceInfo@@H@Z",
|
||||
(void *) &TouchSDK_DisableTouch, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?DisableDrag@TouchSDK@@QEAA_NU_DeviceInfo@@H@Z",
|
||||
(void *) &TouchSDK_DisableDrag, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?DisableWheel@TouchSDK@@QEAA_NU_DeviceInfo@@H@Z",
|
||||
(void *) &TouchSDK_DisableWheel, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?DisableRightClick@TouchSDK@@QEAA_NU_DeviceInfo@@H@Z",
|
||||
(void *) &TouchSDK_DisableRightClick, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?SetMultiTouchMode@TouchSDK@@QEAA_NU_DeviceInfo@@H@Z",
|
||||
(void *) &TouchSDK_SetMultiTouchMode, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?EnableTouchWidthData@TouchSDK@@QEAA_NU_DeviceInfo@@H@Z",
|
||||
(void *) &TouchSDK_EnableTouchWidthData, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?EnableRawData@TouchSDK@@QEAA_NU_DeviceInfo@@H@Z",
|
||||
(void *) &TouchSDK_EnableRawData, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?SetAllEnable@TouchSDK@@QEAA_NU_DeviceInfo@@_NH@Z",
|
||||
(void *) &TouchSDK_SetAllEnable, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?GetTouchDeviceCount@TouchSDK@@QEAAHXZ",
|
||||
(void *) &TouchSDK_GetTouchDeviceCount, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?GetTouchSDKVersion@TouchSDK@@QEAAIXZ",
|
||||
(void *) &TouchSDK_GetTouchSDKVersion, avs::game::DLL_INSTANCE);
|
||||
detour::iat("?InitTouch@TouchSDK@@QEAAHPEAU_DeviceInfo@@HP6AXU2@PEBU_TouchPointData@@HHPEBX@ZP6AX1_N3@ZPEAX@Z",
|
||||
(void *) &TouchSDK_InitTouch, avs::game::DLL_INSTANCE);
|
||||
|
||||
start_touch();
|
||||
} else {
|
||||
log_info("drs", "no native input method detected");
|
||||
log_info("drs", "touch input for dance floor disabled");
|
||||
}
|
||||
|
||||
init_down_motion_hook();
|
||||
|
||||
if (RGB_CAMERA_HOOK) {
|
||||
init_rgb_camera_hook();
|
||||
}
|
||||
|
||||
@@ -20,7 +20,8 @@ std::vector<Button> &games::drs::get_buttons() {
|
||||
"P2 Up",
|
||||
"P2 Down",
|
||||
"P2 Left",
|
||||
"P2 Right"
|
||||
"P2 Right",
|
||||
"Down Motion"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -30,8 +31,8 @@ std::vector<Button> &games::drs::get_buttons() {
|
||||
std::string games::drs::get_buttons_help() {
|
||||
// keep to max 100 characters wide
|
||||
return
|
||||
"Motion camera required for DOWN movement.\n"
|
||||
"Touchscreen supported for dance floor."
|
||||
"Touchscreen supported for dance floor.\n"
|
||||
"Down Motion applies to both players."
|
||||
;
|
||||
}
|
||||
|
||||
|
||||
@@ -20,7 +20,8 @@ namespace games::drs {
|
||||
P2_Up,
|
||||
P2_Down,
|
||||
P2_Left,
|
||||
P2_Right
|
||||
P2_Right,
|
||||
DownMotion
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
#include "games/drs/motion_cam.h"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
#include "avs/game.h"
|
||||
#include "util/detour.h"
|
||||
#include "util/logging.h"
|
||||
#include "util/sigscan.h"
|
||||
#include "io.h"
|
||||
|
||||
namespace games::drs {
|
||||
|
||||
// the game reads down movement from a depth camera whose driver is compiled into the game DLL,
|
||||
// so there is no import to replace.
|
||||
//
|
||||
// with no camera the tracked height never changes, so the motion state never leaves "still"
|
||||
// and DOWN notes can never be hit.
|
||||
//
|
||||
// rather than answer CInputManager::IsDown, the button drives the same state pair the camera
|
||||
// would; that leaves the game's own edge test untouched and keeps every note in a frame seeing
|
||||
// one answer.
|
||||
static int32_t *MOTION_STATE = nullptr;
|
||||
static int32_t *MOTION_STATE_PREV = nullptr;
|
||||
static constexpr int32_t MOTION_STATE_STILL = 1;
|
||||
static constexpr int32_t MOTION_STATE_DOWN = 2;
|
||||
|
||||
static void (*UpdateMotion_orig)() = nullptr;
|
||||
static bool DOWN_MOTION_HELD = false;
|
||||
|
||||
static void InputManager_UpdateMotion() {
|
||||
UpdateMotion_orig();
|
||||
|
||||
auto &buttons = get_buttons();
|
||||
const bool held = GameAPI::Buttons::getState(RI_MGR, buttons.at(Buttons::DownMotion));
|
||||
|
||||
// a state of DOWN only counts as movement when the frame before it was something else
|
||||
if (held) {
|
||||
*MOTION_STATE_PREV = DOWN_MOTION_HELD ? MOTION_STATE_DOWN : MOTION_STATE_STILL;
|
||||
*MOTION_STATE = MOTION_STATE_DOWN;
|
||||
}
|
||||
|
||||
DOWN_MOTION_HELD = held;
|
||||
}
|
||||
|
||||
void init_down_motion_hook() {
|
||||
// only hook motion camera if the user has down motion button bound to something
|
||||
auto &buttons = get_buttons();
|
||||
if (!buttons.at(Buttons::DownMotion).isSet()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// CInputManager::IsDown - read the state pair out of its two operands.
|
||||
// Identical in game versions 2020121400 and 2022121400 / 2024120300:
|
||||
//
|
||||
// 83 3D xx xx xx xx 02 cmp dword [rip+prev], 2 ; state one frame ago
|
||||
// 74 0C je FALSE ; already down, so no new edge
|
||||
// 83 3D xx xx xx xx 02 cmp dword [rip+cur], 2 ; state this frame
|
||||
// 75 03 jne FALSE ; not down
|
||||
// B0 01 mov al, 1 ; went down on this frame
|
||||
// C3 ret
|
||||
// 32 C0 FALSE: xor al, al
|
||||
// C3 ret
|
||||
auto is_down = reinterpret_cast<uint8_t *>(find_pattern(
|
||||
avs::game::DLL_INSTANCE,
|
||||
"833D0000000002740C833D00000000027503B001C332C0C3",
|
||||
"XX????XXXXX????XXXXXXXXX",
|
||||
0, 0));
|
||||
|
||||
if (is_down == nullptr) {
|
||||
log_warning("drs", "motion sensor state not found, DOWN motion button unavailable");
|
||||
return;
|
||||
}
|
||||
|
||||
// rip-relative displacements resolve against the end of their own instruction, and each
|
||||
// cmp above is 7 bytes with its displacement 4 bytes in: the first ends at +7 with its
|
||||
// displacement at +2, the second starts at +9 so it ends at +16 with its own at +11.
|
||||
// read signed, since a target sitting below the instruction encodes as negative.
|
||||
MOTION_STATE_PREV = (int32_t *) (is_down + 7 + *(int32_t *) (is_down + 2));
|
||||
MOTION_STATE = (int32_t *) (is_down + 16 + *(int32_t *) (is_down + 11));
|
||||
|
||||
// CInputManager::UpdateMotion is hooked for the sole purpose of reading the Down Motion
|
||||
// button mapping frequently enough so that the rising edge can be detected.
|
||||
//
|
||||
// Matched over the prologue up to the camera read; the wildcards are a float and a callee:
|
||||
//
|
||||
// 48 83 EC 38 sub rsp, 0x38
|
||||
// 0F 29 74 24 20 movaps [rsp+0x20], xmm6
|
||||
// F3 0F 10 35 xx xx xx xx movss xmm6, [rip+height] ; reading as of last frame
|
||||
// E8 xx xx xx xx call GetPlayVideoProcess
|
||||
// 48 8B C8 mov rcx, rax
|
||||
// 48 8B 10 mov rdx, [rax]
|
||||
// FF 52 60 call [rdx+0x60] ; reading off the newest frame
|
||||
auto update = reinterpret_cast<void *>(find_pattern(
|
||||
avs::game::DLL_INSTANCE,
|
||||
"4883EC380F29742420F30F103500000000E800000000488BC8488B10FF5260",
|
||||
"XXXXXXXXXXXXX????X????XXXXXXXXX",
|
||||
0, 0));
|
||||
|
||||
if (update == nullptr ||
|
||||
!detour::trampoline_try(
|
||||
update, (void *) InputManager_UpdateMotion, (void **) &UpdateMotion_orig)) {
|
||||
log_warning("drs", "motion update not hooked, DOWN motion button unavailable");
|
||||
return;
|
||||
}
|
||||
|
||||
log_info("drs", "hooked DOWN motion at +{:#x}",
|
||||
(uintptr_t) ((uint8_t *) update - (uint8_t *) avs::game::DLL_INSTANCE));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
#pragma once
|
||||
|
||||
namespace games::drs {
|
||||
void init_down_motion_hook();
|
||||
}
|
||||
@@ -39,10 +39,38 @@ namespace games::gitadora {
|
||||
std::optional<socd::SocdAlgorithm> PICK_ALGO = socd::SocdAlgorithm::PreferRecent;
|
||||
std::optional<uint8_t> ARENA_WINDOW_COUNT = std::nullopt;
|
||||
bool ARENA_TWO_HEAD_EXCLUSIVE = false;
|
||||
ArenaSubscreenLandscape ARENA_SUBSCREEN_LANDSCAPE = ArenaSubscreenLandscape::Off;
|
||||
std::optional<std::string> ASIO_DRIVER = std::nullopt;
|
||||
bool ALLOW_REALTEK_AUDIO = false;
|
||||
bool NATIVE_TOUCH = false;
|
||||
|
||||
std::pair<UINT, UINT> arena_subscreen_host_size() {
|
||||
if (GRAPHICS_FS_CUSTOM_RESOLUTION_SUB.has_value()) {
|
||||
return GRAPHICS_FS_CUSTOM_RESOLUTION_SUB.value();
|
||||
}
|
||||
if (arena_subscreen_landscape()) {
|
||||
return { ARENA_SUBSCREEN_LANDSCAPE_WIDTH, ARENA_SUBSCREEN_LANDSCAPE_HEIGHT };
|
||||
}
|
||||
return { ARENA_SUBSCREEN_WIDTH, ARENA_SUBSCREEN_HEIGHT };
|
||||
}
|
||||
|
||||
RECT arena_subscreen_content_rect(LONG host_width, LONG host_height) {
|
||||
if (host_width <= 0 || host_height <= 0) {
|
||||
return RECT {};
|
||||
}
|
||||
|
||||
LONG width = MulDiv(host_height, ARENA_SUBSCREEN_WIDTH, ARENA_SUBSCREEN_HEIGHT);
|
||||
LONG height = host_height;
|
||||
if (width > host_width) {
|
||||
width = host_width;
|
||||
height = MulDiv(host_width, ARENA_SUBSCREEN_HEIGHT, ARENA_SUBSCREEN_WIDTH);
|
||||
}
|
||||
|
||||
const LONG left = (host_width - width) / 2;
|
||||
const LONG top = (host_height - height) / 2;
|
||||
return RECT { left, top, left + width, top + height };
|
||||
}
|
||||
|
||||
/*
|
||||
* Prevent GitaDora from creating folders on F drive
|
||||
*/
|
||||
@@ -343,6 +371,23 @@ namespace games::gitadora {
|
||||
"gitadora",
|
||||
"arena model: unsupported window count: {}", count);
|
||||
}
|
||||
|
||||
if (arena_subscreen_landscape() && !ARENA_TWO_HEAD_EXCLUSIVE) {
|
||||
log_warning(
|
||||
"gitadora",
|
||||
"arena model: landscape subscreen needs full screen two-window mode, ignoring");
|
||||
ARENA_SUBSCREEN_LANDSCAPE = ArenaSubscreenLandscape::Off;
|
||||
}
|
||||
if (ARENA_TWO_HEAD_EXCLUSIVE) {
|
||||
const auto [host_width, host_height] = arena_subscreen_host_size();
|
||||
if (host_width != ARENA_SUBSCREEN_WIDTH
|
||||
|| host_height != ARENA_SUBSCREEN_HEIGHT) {
|
||||
log_info(
|
||||
"gitadora",
|
||||
"arena model: SMALL head runs at {}x{}, subscreen is scaled to fit",
|
||||
host_width, host_height);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <optional>
|
||||
#include <utility>
|
||||
|
||||
#include <windows.h>
|
||||
#include <mmreg.h>
|
||||
@@ -11,6 +12,14 @@
|
||||
|
||||
namespace games::gitadora {
|
||||
|
||||
// what a landscape monitor driving the SMALL head does with the space beside the
|
||||
// portrait subscreen image
|
||||
enum class ArenaSubscreenLandscape {
|
||||
Off, // SMALL head stays portrait
|
||||
Small, // subscreen centered, the space either side stays black
|
||||
All, // that space shows the LEFT and RIGHT heads instead
|
||||
};
|
||||
|
||||
// settings
|
||||
extern bool TWOCHANNEL;
|
||||
extern bool DISABLE_FRAME_LIMITER;
|
||||
@@ -21,14 +30,35 @@ namespace games::gitadora {
|
||||
extern std::optional<socd::SocdAlgorithm> PICK_ALGO;
|
||||
extern std::optional<uint8_t> ARENA_WINDOW_COUNT;
|
||||
extern bool ARENA_TWO_HEAD_EXCLUSIVE;
|
||||
extern ArenaSubscreenLandscape ARENA_SUBSCREEN_LANDSCAPE;
|
||||
extern std::optional<std::string> ASIO_DRIVER;
|
||||
extern bool ALLOW_REALTEK_AUDIO;
|
||||
extern bool NATIVE_TOUCH;
|
||||
|
||||
static inline bool arena_subscreen_landscape() {
|
||||
return ARENA_SUBSCREEN_LANDSCAPE != ArenaSubscreenLandscape::Off;
|
||||
}
|
||||
|
||||
static inline bool arena_subscreen_shows_sides() {
|
||||
return ARENA_SUBSCREEN_LANDSCAPE == ArenaSubscreenLandscape::All;
|
||||
}
|
||||
|
||||
// arena SMALL subscreen (touch panel) resolution
|
||||
static constexpr int ARENA_SUBSCREEN_WIDTH = 800;
|
||||
static constexpr int ARENA_SUBSCREEN_HEIGHT = 1280;
|
||||
|
||||
// used when a landscape monitor drives the SMALL head and -forceressub is unset
|
||||
static constexpr int ARENA_SUBSCREEN_LANDSCAPE_WIDTH = 1920;
|
||||
static constexpr int ARENA_SUBSCREEN_LANDSCAPE_HEIGHT = 1080;
|
||||
|
||||
// resolution the SMALL head actually runs at; the portrait panel size unless
|
||||
// -forceressub or the landscape option overrides it
|
||||
std::pair<UINT, UINT> arena_subscreen_host_size();
|
||||
|
||||
// area of the host the portrait subscreen occupies, centered and aspect-preserved;
|
||||
// whatever is left over on either side stays black
|
||||
RECT arena_subscreen_content_rect(LONG host_width, LONG host_height);
|
||||
|
||||
class GitaDoraGame : public games::Game {
|
||||
public:
|
||||
GitaDoraGame();
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#if SPICE64 && !SPICE_XP
|
||||
|
||||
#include <array>
|
||||
#include <d3d9.h>
|
||||
#include "mf_wrappers.h"
|
||||
#include "avs/game.h"
|
||||
@@ -46,9 +47,7 @@ struct PredefinedHook {
|
||||
uintptr_t hook_afp_texture_offset;
|
||||
};
|
||||
|
||||
PredefinedHook g_predefinedHooks[] = {};
|
||||
|
||||
const DWORD g_predefinedHooksLength = ARRAYSIZE(g_predefinedHooks);
|
||||
std::array<PredefinedHook, 0> g_predefinedHooks = {};
|
||||
|
||||
namespace games::iidx {
|
||||
|
||||
@@ -110,14 +109,14 @@ namespace games::iidx {
|
||||
auto pe = fmt::format("{:x}_{:x}", time_date_stamp, address_of_entry_point);
|
||||
log_info("iidx:camhook", "Locating predefined hook addresses for LDJ-{}", pe);
|
||||
|
||||
for (DWORD i = 0; i < g_predefinedHooksLength; i++) {
|
||||
if (pe.compare(g_predefinedHooks[i].pe_identifier) == 0) {
|
||||
for (auto &hook : g_predefinedHooks) {
|
||||
if (pe.compare(hook.pe_identifier) == 0) {
|
||||
log_misc("iidx:camhook", "Found predefined addresses");
|
||||
addr_hook_a = g_predefinedHooks[i].hook_a;
|
||||
addr_textures = g_predefinedHooks[i].hook_textures;
|
||||
addr_camera_manager = g_predefinedHooks[i].hook_camera_manager;
|
||||
addr_device_offset = g_predefinedHooks[i].hook_device_offset;
|
||||
addr_afp_texture_offset = g_predefinedHooks[i].hook_afp_texture_offset;
|
||||
addr_hook_a = hook.hook_a;
|
||||
addr_textures = hook.hook_textures;
|
||||
addr_camera_manager = hook.hook_camera_manager;
|
||||
addr_device_offset = hook.hook_device_offset;
|
||||
addr_afp_texture_offset = hook.hook_afp_texture_offset;
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
@@ -200,11 +199,11 @@ namespace games::iidx {
|
||||
addr_camera_manager = (addr_camera_manager_ptr - (uint8_t*) iidx_module) + disp_camera_manager + 7;
|
||||
|
||||
// addr_device_offset
|
||||
search_from = (addr_hook_a_ptr - (uint8_t*) iidx_module);
|
||||
search_from = addr_hook_a;
|
||||
uint8_t *addr_device_ptr = reinterpret_cast<uint8_t *>(find_pattern_from(
|
||||
iidx_module,
|
||||
"488B89",
|
||||
"XXX",
|
||||
"488B8F00000000488B014C8B870000000033D2FF9028010000",
|
||||
"XXX????XXXXXX????XXXXXXXX",
|
||||
3, 0, search_from));
|
||||
|
||||
if (addr_device_ptr == nullptr) {
|
||||
@@ -212,7 +211,7 @@ namespace games::iidx {
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
addr_device_offset = *addr_device_ptr;
|
||||
addr_device_offset = *reinterpret_cast<uint32_t*>(addr_device_ptr);
|
||||
|
||||
// --- addr_afp_texture_offset ---
|
||||
uint8_t *addr_afp_texture_ptr = reinterpret_cast<uint8_t *>(find_pattern(
|
||||
@@ -234,13 +233,27 @@ namespace games::iidx {
|
||||
static void **__fastcall camera_hook_a(PBYTE a1) {
|
||||
std::call_once(hook_a_init, [&]{
|
||||
device = *reinterpret_cast<LPDIRECT3DDEVICE9EX*>(a1 + addr_device_offset);
|
||||
auto const preview = *reinterpret_cast<LPDIRECT3DTEXTURE9**>((uint8_t*)iidx_module + addr_textures);
|
||||
auto const registry = reinterpret_cast<Camera::TextureRegistry*>(
|
||||
reinterpret_cast<uint8_t*>(iidx_module) + addr_textures - offsetof(Camera::TextureRegistry, begin));
|
||||
auto const manager = reinterpret_cast<Camera::CCameraManager2*>((uint8_t*)iidx_module + addr_camera_manager);
|
||||
|
||||
camera_texture_a = manager->cameras->a->d3d9_texture(addr_afp_texture_offset);
|
||||
camera_texture_b = manager->cameras->b->d3d9_texture(addr_afp_texture_offset);
|
||||
preview_texture_a = preview;
|
||||
preview_texture_b = preview + 2;
|
||||
auto const camera_count = manager->begin ? manager->end - manager->begin : 0;
|
||||
auto const bind_camera = [&](size_t index, LPDIRECT3DTEXTURE9*& texture, LPDIRECT3DTEXTURE9*& preview) {
|
||||
if (index >= static_cast<size_t>(camera_count)) {
|
||||
return; // IIDX 34 only has the TOP camera.
|
||||
}
|
||||
auto const camera = manager->begin[index];
|
||||
auto const afp = camera ? camera->afp_texture(addr_afp_texture_offset) : nullptr;
|
||||
if (!afp || !registry->begin || afp->handle < registry->handle_base ||
|
||||
afp->handle - registry->handle_base >= registry->end - registry->begin) {
|
||||
log_warning("iidx:camhook", "invalid texture destination for camera {}", index);
|
||||
return;
|
||||
}
|
||||
texture = &afp->texture;
|
||||
preview = registry->begin + (afp->handle - registry->handle_base);
|
||||
};
|
||||
bind_camera(0, camera_texture_a, preview_texture_a);
|
||||
bind_camera(1, camera_texture_b, preview_texture_b);
|
||||
|
||||
init_local_camera();
|
||||
});
|
||||
@@ -382,10 +395,10 @@ namespace games::iidx {
|
||||
log_misc("iidx:camhook", "Adding user-preferred cameras");
|
||||
for (size_t i = 0; i < numDevices && LOCAL_CAMERA_LIST.size() < 2; i++) {
|
||||
auto pActivate = ppDevices[i];
|
||||
if ((int)i == preferred_top_index && top_camera == nullptr) {
|
||||
if ((int)i == preferred_top_index && top_camera == nullptr && camera_texture_a != nullptr) {
|
||||
log_misc("iidx:camhook", "Adding user-preferred top camera {} / '{}'", i, top_camera_id);
|
||||
top_camera = add_top_camera(pActivate);
|
||||
} else if ((int)i == preferred_front_index && front_camera == nullptr) {
|
||||
} else if ((int)i == preferred_front_index && front_camera == nullptr && camera_texture_b != nullptr) {
|
||||
log_misc("iidx:camhook", "Adding user-preferred front camera {} / '{}'", i, front_camera_id);
|
||||
front_camera = add_front_camera(pActivate);
|
||||
}
|
||||
@@ -403,16 +416,16 @@ namespace games::iidx {
|
||||
|
||||
if (!FLIP_CAMS) {
|
||||
// top camera first, then front
|
||||
if (top_camera == nullptr) {
|
||||
if (top_camera == nullptr && camera_texture_a != nullptr) {
|
||||
top_camera = add_top_camera(pActivate);
|
||||
} else if (front_camera == nullptr) {
|
||||
} else if (front_camera == nullptr && camera_texture_b != nullptr) {
|
||||
front_camera = add_front_camera(pActivate);
|
||||
}
|
||||
} else {
|
||||
// front first, then top
|
||||
if (front_camera == nullptr) {
|
||||
if (front_camera == nullptr && camera_texture_b != nullptr) {
|
||||
front_camera = add_front_camera(pActivate);
|
||||
} else if (top_camera == nullptr) {
|
||||
} else if (top_camera == nullptr && camera_texture_a != nullptr) {
|
||||
top_camera = add_top_camera(pActivate);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,21 +70,31 @@ namespace games::iidx {
|
||||
class IIDXCameraSourceReaderCallback;
|
||||
|
||||
namespace Camera {
|
||||
struct AfpTexture {
|
||||
void* vftbl;
|
||||
IDirect3DTexture9* texture;
|
||||
uint32_t handle;
|
||||
};
|
||||
|
||||
struct TextureRegistry {
|
||||
uint32_t handle_base;
|
||||
uint32_t next_slot;
|
||||
IDirect3DTexture9** begin;
|
||||
IDirect3DTexture9** end;
|
||||
IDirect3DTexture9** capacity_end;
|
||||
};
|
||||
|
||||
struct PlayVideoCamera {
|
||||
IDirect3DTexture9** d3d9_texture(const uintptr_t offset) {
|
||||
auto const afp_texture = *reinterpret_cast<uint8_t**>
|
||||
(reinterpret_cast<uint8_t*>(this) + offset);
|
||||
return reinterpret_cast<IDirect3DTexture9**>(afp_texture + 0x8);
|
||||
AfpTexture* afp_texture(const uintptr_t offset) {
|
||||
return *reinterpret_cast<AfpTexture**>(reinterpret_cast<uint8_t*>(this) + offset);
|
||||
}
|
||||
};
|
||||
|
||||
struct CCameraManager2 {
|
||||
using camera_pointers = struct {
|
||||
PlayVideoCamera* a;
|
||||
PlayVideoCamera* b;
|
||||
};
|
||||
void* vftbl;
|
||||
camera_pointers* cameras;
|
||||
PlayVideoCamera** begin;
|
||||
PlayVideoCamera** end;
|
||||
PlayVideoCamera** capacity_end;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -37,6 +37,8 @@
|
||||
#include "qks/io.h"
|
||||
#include "mfg/io.h"
|
||||
#include "pc/io.h"
|
||||
#include "udn/io.h"
|
||||
#include "cardconnect/io.h"
|
||||
|
||||
namespace games {
|
||||
|
||||
@@ -299,6 +301,7 @@ namespace games {
|
||||
buttons.insert({ bc, bc::get_buttons() });
|
||||
buttons_help.insert({ bc, bc::get_buttons_help() });
|
||||
analogs.insert({ bc, bc::get_analogs() });
|
||||
lights.insert({ bc, bc::get_lights() });
|
||||
file_hints[bc].push_back({"game/bsac_app.exe"});
|
||||
|
||||
// ccj
|
||||
@@ -332,6 +335,21 @@ namespace games {
|
||||
analogs.insert({ pc, pc::get_analogs() });
|
||||
lights.insert({ pc, pc::get_lights() });
|
||||
file_hints[pc].push_back({"game/svm.exe"});
|
||||
|
||||
// DANCE aROUND
|
||||
const std::string udn("DANCE aROUND");
|
||||
games.push_back(udn);
|
||||
buttons.insert({ udn, udn::get_buttons() });
|
||||
buttons_help.insert({ udn, udn::get_buttons_help() });
|
||||
lights.insert({ udn, udn::get_lights() });
|
||||
file_hints[udn].push_back({"game/dancearound_Data"});
|
||||
|
||||
// Card Connect
|
||||
const std::string cardconnect("Card Connect");
|
||||
games.push_back(cardconnect);
|
||||
buttons.insert({ cardconnect, cardconnect::get_buttons() });
|
||||
lights.insert({ cardconnect, cardconnect::get_lights() });
|
||||
file_hints[cardconnect].push_back({"game/tcs.exe"});
|
||||
}
|
||||
|
||||
const std::vector<std::string> &get_games() {
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
#if SPICE64 && !SPICE_XP
|
||||
|
||||
#include <array>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <cstdint>
|
||||
#include "util/detour.h"
|
||||
@@ -141,10 +143,100 @@ namespace games::popn {
|
||||
static AIO_SCI_COMM *aioSciComm;
|
||||
static AIO_IOB5_BI3A *aioIob5Bi3a;
|
||||
|
||||
static constexpr size_t PIKA_BUTTON_COUNT = 9;
|
||||
static constexpr size_t PIKA_BUTTON_DATA_SIZE = PIKA_BUTTON_COUNT * 3;
|
||||
static std::array<uint8_t, PIKA_BUTTON_DATA_SIZE> pika_button_staging{};
|
||||
static bool pika_button_staging_dirty = false;
|
||||
static std::mutex pika_button_staging_mutex;
|
||||
|
||||
/*
|
||||
* implementations
|
||||
*/
|
||||
|
||||
static void publish_pika_button_staging() {
|
||||
std::array<uint8_t, PIKA_BUTTON_DATA_SIZE> data;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(pika_button_staging_mutex);
|
||||
if (!pika_button_staging_dirty) {
|
||||
return;
|
||||
}
|
||||
data = pika_button_staging;
|
||||
pika_button_staging_dirty = false;
|
||||
}
|
||||
|
||||
constexpr Lights::popn_lights_t legacy_button_lights[] = {
|
||||
Lights::popn_lights_t::Button1,
|
||||
Lights::popn_lights_t::Button2,
|
||||
Lights::popn_lights_t::Button3,
|
||||
Lights::popn_lights_t::Button4,
|
||||
Lights::popn_lights_t::Button5,
|
||||
Lights::popn_lights_t::Button6,
|
||||
Lights::popn_lights_t::Button7,
|
||||
Lights::popn_lights_t::Button8,
|
||||
Lights::popn_lights_t::Button9
|
||||
};
|
||||
constexpr Lights::popn_lights_t button_lights[] = {
|
||||
Lights::popn_lights_t::PikaButton1_R,
|
||||
Lights::popn_lights_t::PikaButton1_G,
|
||||
Lights::popn_lights_t::PikaButton1_B,
|
||||
Lights::popn_lights_t::PikaButton2_R,
|
||||
Lights::popn_lights_t::PikaButton2_G,
|
||||
Lights::popn_lights_t::PikaButton2_B,
|
||||
Lights::popn_lights_t::PikaButton3_R,
|
||||
Lights::popn_lights_t::PikaButton3_G,
|
||||
Lights::popn_lights_t::PikaButton3_B,
|
||||
Lights::popn_lights_t::PikaButton4_R,
|
||||
Lights::popn_lights_t::PikaButton4_G,
|
||||
Lights::popn_lights_t::PikaButton4_B,
|
||||
Lights::popn_lights_t::PikaButton5_R,
|
||||
Lights::popn_lights_t::PikaButton5_G,
|
||||
Lights::popn_lights_t::PikaButton5_B,
|
||||
Lights::popn_lights_t::PikaButton6_R,
|
||||
Lights::popn_lights_t::PikaButton6_G,
|
||||
Lights::popn_lights_t::PikaButton6_B,
|
||||
Lights::popn_lights_t::PikaButton7_R,
|
||||
Lights::popn_lights_t::PikaButton7_G,
|
||||
Lights::popn_lights_t::PikaButton7_B,
|
||||
Lights::popn_lights_t::PikaButton8_R,
|
||||
Lights::popn_lights_t::PikaButton8_G,
|
||||
Lights::popn_lights_t::PikaButton8_B,
|
||||
Lights::popn_lights_t::PikaButton9_R,
|
||||
Lights::popn_lights_t::PikaButton9_G,
|
||||
Lights::popn_lights_t::PikaButton9_B
|
||||
};
|
||||
|
||||
static_assert(std::size(legacy_button_lights) == PIKA_BUTTON_COUNT);
|
||||
static_assert(std::size(button_lights) == PIKA_BUTTON_DATA_SIZE);
|
||||
|
||||
auto &lights = get_lights();
|
||||
for (size_t button = 0; button < PIKA_BUTTON_COUNT; button++) {
|
||||
const auto data_offset = button * 3;
|
||||
// special handling converting RGB data to non-RGB lights
|
||||
// take the max(R, G, B) and use it to write the light value
|
||||
const auto light_value = std::max({
|
||||
data[data_offset],
|
||||
data[data_offset + 1],
|
||||
data[data_offset + 2]
|
||||
});
|
||||
|
||||
// on the new cab, buttons are colorless plastic and rely on RGB to be lit
|
||||
// at all times, even when "off". When translating to legacy on/off lights,
|
||||
// treat only values above about 60% brightness as fully on to preserve the
|
||||
// dim "off" state.
|
||||
GameAPI::Lights::writeLight(
|
||||
RI_MGR,
|
||||
lights.at(legacy_button_lights[button]),
|
||||
light_value > 150 ? 1.f : 0.f);
|
||||
}
|
||||
|
||||
for (size_t light = 0; light < data.size(); light++) {
|
||||
GameAPI::Lights::writeLight(
|
||||
RI_MGR,
|
||||
lights.at(button_lights[light]),
|
||||
data[light] / 255.f);
|
||||
}
|
||||
}
|
||||
|
||||
// libaio.dll
|
||||
|
||||
static AIO_SCI_COMM_T *__fastcall aioSciComm_Open(AIO_SCI_COMM_T *unk) {
|
||||
@@ -260,6 +352,11 @@ namespace games::popn {
|
||||
log_info("bi3a_hook", "aioIob5Bi3a_Create called with i_pNodeMgr={}, i={}, p={}", fmt::ptr(i_pNodeMgr), i, fmt::ptr(p));
|
||||
|
||||
if (i_pNodeMgr == aioNmgrIob5) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(pika_button_staging_mutex);
|
||||
pika_button_staging.fill(0);
|
||||
pika_button_staging_dirty = false;
|
||||
}
|
||||
aioIob5Bi3a = new AIO_IOB5_BI3A;
|
||||
log_info("bi3a_hook", "aioIob5Bi3a_Create: returning custom AIO_IOB5_BI3A: {}", fmt::ptr(aioIob5Bi3a));
|
||||
return aioIob5Bi3a;
|
||||
@@ -269,11 +366,15 @@ namespace games::popn {
|
||||
}
|
||||
|
||||
static void __fastcall aioIob5Bi3a_GetDeviceStatus(AIO_IOB5_BI3A *i_pNodeCtl, AIO_IOB5_BI3A__DEVSTATUS *o_DevStatus) {
|
||||
RI_MGR->devices_flush_output();
|
||||
if (i_pNodeCtl != aioIob5Bi3a) {
|
||||
return aioIob5Bi3a_GetDeviceStatus_orig(i_pNodeCtl, o_DevStatus);
|
||||
}
|
||||
|
||||
// snapshot the current state of lights and flush the output
|
||||
// this closely mirrors what the game does with real I/O
|
||||
publish_pika_button_staging();
|
||||
RI_MGR->devices_flush_output();
|
||||
|
||||
memset(o_DevStatus, 0, sizeof(*o_DevStatus));
|
||||
auto &buttons = get_buttons();
|
||||
|
||||
@@ -413,61 +514,15 @@ namespace games::popn {
|
||||
i_CnPin, number_of_leds, (uint8_t)i_LedType, fmt::ptr(i_pData), data);
|
||||
}
|
||||
|
||||
auto &lights = get_lights();
|
||||
if (i_CnPin == 0 && number_of_leds == 9 * 3) {
|
||||
// special handling converting to non-RGB lights
|
||||
// take the max(R, G, B) and use it to write the light value
|
||||
uint8_t light_value[9] = { 0 };
|
||||
for (uint32_t i = 0; i < number_of_leds; i += 3) {
|
||||
light_value[i / 3] =
|
||||
std::max({ ((uint8_t *)i_pData)[i], ((uint8_t *)i_pData)[i + 1], ((uint8_t *)i_pData)[i + 2] });
|
||||
}
|
||||
|
||||
constexpr Lights::popn_lights_t legacy_button_lights[] = {
|
||||
Lights::popn_lights_t::Button1,
|
||||
Lights::popn_lights_t::Button2,
|
||||
Lights::popn_lights_t::Button3,
|
||||
Lights::popn_lights_t::Button4,
|
||||
Lights::popn_lights_t::Button5,
|
||||
Lights::popn_lights_t::Button6,
|
||||
Lights::popn_lights_t::Button7,
|
||||
Lights::popn_lights_t::Button8,
|
||||
Lights::popn_lights_t::Button9
|
||||
};
|
||||
|
||||
static_assert(std::size(legacy_button_lights) == 9);
|
||||
|
||||
for (size_t light = 0; light < 9; light++) {
|
||||
// on the new cab, buttons are colorless plastic and they rely on RGB to be lit at all times, even when "off"
|
||||
// when translating to legacy on/off lights, treat anything above ~60% brightness as fully on,
|
||||
// otherwise off, to avoid dimly lit "off" state
|
||||
GameAPI::Lights::writeLight(
|
||||
RI_MGR,
|
||||
lights.at(legacy_button_lights[light]),
|
||||
light_value[light] > 150 ? 1.f : 0.f);
|
||||
}
|
||||
|
||||
// color buttons
|
||||
constexpr Lights::popn_lights_t button_lights[] = {
|
||||
Lights::popn_lights_t::PikaButton1_R, Lights::popn_lights_t::PikaButton1_G, Lights::popn_lights_t::PikaButton1_B,
|
||||
Lights::popn_lights_t::PikaButton2_R, Lights::popn_lights_t::PikaButton2_G, Lights::popn_lights_t::PikaButton2_B,
|
||||
Lights::popn_lights_t::PikaButton3_R, Lights::popn_lights_t::PikaButton3_G, Lights::popn_lights_t::PikaButton3_B,
|
||||
Lights::popn_lights_t::PikaButton4_R, Lights::popn_lights_t::PikaButton4_G, Lights::popn_lights_t::PikaButton4_B,
|
||||
Lights::popn_lights_t::PikaButton5_R, Lights::popn_lights_t::PikaButton5_G, Lights::popn_lights_t::PikaButton5_B,
|
||||
Lights::popn_lights_t::PikaButton6_R, Lights::popn_lights_t::PikaButton6_G, Lights::popn_lights_t::PikaButton6_B,
|
||||
Lights::popn_lights_t::PikaButton7_R, Lights::popn_lights_t::PikaButton7_G, Lights::popn_lights_t::PikaButton7_B,
|
||||
Lights::popn_lights_t::PikaButton8_R, Lights::popn_lights_t::PikaButton8_G, Lights::popn_lights_t::PikaButton8_B,
|
||||
Lights::popn_lights_t::PikaButton9_R, Lights::popn_lights_t::PikaButton9_G, Lights::popn_lights_t::PikaButton9_B
|
||||
};
|
||||
|
||||
static_assert(std::size(button_lights) == 9 * 3);
|
||||
|
||||
for (size_t light = 0; light < number_of_leds; light++) {
|
||||
GameAPI::Lights::writeLight(
|
||||
RI_MGR,
|
||||
lights.at(button_lights[light]),
|
||||
((uint8_t *)i_pData)[light] / 255.f);
|
||||
}
|
||||
// SetTapeLedDataPart is meant to be a temporary staging buffer, so the game occasionally
|
||||
// clears the buffer (set to 0 / lights off) between animations but they are not meant
|
||||
// to be seen by the I/O
|
||||
// therefore, instead of writing the lights out directly here, we stage them in a buffer
|
||||
// and wait for GetDeviceStatus to be called
|
||||
std::lock_guard<std::mutex> lock(pika_button_staging_mutex);
|
||||
memcpy(pika_button_staging.data(), i_pData, pika_button_staging.size());
|
||||
pika_button_staging_dirty = true;
|
||||
}
|
||||
|
||||
if (tapeledutils::is_enabled() && i_CnPin > 0 && i_CnPin < std::size(TAPELED_MAPPING)) {
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
#include "hooks/devicehook.h"
|
||||
#include "hooks/libraryhook.h"
|
||||
#ifdef SPICE64
|
||||
#include <psapi.h>
|
||||
#include "hooks/graphics/nvapi_impl.h"
|
||||
#endif
|
||||
#include "hooks/graphics/nvapi_hook.h"
|
||||
@@ -40,6 +41,9 @@ static decltype(RegEnumKeyA) *RegEnumKeyA_orig = nullptr;
|
||||
static decltype(RegOpenKeyA) *RegOpenKeyA_orig = nullptr;
|
||||
static decltype(RegOpenKeyExA) *RegOpenKeyExA_orig = nullptr;
|
||||
static decltype(RegQueryValueExA) *RegQueryValueExA_orig = nullptr;
|
||||
#ifdef SPICE64
|
||||
static decltype(K32GetPerformanceInfo) *K32GetPerformanceInfo_orig = nullptr;
|
||||
#endif
|
||||
|
||||
namespace games::sdvx {
|
||||
|
||||
@@ -200,6 +204,29 @@ namespace games::sdvx {
|
||||
}
|
||||
|
||||
#ifdef SPICE64
|
||||
|
||||
static BOOL WINAPI K32GetPerformanceInfo_hook(PPERFORMANCE_INFORMATION info, DWORD cb) {
|
||||
if (info == nullptr) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return FALSE;
|
||||
}
|
||||
if (cb < sizeof(*info)) {
|
||||
SetLastError(ERROR_BAD_LENGTH);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
// store a cached copy of the first successful call to K32GetPerformanceInfo
|
||||
static PERFORMANCE_INFORMATION cached {};
|
||||
static const BOOL cached_valid = K32GetPerformanceInfo_orig(&cached, sizeof(cached));
|
||||
if (!cached_valid) {
|
||||
return K32GetPerformanceInfo_orig(info, cb);
|
||||
}
|
||||
|
||||
// return the cached copy to avoid performance issues with the game calling this every frame
|
||||
*info = cached;
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
static bool sdvx64_spam_remover(void *user, const std::string &data, logger::Style style, std::string &out) {
|
||||
if (data.empty() || data[0] != '[') {
|
||||
return false;
|
||||
@@ -534,6 +561,14 @@ namespace games::sdvx {
|
||||
if (is_valkyrie_model()) {
|
||||
sysutils::hook_EnumDisplayDevicesA();
|
||||
}
|
||||
|
||||
// keep one real snapshot for the session instead of querying statistics every frame
|
||||
K32GetPerformanceInfo_orig = detour::iat_try(
|
||||
"K32GetPerformanceInfo", K32GetPerformanceInfo_hook, avs::game::DLL_INSTANCE);
|
||||
if (K32GetPerformanceInfo_orig != nullptr) {
|
||||
log_info("sdvx", "installed cached hook for K32GetPerformanceInfo");
|
||||
}
|
||||
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include <vector>
|
||||
#include <thread>
|
||||
#include <limits>
|
||||
|
||||
#include "avs/game.h"
|
||||
#include "hooks/sleephook.h"
|
||||
@@ -264,7 +265,9 @@ namespace games::shared {
|
||||
|
||||
typedef void (CALLBACK *PFNACBfunc)(DWORD dwErr, short PrintFlag, short PrintUsbNo, long nJid, int CopyNumber);
|
||||
|
||||
static inline std::string get_image_out_path(bool clear, std::string path, const std::string &format) {
|
||||
static std::vector<std::string> get_image_out_paths(
|
||||
bool clear, std::string path, const std::string &format,
|
||||
const std::vector<std::string> &suffixes, bool overwrite = false) {
|
||||
|
||||
// check path
|
||||
if (path.empty()) {
|
||||
@@ -277,28 +280,99 @@ namespace games::shared {
|
||||
path = std::string(path.c_str(), path.length() - 1);
|
||||
|
||||
// find non-existing filename
|
||||
static std::string prefix = "printer_";
|
||||
for (int n = 0; n < 4096; n++) {
|
||||
std::ostringstream filename_s;
|
||||
filename_s << path << "\\" << prefix << n << "." << format;
|
||||
std::string filename = filename_s.str();
|
||||
if (clear && fileutils::file_exists(filename.c_str())) {
|
||||
log_info("printer", "deleting {}...", filename);
|
||||
DeleteFile(filename.c_str());
|
||||
if (PRINTER_OVERWRITE_FILE) {
|
||||
return filename;
|
||||
std::vector<std::string> filenames;
|
||||
bool exists = false;
|
||||
for (const auto &suffix : suffixes) {
|
||||
auto filename = fmt::format("{}\\printer_{}{}.{}", path, n, suffix, format);
|
||||
if (fileutils::file_exists(filename.c_str())) {
|
||||
exists = true;
|
||||
if (clear) {
|
||||
log_info("printer", "deleting {}...", filename);
|
||||
if (!DeleteFileA(filename.c_str())) {
|
||||
log_warning("printer", "could not delete {}: {}", filename, GetLastError());
|
||||
return {};
|
||||
}
|
||||
}
|
||||
}
|
||||
filenames.push_back(std::move(filename));
|
||||
}
|
||||
if ((!clear && !exists) || overwrite) {
|
||||
return filenames;
|
||||
}
|
||||
}
|
||||
|
||||
if (!clear) {
|
||||
log_warning("printer", "could not find an unused printer output filename");
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
bool printer_write_image(const uint8_t *data, int width, int height, int components,
|
||||
const std::string &suffix) {
|
||||
return printer_write_images({{data, width, height, components, suffix}});
|
||||
}
|
||||
|
||||
bool printer_write_images(std::initializer_list<PrinterImage> images) {
|
||||
if (images.size() == 0 || PRINTER_PATH.empty() || PRINTER_FORMAT.empty()) {
|
||||
log_warning("printer", "printer output is uninitialized or contains no images");
|
||||
return false;
|
||||
}
|
||||
std::vector<std::string> suffixes;
|
||||
for (const auto &image : images) {
|
||||
if (!image.data || image.width <= 0 || image.height <= 0 ||
|
||||
(image.components != 1 && image.components != 3) ||
|
||||
image.width > std::numeric_limits<int>::max() / image.components / image.height) {
|
||||
log_warning("printer", "invalid image supplied for printer output");
|
||||
return false;
|
||||
}
|
||||
suffixes.push_back(image.suffix);
|
||||
}
|
||||
bool all_saved = true;
|
||||
for (const auto &path : PRINTER_PATH) {
|
||||
for (const auto &format : PRINTER_FORMAT) {
|
||||
const auto image_paths = get_image_out_paths(
|
||||
PRINTER_OVERWRITE_FILE, path, format, suffixes, PRINTER_OVERWRITE_FILE);
|
||||
if (image_paths.size() != images.size()) {
|
||||
log_warning("printer", "could not allocate printer output paths in {}", path);
|
||||
all_saved = false;
|
||||
continue;
|
||||
}
|
||||
size_t index = 0;
|
||||
for (const auto &image : images) {
|
||||
const auto &image_path = image_paths[index++];
|
||||
bool success = false;
|
||||
if (format == "png") {
|
||||
success = stbi_write_png(
|
||||
image_path.c_str(), image.width, image.height, image.components,
|
||||
image.data, image.width * image.components);
|
||||
} else if (format == "bmp") {
|
||||
success = stbi_write_bmp(image_path.c_str(), image.width, image.height,
|
||||
image.components, image.data);
|
||||
} else if (format == "tga") {
|
||||
success = stbi_write_tga(image_path.c_str(), image.width, image.height,
|
||||
image.components, image.data);
|
||||
} else if (format == "jpg") {
|
||||
success = stbi_write_jpg(
|
||||
image_path.c_str(), image.width, image.height, image.components,
|
||||
image.data, PRINTER_JPG_QUALITY);
|
||||
}
|
||||
if (success) {
|
||||
log_info("printer", "printer emulation has written an image to {}", image_path);
|
||||
overlay::notifications::add(
|
||||
overlay::notifications::Severity::Success,
|
||||
fmt::format("Printer: saved {}", fileutils::basename(image_path)));
|
||||
} else {
|
||||
all_saved = false;
|
||||
log_warning("printer", "printer emulation failed to write image to {}", image_path);
|
||||
overlay::notifications::add(
|
||||
overlay::notifications::Severity::Error,
|
||||
fmt::format("Printer: failed to write {}", fileutils::basename(image_path)));
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (!fileutils::file_exists(filename.c_str()))
|
||||
return filename;
|
||||
}
|
||||
|
||||
// error
|
||||
if (!clear) {
|
||||
log_fatal("printer", "could not find path");
|
||||
}
|
||||
|
||||
return "DUMMY";
|
||||
return all_saved;
|
||||
}
|
||||
|
||||
static inline bool process_image_print(const CPDBandImageParams *pBandImage) {
|
||||
@@ -372,43 +446,8 @@ namespace games::shared {
|
||||
}
|
||||
}
|
||||
|
||||
// iterate folders
|
||||
log_misc("printer", "writing files...");
|
||||
for (const auto &path : PRINTER_PATH) {
|
||||
for (const auto &format : PRINTER_FORMAT) {
|
||||
|
||||
// get image path
|
||||
std::string image_path = get_image_out_path(PRINTER_OVERWRITE_FILE, path, format);
|
||||
bool success = false;
|
||||
|
||||
// call write function depending on format
|
||||
if (format == "png" && stbi_write_png(
|
||||
image_path.c_str(), image_width, image_height, 3, image_data, image_width * 3))
|
||||
success = true;
|
||||
if (format == "bmp" && stbi_write_bmp(
|
||||
image_path.c_str(), image_width, image_height, 3, image_data))
|
||||
success = true;
|
||||
if (format == "tga" && stbi_write_tga(
|
||||
image_path.c_str(), image_width, image_height, 3, image_data))
|
||||
success = true;
|
||||
if (format == "jpg" && stbi_write_jpg(
|
||||
image_path.c_str(), image_width, image_height, 3, image_data, PRINTER_JPG_QUALITY))
|
||||
success = true;
|
||||
|
||||
// logging
|
||||
if (success) {
|
||||
log_info("printer", "printer emulation has written an image to {}", image_path);
|
||||
overlay::notifications::add(
|
||||
overlay::notifications::Severity::Success,
|
||||
fmt::format("Printer: saved {}", fileutils::basename(image_path)));
|
||||
} else {
|
||||
log_warning("printer", "printer emulation failed to write image to {}", image_path);
|
||||
overlay::notifications::add(
|
||||
overlay::notifications::Severity::Error,
|
||||
fmt::format("Printer: failed to write {}", fileutils::basename(image_path)));
|
||||
}
|
||||
}
|
||||
}
|
||||
// preserve the legacy caller's success behavior after reporting file errors
|
||||
printer_write_image(image_data, image_width, image_height, 3);
|
||||
|
||||
// clean up
|
||||
delete[] image_data;
|
||||
@@ -555,9 +594,7 @@ namespace games::shared {
|
||||
log_info("printer", "CPUXInit called");
|
||||
}
|
||||
|
||||
void printer_attach() {
|
||||
log_info("printer", "SpiceTools Printer");
|
||||
|
||||
void printer_init_output(std::initializer_list<std::string> suffixes) {
|
||||
// default parameters
|
||||
if (PRINTER_PATH.empty()) {
|
||||
PRINTER_PATH.emplace_back(".");
|
||||
@@ -588,10 +625,15 @@ namespace games::shared {
|
||||
PRINTER_CLEAR = false;
|
||||
for (const auto &path : PRINTER_PATH) {
|
||||
for (const auto &format : PRINTER_FORMAT) {
|
||||
get_image_out_path(true, path, format);
|
||||
get_image_out_paths(true, path, format, suffixes);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void printer_attach() {
|
||||
log_info("printer", "SpiceTools Printer");
|
||||
printer_init_output();
|
||||
|
||||
// IAT hooks
|
||||
detour::iat_try("CPU9CheckPaperRemain", CPU9CheckPaperRemain);
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <cstdint>
|
||||
#include <initializer_list>
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
@@ -15,4 +17,16 @@ namespace games::shared {
|
||||
extern bool PRINTER_OVERWRITE_FILE;
|
||||
|
||||
void printer_attach();
|
||||
struct PrinterImage {
|
||||
const uint8_t *data;
|
||||
int width;
|
||||
int height;
|
||||
int components;
|
||||
std::string suffix;
|
||||
};
|
||||
|
||||
void printer_init_output(std::initializer_list<std::string> suffixes = {""});
|
||||
bool printer_write_images(std::initializer_list<PrinterImage> images);
|
||||
bool printer_write_image(const uint8_t *data, int width, int height, int components,
|
||||
const std::string &suffix = "");
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
#include "projector.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <cwchar>
|
||||
|
||||
#include "util/logging.h"
|
||||
|
||||
namespace {
|
||||
|
||||
// request/response layout: identifier, command, two zero bytes, payload length,
|
||||
// the payload itself and a checksum over everything before it
|
||||
constexpr size_t HEADER_SIZE = 5;
|
||||
constexpr uint8_t RESPONSE_ID = 0x23;
|
||||
|
||||
constexpr uint8_t COMMAND_COMMON_DATA = 0x8A;
|
||||
constexpr uint8_t COMMAND_TEMPERATURE = 0x99;
|
||||
constexpr uint8_t COMMAND_LAMP_CURRENT = 0x9B;
|
||||
|
||||
// shown in the test menu as PROJTIM, PROJHEATIN and PROJHEAT
|
||||
constexpr uint32_t LAMP_SECONDS = 0;
|
||||
constexpr uint32_t TEMPERATURE_INTAKE = 25;
|
||||
constexpr uint32_t TEMPERATURE_EXHAUST = 35;
|
||||
|
||||
// anything below 1000 is treated as a lamp anomaly and raises PROJERROR unless the exact
|
||||
// value was already recorded in /projecter/current on an earlier boot
|
||||
constexpr uint32_t LAMP_CURRENT = 1000;
|
||||
|
||||
void put32(uint8_t *dest, uint32_t value) {
|
||||
dest[0] = (uint8_t) (value & 0xFF);
|
||||
dest[1] = (uint8_t) ((value >> 8) & 0xFF);
|
||||
dest[2] = (uint8_t) ((value >> 16) & 0xFF);
|
||||
dest[3] = (uint8_t) ((value >> 24) & 0xFF);
|
||||
}
|
||||
}
|
||||
|
||||
bool games::silentscope::ProjectorHandle::open(LPCWSTR lpFileName) {
|
||||
if (wcscmp(lpFileName, L"COM2") != 0 && wcscmp(lpFileName, L"\\\\.\\COM2") != 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
log_info("silentscope", "Opened COM2 (projector)");
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
int games::silentscope::ProjectorHandle::read(LPVOID lpBuffer, DWORD nNumberOfBytesToRead) {
|
||||
std::lock_guard<std::mutex> lock(this->mutex);
|
||||
|
||||
auto buffer = reinterpret_cast<uint8_t *>(lpBuffer);
|
||||
|
||||
DWORD bytes_read = 0;
|
||||
while (bytes_read < nNumberOfBytesToRead && !this->response.empty()) {
|
||||
buffer[bytes_read++] = this->response.front();
|
||||
this->response.pop_front();
|
||||
}
|
||||
|
||||
return (int) bytes_read;
|
||||
}
|
||||
|
||||
int games::silentscope::ProjectorHandle::write(LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite) {
|
||||
std::lock_guard<std::mutex> lock(this->mutex);
|
||||
|
||||
auto buffer = reinterpret_cast<const uint8_t *>(lpBuffer);
|
||||
this->request.insert(this->request.end(), buffer, buffer + nNumberOfBytesToWrite);
|
||||
|
||||
while (this->request.size() >= HEADER_SIZE) {
|
||||
const size_t packet_size = HEADER_SIZE + this->request[4] + 1;
|
||||
if (this->request.size() < packet_size) {
|
||||
break;
|
||||
}
|
||||
|
||||
this->process_request(this->request.data());
|
||||
this->request.erase(this->request.begin(), this->request.begin() + packet_size);
|
||||
}
|
||||
|
||||
return (int) nNumberOfBytesToWrite;
|
||||
}
|
||||
|
||||
size_t games::silentscope::ProjectorHandle::bytes_available() {
|
||||
std::lock_guard<std::mutex> lock(this->mutex);
|
||||
|
||||
return this->response.size();
|
||||
}
|
||||
|
||||
bool games::silentscope::ProjectorHandle::close() {
|
||||
std::lock_guard<std::mutex> lock(this->mutex);
|
||||
|
||||
this->request.clear();
|
||||
this->response.clear();
|
||||
|
||||
log_info("silentscope", "Closed COM2 (projector)");
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void games::silentscope::ProjectorHandle::process_request(const uint8_t *packet) {
|
||||
const uint8_t command = packet[1];
|
||||
const uint8_t length = packet[4];
|
||||
const uint8_t *data = packet + HEADER_SIZE;
|
||||
|
||||
switch (command) {
|
||||
case COMMAND_COMMON_DATA: {
|
||||
|
||||
// the game only looks at the lamp usage time near the end of the block
|
||||
std::vector<uint8_t> payload(98, 0);
|
||||
put32(&payload[94], LAMP_SECONDS);
|
||||
this->reply(command, payload);
|
||||
break;
|
||||
}
|
||||
case COMMAND_TEMPERATURE: {
|
||||
|
||||
// the requested sensor is echoed back along with its reading
|
||||
const uint8_t sensor = length > 0 ? data[0] : 0;
|
||||
std::vector<uint8_t> payload(5, 0);
|
||||
payload[0] = sensor;
|
||||
put32(&payload[1], sensor == 0 ? TEMPERATURE_INTAKE : TEMPERATURE_EXHAUST);
|
||||
this->reply(command, payload);
|
||||
break;
|
||||
}
|
||||
case COMMAND_LAMP_CURRENT: {
|
||||
|
||||
// the three byte item selector is echoed back along with the measurement
|
||||
std::vector<uint8_t> payload(7, 0);
|
||||
memcpy(payload.data(), data, std::min<size_t>(length, 3));
|
||||
put32(&payload[3], LAMP_CURRENT);
|
||||
this->reply(command, payload);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
log_misc("silentscope", "unknown projector command {:#04x}", command);
|
||||
this->reply(command, {});
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void games::silentscope::ProjectorHandle::reply(uint8_t command, const std::vector<uint8_t> &data) {
|
||||
std::vector<uint8_t> packet {
|
||||
RESPONSE_ID, command, 0x00, 0x00, (uint8_t) data.size()
|
||||
};
|
||||
packet.insert(packet.end(), data.begin(), data.end());
|
||||
|
||||
uint8_t checksum = 0;
|
||||
for (auto byte : packet) {
|
||||
checksum += byte;
|
||||
}
|
||||
packet.push_back(checksum);
|
||||
|
||||
this->response.insert(this->response.end(), packet.begin(), packet.end());
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
#include "hooks/devicehook.h"
|
||||
|
||||
namespace games::silentscope {
|
||||
|
||||
// The cabinet talks to its projector over COM2. Without an answer the game stops at
|
||||
// I/O error 5-1560-0004 (IOCOM2, "the projector is not connected correctly").
|
||||
class ProjectorHandle : public CustomHandle {
|
||||
public:
|
||||
bool open(LPCWSTR lpFileName) override;
|
||||
int read(LPVOID lpBuffer, DWORD nNumberOfBytesToRead) override;
|
||||
int write(LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite) override;
|
||||
size_t bytes_available() override;
|
||||
bool close() override;
|
||||
|
||||
private:
|
||||
std::mutex mutex;
|
||||
std::vector<uint8_t> request;
|
||||
std::deque<uint8_t> response;
|
||||
|
||||
void process_request(const uint8_t *packet);
|
||||
void reply(uint8_t command, const std::vector<uint8_t> &data);
|
||||
};
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
#include "silentscope.h"
|
||||
|
||||
#include "acioemu/handle.h"
|
||||
#include "cfg/configurator.h"
|
||||
#include "hooks/devicehook.h"
|
||||
#include "util/libutils.h"
|
||||
|
||||
#include "projector.h"
|
||||
|
||||
namespace games::silentscope {
|
||||
|
||||
SilentScopeGame::SilentScopeGame() : Game("Silent Scope") {
|
||||
@@ -16,9 +17,8 @@ namespace games::silentscope {
|
||||
// load the game DLL so hooks apply
|
||||
libutils::try_library("gamendd.dll");
|
||||
|
||||
// TODO(felix): implement stuff on this port
|
||||
devicehook_init();
|
||||
devicehook_add(new acioemu::ACIOHandle(L"COM2"));
|
||||
devicehook_add(new ProjectorHandle());
|
||||
}
|
||||
|
||||
void SilentScopeGame::detach() {
|
||||
|
||||
@@ -0,0 +1,686 @@
|
||||
#include "bi2x_hook.h"
|
||||
|
||||
#if SPICE64
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
|
||||
#include "acio/icca/icca.h"
|
||||
#include "games/io.h"
|
||||
#include "io.h"
|
||||
#include "misc/eamuse.h"
|
||||
#include "rawinput/rawinput.h"
|
||||
#include "util/execexe.h"
|
||||
#include "util/logging.h"
|
||||
#include "util/tapeled.h"
|
||||
#include "util/utils.h"
|
||||
|
||||
namespace games::udn {
|
||||
|
||||
struct AIO_SCI_COMM {
|
||||
uint8_t data[0xf8];
|
||||
};
|
||||
|
||||
struct AIO_NMGR_IOB2 {
|
||||
uint8_t data[0xe30];
|
||||
};
|
||||
|
||||
struct AIO_IOB2_BI2X_UDN {
|
||||
uint8_t data[0x3b00];
|
||||
};
|
||||
|
||||
struct AIO_IOB2_BI2X_WRFIRM {
|
||||
uint8_t data[0x20f48];
|
||||
};
|
||||
|
||||
struct AIO_IOB_ICCA;
|
||||
|
||||
#pragma pack(push, 1)
|
||||
struct AIO_IOB2_BI2X_UDN__INPUT {
|
||||
uint8_t DevIoCounter;
|
||||
uint8_t bExIoAErr;
|
||||
uint8_t bExIoBErr;
|
||||
uint8_t bPcPowerOn;
|
||||
uint8_t bPcPowerCheck;
|
||||
uint8_t CoinCount;
|
||||
uint8_t bTest;
|
||||
uint8_t bService;
|
||||
uint8_t bCoinSw;
|
||||
uint8_t bCoinJam;
|
||||
uint8_t bStart;
|
||||
uint8_t bUp;
|
||||
uint8_t bDown;
|
||||
uint8_t bLeft;
|
||||
uint8_t bRight;
|
||||
};
|
||||
|
||||
struct AIO_IOB2_BI2X_UDN__DEVSTATUS {
|
||||
uint8_t InputCounter;
|
||||
uint8_t OutputCounter;
|
||||
uint8_t TapeLedCounter;
|
||||
uint8_t TapeLedRate[8];
|
||||
AIO_IOB2_BI2X_UDN__INPUT Input;
|
||||
uint8_t InputData[241];
|
||||
uint8_t OutputData[48];
|
||||
uint8_t IoResetData[4];
|
||||
uint8_t PlyrInHist[18];
|
||||
};
|
||||
|
||||
// Fixed card-status wire format used by the compatibility interface.
|
||||
// The payload is exactly 58 bytes.
|
||||
// Field widths remain explicit to keep the boundary stable.
|
||||
struct AIO_IOB_ICCA__CARDID {
|
||||
uint8_t CardType;
|
||||
uint8_t cbCardId;
|
||||
uint8_t CardId[10];
|
||||
};
|
||||
|
||||
struct AIO_IOB_ICCA__INPUT {
|
||||
uint8_t cuStatus;
|
||||
uint8_t cuError;
|
||||
AIO_IOB_ICCA__CARDID CardId;
|
||||
uint8_t KeyNo;
|
||||
uint8_t KeyCount;
|
||||
uint8_t bKeyDataValid;
|
||||
uint8_t Key2No;
|
||||
uint8_t Key2Count;
|
||||
uint8_t bKey2DataValid;
|
||||
uint8_t bKey0;
|
||||
uint8_t bKey1;
|
||||
uint8_t bKey4;
|
||||
uint8_t bKey7;
|
||||
uint8_t bKey00;
|
||||
uint8_t bKey2;
|
||||
uint8_t bKey5;
|
||||
uint8_t bKey8;
|
||||
uint8_t bKeyBK;
|
||||
uint8_t bKey3;
|
||||
uint8_t bKey6;
|
||||
uint8_t bKey9;
|
||||
uint8_t CN1_1;
|
||||
uint8_t CN1_2;
|
||||
uint8_t CN1_3;
|
||||
uint8_t CN1_4;
|
||||
};
|
||||
|
||||
struct AIO_IOB_ICCA__DEVSTATUS {
|
||||
uint8_t InputCounter;
|
||||
uint8_t OutputCounter;
|
||||
AIO_IOB_ICCA__INPUT Input;
|
||||
uint8_t InputData[16];
|
||||
uint8_t OutputData[4];
|
||||
};
|
||||
#pragma pack(pop)
|
||||
|
||||
static_assert(sizeof(AIO_SCI_COMM) == 0xf8);
|
||||
static_assert(sizeof(AIO_NMGR_IOB2) == 0xe30);
|
||||
static_assert(sizeof(AIO_IOB2_BI2X_UDN) == 0x3b00);
|
||||
static_assert(sizeof(AIO_IOB2_BI2X_WRFIRM) == 0x20f48);
|
||||
static_assert(sizeof(AIO_IOB2_BI2X_UDN__INPUT) == 15);
|
||||
static_assert(sizeof(AIO_IOB2_BI2X_UDN__DEVSTATUS) == 337);
|
||||
static_assert(sizeof(AIO_IOB_ICCA__CARDID) == 12);
|
||||
static_assert(sizeof(AIO_IOB_ICCA__INPUT) == 36);
|
||||
static_assert(sizeof(AIO_IOB_ICCA__DEVSTATUS) == 58);
|
||||
|
||||
using aioIob2Bi2xUDN_Create_t = AIO_IOB2_BI2X_UDN *(__fastcall *)(AIO_NMGR_IOB2 *, uint32_t);
|
||||
using aioIob2Bi2xUDN_GetDeviceStatus_t = uint32_t (__fastcall *)(
|
||||
AIO_IOB2_BI2X_UDN *, AIO_IOB2_BI2X_UDN__DEVSTATUS *, uint32_t);
|
||||
using aioIob2Bi2xAC1_GetDeviceStatus_t = uint32_t (__fastcall *)(void *, void *, uint32_t);
|
||||
using aioIob2Bi2xUDN_IoReset_t = void (__fastcall *)(AIO_IOB2_BI2X_UDN *, uint32_t);
|
||||
using aioIob2Bi2xUDN_SetWatchDogTimer_t = void (__fastcall *)(AIO_IOB2_BI2X_UDN *, uint8_t);
|
||||
using aioIob2Bi2xUDN_ControlCoinBlocker_t = void (__fastcall *)(AIO_IOB2_BI2X_UDN *, uint32_t, bool);
|
||||
using aioIob2Bi2xUDN_AddCounter_t = void (__fastcall *)(AIO_IOB2_BI2X_UDN *, uint32_t, uint32_t);
|
||||
using aioIob2Bi2xUDN_SetStartLamp_t = void (__fastcall *)(AIO_IOB2_BI2X_UDN *, bool);
|
||||
using aioIob2Bi2xUDN_SetPlayerButtonLamp_t = void (__fastcall *)(AIO_IOB2_BI2X_UDN *, uint32_t, bool);
|
||||
using aioIob2Bi2xUDN_SetIccrLed_t = void (__fastcall *)(AIO_IOB2_BI2X_UDN *, uint32_t);
|
||||
using aioIob2Bi2xUDN_SetTapeLedDataLimit_t = void (__fastcall *)(
|
||||
AIO_IOB2_BI2X_UDN *, uint32_t, uint8_t, uint8_t);
|
||||
using aioIob2Bi2xUDN_SetTapeLedData_t = void (__fastcall *)(AIO_IOB2_BI2X_UDN *, uint32_t, uint8_t *);
|
||||
using aioIob2Bi2x_OpenSciUsbCdc_t = AIO_SCI_COMM *(__fastcall *)(uint32_t);
|
||||
using aioIob2Bi2x_CreateWriteFirmContext_t = AIO_IOB2_BI2X_WRFIRM *(__fastcall *)(uint32_t, uint32_t);
|
||||
using aioIob2Bi2x_DestroyWriteFirmContext_t = void (__fastcall *)(AIO_IOB2_BI2X_WRFIRM *);
|
||||
using aioIob2Bi2x_WriteFirmGetState_t = int32_t (__fastcall *)(AIO_IOB2_BI2X_WRFIRM *);
|
||||
|
||||
using aioIobIcca_Create_t = AIO_IOB_ICCA *(__fastcall *)(void *, uint32_t, uint8_t);
|
||||
using aioIobIcca_GetDeviceStatus_t = uint32_t (__fastcall *)(
|
||||
AIO_IOB_ICCA *, AIO_IOB_ICCA__DEVSTATUS *, uint32_t);
|
||||
using aioIobIcca_BeginGetCardId_t = void (__fastcall *)(AIO_IOB_ICCA *);
|
||||
using aioIobIcca_EndGetCardId_t = void (__fastcall *)(AIO_IOB_ICCA *);
|
||||
|
||||
using aioNMgrIob2_Create_t = AIO_NMGR_IOB2 *(__fastcall *)(AIO_SCI_COMM *, uint32_t);
|
||||
using aioNMgrIob_BeginManage_t = void (__fastcall *)(AIO_NMGR_IOB2 *);
|
||||
|
||||
using aioNodeMgr_Destroy_t = void (__fastcall *)(AIO_NMGR_IOB2 *);
|
||||
using aioNodeMgr_GetState_t = int32_t (__fastcall *)(AIO_NMGR_IOB2 *);
|
||||
using aioNodeMgr_IsReady_t = bool (__fastcall *)(AIO_NMGR_IOB2 *, int32_t);
|
||||
using aioNodeCtl_Destroy_t = void (__fastcall *)(AIO_IOB2_BI2X_UDN *);
|
||||
using aioNodeCtl_GetState_t = int32_t (__fastcall *)(AIO_IOB2_BI2X_UDN *);
|
||||
using aioNodeCtl_IsReady_t = bool (__fastcall *)(AIO_IOB2_BI2X_UDN *, int32_t);
|
||||
|
||||
static aioIob2Bi2xUDN_Create_t aioIob2Bi2xUDN_Create_orig = nullptr;
|
||||
static aioIob2Bi2xUDN_GetDeviceStatus_t aioIob2Bi2xUDN_GetDeviceStatus_orig = nullptr;
|
||||
static aioIob2Bi2xAC1_GetDeviceStatus_t aioIob2Bi2xAC1_GetDeviceStatus_orig = nullptr;
|
||||
static aioIob2Bi2xUDN_IoReset_t aioIob2Bi2xUDN_IoReset_orig = nullptr;
|
||||
static aioIob2Bi2xUDN_SetWatchDogTimer_t aioIob2Bi2xUDN_SetWatchDogTimer_orig = nullptr;
|
||||
static aioIob2Bi2xUDN_ControlCoinBlocker_t aioIob2Bi2xUDN_ControlCoinBlocker_orig = nullptr;
|
||||
static aioIob2Bi2xUDN_AddCounter_t aioIob2Bi2xUDN_AddCounter_orig = nullptr;
|
||||
static aioIob2Bi2xUDN_SetStartLamp_t aioIob2Bi2xUDN_SetStartLamp_orig = nullptr;
|
||||
static aioIob2Bi2xUDN_SetPlayerButtonLamp_t aioIob2Bi2xUDN_SetPlayerButtonLamp_orig = nullptr;
|
||||
static aioIob2Bi2xUDN_SetIccrLed_t aioIob2Bi2xUDN_SetIccrLed_orig = nullptr;
|
||||
static aioIob2Bi2xUDN_SetTapeLedDataLimit_t aioIob2Bi2xUDN_SetTapeLedDataLimit_orig = nullptr;
|
||||
static aioIob2Bi2xUDN_SetTapeLedData_t aioIob2Bi2xUDN_SetTapeLedData_orig = nullptr;
|
||||
static aioIob2Bi2x_OpenSciUsbCdc_t aioIob2Bi2x_OpenSciUsbCdc_orig = nullptr;
|
||||
static aioIob2Bi2x_CreateWriteFirmContext_t aioIob2Bi2x_CreateWriteFirmContext_orig = nullptr;
|
||||
static aioIob2Bi2x_DestroyWriteFirmContext_t aioIob2Bi2x_DestroyWriteFirmContext_orig = nullptr;
|
||||
static aioIob2Bi2x_WriteFirmGetState_t aioIob2Bi2x_WriteFirmGetState_orig = nullptr;
|
||||
|
||||
static aioIobIcca_Create_t aioIobIcca_Create_orig = nullptr;
|
||||
static aioIobIcca_GetDeviceStatus_t aioIobIcca_GetDeviceStatus_orig = nullptr;
|
||||
static aioIobIcca_BeginGetCardId_t aioIobIcca_BeginGetCardId_orig = nullptr;
|
||||
static aioIobIcca_EndGetCardId_t aioIobIcca_EndGetCardId_orig = nullptr;
|
||||
|
||||
static aioNMgrIob2_Create_t aioNMgrIob2_Create_orig = nullptr;
|
||||
static aioNMgrIob_BeginManage_t aioNMgrIob_BeginManage_orig = nullptr;
|
||||
|
||||
static aioNodeMgr_Destroy_t aioNodeMgr_Destroy_orig = nullptr;
|
||||
static aioNodeMgr_GetState_t aioNodeMgr_GetState_orig = nullptr;
|
||||
static aioNodeMgr_IsReady_t aioNodeMgr_IsReady_orig = nullptr;
|
||||
static aioNodeCtl_Destroy_t aioNodeCtl_Destroy_orig = nullptr;
|
||||
static aioNodeCtl_GetState_t aioNodeCtl_GetState_orig = nullptr;
|
||||
static aioNodeCtl_IsReady_t aioNodeCtl_IsReady_orig = nullptr;
|
||||
|
||||
static std::unique_ptr<AIO_SCI_COMM> aio_sci_comm;
|
||||
static std::unique_ptr<AIO_NMGR_IOB2> aio_node_manager;
|
||||
static AIO_NMGR_IOB2 *aio_icca_node_manager = nullptr;
|
||||
static std::unique_ptr<AIO_IOB2_BI2X_UDN> aio_udn;
|
||||
static std::unique_ptr<AIO_IOB2_BI2X_WRFIRM> aio_write_firm;
|
||||
static uint8_t input_counter = 0;
|
||||
|
||||
// Native ICCA status/begin/end operations also lock the reader state.
|
||||
// The managed wrapper can destroy its node from a finalizer thread.
|
||||
static std::mutex icca_mutex;
|
||||
static AIO_IOB_ICCA *aio_icca = nullptr;
|
||||
static bool icca_reading = false;
|
||||
static bool icca_card_ready = false;
|
||||
static uint8_t icca_card_uid[8] {};
|
||||
static uint8_t icca_input_counter = 0;
|
||||
|
||||
static void write_light(Lights::udn_lights_t light, float value) {
|
||||
auto &lights = get_lights();
|
||||
GameAPI::Lights::writeLight(RI_MGR, lights.at(light), value);
|
||||
}
|
||||
|
||||
static AIO_IOB2_BI2X_UDN *__fastcall aioIob2Bi2xUDN_Create(
|
||||
AIO_NMGR_IOB2 *node_manager, uint32_t device_id) {
|
||||
|
||||
if (node_manager != aio_node_manager.get()) {
|
||||
return aioIob2Bi2xUDN_Create_orig(node_manager, device_id);
|
||||
}
|
||||
|
||||
if (!aio_udn) {
|
||||
aio_udn = std::make_unique<AIO_IOB2_BI2X_UDN>();
|
||||
log_info("udn_bi2x", "UDN node created");
|
||||
}
|
||||
return aio_udn.get();
|
||||
}
|
||||
|
||||
static uint32_t __fastcall aioIob2Bi2xAC1_GetDeviceStatus(
|
||||
void *node, void *status, uint32_t status_size) {
|
||||
|
||||
// aioIob2Bi2xUDN.GetDeviceStatus() first invokes its managed AC1 base method.
|
||||
if (node == aio_udn.get()) {
|
||||
if (status && status_size > 0) {
|
||||
std::memset(status, 0, status_size);
|
||||
}
|
||||
return status_size;
|
||||
}
|
||||
return aioIob2Bi2xAC1_GetDeviceStatus_orig(node, status, status_size);
|
||||
}
|
||||
|
||||
static uint32_t __fastcall aioIob2Bi2xUDN_GetDeviceStatus(
|
||||
AIO_IOB2_BI2X_UDN *node, AIO_IOB2_BI2X_UDN__DEVSTATUS *status,
|
||||
uint32_t status_size) {
|
||||
|
||||
if (node != aio_udn.get()) {
|
||||
return aioIob2Bi2xUDN_GetDeviceStatus_orig(node, status, status_size);
|
||||
}
|
||||
|
||||
RI_MGR->devices_flush_output();
|
||||
|
||||
AIO_IOB2_BI2X_UDN__DEVSTATUS current {};
|
||||
current.InputCounter = input_counter;
|
||||
current.Input.DevIoCounter = input_counter++;
|
||||
|
||||
auto &buttons = get_buttons();
|
||||
current.Input.bService = GameAPI::Buttons::getState(RI_MGR, buttons[Buttons::Service]) ? 1 : 0;
|
||||
current.Input.bTest = GameAPI::Buttons::getState(RI_MGR, buttons[Buttons::Test]) ? 1 : 0;
|
||||
current.Input.bCoinSw = GameAPI::Buttons::getState(RI_MGR, buttons[Buttons::CoinMech]) ? 1 : 0;
|
||||
current.Input.bStart = GameAPI::Buttons::getState(RI_MGR, buttons[Buttons::Start]) ? 1 : 0;
|
||||
current.Input.bUp = GameAPI::Buttons::getState(RI_MGR, buttons[Buttons::Up]) ? 1 : 0;
|
||||
current.Input.bDown = GameAPI::Buttons::getState(RI_MGR, buttons[Buttons::Down]) ? 1 : 0;
|
||||
current.Input.bLeft = GameAPI::Buttons::getState(RI_MGR, buttons[Buttons::Left]) ? 1 : 0;
|
||||
current.Input.bRight = GameAPI::Buttons::getState(RI_MGR, buttons[Buttons::Right]) ? 1 : 0;
|
||||
// The hardware counter wraps at 256; clamping it would stop accepting
|
||||
// coins once the shared stock reaches 255.
|
||||
current.Input.CoinCount = static_cast<uint8_t>(eamuse_coin_get_stock());
|
||||
|
||||
const auto copy_size = std::min<uint32_t>(status_size, sizeof(current));
|
||||
if (status && copy_size > 0) {
|
||||
std::memcpy(status, ¤t, copy_size);
|
||||
}
|
||||
return copy_size;
|
||||
}
|
||||
|
||||
static void __fastcall aioIob2Bi2xUDN_IoReset(AIO_IOB2_BI2X_UDN *node, uint32_t reset_bits) {
|
||||
if (node != aio_udn.get()) {
|
||||
return aioIob2Bi2xUDN_IoReset_orig(node, reset_bits);
|
||||
}
|
||||
}
|
||||
|
||||
static void __fastcall aioIob2Bi2xUDN_SetWatchDogTimer(AIO_IOB2_BI2X_UDN *node, uint8_t count) {
|
||||
if (node != aio_udn.get()) {
|
||||
return aioIob2Bi2xUDN_SetWatchDogTimer_orig(node, count);
|
||||
}
|
||||
}
|
||||
|
||||
static void __fastcall aioIob2Bi2xUDN_ControlCoinBlocker(
|
||||
AIO_IOB2_BI2X_UDN *node, uint32_t slot, bool open) {
|
||||
|
||||
if (node != aio_udn.get()) {
|
||||
return aioIob2Bi2xUDN_ControlCoinBlocker_orig(node, slot, open);
|
||||
}
|
||||
eamuse_coin_set_block(!open);
|
||||
}
|
||||
|
||||
static void __fastcall aioIob2Bi2xUDN_AddCounter(
|
||||
AIO_IOB2_BI2X_UDN *node, uint32_t counter, uint32_t count) {
|
||||
|
||||
if (node != aio_udn.get()) {
|
||||
return aioIob2Bi2xUDN_AddCounter_orig(node, counter, count);
|
||||
}
|
||||
}
|
||||
|
||||
static void __fastcall aioIob2Bi2xUDN_SetStartLamp(AIO_IOB2_BI2X_UDN *node, bool on) {
|
||||
if (node != aio_udn.get()) {
|
||||
return aioIob2Bi2xUDN_SetStartLamp_orig(node, on);
|
||||
}
|
||||
write_light(Lights::Start, on ? 1.f : 0.f);
|
||||
}
|
||||
|
||||
static void __fastcall aioIob2Bi2xUDN_SetPlayerButtonLamp(
|
||||
AIO_IOB2_BI2X_UDN *node, uint32_t button, bool on) {
|
||||
|
||||
if (node != aio_udn.get()) {
|
||||
return aioIob2Bi2xUDN_SetPlayerButtonLamp_orig(node, button, on);
|
||||
}
|
||||
|
||||
static const Lights::udn_lights_t mapping[] {
|
||||
Lights::Start,
|
||||
Lights::Up,
|
||||
Lights::Down,
|
||||
Lights::Left,
|
||||
Lights::Right,
|
||||
};
|
||||
if (button < std::size(mapping)) {
|
||||
write_light(mapping[button], on ? 1.f : 0.f);
|
||||
}
|
||||
}
|
||||
|
||||
static void __fastcall aioIob2Bi2xUDN_SetIccrLed(AIO_IOB2_BI2X_UDN *node, uint32_t rgb) {
|
||||
if (node != aio_udn.get()) {
|
||||
return aioIob2Bi2xUDN_SetIccrLed_orig(node, rgb);
|
||||
}
|
||||
|
||||
write_light(Lights::CardReaderR, ((rgb >> 16) & 0xff) / 255.f);
|
||||
write_light(Lights::CardReaderG, ((rgb >> 8) & 0xff) / 255.f);
|
||||
write_light(Lights::CardReaderB, (rgb & 0xff) / 255.f);
|
||||
}
|
||||
|
||||
static void __fastcall aioIob2Bi2xUDN_SetTapeLedDataLimit(
|
||||
AIO_IOB2_BI2X_UDN *node, uint32_t channel, uint8_t scale, uint8_t limit) {
|
||||
|
||||
if (node != aio_udn.get()) {
|
||||
return aioIob2Bi2xUDN_SetTapeLedDataLimit_orig(node, channel, scale, limit);
|
||||
}
|
||||
}
|
||||
|
||||
static void __fastcall aioIob2Bi2xUDN_SetTapeLedData(
|
||||
AIO_IOB2_BI2X_UDN *node, uint32_t tape, uint8_t *data) {
|
||||
|
||||
if (node != aio_udn.get()) {
|
||||
return aioIob2Bi2xUDN_SetTapeLedData_orig(node, tape, data);
|
||||
}
|
||||
|
||||
struct TapeMapping {
|
||||
size_t color_count;
|
||||
Lights::udn_lights_t r;
|
||||
Lights::udn_lights_t g;
|
||||
Lights::udn_lights_t b;
|
||||
};
|
||||
static const TapeMapping mapping[] {
|
||||
{62, Lights::TitleR, Lights::TitleG, Lights::TitleB},
|
||||
{152, Lights::PillarRightTopR, Lights::PillarRightTopG, Lights::PillarRightTopB},
|
||||
{165, Lights::PillarRightBottomR, Lights::PillarRightBottomG, Lights::PillarRightBottomB},
|
||||
{9, Lights::StageLeftR, Lights::StageLeftG, Lights::StageLeftB},
|
||||
{17, Lights::CabinetLeftR, Lights::CabinetLeftG, Lights::CabinetLeftB},
|
||||
{152, Lights::PillarLeftTopR, Lights::PillarLeftTopG, Lights::PillarLeftTopB},
|
||||
{165, Lights::PillarLeftBottomR, Lights::PillarLeftBottomG, Lights::PillarLeftBottomB},
|
||||
{9, Lights::StageRightR, Lights::StageRightG, Lights::StageRightB},
|
||||
{17, Lights::CabinetRightR, Lights::CabinetRightG, Lights::CabinetRightB},
|
||||
};
|
||||
|
||||
if (data && tapeledutils::is_enabled() && tape < std::size(mapping)) {
|
||||
const auto &entry = mapping[tape];
|
||||
const auto color = tapeledutils::pick_color_from_led_tape(data, entry.color_count);
|
||||
write_light(entry.r, color.r);
|
||||
write_light(entry.g, color.g);
|
||||
write_light(entry.b, color.b);
|
||||
}
|
||||
}
|
||||
|
||||
static AIO_SCI_COMM *__fastcall aioIob2Bi2x_OpenSciUsbCdc(uint32_t serial_number) {
|
||||
if (!aio_sci_comm) {
|
||||
aio_sci_comm = std::make_unique<AIO_SCI_COMM>();
|
||||
}
|
||||
return aio_sci_comm.get();
|
||||
}
|
||||
|
||||
static AIO_IOB2_BI2X_WRFIRM *__fastcall aioIob2Bi2x_CreateWriteFirmContext(
|
||||
uint32_t serial_number, uint32_t iob_mask) {
|
||||
|
||||
if (!aio_write_firm) {
|
||||
aio_write_firm = std::make_unique<AIO_IOB2_BI2X_WRFIRM>();
|
||||
}
|
||||
return aio_write_firm.get();
|
||||
}
|
||||
|
||||
static void __fastcall aioIob2Bi2x_DestroyWriteFirmContext(AIO_IOB2_BI2X_WRFIRM *context) {
|
||||
if (context != aio_write_firm.get()) {
|
||||
return aioIob2Bi2x_DestroyWriteFirmContext_orig(context);
|
||||
}
|
||||
aio_write_firm.reset();
|
||||
}
|
||||
|
||||
static int32_t __fastcall aioIob2Bi2x_WriteFirmGetState(AIO_IOB2_BI2X_WRFIRM *context) {
|
||||
if (context == aio_write_firm.get()) {
|
||||
// The native state machine treats both 7 (NODEV) and 8
|
||||
// (COMPLETED) as a successful terminal state. UDN additionally
|
||||
// interprets state 8 as "firmware was written this boot" and
|
||||
// deliberately powers the cabinet down after loading so the real
|
||||
// I/O board can reboot. There is no physical BI2X board behind
|
||||
// this emulation, so report NODEV: the check is complete without
|
||||
// scheduling that otherwise endless firmware-update reboot.
|
||||
return 7;
|
||||
}
|
||||
return aioIob2Bi2x_WriteFirmGetState_orig(context);
|
||||
}
|
||||
|
||||
static AIO_IOB_ICCA *__fastcall aioIobIcca_Create(
|
||||
void *node_manager, uint32_t device_id, uint8_t init_mode) {
|
||||
|
||||
auto *node = aioIobIcca_Create_orig(node_manager, device_id, init_mode);
|
||||
if (node) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(icca_mutex);
|
||||
aio_icca = node;
|
||||
aio_icca_node_manager =
|
||||
reinterpret_cast<AIO_NMGR_IOB2 *>(node_manager);
|
||||
icca_reading = false;
|
||||
icca_card_ready = false;
|
||||
std::memset(icca_card_uid, 0, sizeof(icca_card_uid));
|
||||
}
|
||||
log_info("udn_bi2x", "ICCA node attached to Spice CardIO bridge");
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
static uint32_t __fastcall aioIobIcca_GetDeviceStatus(
|
||||
AIO_IOB_ICCA *node, AIO_IOB_ICCA__DEVSTATUS *status, uint32_t status_size) {
|
||||
|
||||
std::unique_lock<std::mutex> lock(icca_mutex);
|
||||
if (node != aio_icca) {
|
||||
lock.unlock();
|
||||
return aioIobIcca_GetDeviceStatus_orig(node, status, status_size);
|
||||
}
|
||||
|
||||
AIO_IOB_ICCA__DEVSTATUS current {};
|
||||
current.InputCounter = icca_input_counter++;
|
||||
current.OutputCounter = current.InputCounter;
|
||||
|
||||
// DNI while idle, BUSY while waiting for a card, READY once a UID is
|
||||
// available. The card-reader state machine accepts a card only on READY.
|
||||
current.Input.cuStatus = icca_reading ? 1 : 0;
|
||||
if (icca_reading && !icca_card_ready && eamuse_card_insert_consume(1, 0)) {
|
||||
uint8_t uid[8] {};
|
||||
if (eamuse_get_card(1, 0, uid)) {
|
||||
std::memcpy(icca_card_uid, uid, sizeof(icca_card_uid));
|
||||
icca_card_ready = true;
|
||||
log_info(
|
||||
"udn_bi2x",
|
||||
"ICCA accepted UID {} from the Spice card queue; reporting READY to Unity",
|
||||
bin2hex(icca_card_uid, sizeof(icca_card_uid)));
|
||||
} else {
|
||||
log_warning(
|
||||
"udn_bi2x",
|
||||
"ICCA consumed a card-insert event but Spice returned no UID");
|
||||
}
|
||||
}
|
||||
|
||||
if (icca_card_ready) {
|
||||
current.Input.cuStatus = 2;
|
||||
current.Input.CardId.CardType = is_card_uid_felica(icca_card_uid) ? 2 : 1;
|
||||
current.Input.CardId.cbCardId = sizeof(icca_card_uid);
|
||||
std::memcpy(current.Input.CardId.CardId, icca_card_uid, sizeof(icca_card_uid));
|
||||
}
|
||||
|
||||
// The ICCA keypad scan-code order is identical to eamuse.h. Keeping
|
||||
// these bits populated also preserves the usual Spice numpad PIN flow.
|
||||
const auto keypad = eamuse_get_keypad_state(0);
|
||||
auto *key_states = ¤t.Input.bKey0;
|
||||
for (size_t key = 0; key < EAM_IO_KEYPAD_COUNT; ++key) {
|
||||
key_states[key] = (keypad & (1u << key)) ? 1 : 0;
|
||||
}
|
||||
|
||||
const auto copy_size = std::min<uint32_t>(status_size, sizeof(current));
|
||||
if (status && copy_size > 0) {
|
||||
std::memcpy(status, ¤t, copy_size);
|
||||
}
|
||||
return copy_size;
|
||||
}
|
||||
|
||||
static void __fastcall aioIobIcca_BeginGetCardId(AIO_IOB_ICCA *node) {
|
||||
std::unique_lock<std::mutex> lock(icca_mutex);
|
||||
if (node != aio_icca) {
|
||||
lock.unlock();
|
||||
return aioIobIcca_BeginGetCardId_orig(node);
|
||||
}
|
||||
if (!icca_reading) {
|
||||
log_info("udn_bi2x", "ICCA BeginGetCardId: waiting for the Spice/CardIO queue");
|
||||
}
|
||||
icca_reading = true;
|
||||
icca_card_ready = false;
|
||||
std::memset(icca_card_uid, 0, sizeof(icca_card_uid));
|
||||
}
|
||||
|
||||
static void __fastcall aioIobIcca_EndGetCardId(AIO_IOB_ICCA *node) {
|
||||
std::unique_lock<std::mutex> lock(icca_mutex);
|
||||
if (node != aio_icca) {
|
||||
lock.unlock();
|
||||
return aioIobIcca_EndGetCardId_orig(node);
|
||||
}
|
||||
if (icca_reading || icca_card_ready) {
|
||||
log_info("udn_bi2x", "ICCA EndGetCardId: returning to idle");
|
||||
}
|
||||
icca_reading = false;
|
||||
icca_card_ready = false;
|
||||
std::memset(icca_card_uid, 0, sizeof(icca_card_uid));
|
||||
}
|
||||
|
||||
static AIO_NMGR_IOB2 *__fastcall aioNMgrIob2_Create(AIO_SCI_COMM *sci, uint32_t mode) {
|
||||
if (sci != aio_sci_comm.get()) {
|
||||
return aioNMgrIob2_Create_orig(sci, mode);
|
||||
}
|
||||
if (!aio_node_manager) {
|
||||
aio_node_manager = std::make_unique<AIO_NMGR_IOB2>();
|
||||
}
|
||||
return aio_node_manager.get();
|
||||
}
|
||||
|
||||
static void __fastcall aioNMgrIob_BeginManage(AIO_NMGR_IOB2 *node_manager) {
|
||||
if (node_manager != aio_node_manager.get()) {
|
||||
return aioNMgrIob_BeginManage_orig(node_manager);
|
||||
}
|
||||
}
|
||||
|
||||
static void __fastcall aioNodeMgr_Destroy(AIO_NMGR_IOB2 *node_manager) {
|
||||
if (node_manager != aio_node_manager.get()) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(icca_mutex);
|
||||
if (node_manager == aio_icca_node_manager) {
|
||||
aio_icca_node_manager = nullptr;
|
||||
}
|
||||
}
|
||||
return aioNodeMgr_Destroy_orig(node_manager);
|
||||
}
|
||||
aio_node_manager.reset();
|
||||
}
|
||||
|
||||
static int32_t __fastcall aioNodeMgr_GetState(AIO_NMGR_IOB2 *node_manager) {
|
||||
bool virtual_manager = node_manager == aio_node_manager.get();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(icca_mutex);
|
||||
virtual_manager |= node_manager == aio_icca_node_manager;
|
||||
}
|
||||
if (virtual_manager) {
|
||||
return 0;
|
||||
}
|
||||
return aioNodeMgr_GetState_orig(node_manager);
|
||||
}
|
||||
|
||||
static bool __fastcall aioNodeMgr_IsReady(AIO_NMGR_IOB2 *node_manager, int32_t state) {
|
||||
bool virtual_manager = node_manager == aio_node_manager.get();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(icca_mutex);
|
||||
virtual_manager |= node_manager == aio_icca_node_manager;
|
||||
}
|
||||
if (virtual_manager) {
|
||||
return true;
|
||||
}
|
||||
return aioNodeMgr_IsReady_orig(node_manager, state);
|
||||
}
|
||||
|
||||
static void __fastcall aioNodeCtl_Destroy(AIO_IOB2_BI2X_UDN *node) {
|
||||
if (node != aio_udn.get()) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(icca_mutex);
|
||||
if (reinterpret_cast<AIO_IOB_ICCA *>(node) == aio_icca) {
|
||||
aio_icca = nullptr;
|
||||
aio_icca_node_manager = nullptr;
|
||||
icca_reading = false;
|
||||
icca_card_ready = false;
|
||||
std::memset(icca_card_uid, 0, sizeof(icca_card_uid));
|
||||
}
|
||||
}
|
||||
return aioNodeCtl_Destroy_orig(node);
|
||||
}
|
||||
aio_udn.reset();
|
||||
}
|
||||
|
||||
static int32_t __fastcall aioNodeCtl_GetState(AIO_IOB2_BI2X_UDN *node) {
|
||||
bool virtual_node = node == aio_udn.get();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(icca_mutex);
|
||||
virtual_node |= reinterpret_cast<AIO_IOB_ICCA *>(node) == aio_icca;
|
||||
}
|
||||
if (virtual_node) {
|
||||
return 0;
|
||||
}
|
||||
return aioNodeCtl_GetState_orig(node);
|
||||
}
|
||||
|
||||
static bool __fastcall aioNodeCtl_IsReady(AIO_IOB2_BI2X_UDN *node, int32_t state) {
|
||||
bool virtual_node = node == aio_udn.get();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(icca_mutex);
|
||||
virtual_node |= reinterpret_cast<AIO_IOB_ICCA *>(node) == aio_icca;
|
||||
}
|
||||
if (virtual_node) {
|
||||
return true;
|
||||
}
|
||||
return aioNodeCtl_IsReady_orig(node, state);
|
||||
}
|
||||
|
||||
void bi2x_hook_init() {
|
||||
log_info("udn_bi2x", "init (BI2X + ICCA/CardIO bridge)");
|
||||
|
||||
// The runtime imports the alias DLL names, not their lib-prefixed originals.
|
||||
const auto aio_iob2_video = "aio-iob2_video.dll";
|
||||
execexe::trampoline_try(aio_iob2_video, "aioIob2Bi2xUDN_Create",
|
||||
aioIob2Bi2xUDN_Create, &aioIob2Bi2xUDN_Create_orig);
|
||||
execexe::trampoline_try(aio_iob2_video, "aioIob2Bi2xUDN_GetDeviceStatus",
|
||||
aioIob2Bi2xUDN_GetDeviceStatus, &aioIob2Bi2xUDN_GetDeviceStatus_orig);
|
||||
execexe::trampoline_try(aio_iob2_video, "aioIob2Bi2xAC1_GetDeviceStatus",
|
||||
aioIob2Bi2xAC1_GetDeviceStatus, &aioIob2Bi2xAC1_GetDeviceStatus_orig);
|
||||
execexe::trampoline_try(aio_iob2_video, "aioIob2Bi2xUDN_IoReset",
|
||||
aioIob2Bi2xUDN_IoReset, &aioIob2Bi2xUDN_IoReset_orig);
|
||||
execexe::trampoline_try(aio_iob2_video, "aioIob2Bi2xUDN_SetWatchDogTimer",
|
||||
aioIob2Bi2xUDN_SetWatchDogTimer, &aioIob2Bi2xUDN_SetWatchDogTimer_orig);
|
||||
execexe::trampoline_try(aio_iob2_video, "aioIob2Bi2xUDN_ControlCoinBlocker",
|
||||
aioIob2Bi2xUDN_ControlCoinBlocker, &aioIob2Bi2xUDN_ControlCoinBlocker_orig);
|
||||
execexe::trampoline_try(aio_iob2_video, "aioIob2Bi2xUDN_AddCounter",
|
||||
aioIob2Bi2xUDN_AddCounter, &aioIob2Bi2xUDN_AddCounter_orig);
|
||||
execexe::trampoline_try(aio_iob2_video, "aioIob2Bi2xUDN_SetStartLamp",
|
||||
aioIob2Bi2xUDN_SetStartLamp, &aioIob2Bi2xUDN_SetStartLamp_orig);
|
||||
execexe::trampoline_try(aio_iob2_video, "aioIob2Bi2xUDN_SetPlayerButtonLamp",
|
||||
aioIob2Bi2xUDN_SetPlayerButtonLamp, &aioIob2Bi2xUDN_SetPlayerButtonLamp_orig);
|
||||
execexe::trampoline_try(aio_iob2_video, "aioIob2Bi2xUDN_SetIccrLed",
|
||||
aioIob2Bi2xUDN_SetIccrLed, &aioIob2Bi2xUDN_SetIccrLed_orig);
|
||||
execexe::trampoline_try(aio_iob2_video, "aioIob2Bi2xUDN_SetTapeLedDataLimit",
|
||||
aioIob2Bi2xUDN_SetTapeLedDataLimit, &aioIob2Bi2xUDN_SetTapeLedDataLimit_orig);
|
||||
execexe::trampoline_try(aio_iob2_video, "aioIob2Bi2xUDN_SetTapeLedData",
|
||||
aioIob2Bi2xUDN_SetTapeLedData, &aioIob2Bi2xUDN_SetTapeLedData_orig);
|
||||
execexe::trampoline_try(aio_iob2_video, "aioIob2Bi2x_OpenSciUsbCdc",
|
||||
aioIob2Bi2x_OpenSciUsbCdc, &aioIob2Bi2x_OpenSciUsbCdc_orig);
|
||||
execexe::trampoline_try(aio_iob2_video, "aioIob2Bi2x_CreateWriteFirmContext",
|
||||
aioIob2Bi2x_CreateWriteFirmContext, &aioIob2Bi2x_CreateWriteFirmContext_orig);
|
||||
execexe::trampoline_try(aio_iob2_video, "aioIob2Bi2x_DestroyWriteFirmContext",
|
||||
aioIob2Bi2x_DestroyWriteFirmContext, &aioIob2Bi2x_DestroyWriteFirmContext_orig);
|
||||
execexe::trampoline_try(aio_iob2_video, "aioIob2Bi2x_WriteFirmGetState",
|
||||
aioIob2Bi2x_WriteFirmGetState, &aioIob2Bi2x_WriteFirmGetState_orig);
|
||||
|
||||
const auto aio_iob_video = "aio-iob_video.dll";
|
||||
execexe::trampoline_try(aio_iob_video, "aioIobIcca_Create",
|
||||
aioIobIcca_Create, &aioIobIcca_Create_orig);
|
||||
execexe::trampoline_try(aio_iob_video, "aioIobIcca_GetDeviceStatus",
|
||||
aioIobIcca_GetDeviceStatus, &aioIobIcca_GetDeviceStatus_orig);
|
||||
execexe::trampoline_try(aio_iob_video, "aioIobIcca_BeginGetCardId",
|
||||
aioIobIcca_BeginGetCardId, &aioIobIcca_BeginGetCardId_orig);
|
||||
execexe::trampoline_try(aio_iob_video, "aioIobIcca_EndGetCardId",
|
||||
aioIobIcca_EndGetCardId, &aioIobIcca_EndGetCardId_orig);
|
||||
|
||||
const auto aio_iob = "aio-iob.dll";
|
||||
execexe::trampoline_try(aio_iob, "aioNMgrIob2_Create",
|
||||
aioNMgrIob2_Create, &aioNMgrIob2_Create_orig);
|
||||
execexe::trampoline_try(aio_iob, "aioNMgrIob_BeginManage",
|
||||
aioNMgrIob_BeginManage, &aioNMgrIob_BeginManage_orig);
|
||||
|
||||
const auto aio = "aio.dll";
|
||||
execexe::trampoline_try(aio, "aioNodeMgr_Destroy",
|
||||
aioNodeMgr_Destroy, &aioNodeMgr_Destroy_orig);
|
||||
execexe::trampoline_try(aio, "aioNodeMgr_GetState",
|
||||
aioNodeMgr_GetState, &aioNodeMgr_GetState_orig);
|
||||
execexe::trampoline_try(aio, "aioNodeMgr_IsReady",
|
||||
aioNodeMgr_IsReady, &aioNodeMgr_IsReady_orig);
|
||||
execexe::trampoline_try(aio, "aioNodeCtl_Destroy",
|
||||
aioNodeCtl_Destroy, &aioNodeCtl_Destroy_orig);
|
||||
execexe::trampoline_try(aio, "aioNodeCtl_GetState",
|
||||
aioNodeCtl_GetState, &aioNodeCtl_GetState_orig);
|
||||
execexe::trampoline_try(aio, "aioNodeCtl_IsReady",
|
||||
aioNodeCtl_IsReady, &aioNodeCtl_IsReady_orig);
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,5 @@
|
||||
#pragma once
|
||||
|
||||
namespace games::udn {
|
||||
void bi2x_hook_init();
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
#include "io.h"
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
std::vector<Button> &games::udn::get_buttons() {
|
||||
static std::vector<Button> buttons;
|
||||
|
||||
if (buttons.empty()) {
|
||||
buttons = GameAPI::Buttons::getButtons("DANCE aROUND");
|
||||
|
||||
const std::vector<std::string> names {
|
||||
"Service",
|
||||
"Test",
|
||||
"Coin Mech",
|
||||
"Start",
|
||||
"Up",
|
||||
"Down",
|
||||
"Left",
|
||||
"Right",
|
||||
};
|
||||
const std::vector<unsigned short> vkey_defaults {
|
||||
0xFF,
|
||||
0xFF,
|
||||
0xFF,
|
||||
VK_RETURN,
|
||||
VK_UP,
|
||||
VK_DOWN,
|
||||
VK_LEFT,
|
||||
VK_RIGHT,
|
||||
};
|
||||
|
||||
buttons = GameAPI::Buttons::sortButtons(buttons, names, &vkey_defaults);
|
||||
}
|
||||
|
||||
return buttons;
|
||||
}
|
||||
|
||||
std::string games::udn::get_buttons_help() {
|
||||
return
|
||||
" Arrow keys: menu directions\n"
|
||||
" Enter: start/confirm\n"
|
||||
" MIDI input is disabled for this game.\n";
|
||||
}
|
||||
|
||||
std::vector<Light> &games::udn::get_lights() {
|
||||
static std::vector<Light> lights;
|
||||
|
||||
if (lights.empty()) {
|
||||
lights = GameAPI::Lights::getLights("DANCE aROUND");
|
||||
GameAPI::Lights::sortLights(
|
||||
&lights,
|
||||
"Card Reader R",
|
||||
"Card Reader G",
|
||||
"Card Reader B",
|
||||
"Start",
|
||||
"Up",
|
||||
"Down",
|
||||
"Left",
|
||||
"Right",
|
||||
"Title R",
|
||||
"Title G",
|
||||
"Title B",
|
||||
"Pillar Right Top R",
|
||||
"Pillar Right Top G",
|
||||
"Pillar Right Top B",
|
||||
"Pillar Right Bottom R",
|
||||
"Pillar Right Bottom G",
|
||||
"Pillar Right Bottom B",
|
||||
"Stage Left R",
|
||||
"Stage Left G",
|
||||
"Stage Left B",
|
||||
"Cabinet Left R",
|
||||
"Cabinet Left G",
|
||||
"Cabinet Left B",
|
||||
"Pillar Left Top R",
|
||||
"Pillar Left Top G",
|
||||
"Pillar Left Top B",
|
||||
"Pillar Left Bottom R",
|
||||
"Pillar Left Bottom G",
|
||||
"Pillar Left Bottom B",
|
||||
"Stage Right R",
|
||||
"Stage Right G",
|
||||
"Stage Right B",
|
||||
"Cabinet Right R",
|
||||
"Cabinet Right G",
|
||||
"Cabinet Right B"
|
||||
);
|
||||
}
|
||||
|
||||
return lights;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
#pragma once
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include "cfg/api.h"
|
||||
|
||||
namespace games::udn {
|
||||
namespace Buttons {
|
||||
enum {
|
||||
Service,
|
||||
Test,
|
||||
CoinMech,
|
||||
Start,
|
||||
Up,
|
||||
Down,
|
||||
Left,
|
||||
Right,
|
||||
};
|
||||
}
|
||||
|
||||
namespace Lights {
|
||||
enum udn_lights_t {
|
||||
CardReaderR,
|
||||
CardReaderG,
|
||||
CardReaderB,
|
||||
Start,
|
||||
Up,
|
||||
Down,
|
||||
Left,
|
||||
Right,
|
||||
TitleR,
|
||||
TitleG,
|
||||
TitleB,
|
||||
PillarRightTopR,
|
||||
PillarRightTopG,
|
||||
PillarRightTopB,
|
||||
PillarRightBottomR,
|
||||
PillarRightBottomG,
|
||||
PillarRightBottomB,
|
||||
StageLeftR,
|
||||
StageLeftG,
|
||||
StageLeftB,
|
||||
CabinetLeftR,
|
||||
CabinetLeftG,
|
||||
CabinetLeftB,
|
||||
PillarLeftTopR,
|
||||
PillarLeftTopG,
|
||||
PillarLeftTopB,
|
||||
PillarLeftBottomR,
|
||||
PillarLeftBottomG,
|
||||
PillarLeftBottomB,
|
||||
StageRightR,
|
||||
StageRightG,
|
||||
StageRightB,
|
||||
CabinetRightR,
|
||||
CabinetRightG,
|
||||
CabinetRightB,
|
||||
};
|
||||
}
|
||||
|
||||
std::vector<Button> &get_buttons();
|
||||
std::string get_buttons_help();
|
||||
std::vector<Light> &get_lights();
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
// QueryDisplayConfig
|
||||
#define _WIN32_WINNT 0x0601
|
||||
|
||||
#include "udn.h"
|
||||
|
||||
#include <format>
|
||||
|
||||
#include "acioemu/handle.h"
|
||||
#include "bi2x_hook.h"
|
||||
#include "cfg/screen_resize.h"
|
||||
#include "hooks/devicehook.h"
|
||||
#include "hooks/graphics/graphics.h"
|
||||
#include "rawinput/rawinput.h"
|
||||
#include "util/detour.h"
|
||||
#include "util/execexe.h"
|
||||
#include "util/logging.h"
|
||||
#include "util/unity_player.h"
|
||||
#include "util/utils.h"
|
||||
|
||||
namespace games::udn {
|
||||
std::string UDN_INJECT_ARGS = "";
|
||||
bool UDN_NO_IO = false;
|
||||
|
||||
static acioemu::ACIOHandle *acio_handle = nullptr;
|
||||
static const std::wstring port_name = L"COM1";
|
||||
|
||||
static decltype(RegisterRawInputDevices) *RegisterRawInputDevices_orig = nullptr;
|
||||
static decltype(EnumDisplaySettingsW) *EnumDisplaySettingsW_orig = nullptr;
|
||||
static decltype(QueryDisplayConfig) *QueryDisplayConfig_orig = nullptr;
|
||||
|
||||
// Unity reapplies its cabinet window settings after startup. Use the
|
||||
// existing graphics message callback so changes stay on the window thread.
|
||||
static LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM w_param, LPARAM l_param) {
|
||||
if (!GRAPHICS_WINDOWED || GRAPHICS_HOOKED_WINDOW != window) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
static bool interactive_resize = false;
|
||||
switch (message) {
|
||||
case WM_ENTERSIZEMOVE:
|
||||
interactive_resize = true;
|
||||
break;
|
||||
case WM_EXITSIZEMOVE:
|
||||
interactive_resize = false;
|
||||
break;
|
||||
case WM_STYLECHANGING:
|
||||
if (w_param == static_cast<WPARAM>(GWL_STYLE)) {
|
||||
auto styles = reinterpret_cast<STYLESTRUCT *>(l_param);
|
||||
styles->styleNew &= ~WS_POPUP;
|
||||
if (cfg::SCREENRESIZE->window_decoration == cfg::WindowDecorationMode::Borderless) {
|
||||
styles->styleNew &= ~WS_OVERLAPPEDWINDOW;
|
||||
} else {
|
||||
styles->styleNew |= WS_OVERLAPPEDWINDOW;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case WM_WINDOWPOSCHANGING:
|
||||
if (!interactive_resize && cfg::SCREENRESIZE->enable_window_resize) {
|
||||
auto position = reinterpret_cast<WINDOWPOS *>(l_param);
|
||||
// The shared WM_MOVE/WM_SIZE handlers keep these values in
|
||||
// sync with interactive changes and the overlay settings.
|
||||
if (!(position->flags & SWP_NOMOVE)) {
|
||||
position->x = cfg::SCREENRESIZE->window_offset_x;
|
||||
position->y = cfg::SCREENRESIZE->window_offset_y;
|
||||
}
|
||||
if (!(position->flags & SWP_NOSIZE)) {
|
||||
position->cx = cfg::SCREENRESIZE->client_width +
|
||||
cfg::SCREENRESIZE->window_deco_width;
|
||||
position->cy = cfg::SCREENRESIZE->client_height +
|
||||
cfg::SCREENRESIZE->window_deco_height;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static BOOL WINAPI RegisterRawInputDevices_hook(
|
||||
PCRAWINPUTDEVICE devices, UINT device_count, UINT structure_size) {
|
||||
|
||||
if (devices && device_count > 0 && devices[0].hwndTarget == RI_MGR->input_hwnd) {
|
||||
return RegisterRawInputDevices_orig(devices, device_count, structure_size);
|
||||
}
|
||||
|
||||
SetLastError(0xDEADBEEF);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
static BOOL WINAPI EnumDisplaySettingsW_hook(
|
||||
LPCWSTR device_name, DWORD mode_number, DEVMODEW *mode) {
|
||||
|
||||
const auto result = EnumDisplaySettingsW_orig(device_name, mode_number, mode);
|
||||
if (result && mode_number == ENUM_CURRENT_SETTINGS) {
|
||||
mode->dmPelsWidth = 1920;
|
||||
mode->dmPelsHeight = 1080;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
static LONG WINAPI QueryDisplayConfig_hook(
|
||||
UINT32, UINT32 *, DISPLAYCONFIG_PATH_INFO *, UINT32 *, DISPLAYCONFIG_MODE_INFO *,
|
||||
DISPLAYCONFIG_TOPOLOGY_ID *) {
|
||||
return ERROR_NOT_SUPPORTED;
|
||||
}
|
||||
|
||||
void UDNGame::pre_attach() {
|
||||
// The title has no MIDI controls. The legacy WinMM provider can fault in
|
||||
// MMDevAPI while Unity and its audio backend initialize concurrently, so
|
||||
// disable MIDI enumeration for this game.
|
||||
rawinput::DISABLE_MIDI = true;
|
||||
log_info("udn", "MIDI input disabled to avoid WinMM initialization errors");
|
||||
}
|
||||
|
||||
void UDNGame::attach() {
|
||||
Game::attach();
|
||||
|
||||
acio_handle = new acioemu::ACIOHandle(port_name.c_str(), 1);
|
||||
devicehook_init_trampoline();
|
||||
devicehook_add(acio_handle);
|
||||
|
||||
execexe::init();
|
||||
execexe::init_deferred([]() {
|
||||
execexe::init_port_hook(port_name, acio_handle);
|
||||
|
||||
// Runtime import names omit the "lib" prefix.
|
||||
execexe::load_library("aio.dll");
|
||||
execexe::load_library("aio-iob.dll");
|
||||
execexe::load_library("aio-iob_video.dll");
|
||||
execexe::load_library("aio-iob2_video.dll");
|
||||
execexe::load_library("win10actlog.dll", false);
|
||||
|
||||
#if SPICE64
|
||||
if (!UDN_NO_IO) {
|
||||
bi2x_hook_init();
|
||||
}
|
||||
#endif
|
||||
});
|
||||
|
||||
const auto user32_dll = "user32.dll";
|
||||
detour::trampoline_try(user32_dll, "RegisterRawInputDevices",
|
||||
RegisterRawInputDevices_hook, &RegisterRawInputDevices_orig);
|
||||
if (GRAPHICS_WINDOWED) {
|
||||
// Keep Unity's cabinet-sized UI in windowed mode. Fullscreen uses
|
||||
// the real display topology and resolution.
|
||||
detour::trampoline_try(user32_dll, "QueryDisplayConfig",
|
||||
QueryDisplayConfig_hook, &QueryDisplayConfig_orig);
|
||||
detour::trampoline_try(user32_dll, "EnumDisplaySettingsW",
|
||||
EnumDisplaySettingsW_hook, &EnumDisplaySettingsW_orig);
|
||||
graphics_add_wnd_proc(window_proc);
|
||||
}
|
||||
|
||||
if (GRAPHICS_SHOW_CURSOR) {
|
||||
unity_utils::force_show_cursor(true);
|
||||
}
|
||||
|
||||
unity_utils::set_args(
|
||||
std::format("{} {}{}",
|
||||
GetCommandLineA(),
|
||||
UDN_INJECT_ARGS,
|
||||
unity_utils::get_unity_player_args()));
|
||||
}
|
||||
|
||||
void UDNGame::detach() {
|
||||
Game::detach();
|
||||
graphics_remove_wnd_proc(window_proc);
|
||||
devicehook_dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include "games/game.h"
|
||||
|
||||
namespace games::udn {
|
||||
extern std::string UDN_INJECT_ARGS;
|
||||
extern bool UDN_NO_IO;
|
||||
|
||||
class UDNGame : public games::Game {
|
||||
public:
|
||||
UDNGame() : Game("DANCE aROUND") {}
|
||||
|
||||
virtual void pre_attach() override;
|
||||
virtual void attach() override;
|
||||
virtual void detach() override;
|
||||
};
|
||||
}
|
||||
@@ -29,6 +29,10 @@ DEFINE_GUID(IID_IAudioClient,
|
||||
0x1cb9ad4c, 0xdbfa, 0x4c32,
|
||||
0xb1, 0x78, 0xc2, 0xf5, 0x68, 0xa7, 0x03, 0xb2);
|
||||
|
||||
DEFINE_GUID(IID_IAudioClient3,
|
||||
0x7ed4ee07, 0x8e67, 0x4cd4,
|
||||
0x8c, 0x1a, 0x2b, 0x7a, 0x59, 0x87, 0xad, 0x42);
|
||||
|
||||
DEFINE_GUID(IID_IAudioClock,
|
||||
0xcd63314f, 0x3fba, 0x4a1b,
|
||||
0x81, 0x2c, 0xef, 0x96, 0x35, 0x87, 0x28, 0xe7);
|
||||
|
||||
@@ -30,6 +30,7 @@ void graphics_d3d11_shutdown() {}
|
||||
#include <dxgi.h>
|
||||
#include <dxgi1_2.h>
|
||||
|
||||
#include "avs/game.h"
|
||||
#include "d3d11_internal.h"
|
||||
#include "util/nt_loader.h"
|
||||
|
||||
@@ -237,10 +238,11 @@ bool d3dcompiler_available() {
|
||||
} // namespace
|
||||
|
||||
void graphics_d3d11_init() {
|
||||
// dx11 titles always run under execexe. skipping on pure-dx9 games keeps
|
||||
// their startup path completely untouched (no exports patched, no poll
|
||||
// thread, no LDR callback).
|
||||
if (!GetModuleHandleW(L"execexe.dll")) {
|
||||
// dx11 titles run under execexe, except Silent Scope: Bone Eater, whose Aska
|
||||
// engine LoadLibrary's d3d11 itself. skipping on pure-dx9 games keeps their
|
||||
// startup path completely untouched (no exports patched, no poll thread, no
|
||||
// LDR callback).
|
||||
if (!GetModuleHandleW(L"execexe.dll") && !avs::game::is_model("NDD")) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ namespace d3d11_hooks {
|
||||
// ignore_hwnd.
|
||||
void note_main_hwnd(HWND hwnd);
|
||||
HWND main_hwnd();
|
||||
bool is_main_game_swapchain(IDXGISwapChain *swapchain);
|
||||
void ignore_hwnd(HWND hwnd);
|
||||
|
||||
// capture backbuffer to PNG if a screenshot was requested.
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
#include <dxgi1_2.h>
|
||||
|
||||
#include "d3d11_internal.h"
|
||||
#include "d3d11_swapchain_udn.h"
|
||||
|
||||
#include "external/imgui/imgui.h"
|
||||
#include "external/imgui/backends/imgui_impl_dx11.h"
|
||||
@@ -115,34 +116,6 @@ bool looks_like_game_window(HWND hwnd) {
|
||||
&& client.bottom > client.top;
|
||||
}
|
||||
|
||||
// only the main game window; ignore sub-screens / IME helpers.
|
||||
bool is_main_game_swapchain(IDXGISwapChain *swapchain) {
|
||||
DXGI_SWAP_CHAIN_DESC desc {};
|
||||
if (!swapchain || FAILED(swapchain->GetDesc(&desc)) || !desc.OutputWindow) {
|
||||
return false;
|
||||
}
|
||||
|
||||
HWND main = d3d11_hooks::main_hwnd();
|
||||
if (!main) {
|
||||
// no creation hook recorded a window, so fall back to the presenting one;
|
||||
// the choice is permanent, so require a plausible game window
|
||||
if (!looks_like_game_window(desc.OutputWindow)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
log_misc(
|
||||
"graphics::d3d11",
|
||||
"try to notemain hwnd from swapchain present: 0x{:x}",
|
||||
(uintptr_t)desc.OutputWindow);
|
||||
|
||||
d3d11_hooks::note_main_hwnd(desc.OutputWindow);
|
||||
|
||||
// it may have been ignored, or another thread may have won the slot
|
||||
main = d3d11_hooks::main_hwnd();
|
||||
}
|
||||
return desc.OutputWindow == main;
|
||||
}
|
||||
|
||||
// checks are ordered cheapest first, since this runs on every present
|
||||
void try_create_overlay(IDXGISwapChain *swapchain) {
|
||||
if (!swapchain) {
|
||||
@@ -160,7 +133,7 @@ void try_create_overlay(IDXGISwapChain *swapchain) {
|
||||
}
|
||||
|
||||
// ignore sub windows
|
||||
if (!is_main_game_swapchain(swapchain)) {
|
||||
if (!d3d11_hooks::is_main_game_swapchain(swapchain)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -198,7 +171,7 @@ void try_create_overlay(IDXGISwapChain *swapchain) {
|
||||
void pump_frame(IDXGISwapChain *swapchain) {
|
||||
const bool has_overlay =
|
||||
overlay::OVERLAY && overlay::OVERLAY->uses_swapchain(swapchain);
|
||||
if (!has_overlay && !is_main_game_swapchain(swapchain)) {
|
||||
if (!has_overlay && !d3d11_hooks::is_main_game_swapchain(swapchain)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -240,8 +213,10 @@ HRESULT STDMETHODCALLTYPE Present_hook(
|
||||
{
|
||||
// a test present doesn't display anything; don't pick a window or take a screenshot off it
|
||||
if (!(Flags & DXGI_PRESENT_TEST)) {
|
||||
d3d11_hooks::udn::schedule_window_attach(swapchain);
|
||||
try_create_overlay(swapchain);
|
||||
pump_frame(swapchain);
|
||||
d3d11_hooks::udn::apply_present_policy(swapchain, SyncInterval);
|
||||
}
|
||||
return Present_orig(swapchain, SyncInterval, Flags);
|
||||
}
|
||||
@@ -251,8 +226,10 @@ HRESULT STDMETHODCALLTYPE Present1_hook(
|
||||
const DXGI_PRESENT_PARAMETERS *pParams)
|
||||
{
|
||||
if (!(Flags & DXGI_PRESENT_TEST)) {
|
||||
d3d11_hooks::udn::schedule_window_attach(swapchain);
|
||||
try_create_overlay(swapchain);
|
||||
pump_frame(swapchain);
|
||||
d3d11_hooks::udn::apply_present_policy(swapchain, SyncInterval);
|
||||
}
|
||||
return Present1_orig(swapchain, SyncInterval, Flags, pParams);
|
||||
}
|
||||
@@ -287,6 +264,33 @@ namespace {
|
||||
std::atomic<HWND> g_ignored_hwnd { nullptr };
|
||||
}
|
||||
|
||||
bool is_main_game_swapchain(IDXGISwapChain *swapchain) {
|
||||
DXGI_SWAP_CHAIN_DESC desc {};
|
||||
if (!swapchain || FAILED(swapchain->GetDesc(&desc)) || !desc.OutputWindow) {
|
||||
return false;
|
||||
}
|
||||
|
||||
HWND main = d3d11_hooks::main_hwnd();
|
||||
if (!main) {
|
||||
// no creation hook recorded a window, so fall back to the presenting one;
|
||||
// the choice is permanent, so require a plausible game window
|
||||
if (!looks_like_game_window(desc.OutputWindow)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
log_misc(
|
||||
"graphics::d3d11",
|
||||
"try to notemain hwnd from swapchain present: 0x{:x}",
|
||||
(uintptr_t)desc.OutputWindow);
|
||||
|
||||
d3d11_hooks::note_main_hwnd(desc.OutputWindow);
|
||||
|
||||
// it may have been ignored, or another thread may have won the slot
|
||||
main = d3d11_hooks::main_hwnd();
|
||||
}
|
||||
return desc.OutputWindow == main;
|
||||
}
|
||||
|
||||
void note_main_hwnd(HWND hwnd) {
|
||||
if (!hwnd || hwnd == g_ignored_hwnd.load()) {
|
||||
return;
|
||||
@@ -326,6 +330,8 @@ void install_swapchain_hooks(IDXGISwapChain *swapchain) {
|
||||
}
|
||||
}
|
||||
|
||||
udn::install_swapchain_hooks(swapchain);
|
||||
|
||||
if (!g_swapchain1_hooked) {
|
||||
IDXGISwapChain1 *sc1 = nullptr;
|
||||
if (SUCCEEDED(swapchain->QueryInterface(IID_PPV_ARGS(&sc1))) && sc1) {
|
||||
|
||||
Loaded 100 of 151 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user