Initial version
This commit is contained in:
1 parent
2cff35f215
commit
fe8e2cb5e7
360 files changed
+253989
-74
No files matched your search
@@ -0,0 +1,614 @@
|
||||
|
||||
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::alloc::Layout;
|
||||
use std::collections::VecDeque;
|
||||
use std::ffi::c_void;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use opus_pure::OpusDecoder;
|
||||
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
|
||||
use windows_sys::Win32::System::Threading::{CreateEventW, SetEvent};
|
||||
|
||||
use super::xasync::E_INVALIDARG;
|
||||
use super::xgameruntime::{HRESULT, S_OK};
|
||||
use crate::hle::{HleModule};
|
||||
use crate::hle_export;
|
||||
|
||||
const E_NOTIMPL: HRESULT = 0x8000_4001_u32 as i32;
|
||||
const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32;
|
||||
const QUEUE_FULL: HRESULT = 0x8AC8_1000_u32 as i32;
|
||||
|
||||
pub(crate) const PENDING_RESULTS: HRESULT = 0x8AC8_1001_u32 as i32;
|
||||
const INVALID_COMMAND: HRESULT = 0x8AC8_1002_u32 as i32;
|
||||
const INVALID_STREAM: HRESULT = 0x8AC8_1003_u32 as i32;
|
||||
const ALREADY_ACTIVE: HRESULT = 0x8AC8_1005_u32 as i32;
|
||||
const BAD_PACKET: HRESULT = 0x8AC8_1008_u32 as i32;
|
||||
|
||||
const DECODE_OPUS: u32 = 1;
|
||||
const DECODE_CONVERT_OPUS: u32 = 2;
|
||||
const CONVERT_PCM: u32 = 3;
|
||||
|
||||
const ACTIVATE: u32 = 1;
|
||||
const DEACTIVATE: u32 = 2;
|
||||
const PROCESS: u32 = 3;
|
||||
const NOTIFY: u32 = 4;
|
||||
const RESET: u32 = 5;
|
||||
|
||||
const SIGNAL: u32 = 1;
|
||||
const FLUSH: u32 = 2;
|
||||
const RESET_DECODER: u32 = 4;
|
||||
|
||||
const DEINTERLEAVED_INPUT: u32 = 2;
|
||||
const DEINTERLEAVED_OUTPUT: u32 = 4;
|
||||
const RESULT_EVENT: u32 = 8;
|
||||
|
||||
const MAX_FRAMES: usize = 5760;
|
||||
|
||||
#[repr(C)]
|
||||
pub struct ConnectInput {
|
||||
process: u32,
|
||||
streams: u32,
|
||||
commands_per_stream: u32,
|
||||
memory: u32,
|
||||
frames_per_output: u32,
|
||||
options: u32,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct ConnectOutput {
|
||||
memory: *mut c_void,
|
||||
result_event: HANDLE,
|
||||
}
|
||||
|
||||
#[repr(C, packed)]
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct CommandId {
|
||||
kind: u32,
|
||||
stream: u32,
|
||||
sequence: u32,
|
||||
options: u32,
|
||||
context: u64,
|
||||
}
|
||||
|
||||
#[repr(C, packed)]
|
||||
struct Activate {
|
||||
id: CommandId,
|
||||
channels: u32,
|
||||
init_length: u32,
|
||||
init: *const c_void,
|
||||
start_pitch: f32,
|
||||
processing_length: u32,
|
||||
processing: *mut c_void,
|
||||
}
|
||||
|
||||
#[repr(C, packed)]
|
||||
#[derive(Clone, Copy)]
|
||||
struct Process {
|
||||
id: CommandId,
|
||||
pitch_ramp: f32,
|
||||
target_pitch: f32,
|
||||
first_frame: u32,
|
||||
frame_count: u32,
|
||||
input_length: u32,
|
||||
input: *const u8,
|
||||
output_length: u32,
|
||||
output: *mut u8,
|
||||
}
|
||||
|
||||
#[repr(C, packed)]
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct ApuResult {
|
||||
id: CommandId,
|
||||
state: u32,
|
||||
state_data: u64,
|
||||
usec: u64,
|
||||
error: HRESULT,
|
||||
frames: u32,
|
||||
output_length: u32,
|
||||
output: *mut u8,
|
||||
pitch: f32,
|
||||
input_length: u32,
|
||||
input: *const u8,
|
||||
}
|
||||
|
||||
unsafe impl Send for ApuResult {}
|
||||
|
||||
pub struct Connection {
|
||||
memory: *mut u8,
|
||||
layout: Layout,
|
||||
event: HANDLE,
|
||||
options: u32,
|
||||
per_stream: u32,
|
||||
|
||||
process: u32,
|
||||
chunk: usize,
|
||||
state: Mutex<State>,
|
||||
}
|
||||
|
||||
struct State {
|
||||
streams: Vec<Option<Stream>>,
|
||||
|
||||
queued: Vec<u32>,
|
||||
results: VecDeque<ApuResult>,
|
||||
commands: u32,
|
||||
dequeued: u32,
|
||||
}
|
||||
|
||||
fn lock(c: &Connection) -> std::sync::MutexGuard<'_, State> {
|
||||
c.state.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
pub extern "system" fn XApuConnect(
|
||||
input: *const ConnectInput,
|
||||
output: *mut ConnectOutput,
|
||||
handle: *mut *mut Connection,
|
||||
) -> HRESULT {
|
||||
if input.is_null() || output.is_null() || handle.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
|
||||
let input = unsafe { &*input };
|
||||
if !(1..=500).contains(&input.streams)
|
||||
|| !(1..=16).contains(&input.commands_per_stream)
|
||||
|| input.memory == 0
|
||||
{
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
|
||||
match (input.process, input.frames_per_output) {
|
||||
(DECODE_OPUS, 0) => {}
|
||||
(DECODE_CONVERT_OPUS | CONVERT_PCM, 256 | 480 | 512 | 960 | 1024) => {}
|
||||
(DECODE_OPUS | DECODE_CONVERT_OPUS | CONVERT_PCM, _) => return E_INVALIDARG,
|
||||
(process, _) => {
|
||||
tracing::warn!(process, "audio decoder: unknown processing kind");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
}
|
||||
let Ok(layout) = Layout::from_size_align(input.memory as usize, 16) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
|
||||
let memory = unsafe { std::alloc::alloc_zeroed(layout) };
|
||||
if memory.is_null() {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
let event = if input.options & RESULT_EVENT != 0 {
|
||||
|
||||
let event = unsafe { CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) };
|
||||
if event.is_null() {
|
||||
|
||||
unsafe { std::alloc::dealloc(memory, layout) };
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
event
|
||||
} else {
|
||||
std::ptr::null_mut()
|
||||
};
|
||||
let streams = input.streams as usize;
|
||||
tracing::info!(
|
||||
streams,
|
||||
memory = input.memory,
|
||||
options = input.options,
|
||||
"audio decoder connected"
|
||||
);
|
||||
let connection = Box::new(Connection {
|
||||
memory,
|
||||
layout,
|
||||
event,
|
||||
options: input.options,
|
||||
per_stream: input.commands_per_stream,
|
||||
process: input.process,
|
||||
chunk: input.frames_per_output as usize,
|
||||
state: Mutex::new(State {
|
||||
streams: (0..streams).map(|_| None).collect(),
|
||||
queued: vec![0; streams],
|
||||
results: VecDeque::new(),
|
||||
commands: 0,
|
||||
dequeued: 0,
|
||||
}),
|
||||
});
|
||||
|
||||
unsafe {
|
||||
output.write(ConnectOutput {
|
||||
memory: memory.cast(),
|
||||
result_event: event,
|
||||
});
|
||||
handle.write(Box::into_raw(connection));
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub extern "system" fn XApuDisconnect(handle: *mut Connection) -> HRESULT {
|
||||
if handle.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
|
||||
let connection = unsafe { Box::from_raw(handle) };
|
||||
if !connection.event.is_null() {
|
||||
|
||||
unsafe { CloseHandle(connection.event) };
|
||||
}
|
||||
|
||||
unsafe { std::alloc::dealloc(connection.memory, connection.layout) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub extern "system" fn XApuEnqueueCommand(
|
||||
handle: *mut Connection,
|
||||
command: *const CommandId,
|
||||
total: *mut u32,
|
||||
) -> HRESULT {
|
||||
if handle.is_null() || command.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
|
||||
let (connection, id) = unsafe { (&*handle, command.read_unaligned()) };
|
||||
let mut state = lock(connection);
|
||||
let stream = id.stream as usize;
|
||||
if stream >= state.streams.len() {
|
||||
return INVALID_STREAM;
|
||||
}
|
||||
if state.queued[stream] >= connection.per_stream {
|
||||
return QUEUE_FULL;
|
||||
}
|
||||
let mut result = ApuResult {
|
||||
id,
|
||||
state: 0,
|
||||
state_data: 0,
|
||||
usec: 0,
|
||||
error: S_OK,
|
||||
frames: 0,
|
||||
output_length: 0,
|
||||
output: std::ptr::null_mut(),
|
||||
pitch: 1.0,
|
||||
input_length: 0,
|
||||
input: std::ptr::null(),
|
||||
};
|
||||
let slot = &mut state.streams[stream];
|
||||
match id.kind {
|
||||
ACTIVATE => {
|
||||
|
||||
let activate = unsafe { command.cast::<Activate>().read_unaligned() };
|
||||
let (channels, start_pitch) = (activate.channels, activate.start_pitch);
|
||||
tracing::debug!(stream, channels, process = connection.process, "audio stream activated");
|
||||
result.error = if slot.is_some() {
|
||||
ALREADY_ACTIVE
|
||||
} else {
|
||||
match Stream::new(connection.process, channels, start_pitch) {
|
||||
Some(s) => {
|
||||
*slot = Some(s);
|
||||
S_OK
|
||||
}
|
||||
None => E_INVALIDARG,
|
||||
}
|
||||
};
|
||||
}
|
||||
DEACTIVATE => {
|
||||
*slot = None;
|
||||
#[cfg(feature = "diagnostics")]
|
||||
opus_log(handle, stream, None);
|
||||
}
|
||||
RESET => {
|
||||
if let Some(s) = slot {
|
||||
s.reset(id.options & RESET_DECODER != 0);
|
||||
}
|
||||
}
|
||||
NOTIFY => {}
|
||||
PROCESS => {
|
||||
|
||||
let command = unsafe { command.cast::<Process>().read_unaligned() };
|
||||
match slot {
|
||||
Some(Stream { decoder: Some(d), converter: None, .. }) => {
|
||||
process(d, connection.options, &command, &mut result);
|
||||
}
|
||||
Some(s) => s.convert(connection, &command, &mut result),
|
||||
None => result.error = INVALID_STREAM,
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
opus_log(handle, stream, Some(result.frames));
|
||||
}
|
||||
_ => return INVALID_COMMAND,
|
||||
}
|
||||
state.queued[stream] += 1;
|
||||
state.commands = state.commands.wrapping_add(1);
|
||||
state.results.push_back(result);
|
||||
if !total.is_null() {
|
||||
|
||||
unsafe { total.write(state.commands) };
|
||||
}
|
||||
if id.options & SIGNAL != 0 && !connection.event.is_null() {
|
||||
|
||||
unsafe { SetEvent(connection.event) };
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
struct Stream {
|
||||
decoder: Option<OpusDecoder>,
|
||||
converter: Option<Converter>,
|
||||
}
|
||||
|
||||
impl Stream {
|
||||
fn new(process: u32, channels: u32, start_pitch: f32) -> Option<Stream> {
|
||||
if !(1..=2).contains(&channels) {
|
||||
return None;
|
||||
}
|
||||
let channels = channels as usize;
|
||||
let decoder = match process {
|
||||
CONVERT_PCM => None,
|
||||
_ => Some(OpusDecoder::new(48_000, channels).ok()?),
|
||||
};
|
||||
let converter = (process != DECODE_OPUS).then(|| Converter::new(channels, start_pitch));
|
||||
Some(Stream { decoder, converter })
|
||||
}
|
||||
|
||||
fn reset(&mut self, decoder_only: bool) {
|
||||
if let Some(d) = &mut self.decoder {
|
||||
let _ = d.reset_state();
|
||||
}
|
||||
if let Some(c) = &mut self.converter
|
||||
&& !decoder_only
|
||||
{
|
||||
c.reset();
|
||||
}
|
||||
}
|
||||
|
||||
fn convert(&mut self, connection: &Connection, command: &Process, result: &mut ApuResult) {
|
||||
let Some(converter) = &mut self.converter else {
|
||||
result.error = INVALID_STREAM;
|
||||
return;
|
||||
};
|
||||
let channels = converter.channels;
|
||||
let (input, input_length) = (command.input, command.input_length);
|
||||
let (output, output_length) = (command.output, command.output_length);
|
||||
(result.input, result.input_length, result.output) = (input, input_length, output);
|
||||
if input.is_null() || output.is_null() {
|
||||
result.error = E_INVALIDARG;
|
||||
return;
|
||||
}
|
||||
|
||||
let bytes = unsafe { std::slice::from_raw_parts(input, input_length as usize) };
|
||||
let frames: Vec<f32> = match &mut self.decoder {
|
||||
Some(decoder) => {
|
||||
let mut pcm = vec![0f32; MAX_FRAMES * channels];
|
||||
let Ok(decoded) = decoder.decode(bytes, MAX_FRAMES, &mut pcm) else {
|
||||
result.error = BAD_PACKET;
|
||||
return;
|
||||
};
|
||||
let first = (command.first_frame as usize).min(decoded);
|
||||
let count = (decoded - first).min(command.frame_count as usize);
|
||||
pcm[first * channels..(first + count) * channels].to_vec()
|
||||
}
|
||||
None => {
|
||||
let samples: Vec<f32> = bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect();
|
||||
let count = samples.len() / channels;
|
||||
if connection.options & DEINTERLEAVED_INPUT != 0 && channels == 2 {
|
||||
(0..count).flat_map(|i| [samples[i], samples[count + i]]).collect()
|
||||
} else {
|
||||
samples[..count * channels].to_vec()
|
||||
}
|
||||
}
|
||||
};
|
||||
let unconverted_before = converter.input.len() / channels;
|
||||
converter.input.extend_from_slice(&frames);
|
||||
let used = converter.run(command.target_pitch, command.pitch_ramp);
|
||||
let used_here = used.min(unconverted_before + frames.len() / channels);
|
||||
|
||||
let chunk = connection.chunk;
|
||||
let deinterleaved = connection.options & DEINTERLEAVED_OUTPUT != 0 && channels == 2;
|
||||
let ready = converter.output.len() / channels;
|
||||
let flush = command.id.options & FLUSH != 0;
|
||||
let mut give = if ready >= chunk { chunk } else if flush { ready } else { 0 };
|
||||
|
||||
let room = output_length as usize / 4;
|
||||
give = give.min(if deinterleaved { room.saturating_sub(chunk).min(chunk) } else { room / channels });
|
||||
let out: Vec<f32> = converter.output.drain(..give * channels).collect();
|
||||
|
||||
let write = |at: usize, v: f32| unsafe { output.add(at * 4).cast::<[u8; 4]>().write_unaligned(v.to_le_bytes()) };
|
||||
for i in 0..give {
|
||||
if deinterleaved {
|
||||
write(i, out[2 * i]);
|
||||
write(chunk + i, out[2 * i + 1]);
|
||||
} else {
|
||||
for c in 0..channels {
|
||||
write(i * channels + c, out[i * channels + c]);
|
||||
}
|
||||
}
|
||||
}
|
||||
let left = converter.output.len() / channels;
|
||||
result.frames = give as u32;
|
||||
result.output_length = match (give, deinterleaved) {
|
||||
(0, _) => 0,
|
||||
(_, true) => ((chunk + give) * 4) as u32,
|
||||
_ => (give * channels * 4) as u32,
|
||||
};
|
||||
result.pitch = converter.pitch;
|
||||
result.state = (u32::from(give > 0) * OUTPUT_READY)
|
||||
| if left >= chunk { MORE_OUTPUT_AVAILABLE } else { NEED_MORE_INPUT };
|
||||
|
||||
let kept = (converter.input.len() / channels) as u64;
|
||||
result.state_data = (left as u64).min(0xffff) | (used_here as u64).min(0xffff) << 16 | kept.min(0xffff) << 48;
|
||||
}
|
||||
}
|
||||
|
||||
const OUTPUT_READY: u32 = 1;
|
||||
const NEED_MORE_INPUT: u32 = 2;
|
||||
const MORE_OUTPUT_AVAILABLE: u32 = 4;
|
||||
|
||||
const PITCHES: std::ops::RangeInclusive<f32> = 0.125..=8.0;
|
||||
|
||||
struct Converter {
|
||||
channels: usize,
|
||||
start_pitch: f32,
|
||||
pitch: f32,
|
||||
|
||||
input: Vec<f32>,
|
||||
pos: f64,
|
||||
|
||||
output: VecDeque<f32>,
|
||||
}
|
||||
|
||||
impl Converter {
|
||||
fn new(channels: usize, start_pitch: f32) -> Converter {
|
||||
let start_pitch = if start_pitch.is_finite() { start_pitch.clamp(*PITCHES.start(), *PITCHES.end()) } else { 1.0 };
|
||||
Converter { channels, start_pitch, pitch: start_pitch, input: Vec::new(), pos: 0.0, output: VecDeque::new() }
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
*self = Converter::new(self.channels, self.start_pitch);
|
||||
}
|
||||
|
||||
fn run(&mut self, target: f32, ramp: f32) -> usize {
|
||||
let channels = self.channels;
|
||||
let frames = self.input.len() / channels;
|
||||
let target = if target.is_finite() { target.clamp(*PITCHES.start(), *PITCHES.end()) } else { self.pitch };
|
||||
let ramp = ramp.abs();
|
||||
while (self.pos as usize) + 1 < frames {
|
||||
let i = self.pos as usize;
|
||||
let t = (self.pos - i as f64) as f32;
|
||||
for c in 0..channels {
|
||||
let (a, b) = (self.input[i * channels + c], self.input[(i + 1) * channels + c]);
|
||||
self.output.push_back(a + (b - a) * t);
|
||||
}
|
||||
self.pos += f64::from(self.pitch);
|
||||
|
||||
self.pitch = if ramp == 0.0 {
|
||||
target
|
||||
} else if self.pitch < target {
|
||||
(self.pitch + ramp).min(target)
|
||||
} else {
|
||||
(self.pitch - ramp).max(target)
|
||||
};
|
||||
}
|
||||
let used = (self.pos as usize).min(frames);
|
||||
self.input.drain(..used * channels);
|
||||
self.pos -= used as f64;
|
||||
used
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "diagnostics")]
|
||||
fn opus_log(connection: *const Connection, stream: usize, frames: Option<u32>) {
|
||||
use std::collections::BTreeMap;
|
||||
use std::time::Instant;
|
||||
type Log = (Option<Instant>, BTreeMap<(usize, usize), u64>);
|
||||
static LOG: Mutex<Log> = Mutex::new((None, BTreeMap::new()));
|
||||
let Some(ms) = super::audio::voice_log_ms() else {
|
||||
return;
|
||||
};
|
||||
let mut log = LOG.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let key = (connection as usize, stream);
|
||||
let Some(frames) = frames else {
|
||||
log.1.remove(&key);
|
||||
return;
|
||||
};
|
||||
*log.1.entry(key).or_default() += u64::from(frames);
|
||||
if log.0.is_some_and(|t| t.elapsed().as_millis() < ms) {
|
||||
return;
|
||||
}
|
||||
log.0 = Some(Instant::now());
|
||||
for (&(connection, stream), &frames) in &log.1 {
|
||||
tracing::info!(
|
||||
connection = format_args!("{connection:#x}"),
|
||||
stream,
|
||||
frames,
|
||||
"Opus stream position"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn process(decoder: &mut OpusDecoder, options: u32, command: &Process, result: &mut ApuResult) {
|
||||
let channels = decoder.channels();
|
||||
let (input, input_length) = (command.input, command.input_length);
|
||||
let (output, output_length) = (command.output, command.output_length);
|
||||
result.input = input;
|
||||
result.input_length = input_length;
|
||||
result.output = output;
|
||||
if input.is_null() || output.is_null() || input_length == 0 {
|
||||
result.error = E_INVALIDARG;
|
||||
return;
|
||||
}
|
||||
|
||||
let packet = unsafe { std::slice::from_raw_parts(input, input_length as usize) };
|
||||
let mut pcm = vec![0f32; MAX_FRAMES * channels];
|
||||
let decoded = match decoder.decode(packet, MAX_FRAMES, &mut pcm) {
|
||||
Ok(n) => n,
|
||||
Err(_) => {
|
||||
result.error = BAD_PACKET;
|
||||
return;
|
||||
}
|
||||
};
|
||||
let first = (command.first_frame as usize).min(decoded);
|
||||
let frames = (decoded - first)
|
||||
.min(command.frame_count as usize)
|
||||
.min(output_length as usize / (4 * channels));
|
||||
let kept = &pcm[first * channels..(first + frames) * channels];
|
||||
let bytes = frames * channels * 4;
|
||||
if bytes > 0 {
|
||||
|
||||
let out = unsafe { std::slice::from_raw_parts_mut(output, bytes) };
|
||||
if options & DEINTERLEAVED_OUTPUT != 0 && channels == 2 {
|
||||
let (left, right) = out.split_at_mut(frames * 4);
|
||||
let (left, _) = left.as_chunks_mut::<4>();
|
||||
let (right, _) = right.as_chunks_mut::<4>();
|
||||
for (i, frame) in kept.as_chunks::<2>().0.iter().enumerate() {
|
||||
left[i] = frame[0].to_le_bytes();
|
||||
right[i] = frame[1].to_le_bytes();
|
||||
}
|
||||
} else {
|
||||
for (dst, &sample) in out.as_chunks_mut::<4>().0.iter_mut().zip(kept) {
|
||||
*dst = sample.to_le_bytes();
|
||||
}
|
||||
}
|
||||
}
|
||||
result.frames = frames as u32;
|
||||
result.output_length = bytes as u32;
|
||||
}
|
||||
|
||||
pub extern "system" fn XApuDequeueResult(handle: *mut Connection, out: *mut ApuResult) -> HRESULT {
|
||||
if handle.is_null() || out.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
|
||||
let mut state = lock(unsafe { &*handle });
|
||||
let Some(result) = state.results.pop_front() else {
|
||||
return PENDING_RESULTS;
|
||||
};
|
||||
let stream = result.id.stream as usize;
|
||||
state.queued[stream] -= 1;
|
||||
state.dequeued = state.dequeued.wrapping_add(1);
|
||||
|
||||
unsafe { out.write_unaligned(result) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub extern "system" fn XApuGetResultCount(handle: *mut Connection, total: *mut u32) -> u32 {
|
||||
if handle.is_null() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let state = lock(unsafe { &*handle });
|
||||
if !total.is_null() {
|
||||
|
||||
unsafe { total.write(state.dequeued) };
|
||||
}
|
||||
state.results.len() as u32
|
||||
}
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "apu",
|
||||
dlls: &["xapu.dll"],
|
||||
exports: vec![
|
||||
hle_export!(XApuConnect),
|
||||
hle_export!(XApuDisconnect),
|
||||
hle_export!(XApuEnqueueCommand),
|
||||
hle_export!(XApuDequeueResult),
|
||||
hle_export!(XApuGetResultCount),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,214 @@
|
||||
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::{Seek, SeekFrom, Write};
|
||||
use std::path::Path;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use windows::Win32::Media::Audio::{
|
||||
AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY, AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED,
|
||||
AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, AUDCLNT_STREAMFLAGS_LOOPBACK,
|
||||
AUDIOCLIENT_ACTIVATION_PARAMS, AUDIOCLIENT_ACTIVATION_PARAMS_0,
|
||||
AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK, AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS,
|
||||
ActivateAudioInterfaceAsync, IActivateAudioInterfaceAsyncOperation,
|
||||
IActivateAudioInterfaceCompletionHandler, IActivateAudioInterfaceCompletionHandler_Impl,
|
||||
IAudioCaptureClient, IAudioClient, PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE,
|
||||
VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, WAVE_FORMAT_PCM, WAVEFORMATEX,
|
||||
};
|
||||
use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx};
|
||||
use windows::Win32::Foundation::WAIT_OBJECT_0;
|
||||
use windows::Win32::System::Threading::{
|
||||
OpenProcess, PROCESS_SYNCHRONIZE, Sleep, WaitForSingleObject,
|
||||
};
|
||||
use windows::core::{HRESULT, IUnknown, Interface, Ref, implement};
|
||||
|
||||
const RATE: u32 = 48_000;
|
||||
const FRAME_BYTES: usize = 4;
|
||||
|
||||
#[implement(IActivateAudioInterfaceCompletionHandler)]
|
||||
struct Activated;
|
||||
|
||||
impl IActivateAudioInterfaceCompletionHandler_Impl for Activated_Impl {
|
||||
fn ActivateCompleted(
|
||||
&self,
|
||||
_: Ref<IActivateAudioInterfaceAsyncOperation>,
|
||||
) -> windows::core::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
const TARGET: &str = "EONACAT_XS_AUDIO_CAPTURE_OF";
|
||||
|
||||
pub fn start() {
|
||||
if tracing::enabled!(tracing::Level::DEBUG) {
|
||||
let _ = std::thread::Builder::new()
|
||||
.name("eonacat-xsbox timing probe".into())
|
||||
.spawn(|| {
|
||||
loop {
|
||||
std::thread::sleep(Duration::from_secs(1));
|
||||
let at = Instant::now();
|
||||
|
||||
unsafe { Sleep(1) };
|
||||
let ms = at.elapsed().as_secs_f32() * 1000.0;
|
||||
tracing::debug!(ms, "Sleep(1) took");
|
||||
}
|
||||
});
|
||||
}
|
||||
if std::env::var_os("EONACAT_XS_AUDIO_CAPTURE").is_some()
|
||||
&& let Err(e) = std::env::current_exe().and_then(|exe| {
|
||||
std::process::Command::new(exe)
|
||||
.env(TARGET, std::process::id().to_string())
|
||||
.spawn()
|
||||
})
|
||||
{
|
||||
tracing::warn!("audio capture not started: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
pub fn child() -> bool {
|
||||
let (Some(pid), Some(path)) = (
|
||||
std::env::var(TARGET).ok().and_then(|p| p.parse().ok()),
|
||||
std::env::var_os("EONACAT_XS_AUDIO_CAPTURE"),
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
if let Err(e) = record(pid, Path::new(&path)) {
|
||||
tracing::warn!("audio capture stopped: {e}");
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn header(frames: u64) -> [u8; 44] {
|
||||
let data = u32::try_from(frames * FRAME_BYTES as u64).unwrap_or(u32::MAX - 36);
|
||||
let mut h = [0u8; 44];
|
||||
let fields: [(&[u8], usize); 11] = [
|
||||
(b"RIFF", 0),
|
||||
(&(36 + data).to_le_bytes(), 4),
|
||||
(b"WAVEfmt ", 8),
|
||||
(&16u32.to_le_bytes(), 16),
|
||||
(&1u16.to_le_bytes(), 20),
|
||||
(&2u16.to_le_bytes(), 22),
|
||||
(&RATE.to_le_bytes(), 24),
|
||||
(&(RATE * FRAME_BYTES as u32).to_le_bytes(), 28),
|
||||
(&(FRAME_BYTES as u16).to_le_bytes(), 32),
|
||||
(&16u16.to_le_bytes(), 34),
|
||||
(b"data", 36),
|
||||
];
|
||||
for (bytes, at) in fields {
|
||||
h[at..at + bytes.len()].copy_from_slice(bytes);
|
||||
}
|
||||
h[40..].copy_from_slice(&data.to_le_bytes());
|
||||
h
|
||||
}
|
||||
|
||||
fn record(pid: u32, path: &Path) -> Result<(), Box<dyn std::error::Error>> {
|
||||
|
||||
unsafe {
|
||||
CoInitializeEx(None, COINIT_MULTITHREADED).ok()?;
|
||||
let target = OpenProcess(PROCESS_SYNCHRONIZE, false, pid)?;
|
||||
let params = AUDIOCLIENT_ACTIVATION_PARAMS {
|
||||
ActivationType: AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK,
|
||||
Anonymous: AUDIOCLIENT_ACTIVATION_PARAMS_0 {
|
||||
ProcessLoopbackParams: AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS {
|
||||
TargetProcessId: pid,
|
||||
ProcessLoopbackMode: PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
#[repr(C)]
|
||||
struct Blob {
|
||||
vt: u16,
|
||||
reserved: [u16; 3],
|
||||
size: u32,
|
||||
data: *const AUDIOCLIENT_ACTIVATION_PARAMS,
|
||||
}
|
||||
let blob = Blob {
|
||||
vt: 0x41,
|
||||
reserved: [0; 3],
|
||||
size: size_of_val(¶ms) as u32,
|
||||
data: ¶ms,
|
||||
};
|
||||
let handler: IActivateAudioInterfaceCompletionHandler = Activated.into();
|
||||
let operation = ActivateAudioInterfaceAsync(
|
||||
VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK,
|
||||
&IAudioClient::IID,
|
||||
Some((&raw const blob).cast()),
|
||||
&handler,
|
||||
)?;
|
||||
let client = loop {
|
||||
let (mut hr, mut client) = (HRESULT(0), None::<IUnknown>);
|
||||
|
||||
if operation.GetActivateResult(&mut hr, &mut client).is_ok() {
|
||||
hr.ok()?;
|
||||
break client.ok_or("no audio client")?.cast::<IAudioClient>()?;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
let format = WAVEFORMATEX {
|
||||
wFormatTag: WAVE_FORMAT_PCM as u16,
|
||||
nChannels: 2,
|
||||
nSamplesPerSec: RATE,
|
||||
nAvgBytesPerSec: RATE * FRAME_BYTES as u32,
|
||||
nBlockAlign: FRAME_BYTES as u16,
|
||||
wBitsPerSample: 16,
|
||||
cbSize: 0,
|
||||
};
|
||||
client.Initialize(
|
||||
AUDCLNT_SHAREMODE_SHARED,
|
||||
AUDCLNT_STREAMFLAGS_LOOPBACK | AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM,
|
||||
10_000_000,
|
||||
0,
|
||||
&format,
|
||||
None,
|
||||
)?;
|
||||
let capture: IAudioCaptureClient = client.GetService()?;
|
||||
let mut file = File::create(path)?;
|
||||
file.write_all(&header(0))?;
|
||||
client.Start()?;
|
||||
tracing::info!(path = %path.display(), "recording the title's audio");
|
||||
|
||||
let (mut written, mut first) = (0u64, None);
|
||||
let mut patched = Instant::now();
|
||||
loop {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
let ended = WaitForSingleObject(target, 0) == WAIT_OBJECT_0;
|
||||
while capture.GetNextPacketSize()? > 0 {
|
||||
let (mut data, mut frames, mut flags, mut qpc) = (std::ptr::null_mut(), 0, 0, 0);
|
||||
capture.GetBuffer(&mut data, &mut frames, &mut flags, None, Some(&mut qpc))?;
|
||||
|
||||
let at = (qpc - *first.get_or_insert(qpc)) * u64::from(RATE) / 10_000_000;
|
||||
if at > written + u64::from(RATE / 500) {
|
||||
tracing::debug!(
|
||||
ms = (at - written) * 1000 / u64::from(RATE),
|
||||
"audio capture: nothing played"
|
||||
);
|
||||
let silence = vec![0u8; (at - written) as usize * FRAME_BYTES];
|
||||
file.write_all(&silence)?;
|
||||
written = at;
|
||||
}
|
||||
let bytes = frames as usize * FRAME_BYTES;
|
||||
if flags & AUDCLNT_BUFFERFLAGS_SILENT.0 as u32 != 0 {
|
||||
file.write_all(&vec![0u8; bytes])?;
|
||||
} else {
|
||||
file.write_all(std::slice::from_raw_parts(data, bytes))?;
|
||||
}
|
||||
if flags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY.0 as u32 != 0 && written > 0 {
|
||||
tracing::debug!("audio capture: discontinuity");
|
||||
}
|
||||
written += u64::from(frames);
|
||||
capture.ReleaseBuffer(frames)?;
|
||||
}
|
||||
if ended || patched.elapsed() >= Duration::from_secs(1) {
|
||||
|
||||
file.seek(SeekFrom::Start(0))?;
|
||||
file.write_all(&header(written))?;
|
||||
file.seek(SeekFrom::End(0))?;
|
||||
patched = Instant::now();
|
||||
}
|
||||
if ended {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
|
||||
|
||||
use windows::Win32::Media::Audio::{IMMDeviceEnumerator, MMDeviceEnumerator, eConsole, eRender};
|
||||
use windows::Win32::System::Com::{
|
||||
CLSCTX_ALL, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, CoUninitialize,
|
||||
};
|
||||
use windows::core::HRESULT;
|
||||
|
||||
const E_NOTFOUND: HRESULT = HRESULT(0x8007_0490_u32 as i32);
|
||||
|
||||
pub const NO_OUTPUT_NOTICE: [&str; 3] = [
|
||||
"NO AUDIO OUTPUT: THE GAME FREEZES WHEN LOADING",
|
||||
"TURN ON A PLAYBACK DEVICE (EVEN A VIRTUAL ONE)",
|
||||
"IN WINDOWS SOUND SETTINGS, THEN START AGAIN",
|
||||
];
|
||||
|
||||
pub fn has_playback_device() -> Option<bool> {
|
||||
std::thread::Builder::new()
|
||||
.name("eonacat-xsbox audio output check".into())
|
||||
.spawn(ask)
|
||||
.ok()?
|
||||
.join()
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
fn ask() -> Option<bool> {
|
||||
|
||||
unsafe {
|
||||
CoInitializeEx(None, COINIT_MULTITHREADED).ok().ok()?;
|
||||
let answer = CoCreateInstance::<_, IMMDeviceEnumerator>(&MMDeviceEnumerator, None, CLSCTX_ALL)
|
||||
.ok()
|
||||
.and_then(|devices| match devices.GetDefaultAudioEndpoint(eRender, eConsole) {
|
||||
Ok(_) => Some(true),
|
||||
Err(e) if e.code() == E_NOTFOUND => Some(false),
|
||||
Err(_) => None,
|
||||
});
|
||||
CoUninitialize();
|
||||
answer
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,419 @@
|
||||
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::OsStr;
|
||||
use std::sync::atomic::{AtomicU8, AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
use std::time::Instant;
|
||||
|
||||
use eonacat_xsbox_gpu::loader::{ImportResolver, Provenance, Resolution};
|
||||
use eonacat_xsbox_gpu::pe::ImportSymbol;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[repr(u8)]
|
||||
enum Mode {
|
||||
Off,
|
||||
|
||||
NotLooping,
|
||||
All,
|
||||
|
||||
Intro,
|
||||
}
|
||||
|
||||
fn parse_mode(value: Option<&OsStr>) -> Mode {
|
||||
let Some(value) = value.and_then(OsStr::to_str) else {
|
||||
return Mode::Off;
|
||||
};
|
||||
match value.trim() {
|
||||
"" | "0" => Mode::Off,
|
||||
"1" => Mode::NotLooping,
|
||||
v if v.eq_ignore_ascii_case("all") => Mode::All,
|
||||
v if v.eq_ignore_ascii_case("intro") => Mode::Intro,
|
||||
v => {
|
||||
tracing::warn!(
|
||||
value = v,
|
||||
"EONACAT_XS_SKIP_BINK: expected 1, intro or all; not skipping"
|
||||
);
|
||||
Mode::Off
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[allow(dead_code)]
|
||||
struct Movie {
|
||||
width: u32,
|
||||
height: u32,
|
||||
frames: u32,
|
||||
|
||||
frame_num: u32,
|
||||
last_frame_num: u32,
|
||||
frame_rate: u32,
|
||||
frame_rate_div: u32,
|
||||
read_error: u32,
|
||||
open_flags: u32,
|
||||
}
|
||||
const _: () = assert!(std::mem::offset_of!(Movie, open_flags) == 0x20);
|
||||
|
||||
const WILL_LOOP: u32 = 0x80;
|
||||
|
||||
const NAMES: [&str; 12] = [
|
||||
"BinkClose",
|
||||
"BinkWait",
|
||||
"BinkShouldSkip",
|
||||
"BinkDoFrame",
|
||||
"BinkDoFrameAsync",
|
||||
"BinkDoFrameAsyncMulti",
|
||||
"BinkDoFrameAsyncWait",
|
||||
"BinkNextFrame",
|
||||
"BinkGoto",
|
||||
"BinkPause",
|
||||
"BinkCopyToBuffer",
|
||||
"BinkCopyToBufferRect",
|
||||
];
|
||||
const CLOSE: usize = 0;
|
||||
|
||||
const PAUSE: usize = 9;
|
||||
|
||||
type Export = extern "system" fn(*mut Movie, usize, usize, usize) -> usize;
|
||||
|
||||
const WRAPPERS: [Export; 10] = [
|
||||
close,
|
||||
wait,
|
||||
should_skip,
|
||||
do_frame,
|
||||
do_frame_async,
|
||||
do_frame_async_multi,
|
||||
do_frame_async_wait,
|
||||
next_frame,
|
||||
goto,
|
||||
pause,
|
||||
];
|
||||
|
||||
const COPIES: [Copy; 2] = [copy_to_buffer, copy_to_buffer_rect];
|
||||
|
||||
static ORIGINALS: [AtomicUsize; 12] = [const { AtomicUsize::new(0) }; 12];
|
||||
|
||||
static MODE: AtomicU8 = AtomicU8::new(Mode::Off as u8);
|
||||
|
||||
static MOVIES: Mutex<Option<HashMap<usize, bool>>> = Mutex::new(None);
|
||||
|
||||
pub fn wrap(dll: &str, name: &str, address: usize) -> usize {
|
||||
static FROM_ENV: OnceLock<Mode> = OnceLock::new();
|
||||
let mode = *FROM_ENV.get_or_init(|| {
|
||||
let mode = parse_mode(std::env::var_os("EONACAT_XS_SKIP_BINK").as_deref());
|
||||
if mode != Mode::Off {
|
||||
tracing::info!(?mode, "Bink movies are skipped");
|
||||
}
|
||||
mode
|
||||
});
|
||||
wrap_with(mode, dll, name, address)
|
||||
}
|
||||
|
||||
fn wrap_with(mode: Mode, dll: &str, name: &str, address: usize) -> usize {
|
||||
let is_bink = dll
|
||||
.get(..4)
|
||||
.is_some_and(|start| start.eq_ignore_ascii_case("bink"));
|
||||
if !is_bink || address == 0 {
|
||||
return address;
|
||||
}
|
||||
if name == "BinkRegisterFrameBuffers" {
|
||||
if REGISTER.compare_exchange(0, address, Ordering::AcqRel, Ordering::Acquire).is_err_and(|bound| bound != address) {
|
||||
return address;
|
||||
}
|
||||
return register_frame_buffers as *const () as usize;
|
||||
}
|
||||
let Some(i) = NAMES.iter().position(|&n| n == name) else {
|
||||
return address;
|
||||
};
|
||||
|
||||
let first = ORIGINALS[i].compare_exchange(0, address, Ordering::AcqRel, Ordering::Acquire);
|
||||
if first.is_err_and(|bound| bound != address) {
|
||||
tracing::warn!(dll, name, "a second Bink DLL: its movies are not skipped");
|
||||
return address;
|
||||
}
|
||||
MODE.store(mode as u8, Ordering::Relaxed);
|
||||
match WRAPPERS.get(i) {
|
||||
Some(&w) => w as usize,
|
||||
None => COPIES[i - WRAPPERS.len()] as usize,
|
||||
}
|
||||
}
|
||||
|
||||
static CALLS: [AtomicU64; 12] = [const { AtomicU64::new(0) }; 12];
|
||||
static CALL_US: [AtomicU64; 12] = [const { AtomicU64::new(0) }; 12];
|
||||
static CALL_MAX_US: [AtomicU64; 12] = [const { AtomicU64::new(0) }; 12];
|
||||
|
||||
fn timed<T>(i: usize, call: impl FnOnce() -> T) -> T {
|
||||
let began = Instant::now();
|
||||
let result = call();
|
||||
let us = began.elapsed().as_micros() as u64;
|
||||
CALLS[i].fetch_add(1, Ordering::Relaxed);
|
||||
CALL_US[i].fetch_add(us, Ordering::Relaxed);
|
||||
CALL_MAX_US[i].fetch_max(us, Ordering::Relaxed);
|
||||
let n = CALLS[i].load(Ordering::Relaxed);
|
||||
if n == 1 || n.is_power_of_two() {
|
||||
tracing::info!(
|
||||
export = NAMES[i], calls = n, total_ms = CALL_US[i].load(Ordering::Relaxed) as f64 / 1000.0,
|
||||
average_us = CALL_US[i].load(Ordering::Relaxed) as f64 / n as f64,
|
||||
max_ms = CALL_MAX_US[i].load(Ordering::Relaxed) as f64 / 1000.0,
|
||||
"Bink export timing (wall time; async start and wait are separate)"
|
||||
);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn forward(i: usize, movie: *mut Movie, a: usize, b: usize, c: usize) -> usize {
|
||||
let address = ORIGINALS[i].load(Ordering::Acquire);
|
||||
|
||||
let original: Export = unsafe { std::mem::transmute::<usize, Export>(address) };
|
||||
|
||||
if (3..=6).contains(&i) {
|
||||
timed(i, || original(movie, a, b, c))
|
||||
} else {
|
||||
original(movie, a, b, c)
|
||||
}
|
||||
}
|
||||
|
||||
static REGISTER: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
static PLANES: Mutex<Option<HashMap<usize, Vec<(usize, usize)>>>> = Mutex::new(None);
|
||||
|
||||
extern "system" fn register_frame_buffers(movie: *mut Movie, buffers: usize, b: usize, c: usize) -> usize {
|
||||
if !movie.is_null() && buffers != 0 {
|
||||
|
||||
let mut bytes = vec![0u8; 24 + 4 * 5 * 24];
|
||||
let mut got = 0usize;
|
||||
|
||||
unsafe {
|
||||
windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory(
|
||||
windows_sys::Win32::System::Threading::GetCurrentProcess(),
|
||||
buffers as *const _,
|
||||
bytes.as_mut_ptr().cast(),
|
||||
bytes.len(),
|
||||
&mut got,
|
||||
)
|
||||
};
|
||||
let word = |at: usize| u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap_or_default());
|
||||
let (total, height) = (word(0), word(8).max(word(16)) as usize);
|
||||
let mut planes = Vec::new();
|
||||
if got >= 24 && (1..=4).contains(&total) && (1..=16_384).contains(&height) {
|
||||
let span = (24 + total as usize * 5 * 24).min(got);
|
||||
let mut at = 24;
|
||||
while at + 16 <= span {
|
||||
|
||||
let pointer = u64::from_le_bytes(bytes[at..at + 8].try_into().unwrap_or_default()) as usize;
|
||||
let pitch = word(at + 12) as usize;
|
||||
if pointer > 0x10000 && pointer < 1 << 40 && (16..=65_536).contains(&pitch) {
|
||||
planes.push((pointer, pitch * height));
|
||||
}
|
||||
at += 8;
|
||||
}
|
||||
planes.sort_unstable();
|
||||
planes.dedup();
|
||||
}
|
||||
|
||||
static SHOWN: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
let words: Vec<String> = if SHOWN.fetch_add(1, Ordering::Relaxed) < 4 {
|
||||
bytes[..got.min(bytes.len())].chunks(8).map(|c| format!("{:016x}", u64::from_le_bytes(c.try_into().unwrap_or_default()))).collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
tracing::info!(
|
||||
movie = format_args!("{:#x}", movie as usize),
|
||||
total,
|
||||
height,
|
||||
planes = planes.len(),
|
||||
bytes = %words.join(" "),
|
||||
"Bink frame buffers registered"
|
||||
);
|
||||
PLANES.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashMap::new).insert(movie as usize, planes);
|
||||
}
|
||||
let address = REGISTER.load(Ordering::Acquire);
|
||||
|
||||
let original: Export = unsafe { std::mem::transmute::<usize, Export>(address) };
|
||||
original(movie, buffers, b, c)
|
||||
}
|
||||
|
||||
fn frame_decoded(movie: *mut Movie) {
|
||||
let planes = PLANES.lock().unwrap_or_else(|e| e.into_inner()).as_ref().and_then(|p| p.get(&(movie as usize)).cloned());
|
||||
for (at, len) in planes.unwrap_or_default() {
|
||||
eonacat_xsbox_gpu::bink_frame_written(at, len);
|
||||
}
|
||||
}
|
||||
|
||||
fn movies() -> std::sync::MutexGuard<'static, Option<HashMap<usize, bool>>> {
|
||||
MOVIES.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
fn plausible(m: &Movie) -> bool {
|
||||
(1..=16_384).contains(&m.width)
|
||||
&& (1..=16_384).contains(&m.height)
|
||||
&& (1..=10_000_000).contains(&m.frames)
|
||||
&& m.frame_rate > 0
|
||||
&& m.frame_rate_div > 0
|
||||
}
|
||||
|
||||
fn decide(mode: u8, looping: bool, world: bool) -> bool {
|
||||
match mode {
|
||||
m if m == Mode::NotLooping as u8 => !looping,
|
||||
m if m == Mode::All as u8 => true,
|
||||
m if m == Mode::Intro as u8 => !looping && !world,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn skipped(movie: *mut Movie) -> bool {
|
||||
if movie.is_null() {
|
||||
return false;
|
||||
}
|
||||
let mode = MODE.load(Ordering::Relaxed);
|
||||
let mut first = false;
|
||||
let skip = {
|
||||
let mut movies = movies();
|
||||
let movies = movies.get_or_insert_with(HashMap::new);
|
||||
*movies.entry(movie as usize).or_insert_with(|| {
|
||||
|
||||
let m = unsafe { &*movie };
|
||||
let looping = m.open_flags & WILL_LOOP != 0;
|
||||
|
||||
eonacat_xsbox_gpu::streamline::bink_movie_opened();
|
||||
if !plausible(m) {
|
||||
tracing::warn!(
|
||||
width = m.width,
|
||||
height = m.height,
|
||||
frames = m.frames,
|
||||
"a Bink movie whose structure is not the one known here (another Bink version?): not skipped"
|
||||
);
|
||||
return false;
|
||||
}
|
||||
let skip = decide(mode, looping, eonacat_xsbox_gpu::world_since().is_some());
|
||||
tracing::info!(width = m.width, height = m.height, frames = m.frames, looping, skip, "Bink movie");
|
||||
first = skip;
|
||||
skip
|
||||
})
|
||||
};
|
||||
if first && ORIGINALS[PAUSE].load(Ordering::Acquire) != 0 {
|
||||
|
||||
forward(PAUSE, movie, 1, 0, 0);
|
||||
}
|
||||
if skip {
|
||||
|
||||
unsafe {
|
||||
let frames = (*movie).frames;
|
||||
(*movie).frame_num = frames;
|
||||
(*movie).last_frame_num = frames;
|
||||
}
|
||||
|
||||
eonacat_xsbox_gpu::streamline::note_bink_movie();
|
||||
}
|
||||
skip
|
||||
}
|
||||
|
||||
extern "system" fn close(movie: *mut Movie, a: usize, b: usize, c: usize) -> usize {
|
||||
if movies()
|
||||
.as_mut()
|
||||
.is_some_and(|movies| movies.remove(&(movie as usize)).is_some())
|
||||
{
|
||||
eonacat_xsbox_gpu::streamline::bink_movie_closed();
|
||||
}
|
||||
forward(CLOSE, movie, a, b, c)
|
||||
}
|
||||
|
||||
macro_rules! wrapper {
|
||||
($name:ident, $i:literal, $skipped:expr) => {
|
||||
extern "system" fn $name(movie: *mut Movie, a: usize, b: usize, c: usize) -> usize {
|
||||
if skipped(movie) {
|
||||
return $skipped;
|
||||
}
|
||||
|
||||
eonacat_xsbox_gpu::streamline::note_bink_movie();
|
||||
forward($i, movie, a, b, c)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! decoding_wrapper {
|
||||
($name:ident, $i:literal, $skipped:expr, $done:expr) => {
|
||||
extern "system" fn $name(movie: *mut Movie, a: usize, b: usize, c: usize) -> usize {
|
||||
if skipped(movie) {
|
||||
return $skipped;
|
||||
}
|
||||
eonacat_xsbox_gpu::streamline::note_bink_movie();
|
||||
let got = forward($i, movie, a, b, c);
|
||||
if ($done)(got) {
|
||||
frame_decoded(movie);
|
||||
}
|
||||
got
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
wrapper!(wait, 1, 0);
|
||||
wrapper!(should_skip, 2, 0);
|
||||
decoding_wrapper!(do_frame, 3, 0, |_| true);
|
||||
wrapper!(do_frame_async, 4, 1);
|
||||
wrapper!(do_frame_async_multi, 5, 1);
|
||||
decoding_wrapper!(do_frame_async_wait, 6, 1, |done| done != 0);
|
||||
wrapper!(next_frame, 7, 0);
|
||||
wrapper!(goto, 8, 0);
|
||||
|
||||
type Copy = extern "system" fn(*mut Movie, usize, usize, usize, usize, usize, usize, usize, usize, usize, usize) -> usize;
|
||||
|
||||
macro_rules! copy_wrapper {
|
||||
($name:ident, $i:literal) => {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
extern "system" fn $name(
|
||||
movie: *mut Movie,
|
||||
a: usize,
|
||||
b: usize,
|
||||
c: usize,
|
||||
d: usize,
|
||||
e: usize,
|
||||
f: usize,
|
||||
g: usize,
|
||||
h: usize,
|
||||
i: usize,
|
||||
j: usize,
|
||||
) -> usize {
|
||||
if skipped(movie) {
|
||||
return 0;
|
||||
}
|
||||
let address = ORIGINALS[$i].load(Ordering::Acquire);
|
||||
|
||||
let original: Copy = unsafe { std::mem::transmute::<usize, Copy>(address) };
|
||||
timed($i, || original(movie, a, b, c, d, e, f, g, h, i, j))
|
||||
}
|
||||
};
|
||||
}
|
||||
copy_wrapper!(copy_to_buffer, 10);
|
||||
copy_wrapper!(copy_to_buffer_rect, 11);
|
||||
|
||||
extern "system" fn pause(movie: *mut Movie, a: usize, b: usize, c: usize) -> usize {
|
||||
if skipped(movie) {
|
||||
return forward(PAUSE, movie, 1, b, c);
|
||||
}
|
||||
forward(PAUSE, movie, a, b, c)
|
||||
}
|
||||
|
||||
pub struct SkipMovies<'a> {
|
||||
pub inner: &'a dyn ImportResolver,
|
||||
}
|
||||
|
||||
impl ImportResolver for SkipMovies<'_> {
|
||||
fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution {
|
||||
match (self.inner.resolve(dll, symbol), symbol) {
|
||||
(
|
||||
Resolution::Found {
|
||||
address,
|
||||
provenance: Provenance::Title,
|
||||
},
|
||||
ImportSymbol::Name { name, .. },
|
||||
) => Resolution::Found {
|
||||
address: wrap(dll, name, address),
|
||||
provenance: Provenance::Title,
|
||||
},
|
||||
(found, _) => found,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
use eonacat_xsbox_gpu::device;
|
||||
use eonacat_xsbox_gpu::object::{HRESULT, Iid, Object, guid};
|
||||
|
||||
use crate::hle::{HleExport, HleModule};
|
||||
|
||||
fn prepare_device() {
|
||||
eonacat_xsbox_gpu::resource::use_allocator(super::xmem::XMemAlloc, super::xmem::XMemFree);
|
||||
eonacat_xsbox_gpu::resource::use_page_mapper(super::xmem::map_alias);
|
||||
eonacat_xsbox_gpu::resource::use_many_page_mapper(super::xmem::map_aliases);
|
||||
#[cfg(windows)]
|
||||
eonacat_xsbox_gpu::on_failure(host_gpu_failed);
|
||||
}
|
||||
|
||||
extern "system" fn create_device(
|
||||
adapter: *const c_void,
|
||||
parameters: *const u32,
|
||||
iid: *const Iid,
|
||||
out: *mut *const Object,
|
||||
) -> HRESULT {
|
||||
prepare_device();
|
||||
device::create(adapter, parameters, iid, out)
|
||||
}
|
||||
|
||||
extern "system" fn create_device_with_level(
|
||||
adapter: *const c_void,
|
||||
minimum: u32,
|
||||
iid: *const Iid,
|
||||
out: *mut *const Object,
|
||||
) -> HRESULT {
|
||||
prepare_device();
|
||||
device::create_with_level(adapter, minimum, iid, out)
|
||||
}
|
||||
|
||||
const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32;
|
||||
const S_OK: HRESULT = 0;
|
||||
|
||||
extern "system" fn get_debug_interface(iid: *const Iid, out: *mut *mut c_void) -> HRESULT {
|
||||
if !out.is_null() {
|
||||
|
||||
unsafe { out.write(std::ptr::null_mut()) };
|
||||
}
|
||||
|
||||
let iid = unsafe { iid.as_ref() }.map(eonacat_xsbox_gpu::object::guid_text);
|
||||
tracing::info!(?iid, "D3D12GetDebugInterface: no debug layer");
|
||||
E_NOINTERFACE
|
||||
}
|
||||
|
||||
static DEBUG_FLAGS: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
extern "system" fn set_process_debug_flags(flags: u32) -> HRESULT {
|
||||
DEBUG_FLAGS.store(flags, Ordering::Relaxed);
|
||||
if flags != 0 {
|
||||
tracing::warn!(
|
||||
flags = format_args!("{flags:#x}"),
|
||||
"D3D12 process debug flags kept but not acted on (no debug layer)"
|
||||
);
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
extern "system" fn get_process_debug_flags() -> u32 {
|
||||
DEBUG_FLAGS.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
extern "system" fn unload_driver_module() {}
|
||||
|
||||
extern "system" fn flush_entire_cpu_cache() {
|
||||
std::sync::atomic::fence(Ordering::SeqCst);
|
||||
}
|
||||
|
||||
static DATA_IDS: [(&str, Iid); 31] = [
|
||||
("IID_ID3D12CommandAllocator", guid(0x6102dee4, 0xaf59, 0x4b09, [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24])),
|
||||
("IID_ID3D12CommandList", guid(0x7116d91c, 0xe7e4, 0x47ce, [0xb8, 0xc6, 0xec, 0x81, 0x68, 0xf4, 0x37, 0xe5])),
|
||||
("IID_ID3D12CommandQueue", guid(0x0ec870a6, 0x5d7e, 0x4c22, [0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed])),
|
||||
("IID_ID3D12Debug", guid(0x344488b7, 0x6846, 0x474b, [0xb9, 0x89, 0xf0, 0x27, 0x44, 0x82, 0x45, 0xe0])),
|
||||
("IID_ID3D12DescriptorHeap", guid(0x8efb471d, 0x616c, 0x4f49, [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51])),
|
||||
("IID_ID3D12DeviceChild", guid(0x905db94b, 0xa00c, 0x4140, [0x9d, 0xf5, 0x2b, 0x64, 0xca, 0x9e, 0xa3, 0x57])),
|
||||
("IID_ID3D12Fence", guid(0x0a753dcf, 0xc4d8, 0x4b91, [0xad, 0xf6, 0xbe, 0x5a, 0x60, 0xd9, 0x5a, 0x76])),
|
||||
("IID_ID3D12GraphicsCommandList", guid(0x5b160d0f, 0xac1b, 0x4185, [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55])),
|
||||
("IID_ID3D12Heap", guid(0x6b3b2502, 0x6e51, 0x45b3, [0x90, 0xee, 0x98, 0x84, 0x26, 0x5e, 0x8d, 0xf3])),
|
||||
("IID_ID3D12Object", guid(0xc4fec28f, 0x7966, 0x4e95, [0x9f, 0x94, 0xf4, 0x31, 0xcb, 0x56, 0xc3, 0xb8])),
|
||||
("IID_ID3D12Pageable", guid(0x63ee58fb, 0x1268, 0x4835, [0x86, 0xda, 0xf0, 0x08, 0xce, 0x62, 0xf0, 0xd6])),
|
||||
("IID_ID3D12PipelineState", guid(0x765a30f3, 0xf624, 0x4c6f, [0xa8, 0x28, 0xac, 0xe9, 0x48, 0x62, 0x24, 0x45])),
|
||||
("IID_ID3D12Resource", guid(0x696442be, 0xa72e, 0x4059, [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad])),
|
||||
("IID_ID3D12RootSignature", guid(0xc54a6b66, 0x72df, 0x4ee8, [0x8b, 0xe5, 0xa9, 0x46, 0xa1, 0x42, 0x92, 0x14])),
|
||||
("IID_ID3D12RootSignatureDeserializer", guid(0x34ab647b, 0x3cc8, 0x46ac, [0x84, 0x1b, 0xc0, 0x96, 0x56, 0x45, 0xc0, 0x46])),
|
||||
("IID_ID3D12XboxDmaCommandList", guid(0x30bc77b9, 0x8379, 0x4b25, [0x95, 0xde, 0xb8, 0x58, 0x8c, 0x42, 0x27, 0x5d])),
|
||||
("IID_IDXGIAdapter", guid(0x2411e7e1, 0x12ac, 0x4ccf, [0xbd, 0x14, 0x97, 0x98, 0xe8, 0x53, 0x4d, 0xc0])),
|
||||
("IID_IDXGIAdapter1", guid(0x29038f61, 0x3839, 0x4626, [0x91, 0xfd, 0x08, 0x68, 0x79, 0x01, 0x1a, 0x05])),
|
||||
("IID_IDXGIAdapter2", guid(0x0aa1ae0a, 0xfa0e, 0x4b84, [0x86, 0x44, 0xe0, 0x5f, 0xf8, 0xe5, 0xac, 0xb5])),
|
||||
("IID_IDXGIDevice", guid(0x54ec77fa, 0x1377, 0x44e6, [0x8c, 0x32, 0x88, 0xfd, 0x5f, 0x44, 0xc8, 0x4c])),
|
||||
("IID_IDXGIDevice1", guid(0x77db970f, 0x6276, 0x48ba, [0xba, 0x28, 0x07, 0x01, 0x43, 0xb4, 0x39, 0x2c])),
|
||||
("IID_IDXGIDevice2", guid(0x05008617, 0xfbfd, 0x4051, [0xa7, 0x90, 0x14, 0x48, 0x84, 0xb4, 0xf6, 0xa9])),
|
||||
("IID_IDXGIDeviceSubObject", guid(0x3d3e0379, 0xf9de, 0x4d58, [0xbb, 0x6c, 0x18, 0xd6, 0x29, 0x92, 0xf1, 0xa6])),
|
||||
("IID_IDXGIFactory", guid(0x7b7166ec, 0x21c7, 0x44ae, [0xb2, 0x1a, 0xc9, 0xae, 0x32, 0x1a, 0xe3, 0x69])),
|
||||
("IID_IDXGIFactory1", guid(0x770aae78, 0xf26f, 0x4dba, [0xa8, 0x29, 0x25, 0x3c, 0x83, 0xd1, 0xb3, 0x87])),
|
||||
("IID_IDXGIFactory2", guid(0x50c83a1c, 0xe072, 0x4c48, [0x87, 0xb0, 0x36, 0x30, 0xfa, 0x36, 0xa6, 0xd0])),
|
||||
("IID_IDXGIObject", guid(0xaec22fb8, 0x76f3, 0x4639, [0x9b, 0xe0, 0x28, 0xeb, 0x43, 0xa6, 0x7a, 0x2e])),
|
||||
("IID_IDXGISwapChain", guid(0x310d36a0, 0xd2e7, 0x4c0a, [0xaa, 0x04, 0x6a, 0x9d, 0x23, 0xb8, 0x88, 0x6a])),
|
||||
("IID_IDXGISwapChain1", guid(0x790a45f7, 0x0d42, 0x4876, [0x98, 0x3a, 0x0a, 0x55, 0xcf, 0xe6, 0xf4, 0xaa])),
|
||||
("IID_IGraphicsUnknown", guid(0xaceeea63, 0xe0a9, 0x4a1c, [0xbb, 0xec, 0x71, 0xb2, 0xf4, 0x85, 0xf7, 0x58])),
|
||||
("WKPDID_D3DDebugObjectNameW", guid(0x4cca5fd8, 0x921f, 0x42c8, [0x85, 0x66, 0x70, 0xca, 0xf2, 0xa9, 0xb7, 0x41])),
|
||||
];
|
||||
|
||||
#[cfg(windows)]
|
||||
fn host_gpu_failed(what: &str) -> ! {
|
||||
use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess};
|
||||
eonacat_xsbox_gpu::loader::log_crash(&format!("eonacat-xs: host GPU failure: {what}"));
|
||||
|
||||
eonacat_xsbox_gpu::core::logging::flush(std::time::Duration::from_secs(2));
|
||||
const DXGI_ERROR_DEVICE_REMOVED: u32 = 0x887A_0005;
|
||||
|
||||
unsafe { TerminateProcess(GetCurrentProcess(), DXGI_ERROR_DEVICE_REMOVED) };
|
||||
unreachable!("the process has ended")
|
||||
}
|
||||
|
||||
pub fn precompile(container: &[u8]) -> Result<bool, String> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
eonacat_xsbox_gpu::shader_cache::precompile(container)
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = container;
|
||||
Err("no host".into())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn warm_shader(container: &[u8]) -> Result<bool, String> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
eonacat_xsbox_gpu::shader_cache::precompile(container).map(|was_there| !was_there)
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = container;
|
||||
Err("no shader cache on this host".into())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn shader_translator_id() -> Option<String> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
Some(eonacat_xsbox_gpu::shader_cache::translator_id())
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn use_shader_cache(dir: std::path::PathBuf) {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
eonacat_xsbox_gpu::pipeline::use_pipeline_cache(dir.with_file_name("pipelines"));
|
||||
eonacat_xsbox_gpu::shader_cache::use_shader_cache(dir);
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = dir;
|
||||
}
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
let function = |name, address: *const ()| HleExport {
|
||||
name,
|
||||
address: address as usize,
|
||||
};
|
||||
let mut exports = vec![
|
||||
function("D3D12ConfigureVirtualMemoryX", device::configure_virtual_memory as *const ()),
|
||||
function("D3D12XboxCreateDevice", create_device as *const ()),
|
||||
function("D3D12CreateDevice", create_device_with_level as *const ()),
|
||||
function("D3D12SerializeRootSignature", eonacat_xsbox_gpu::root::serialize as *const ()),
|
||||
function(
|
||||
"D3D12SerializeVersionedRootSignature",
|
||||
eonacat_xsbox_gpu::root::serialize_versioned as *const (),
|
||||
),
|
||||
|
||||
function(
|
||||
"D3D12CreateRootSignatureDeserializer",
|
||||
eonacat_xsbox_gpu::root::create_deserializer as *const (),
|
||||
),
|
||||
function(
|
||||
"D3D12CreateVersionedRootSignatureDeserializer",
|
||||
eonacat_xsbox_gpu::root::create_versioned_deserializer as *const (),
|
||||
),
|
||||
function("D3D10CreateBlob", eonacat_xsbox_gpu::root::create_blob as *const ()),
|
||||
function("D3D12GetDebugInterface", get_debug_interface as *const ()),
|
||||
function("D3D12XboxSetProcessDebugFlags", set_process_debug_flags as *const ()),
|
||||
function("D3D12XboxGetProcessDebugFlags", get_process_debug_flags as *const ()),
|
||||
function("D3D12XboxUnloadDriverModule", unload_driver_module as *const ()),
|
||||
function("D3DFlushEntireCpuCache", flush_entire_cpu_cache as *const ()),
|
||||
|
||||
HleExport {
|
||||
name: "IID_ID3D12Device",
|
||||
address: (&raw const device::IID) as usize,
|
||||
},
|
||||
];
|
||||
exports.extend(DATA_IDS.iter().map(|(name, id)| HleExport {
|
||||
name,
|
||||
address: (id as *const Iid) as usize,
|
||||
}));
|
||||
HleModule {
|
||||
name: "d3d12x",
|
||||
dlls: &["d3d12_xs.dll"],
|
||||
exports,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
|
||||
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::{c_char, c_void};
|
||||
|
||||
use super::xgameruntime::{
|
||||
Guid, HRESULT, Interface, Methods, NOT_SUPPORTED, Object, S_OK, add_ref, missing, put, text,
|
||||
with_spare,
|
||||
};
|
||||
|
||||
pub const HDR_PROVIDER: Guid = Guid::new(
|
||||
0x03f0_fe74,
|
||||
0xfdd9,
|
||||
0x4e5c,
|
||||
[0xb6, 0x30, 0xf9, 0x33, 0x9c, 0x47, 0xac, 0xc5],
|
||||
);
|
||||
pub const HDR_IID: Guid = Guid::new(
|
||||
0x35f0_7670,
|
||||
0x706e,
|
||||
0x4bfb,
|
||||
[0x94, 0x76, 0x09, 0x07, 0x98, 0xc5, 0xeb, 0xf3],
|
||||
);
|
||||
|
||||
pub const SHELL: Guid = Guid::new(
|
||||
0x1b33_9674,
|
||||
0x328d,
|
||||
0x4283,
|
||||
[0xa2, 0x00, 0x31, 0x71, 0xf1, 0x8d, 0x36, 0x39],
|
||||
);
|
||||
|
||||
pub const CAPTURE_PROVIDER: Guid = Guid::new(
|
||||
0xa4f1_aee2,
|
||||
0x4bf1,
|
||||
0x4485,
|
||||
[0xb0, 0x08, 0xa7, 0xc2, 0x6d, 0x52, 0xac, 0x27],
|
||||
);
|
||||
|
||||
pub const CAPTURE_IID_2026: Guid = Guid::new(
|
||||
0x22e6_72d7,
|
||||
0xb4e3,
|
||||
0x406c,
|
||||
[0xbd, 0x50, 0x8f, 0x0d, 0x25, 0x23, 0x6f, 0x9e],
|
||||
);
|
||||
|
||||
pub static HDR_OBJECT: Object = Object::new("hdr", &HDR_VTABLE);
|
||||
pub static SHELL_OBJECT: Object = Object::new("shell", &SHELL_VTABLE);
|
||||
pub static CAPTURE_OBJECT: Object = Object::new("capture", &CAPTURE_VTABLE);
|
||||
|
||||
pub const INTERFACES: &[Interface] = &[
|
||||
(HDR_PROVIDER, HDR_IID, &HDR_OBJECT),
|
||||
(SHELL, SHELL, &SHELL_OBJECT),
|
||||
(CAPTURE_PROVIDER, CAPTURE_IID_2026, &CAPTURE_OBJECT),
|
||||
];
|
||||
|
||||
type This = *const Object;
|
||||
|
||||
extern "system" fn try_enable_hdr(_: This, preference: u32, info: *mut HdrModeInfo) -> u32 {
|
||||
tracing::info!(preference, "HDR mode: disabled (SDR presentation)");
|
||||
if !info.is_null() {
|
||||
|
||||
unsafe {
|
||||
info.write(HdrModeInfo {
|
||||
min_tone_map_luminance: 0.0,
|
||||
max_tone_map_luminance: 100.0,
|
||||
max_full_frame_tone_map_luminance: 100.0,
|
||||
});
|
||||
}
|
||||
}
|
||||
2
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct HdrModeInfo {
|
||||
min_tone_map_luminance: f32,
|
||||
max_tone_map_luminance: f32,
|
||||
max_full_frame_tone_map_luminance: f32,
|
||||
}
|
||||
|
||||
extern "system" fn launch_uri(_: This, _user: *const c_void, uri: *const c_char) -> HRESULT {
|
||||
tracing::info!(uri = text(uri).unwrap_or_default(), "URI not launched");
|
||||
NOT_SUPPORTED
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
extern "system" fn acquire_deferral(_: This, out: *mut *mut c_void) -> HRESULT {
|
||||
use windows_sys::Win32::System::Power::{
|
||||
PowerCreateRequest, PowerRequestDisplayRequired, PowerSetRequest,
|
||||
};
|
||||
use windows_sys::Win32::System::Threading::{
|
||||
POWER_REQUEST_CONTEXT_SIMPLE_STRING, REASON_CONTEXT,
|
||||
};
|
||||
if out.is_null() {
|
||||
return super::xasync::E_INVALIDARG;
|
||||
}
|
||||
let mut reason: Vec<u16> = "Title display deferral\0".encode_utf16().collect();
|
||||
let mut context = REASON_CONTEXT {
|
||||
Flags: POWER_REQUEST_CONTEXT_SIMPLE_STRING,
|
||||
..Default::default()
|
||||
};
|
||||
context.Reason.SimpleReasonString = reason.as_mut_ptr();
|
||||
|
||||
let request = unsafe { PowerCreateRequest(&context) };
|
||||
if request as isize == -1 {
|
||||
return last_error();
|
||||
}
|
||||
|
||||
if unsafe { PowerSetRequest(request, PowerRequestDisplayRequired) } == 0 {
|
||||
let hr = last_error();
|
||||
|
||||
unsafe { windows_sys::Win32::Foundation::CloseHandle(request) };
|
||||
return hr;
|
||||
}
|
||||
put(out, request)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
extern "system" fn close_deferral(_: This, handle: *mut c_void) {
|
||||
use windows_sys::Win32::Foundation::CloseHandle;
|
||||
use windows_sys::Win32::System::Power::{PowerClearRequest, PowerRequestDisplayRequired};
|
||||
if !handle.is_null() {
|
||||
|
||||
unsafe {
|
||||
PowerClearRequest(handle, PowerRequestDisplayRequired);
|
||||
CloseHandle(handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn last_error() -> HRESULT {
|
||||
|
||||
let code = unsafe { windows_sys::Win32::Foundation::GetLastError() };
|
||||
(0x8007_0000 | (code & 0xffff)) as i32
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct ScreenshotResult {
|
||||
pub local_id: [u8; 250],
|
||||
pub formats: u16,
|
||||
}
|
||||
|
||||
const SDR: u16 = 1;
|
||||
|
||||
#[cfg(windows)]
|
||||
extern "system" fn take_screenshot(
|
||||
_: This,
|
||||
_user: *const c_void,
|
||||
result: *mut ScreenshotResult,
|
||||
) -> HRESULT {
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
static TAKEN: AtomicU32 = AtomicU32::new(0);
|
||||
if result.is_null() {
|
||||
return super::xasync::E_INVALIDARG;
|
||||
}
|
||||
let seconds = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_secs());
|
||||
let name = format!(
|
||||
"photo-{seconds}-{}.png",
|
||||
TAKEN.fetch_add(1, Ordering::Relaxed)
|
||||
);
|
||||
let path = crate::hle::runtime::title().screenshots().join(&name);
|
||||
tracing::info!(path = %path.display(), "screenshot asked for: the next frame shown");
|
||||
eonacat_xsbox_gpu::screenshot::request(path);
|
||||
let mut out = ScreenshotResult {
|
||||
local_id: [0; 250],
|
||||
formats: SDR,
|
||||
};
|
||||
out.local_id[..name.len()].copy_from_slice(name.as_bytes());
|
||||
|
||||
unsafe { result.write(out) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
extern "system" fn take_screenshot(
|
||||
_: This,
|
||||
_user: *const c_void,
|
||||
_result: *mut ScreenshotResult,
|
||||
) -> HRESULT {
|
||||
tracing::info!("screenshot not taken");
|
||||
NOT_SUPPORTED
|
||||
}
|
||||
|
||||
static HDR_VTABLE: Methods<13> = with_spare([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
missing::<3> as *const (),
|
||||
try_enable_hdr as *const (),
|
||||
]);
|
||||
|
||||
#[cfg(windows)]
|
||||
static SHELL_VTABLE: Methods<14> = with_spare([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
launch_uri as *const (),
|
||||
acquire_deferral as *const (),
|
||||
close_deferral as *const (),
|
||||
]);
|
||||
#[cfg(not(windows))]
|
||||
static SHELL_VTABLE: Methods<14> = with_spare([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
launch_uri as *const (),
|
||||
missing::<4> as *const (),
|
||||
missing::<5> as *const (),
|
||||
]);
|
||||
|
||||
static CAPTURE_VTABLE: Methods<26> = with_spare([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
missing::<3> as *const (),
|
||||
missing::<4> as *const (),
|
||||
take_screenshot as *const (),
|
||||
missing::<6> as *const (),
|
||||
missing::<7> as *const (),
|
||||
missing::<8> as *const (),
|
||||
missing::<9> as *const (),
|
||||
missing::<10> as *const (),
|
||||
missing::<11> as *const (),
|
||||
missing::<12> as *const (),
|
||||
missing::<13> as *const (),
|
||||
missing::<14> as *const (),
|
||||
missing::<15> as *const (),
|
||||
missing::<16> as *const (),
|
||||
missing::<17> as *const (),
|
||||
]);
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
|
||||
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicI32, AtomicU32, Ordering};
|
||||
|
||||
use super::xasync::E_INVALIDARG;
|
||||
use super::xgameruntime::{HRESULT, S_OK};
|
||||
use crate::hle::{HleModule};
|
||||
use crate::hle_export;
|
||||
|
||||
mod convolve;
|
||||
|
||||
fn convolve_on() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("EONACAT_XS_DSP_CONVOLVE").is_none_or(|v| v != "0"))
|
||||
}
|
||||
|
||||
const GAIN: f32 = 2.0;
|
||||
|
||||
fn gain() -> f32 {
|
||||
static GAIN_SET: std::sync::OnceLock<f32> = std::sync::OnceLock::new();
|
||||
*GAIN_SET.get_or_init(|| {
|
||||
std::env::var("EONACAT_XS_DSP_GAIN").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(GAIN)
|
||||
})
|
||||
}
|
||||
|
||||
const E_POINTER: HRESULT = 0x8000_4003_u32 as i32;
|
||||
const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32;
|
||||
|
||||
const CONVOLUTION: u32 = 1;
|
||||
|
||||
const STEREO_OPTIONS: u32 = 2 | 8;
|
||||
const NOT_FOR_CONVOLUTION: u32 = 4;
|
||||
|
||||
pub struct Dsp {
|
||||
max_streams: u32,
|
||||
active: Mutex<u32>,
|
||||
}
|
||||
|
||||
#[repr(C, packed)]
|
||||
pub struct StreamDesc {
|
||||
kind: u32,
|
||||
options: u32,
|
||||
frames: u32,
|
||||
channels: u32,
|
||||
ir_floats: u32,
|
||||
ir: *const f32,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct Status {
|
||||
submitted: AtomicU32,
|
||||
completed: AtomicU32,
|
||||
reserved: AtomicU32,
|
||||
result: AtomicI32,
|
||||
}
|
||||
|
||||
const _: () = {
|
||||
assert!(size_of::<Status>() == 16);
|
||||
assert!(align_of::<Status>() == 4);
|
||||
assert!(std::mem::offset_of!(Status, submitted) == 0);
|
||||
assert!(std::mem::offset_of!(Status, completed) == 4);
|
||||
assert!(std::mem::offset_of!(Status, reserved) == 8);
|
||||
assert!(std::mem::offset_of!(Status, result) == 12);
|
||||
};
|
||||
|
||||
struct SubmitState {
|
||||
last: u32,
|
||||
|
||||
convolver: Option<convolve::Convolver>,
|
||||
}
|
||||
|
||||
pub struct Stream {
|
||||
dsp: *mut Dsp,
|
||||
frames: u32,
|
||||
channels: u32,
|
||||
|
||||
submit: Mutex<SubmitState>,
|
||||
status: Box<Status>,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct Command {
|
||||
gains: [f32; 2],
|
||||
input: *const f32,
|
||||
output: *mut f32,
|
||||
reserved: u64,
|
||||
}
|
||||
|
||||
pub extern "system" fn XDspConnectWithMaximumStreamLimit(
|
||||
base: *mut c_void,
|
||||
base_length: u32,
|
||||
ir_seconds: u32,
|
||||
max_streams: u32,
|
||||
max_channels: u32,
|
||||
out: *mut *mut Dsp,
|
||||
) -> HRESULT {
|
||||
if base.is_null()
|
||||
|| !(0x1_0000..=0x1F40_0000).contains(&base_length)
|
||||
|| ir_seconds > 0x80
|
||||
|| max_streams > 0x100
|
||||
|| max_channels > 2
|
||||
{
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if out.is_null() {
|
||||
return E_POINTER;
|
||||
}
|
||||
tracing::info!(
|
||||
base_length,
|
||||
ir_seconds,
|
||||
max_streams,
|
||||
max_channels,
|
||||
"audio DSP connected"
|
||||
);
|
||||
let dsp = Box::new(Dsp {
|
||||
max_streams,
|
||||
active: Mutex::new(0),
|
||||
});
|
||||
|
||||
unsafe { out.write(Box::into_raw(dsp)) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub extern "system" fn XDspDisconnect(dsp: *mut Dsp) -> HRESULT {
|
||||
if dsp.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
|
||||
drop(unsafe { Box::from_raw(dsp) });
|
||||
S_OK
|
||||
}
|
||||
|
||||
fn valid(desc: &StreamDesc) -> bool {
|
||||
let (kind, options, frames, channels) = (desc.kind, desc.options, desc.frames, desc.channels);
|
||||
let shape = if kind == CONVOLUTION {
|
||||
(1..=2).contains(&channels)
|
||||
&& matches!(frames, 0x200 | 0x400)
|
||||
&& options & NOT_FOR_CONVOLUTION == 0
|
||||
} else {
|
||||
channels == 1 && matches!(frames, 0x200 | 0x400 | 0x800)
|
||||
};
|
||||
shape && (options & STEREO_OPTIONS == 0 || channels == 2)
|
||||
}
|
||||
|
||||
pub extern "system" fn XDspActivate(
|
||||
dsp: *mut Dsp,
|
||||
desc: *const StreamDesc,
|
||||
status: *mut *const Status,
|
||||
stream: *mut *mut Stream,
|
||||
) -> HRESULT {
|
||||
if status.is_null() || stream.is_null() {
|
||||
return E_POINTER;
|
||||
}
|
||||
if dsp.is_null() || desc.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
|
||||
let desc = unsafe { &*desc };
|
||||
if !valid(desc) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let (kind, options, frames, channels) = (desc.kind, desc.options, desc.frames, desc.channels);
|
||||
let (ir, ir_floats) = (desc.ir, desc.ir_floats);
|
||||
let convolver = if convolve_on() && kind == CONVOLUTION && channels == 1 && frames == 0x400 && !ir.is_null() {
|
||||
|
||||
convolve::Convolver::new(unsafe { std::slice::from_raw_parts(ir, ir_floats as usize) })
|
||||
} else {
|
||||
None
|
||||
};
|
||||
tracing::debug!(
|
||||
kind,
|
||||
options,
|
||||
frames,
|
||||
channels,
|
||||
ir_floats,
|
||||
computed = convolver.is_some(),
|
||||
"audio DSP stream activated"
|
||||
);
|
||||
{
|
||||
|
||||
let dsp = unsafe { &*dsp };
|
||||
let mut active = dsp.active.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if *active >= dsp.max_streams {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
*active += 1;
|
||||
}
|
||||
let new = Box::new(Stream {
|
||||
dsp,
|
||||
frames: desc.frames,
|
||||
channels: desc.channels,
|
||||
submit: Mutex::new(SubmitState { last: 0, convolver }),
|
||||
status: Box::new(Status {
|
||||
submitted: AtomicU32::new(0),
|
||||
completed: AtomicU32::new(0),
|
||||
reserved: AtomicU32::new(0),
|
||||
result: AtomicI32::new(S_OK),
|
||||
}),
|
||||
});
|
||||
let raw = Box::into_raw(new);
|
||||
|
||||
unsafe {
|
||||
status.write(std::ptr::from_ref(&*(*raw).status));
|
||||
stream.write(raw);
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub extern "system" fn XDspDeactivate(stream: *mut Stream) -> HRESULT {
|
||||
if stream.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
|
||||
let stream = unsafe { Box::from_raw(stream) };
|
||||
|
||||
let dsp = unsafe { &*stream.dsp };
|
||||
*dsp.active.lock().unwrap_or_else(|e| e.into_inner()) -= 1;
|
||||
S_OK
|
||||
}
|
||||
|
||||
fn ramp(output: &mut [f32], frames: u32, channels: u32, [begin, end]: [f32; 2]) {
|
||||
if (begin, end) == (1.0, 1.0) || frames == 0 {
|
||||
return;
|
||||
}
|
||||
let step = (end - begin) / frames as f32;
|
||||
let channels = channels.max(1) as usize;
|
||||
for (i, frame) in output.chunks_mut(channels).enumerate() {
|
||||
let scale = begin + i as f32 * step;
|
||||
frame.iter_mut().for_each(|s| *s *= scale);
|
||||
}
|
||||
}
|
||||
|
||||
pub extern "system" fn XDspSubmitCommand(
|
||||
stream: *mut Stream,
|
||||
command: *const Command,
|
||||
ticket: *mut u32,
|
||||
) -> HRESULT {
|
||||
if stream.is_null() || command.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
|
||||
let (stream, command) = unsafe { (&*stream, &*command) };
|
||||
let mut submit = stream.submit.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let next = submit.last.wrapping_add(1);
|
||||
submit.last = next;
|
||||
stream.status.submitted.store(next, Ordering::Release);
|
||||
let samples = (stream.frames * stream.channels) as usize;
|
||||
if !command.output.is_null() && !command.input.is_null() && let Some(convolver) = submit.convolver.as_mut() {
|
||||
|
||||
let (input, output) = unsafe {
|
||||
(std::slice::from_raw_parts(command.input, samples), std::slice::from_raw_parts_mut(command.output, samples))
|
||||
};
|
||||
convolver.process(input, output, gain());
|
||||
ramp(output, stream.frames, stream.channels, command.gains);
|
||||
} else if !command.output.is_null() {
|
||||
|
||||
unsafe { std::ptr::write_bytes(command.output, 0, samples) };
|
||||
}
|
||||
stream.status.result.store(S_OK, Ordering::Relaxed);
|
||||
|
||||
stream.status.completed.store(next, Ordering::Release);
|
||||
drop(submit);
|
||||
if !ticket.is_null() {
|
||||
|
||||
unsafe { ticket.write(next) };
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "dsp",
|
||||
dlls: &["chad.dll"],
|
||||
exports: vec![
|
||||
hle_export!(XDspConnectWithMaximumStreamLimit),
|
||||
hle_export!(XDspDisconnect),
|
||||
hle_export!(XDspActivate),
|
||||
hle_export!(XDspDeactivate),
|
||||
hle_export!(XDspSubmitCommand),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
|
||||
|
||||
const N: usize = 2048;
|
||||
const B: usize = 1024;
|
||||
const TRAILER: u32 = 0xFFFF_ACE1;
|
||||
|
||||
struct Fft {
|
||||
cos: Vec<f32>,
|
||||
sin: Vec<f32>,
|
||||
rev: Vec<u16>,
|
||||
}
|
||||
|
||||
fn fft() -> &'static Fft {
|
||||
static FFT: std::sync::OnceLock<Fft> = std::sync::OnceLock::new();
|
||||
FFT.get_or_init(|| {
|
||||
let bits = N.trailing_zeros();
|
||||
let rev = (0..N).map(|i| (i.reverse_bits() >> (usize::BITS - bits)) as u16).collect();
|
||||
let (cos, sin) = (0..N / 2)
|
||||
.map(|k| {
|
||||
let a = -2.0 * std::f64::consts::PI * k as f64 / N as f64;
|
||||
(a.cos() as f32, a.sin() as f32)
|
||||
})
|
||||
.unzip();
|
||||
Fft { cos, sin, rev }
|
||||
})
|
||||
}
|
||||
|
||||
impl Fft {
|
||||
|
||||
fn run(&self, re: &mut [f32; N], im: &mut [f32; N], inverse: bool) {
|
||||
for i in 0..N {
|
||||
let j = self.rev[i] as usize;
|
||||
if i < j {
|
||||
re.swap(i, j);
|
||||
im.swap(i, j);
|
||||
}
|
||||
}
|
||||
let sign = if inverse { -1.0 } else { 1.0 };
|
||||
let mut len = 2;
|
||||
while len <= N {
|
||||
let half = len / 2;
|
||||
let step = N / len;
|
||||
for start in (0..N).step_by(len) {
|
||||
for k in 0..half {
|
||||
let (wr, wi) = (self.cos[k * step], sign * self.sin[k * step]);
|
||||
let (a, b) = (start + k, start + k + half);
|
||||
let (br, bi) = (re[b] * wr - im[b] * wi, re[b] * wi + im[b] * wr);
|
||||
re[b] = re[a] - br;
|
||||
im[b] = im[a] - bi;
|
||||
re[a] += br;
|
||||
im[a] += bi;
|
||||
}
|
||||
}
|
||||
len *= 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct Convolver {
|
||||
|
||||
h_re: Vec<f32>,
|
||||
h_im: Vec<f32>,
|
||||
parts: usize,
|
||||
|
||||
x_re: Vec<f32>,
|
||||
x_im: Vec<f32>,
|
||||
head: usize,
|
||||
|
||||
quiet: usize,
|
||||
}
|
||||
|
||||
impl Convolver {
|
||||
|
||||
pub(super) fn new(ir: &[f32]) -> Option<Self> {
|
||||
if ir.is_empty() || !ir.len().is_multiple_of(N) {
|
||||
return None;
|
||||
}
|
||||
let mut blocks = ir.len() / N;
|
||||
if ir[(blocks - 1) * N].to_bits() == TRAILER {
|
||||
blocks -= 1;
|
||||
}
|
||||
|
||||
while blocks > 0 && ir[(blocks - 1) * N..blocks * N].iter().all(|&v| v == 0.0) {
|
||||
blocks -= 1;
|
||||
}
|
||||
let parts = blocks.max(1);
|
||||
let mut h_re = vec![0f32; parts * B];
|
||||
let mut h_im = vec![0f32; parts * B];
|
||||
for k in 0..blocks {
|
||||
let block = &ir[k * N..(k + 1) * N];
|
||||
for bin in 0..B {
|
||||
let (r, i) = (block[2 * bin], block[2 * bin + 1]);
|
||||
|
||||
h_re[k * B + bin] = if r.is_finite() { r } else { 0.0 };
|
||||
h_im[k * B + bin] = if i.is_finite() { i } else { 0.0 };
|
||||
}
|
||||
}
|
||||
Some(Self {
|
||||
h_re,
|
||||
h_im,
|
||||
parts,
|
||||
x_re: vec![0f32; parts * B],
|
||||
x_im: vec![0f32; parts * B],
|
||||
head: 0,
|
||||
quiet: usize::MAX,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn process(&mut self, input: &[f32], output: &mut [f32], gain: f32) {
|
||||
let silent = input.iter().all(|&v| v == 0.0 || !v.is_finite());
|
||||
self.quiet = if silent { self.quiet.saturating_add(1) } else { 0 };
|
||||
self.head = (self.head + 1) % self.parts;
|
||||
let slot = self.head * B;
|
||||
if silent {
|
||||
self.x_re[slot..slot + B].fill(0.0);
|
||||
self.x_im[slot..slot + B].fill(0.0);
|
||||
if self.quiet >= self.parts {
|
||||
output.fill(0.0);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
let mut re = [0f32; N];
|
||||
let mut im = [0f32; N];
|
||||
for (r, &v) in re.iter_mut().zip(input) {
|
||||
*r = if v.is_finite() { v } else { 0.0 };
|
||||
}
|
||||
fft().run(&mut re, &mut im, false);
|
||||
self.x_re[slot..slot + B].copy_from_slice(&re[..B]);
|
||||
self.x_im[slot..slot + B].copy_from_slice(&im[..B]);
|
||||
}
|
||||
|
||||
let mut yr = [0f32; N];
|
||||
let mut yi = [0f32; N];
|
||||
for k in 0..self.parts {
|
||||
let x = ((self.head + self.parts - k) % self.parts) * B;
|
||||
let h = k * B;
|
||||
let (xr, xi) = (&self.x_re[x..x + B], &self.x_im[x..x + B]);
|
||||
let (hr, hi) = (&self.h_re[h..h + B], &self.h_im[h..h + B]);
|
||||
for bin in 0..B {
|
||||
yr[bin] += xr[bin] * hr[bin] - xi[bin] * hi[bin];
|
||||
yi[bin] += xr[bin] * hi[bin] + xi[bin] * hr[bin];
|
||||
}
|
||||
}
|
||||
|
||||
for bin in 1..B {
|
||||
yr[N - bin] = yr[bin];
|
||||
yi[N - bin] = -yi[bin];
|
||||
}
|
||||
yi[0] = 0.0;
|
||||
fft().run(&mut yr, &mut yi, true);
|
||||
let scale = gain / N as f32;
|
||||
for (o, &v) in output.iter_mut().zip(&yr[B..]) {
|
||||
*o = v * scale;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,61 @@
|
||||
|
||||
|
||||
use std::{ffi::{c_char, c_void}, fs::File, os::windows::{ffi::OsStrExt, io::AsRawHandle}, sync::OnceLock};
|
||||
|
||||
type Open = unsafe extern "system" fn(*mut c_void, *mut *mut c_void) -> i32;
|
||||
type Read = unsafe extern "system" fn(*mut c_void, *mut c_void, u32, u64) -> i32;
|
||||
type Close = unsafe extern "system" fn(*mut c_void);
|
||||
type Limits = unsafe extern "system" fn(*mut u32, *mut u32, *mut u64);
|
||||
struct Api { open: Open, read: Read, close: Close, limits: Option<Limits> }
|
||||
#[link(name="kernel32")]
|
||||
unsafe extern "system" {
|
||||
fn LoadLibraryExW(path: *const u16, file: *mut c_void, flags: u32) -> *mut c_void;
|
||||
fn GetProcAddress(module: *mut c_void, name: *const c_char) -> *const c_void;
|
||||
}
|
||||
fn api() -> Option<&'static Api> {
|
||||
static API: OnceLock<Option<Api>> = OnceLock::new();
|
||||
API.get_or_init(|| {
|
||||
let path = std::env::current_exe().ok()?.parent()?.join("eonacat-xs-dstorage-bridge.dll");
|
||||
let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
|
||||
|
||||
let lib = unsafe { LoadLibraryExW(wide.as_ptr(), std::ptr::null_mut(), 0x100 | 0x1000) };
|
||||
if lib.is_null() { return None; }
|
||||
let open = unsafe { GetProcAddress(lib, c"eonacat_xs_ds_open".as_ptr()) };
|
||||
let read = unsafe { GetProcAddress(lib, c"eonacat_xs_ds_read".as_ptr()) };
|
||||
let close = unsafe { GetProcAddress(lib, c"eonacat_xs_ds_close".as_ptr()) };
|
||||
if open.is_null() || read.is_null() || close.is_null() { return None; }
|
||||
let limits = unsafe { GetProcAddress(lib, c"eonacat_xs_ds_get_limits".as_ptr()) };
|
||||
Some(Api {
|
||||
open: unsafe { std::mem::transmute::<*const c_void, Open>(open) },
|
||||
read: unsafe { std::mem::transmute::<*const c_void, Read>(read) },
|
||||
close: unsafe { std::mem::transmute::<*const c_void, Close>(close) },
|
||||
limits: if limits.is_null() { None } else { Some(unsafe { std::mem::transmute::<*const c_void, Limits>(limits) }) },
|
||||
})
|
||||
}).as_ref()
|
||||
}
|
||||
|
||||
pub(super) struct NativeFile { context: *mut c_void, api: &'static Api }
|
||||
|
||||
unsafe impl Send for NativeFile {}
|
||||
unsafe impl Sync for NativeFile {}
|
||||
impl NativeFile {
|
||||
pub(super) fn open(file: &File) -> Option<Self> {
|
||||
let api=api()?; let mut context=std::ptr::null_mut();
|
||||
let result=unsafe { (api.open)(file.as_raw_handle().cast(), &mut context) };
|
||||
(result >= 0 && !context.is_null()).then_some(Self { context, api })
|
||||
}
|
||||
pub(super) fn limits(&self) -> Option<(u32, u32, u64)> {
|
||||
let limits = self.api.limits?;
|
||||
let (mut slots, mut wait_ms, mut staging_bytes) = (0, 0, 0);
|
||||
unsafe { limits(&mut slots, &mut wait_ms, &mut staging_bytes) };
|
||||
Some((slots, wait_ms, staging_bytes))
|
||||
}
|
||||
pub(super) fn read(&self, output: &mut [u8], offset: u64) -> Result<usize,i32> {
|
||||
let len=u32::try_from(output.len()).map_err(|_| -1)?;
|
||||
|
||||
let hr=unsafe { (self.api.read)(self.context, output.as_mut_ptr().cast(), len, offset) };
|
||||
if hr < 0 { Err(hr) } else { Ok(output.len()) }
|
||||
}
|
||||
}
|
||||
impl Drop for NativeFile { fn drop(&mut self) { unsafe { (self.api.close)(self.context) } } }
|
||||
|
||||
@@ -0,0 +1,392 @@
|
||||
|
||||
|
||||
#![allow(non_snake_case)]
|
||||
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::c_void;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
|
||||
|
||||
use eonacat_xsbox_gpu::object::Object;
|
||||
use eonacat_xsbox_gpu::streamline::{self, Taken, Upscale, plan::Camera};
|
||||
use eonacat_xsbox_gpu::loader::{ImportResolver, Provenance, Resolution};
|
||||
use eonacat_xsbox_gpu::pe::ImportSymbol;
|
||||
|
||||
pub const LOADER_DLL: &str = "amd_fidelityfx_loader_xbox.dll";
|
||||
|
||||
const OK: u32 = 0;
|
||||
const PARAMETER: u32 = 6;
|
||||
|
||||
const CREATE_UPSCALE: u64 = 0x1_0000;
|
||||
const DISPATCH_UPSCALE: u64 = 0x1_0001;
|
||||
|
||||
pub fn init_pc(dir: &std::path::Path) -> bool {
|
||||
match pc::init(dir) {
|
||||
Ok(()) => true,
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "PC FidelityFX is unavailable; retaining the title renderer");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Header {
|
||||
kind: u64,
|
||||
next: *mut Header,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct CreateUpscale {
|
||||
header: Header,
|
||||
flags: u32,
|
||||
max_render: [u32; 2],
|
||||
max_output: [u32; 2],
|
||||
message: usize,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Resource {
|
||||
resource: *mut c_void,
|
||||
description: [u32; 8],
|
||||
state: u32,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct DispatchUpscale {
|
||||
header: Header,
|
||||
list: *mut c_void,
|
||||
resources: [Resource; 7],
|
||||
jitter: [f32; 2],
|
||||
motion_scale: [f32; 2],
|
||||
render_size: [u32; 2],
|
||||
upscale_size: [u32; 2],
|
||||
enable_sharpening: u8,
|
||||
sharpness: f32,
|
||||
frame_time_delta: f32,
|
||||
pre_exposure: f32,
|
||||
reset: u8,
|
||||
camera_near: f32,
|
||||
camera_far: f32,
|
||||
camera_fov_angle_vertical: f32,
|
||||
view_space_to_meters_factor: f32,
|
||||
flags: u32,
|
||||
}
|
||||
|
||||
const _: () = assert!(size_of::<CreateUpscale>() == 0x30);
|
||||
const _: () = assert!(size_of::<Resource>() == 0x30);
|
||||
const _: () = assert!(size_of::<DispatchUpscale>() == 0x1b0);
|
||||
|
||||
type Create = unsafe extern "C" fn(*mut *mut c_void, *mut Header, *const c_void) -> u32;
|
||||
type Destroy = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> u32;
|
||||
|
||||
type Call = unsafe extern "C" fn(*mut *mut c_void, *mut Header) -> u32;
|
||||
|
||||
static ORIGINALS: [AtomicUsize; 5] = [const { AtomicUsize::new(0) }; 5];
|
||||
const NAMES: [&str; 5] = ["ffxCreateContext", "ffxDestroyContext", "ffxConfigure", "ffxQuery", "ffxDispatch"];
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct Created {
|
||||
flags: u32,
|
||||
max_render: [u32; 2],
|
||||
max_output: [u32; 2],
|
||||
|
||||
clamped: bool,
|
||||
}
|
||||
|
||||
static CONTEXTS: Mutex<Option<HashMap<usize, Created>>> = Mutex::new(None);
|
||||
|
||||
macro_rules! once {
|
||||
($level:ident, $($arg:tt)*) => {{
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
ONCE.call_once(|| tracing::$level!($($arg)*));
|
||||
}};
|
||||
}
|
||||
|
||||
mod pc;
|
||||
|
||||
pub struct Interpose<'a> {
|
||||
pub inner: &'a dyn ImportResolver,
|
||||
}
|
||||
|
||||
impl ImportResolver for Interpose<'_> {
|
||||
fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution {
|
||||
let found = self.inner.resolve(dll, symbol);
|
||||
if !dll.eq_ignore_ascii_case(LOADER_DLL) || !(streamline::serving() || pc::active()) {
|
||||
return found;
|
||||
}
|
||||
match (&found, symbol) {
|
||||
(&Resolution::Found { address, .. }, ImportSymbol::Name { name, .. }) => match interpose(name, address) {
|
||||
Some(ours) => Resolution::Found { address: ours, provenance: Provenance::Hle },
|
||||
None => found,
|
||||
},
|
||||
_ => found,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn wrap(dll: &str, name: &str, address: usize) -> usize {
|
||||
if address == 0 || !dll.eq_ignore_ascii_case(LOADER_DLL) || !streamline::serving() {
|
||||
return address;
|
||||
}
|
||||
interpose(name, address).unwrap_or(address)
|
||||
}
|
||||
|
||||
fn interpose(name: &str, original: usize) -> Option<usize> {
|
||||
let i = NAMES.iter().position(|n| *n == name)?;
|
||||
ORIGINALS[i].store(original, Relaxed);
|
||||
let ours = [
|
||||
ffxCreateContext as *const () as usize,
|
||||
ffxDestroyContext as *const () as usize,
|
||||
ffxConfigure as *const () as usize,
|
||||
ffxQuery as *const () as usize,
|
||||
ffxDispatch as *const () as usize,
|
||||
][i];
|
||||
tracing::info!(name, original = format_args!("{original:#x}"), "FidelityFX: the title's import goes through ours (DLSS / frame generation)");
|
||||
Some(ours)
|
||||
}
|
||||
|
||||
fn original(i: usize) -> Option<*const ()> {
|
||||
let address = ORIGINALS[i].load(Relaxed);
|
||||
(address != 0).then_some(address as *const ())
|
||||
}
|
||||
|
||||
fn contexts<T>(f: impl FnOnce(&mut HashMap<usize, Created>) -> T) -> T {
|
||||
let mut contexts = CONTEXTS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
f(contexts.get_or_insert_with(HashMap::new))
|
||||
}
|
||||
|
||||
const SHIPPING_MAX_OUTPUT: [u32; 2] = [1920, 1080];
|
||||
const SHIPPING_MAX_RENDER: [u32; 2] = [1280, 720];
|
||||
|
||||
fn shipping_sizes(render: [u32; 2], output: [u32; 2]) -> Option<([u32; 2], [u32; 2])> {
|
||||
((render, output) != (SHIPPING_MAX_RENDER, SHIPPING_MAX_OUTPUT)).then_some((SHIPPING_MAX_RENDER, SHIPPING_MAX_OUTPUT))
|
||||
}
|
||||
|
||||
fn find(desc: *mut Header, kind: u64) -> Option<*mut Header> {
|
||||
let mut at = desc;
|
||||
for _ in 0..16 {
|
||||
if at.is_null() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let header = unsafe { at.read() };
|
||||
if header.kind == kind {
|
||||
return Some(at);
|
||||
}
|
||||
at = header.next;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
extern "C" fn ffxCreateContext(context: *mut *mut c_void, desc: *mut Header, memory: *const c_void) -> u32 {
|
||||
let Some(create) = original(0) else { return PARAMETER };
|
||||
|
||||
let call = |desc: *mut Header| unsafe { std::mem::transmute::<*const (), Create>(create)(context, desc, memory) };
|
||||
let Some(upscale) = find(desc, CREATE_UPSCALE) else {
|
||||
return call(desc);
|
||||
};
|
||||
|
||||
let asked = unsafe { upscale.cast::<CreateUpscale>().read() };
|
||||
if pc::active() && !streamline::upscaling() {
|
||||
return pc::create(context, asked, memory);
|
||||
}
|
||||
|
||||
let shipping = streamline::upscaling().then(|| shipping_sizes(asked.max_render, asked.max_output)).flatten();
|
||||
let clamped = shipping.is_some();
|
||||
let code = if let Some((render, output)) = shipping {
|
||||
let mut fitted = asked;
|
||||
fitted.max_render = render;
|
||||
fitted.max_output = output;
|
||||
|
||||
unsafe { upscale.cast::<CreateUpscale>().write(fitted) };
|
||||
let code = call(desc);
|
||||
|
||||
unsafe { upscale.cast::<CreateUpscale>().write(asked) };
|
||||
tracing::info!(
|
||||
asked_render = ?asked.max_render,
|
||||
asked_output = ?asked.max_output,
|
||||
made_render = ?fitted.max_render,
|
||||
made_output = ?fitted.max_output,
|
||||
code,
|
||||
"FidelityFX: the title's upscaler made at a size its shipping FSR4 accepts; DLSS upscales to the size asked"
|
||||
);
|
||||
code
|
||||
} else {
|
||||
call(desc)
|
||||
};
|
||||
if code != OK || context.is_null() {
|
||||
|
||||
if code != OK && !streamline::upscaling() {
|
||||
tracing::error!(
|
||||
code,
|
||||
max_render = ?asked.max_render,
|
||||
max_output = ?asked.max_output,
|
||||
"FidelityFX: the title's own upscaler was not made at these sizes (its shipping FSR4 takes 1280x720 or 1920x1080 in, 1920x1080 out): with frame generation at another output size, set EONACAT_XS_DLSS=1 as well; the title fails at its first upscaling without an upscaler"
|
||||
);
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
let handle = unsafe { *context } as usize;
|
||||
let created = Created { flags: asked.flags, max_render: asked.max_render, max_output: asked.max_output, clamped };
|
||||
tracing::info!(
|
||||
context = format_args!("{handle:#x}"),
|
||||
flags = format_args!("{:#x}", created.flags),
|
||||
max_render = ?created.max_render,
|
||||
max_output = ?created.max_output,
|
||||
"FidelityFX: the title made its upscaler"
|
||||
);
|
||||
contexts(|c| c.insert(handle, created));
|
||||
code
|
||||
}
|
||||
|
||||
extern "C" fn ffxDestroyContext(context: *mut *mut c_void, memory: *const c_void) -> u32 {
|
||||
if let Some(code) = pc::destroy(context) {
|
||||
return code;
|
||||
}
|
||||
let Some(destroy) = original(1) else { return PARAMETER };
|
||||
if !context.is_null() {
|
||||
|
||||
let handle = unsafe { *context } as usize;
|
||||
if contexts(|c| c.remove(&handle)).is_some() {
|
||||
streamline::upscaler_destroyed(handle);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe { std::mem::transmute::<*const (), Destroy>(destroy)(context, memory) }
|
||||
}
|
||||
|
||||
extern "C" fn ffxConfigure(context: *mut *mut c_void, desc: *mut Header) -> u32 {
|
||||
if let Some(code) = pc::call(context, desc, false) {
|
||||
return code;
|
||||
}
|
||||
let Some(configure) = original(2) else { return PARAMETER };
|
||||
|
||||
unsafe { std::mem::transmute::<*const (), Call>(configure)(context, desc) }
|
||||
}
|
||||
|
||||
extern "C" fn ffxQuery(context: *mut *mut c_void, desc: *mut Header) -> u32 {
|
||||
if let Some(code) = pc::call(context, desc, true) {
|
||||
return code;
|
||||
}
|
||||
let Some(query) = original(3) else { return PARAMETER };
|
||||
if !desc.is_null() {
|
||||
|
||||
let kind = unsafe { (*desc).kind };
|
||||
static SEEN: Mutex<Vec<u64>> = Mutex::new(Vec::new());
|
||||
let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if !seen.contains(&kind) && seen.len() < 32 {
|
||||
seen.push(kind);
|
||||
tracing::info!(kind = format_args!("{kind:#x}"), "FidelityFX: the title asks a query of this kind (answered by its own DLL)");
|
||||
}
|
||||
}
|
||||
|
||||
unsafe { std::mem::transmute::<*const (), Call>(query)(context, desc) }
|
||||
}
|
||||
|
||||
extern "C" fn ffxDispatch(context: *mut *mut c_void, desc: *mut Header) -> u32 {
|
||||
if let Some(code) = pc::dispatch(context, desc) {
|
||||
return code;
|
||||
}
|
||||
let Some(dispatch) = original(4) else { return PARAMETER };
|
||||
|
||||
let own = || unsafe { std::mem::transmute::<*const (), Call>(dispatch)(context, desc) };
|
||||
if context.is_null() || desc.is_null() {
|
||||
return own();
|
||||
}
|
||||
|
||||
let handle = unsafe { *context as usize };
|
||||
let Some(asked) = find(desc, DISPATCH_UPSCALE) else {
|
||||
return own();
|
||||
};
|
||||
let Some(created) = contexts(|c| c.get(&handle).copied()) else {
|
||||
once!(warn, "FidelityFX: an upscale dispatch on a context we did not see made; the title's own runs");
|
||||
return own();
|
||||
};
|
||||
|
||||
let d = unsafe { asked.cast::<DispatchUpscale>().read() };
|
||||
first_dispatch(&d, &created);
|
||||
let up = upscale(&d, &created, handle);
|
||||
match streamline::upscale(&up) {
|
||||
Taken::Dlss => OK,
|
||||
Taken::Noted => own(),
|
||||
Taken::No(why) if created.clamped => {
|
||||
|
||||
refused(why);
|
||||
if eonacat_xsbox_gpu::upscale_fallback::upscale(&up) {
|
||||
once!(warn, "FidelityFX: DLSS did not take an upscaling on a context made smaller than asked; a plain (bilinear) one ran");
|
||||
} else {
|
||||
once!(warn, "FidelityFX: DLSS did not take an upscaling on a context made smaller than asked; none ran");
|
||||
}
|
||||
OK
|
||||
}
|
||||
Taken::No(why) => {
|
||||
streamline::forwarded();
|
||||
refused(why);
|
||||
own()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn refused(why: &'static str) {
|
||||
static SEEN: Mutex<Vec<&'static str>> = Mutex::new(Vec::new());
|
||||
let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if !seen.contains(&why) {
|
||||
seen.push(why);
|
||||
tracing::warn!("FidelityFX: the title's own upscaling runs: {why}");
|
||||
}
|
||||
}
|
||||
|
||||
fn first_dispatch(d: &DispatchUpscale, created: &Created) {
|
||||
once!(
|
||||
info,
|
||||
render = ?d.render_size,
|
||||
output = ?d.upscale_size,
|
||||
max_render = ?created.max_render,
|
||||
max_output = ?created.max_output,
|
||||
create_flags = format_args!("{:#x}", created.flags),
|
||||
flags = format_args!("{:#x}", d.flags),
|
||||
jitter = ?d.jitter,
|
||||
motion_vector_scale = ?d.motion_scale,
|
||||
near = d.camera_near,
|
||||
far = d.camera_far,
|
||||
fov = d.camera_fov_angle_vertical,
|
||||
frame_ms = d.frame_time_delta,
|
||||
pre_exposure = d.pre_exposure,
|
||||
reset = d.reset != 0,
|
||||
sharpening = d.enable_sharpening != 0,
|
||||
resources = ?d.resources.iter().map(|r| (r.resource as usize != 0, r.description[1], r.description[2], r.description[3], r.state)).collect::<Vec<_>>(),
|
||||
"FidelityFX: the title's first upscale dispatch (resources: present, format, width, height, state)"
|
||||
);
|
||||
}
|
||||
|
||||
fn upscale(d: &DispatchUpscale, created: &Created, context: usize) -> Upscale {
|
||||
let output = if d.upscale_size == [0, 0] { created.max_output } else { d.upscale_size };
|
||||
Upscale {
|
||||
context,
|
||||
list: d.list.cast::<Object>().cast_const(),
|
||||
resources: d.resources.map(|r| (r.resource.cast::<Object>().cast_const(), r.state)),
|
||||
camera: Camera {
|
||||
jitter: d.jitter,
|
||||
motion_scale: d.motion_scale,
|
||||
render: d.render_size,
|
||||
output,
|
||||
near: d.camera_near,
|
||||
far: d.camera_far,
|
||||
fov_y: d.camera_fov_angle_vertical,
|
||||
reset: d.reset != 0,
|
||||
flags: created.flags,
|
||||
},
|
||||
pre_exposure: d.pre_exposure,
|
||||
frame_ms: d.frame_time_delta,
|
||||
view_space_to_meters: d.view_space_to_meters_factor,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
|
||||
|
||||
use super::*;
|
||||
use std::ffi::CStr;
|
||||
use std::path::Path;
|
||||
use std::ptr::{null, null_mut};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use windows_sys::Win32::Foundation::FreeLibrary;
|
||||
use windows_sys::Win32::System::LibraryLoader::{
|
||||
GetProcAddress, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW,
|
||||
};
|
||||
|
||||
const UPSCALER_DLL: &str = "amd_fidelityfx_upscaler_dx12.dll";
|
||||
const GET_VERSIONS: u64 = 4;
|
||||
const GET_PROVIDER_VERSION: u64 = 6;
|
||||
const QUERY_MEMORY_USAGE: u64 = 0x1_0009;
|
||||
const NO_PROVIDER: u32 = 4;
|
||||
|
||||
#[repr(C)]
|
||||
struct Versions {
|
||||
header: Header,
|
||||
effect: u64,
|
||||
device: *mut c_void,
|
||||
count: *mut u64,
|
||||
ids: *mut u64,
|
||||
names: *mut *const std::ffi::c_char,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct Backend {
|
||||
header: Header,
|
||||
device: *mut c_void,
|
||||
}
|
||||
|
||||
struct Module(usize);
|
||||
impl Drop for Module {
|
||||
fn drop(&mut self) {
|
||||
|
||||
unsafe { FreeLibrary(self.0 as _) };
|
||||
}
|
||||
}
|
||||
|
||||
struct Api {
|
||||
_library: Module,
|
||||
create: Create,
|
||||
destroy: Destroy,
|
||||
configure: Call,
|
||||
query: Call,
|
||||
dispatch: Call,
|
||||
device: usize,
|
||||
}
|
||||
|
||||
static API: OnceLock<Api> = OnceLock::new();
|
||||
|
||||
struct Context {
|
||||
handle: Mutex<usize>,
|
||||
created: Created,
|
||||
}
|
||||
|
||||
impl Drop for Context {
|
||||
fn drop(&mut self) {
|
||||
if let Some(api) = API.get() {
|
||||
let handle = *self.handle.get_mut().unwrap_or_else(|e| e.into_inner());
|
||||
let mut handle = handle as *mut c_void;
|
||||
|
||||
unsafe { (api.destroy)(&mut handle, null()) };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static CONTEXTS: Mutex<Option<HashMap<usize, Arc<Context>>>> = Mutex::new(None);
|
||||
|
||||
pub(super) fn init(dir: &Path) -> Result<(), String> {
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
let path = std::path::absolute(dir.join(UPSCALER_DLL)).map_err(|e| e.to_string())?;
|
||||
streamline::verify_signature(&path)?;
|
||||
let wide: Vec<u16> = path.as_os_str().encode_wide().chain([0]).collect();
|
||||
|
||||
let module = unsafe {
|
||||
LoadLibraryExW(
|
||||
wide.as_ptr(),
|
||||
null_mut(),
|
||||
LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32,
|
||||
)
|
||||
};
|
||||
if module.is_null() {
|
||||
return Err(std::io::Error::last_os_error().to_string());
|
||||
}
|
||||
let library = Module(module as usize);
|
||||
let export = |name: &CStr| {
|
||||
|
||||
unsafe { GetProcAddress(module, name.as_ptr().cast()) }
|
||||
.map(|f| f as *const ())
|
||||
.ok_or_else(|| format!("missing {}", name.to_string_lossy()))
|
||||
};
|
||||
let device = streamline::host_upscale_device().ok_or("no host D3D12 device")?;
|
||||
let device_ptr = windows::core::Interface::as_raw(&device);
|
||||
|
||||
let api = unsafe {
|
||||
Api {
|
||||
_library: library,
|
||||
create: std::mem::transmute::<*const (), Create>(export(c"ffxCreateContext")?),
|
||||
destroy: std::mem::transmute::<*const (), Destroy>(export(c"ffxDestroyContext")?),
|
||||
configure: std::mem::transmute::<*const (), Call>(export(c"ffxConfigure")?),
|
||||
query: std::mem::transmute::<*const (), Call>(export(c"ffxQuery")?),
|
||||
dispatch: std::mem::transmute::<*const (), Call>(export(c"ffxDispatch")?),
|
||||
device: device_ptr as usize,
|
||||
}
|
||||
};
|
||||
let mut count = 0;
|
||||
let mut versions = Versions {
|
||||
header: Header {
|
||||
kind: GET_VERSIONS,
|
||||
next: null_mut(),
|
||||
},
|
||||
effect: CREATE_UPSCALE,
|
||||
device: device_ptr,
|
||||
count: &mut count,
|
||||
ids: null_mut(),
|
||||
names: null_mut(),
|
||||
};
|
||||
|
||||
if unsafe { (api.query)(null_mut(), &mut versions.header) } != OK || count == 0 {
|
||||
return Err("the selected device exposes no PC FidelityFX upscaler".to_owned());
|
||||
}
|
||||
let _ = API.set(api);
|
||||
tracing::info!(count, dll = %path.display(), "PC FidelityFX upscaling available");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn active() -> bool {
|
||||
API.get().is_some()
|
||||
}
|
||||
|
||||
pub(super) fn create(
|
||||
context: *mut *mut c_void,
|
||||
mut asked: CreateUpscale,
|
||||
memory: *const c_void,
|
||||
) -> u32 {
|
||||
let Some(api) = API.get() else {
|
||||
return NO_PROVIDER;
|
||||
};
|
||||
if context.is_null() {
|
||||
return PARAMETER;
|
||||
}
|
||||
let mut backend = Backend {
|
||||
header: Header {
|
||||
kind: 2,
|
||||
next: asked.header.next,
|
||||
},
|
||||
device: api.device as *mut c_void,
|
||||
};
|
||||
|
||||
if let Some(extension) = unsafe { asked.header.next.as_ref() }
|
||||
&& extension.kind == 0x100_0002
|
||||
{
|
||||
backend.header.next = extension.next;
|
||||
}
|
||||
asked.header.next = &raw mut backend.header;
|
||||
|
||||
let code = unsafe { (api.create)(context, &mut asked.header, memory) };
|
||||
if code != OK || context.is_null() {
|
||||
tracing::warn!(code, render = ?asked.max_render, output = ?asked.max_output, "PC FidelityFX context creation failed");
|
||||
return code;
|
||||
}
|
||||
|
||||
let handle = unsafe { *context } as usize;
|
||||
if handle == 0 {
|
||||
return NO_PROVIDER;
|
||||
}
|
||||
let created = Created {
|
||||
flags: asked.flags,
|
||||
max_render: asked.max_render,
|
||||
max_output: asked.max_output,
|
||||
clamped: false,
|
||||
};
|
||||
CONTEXTS
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.get_or_insert_with(HashMap::new)
|
||||
.insert(
|
||||
handle,
|
||||
Arc::new(Context {
|
||||
handle: Mutex::new(handle),
|
||||
created,
|
||||
}),
|
||||
);
|
||||
|
||||
let provider = provider_version(api, context);
|
||||
tracing::info!(
|
||||
render = ?asked.max_render,
|
||||
output = ?asked.max_output,
|
||||
provider = provider.as_deref().unwrap_or("?"),
|
||||
"PC FidelityFX upscaler created"
|
||||
);
|
||||
OK
|
||||
}
|
||||
|
||||
fn provider_version(api: &Api, context: *mut *mut c_void) -> Option<String> {
|
||||
#[repr(C)]
|
||||
struct ProviderVersion {
|
||||
header: Header,
|
||||
id: u64,
|
||||
name: *const std::ffi::c_char,
|
||||
}
|
||||
const _: () = assert!(size_of::<ProviderVersion>() == 32);
|
||||
let mut asked = ProviderVersion { header: Header { kind: GET_PROVIDER_VERSION, next: null_mut() }, id: 0, name: null() };
|
||||
|
||||
if unsafe { (api.query)(context, &mut asked.header) } != OK || asked.name.is_null() {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(unsafe { CStr::from_ptr(asked.name) }.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
fn get(slot: *mut *mut c_void) -> Option<(usize, Arc<Context>)> {
|
||||
|
||||
let key = unsafe { *slot.as_ref()? } as usize;
|
||||
let contexts = CONTEXTS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
Some((key, contexts.as_ref()?.get(&key)?.clone()))
|
||||
}
|
||||
|
||||
pub(super) fn destroy(slot: *mut *mut c_void) -> Option<u32> {
|
||||
let (key, context) = get(slot)?;
|
||||
streamline::finish_host_upscale();
|
||||
CONTEXTS
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.as_mut()?
|
||||
.remove(&key);
|
||||
drop(context);
|
||||
|
||||
unsafe { *slot = null_mut() };
|
||||
Some(OK)
|
||||
}
|
||||
|
||||
pub(super) fn call(slot: *mut *mut c_void, desc: *mut Header, query: bool) -> Option<u32> {
|
||||
let api = API.get()?;
|
||||
|
||||
if query
|
||||
&& unsafe { desc.as_ref() }
|
||||
.is_some_and(|header| matches!(header.kind, GET_VERSIONS | QUERY_MEMORY_USAGE))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let (_, context) = get(slot)?;
|
||||
let handle = context.handle.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut handle = *handle as *mut c_void;
|
||||
let call = if query { api.query } else { api.configure };
|
||||
|
||||
Some(unsafe { call(&mut handle, desc) })
|
||||
}
|
||||
|
||||
struct Dispatch(DispatchUpscale);
|
||||
|
||||
unsafe impl Send for Dispatch {}
|
||||
|
||||
impl Dispatch {
|
||||
fn record(
|
||||
mut self,
|
||||
api: &Api,
|
||||
context: &Context,
|
||||
list: &windows::Win32::Graphics::Direct3D12::ID3D12GraphicsCommandList,
|
||||
textures: [Option<windows::Win32::Graphics::Direct3D12::ID3D12Resource>; 7],
|
||||
) -> bool {
|
||||
use windows::core::Interface;
|
||||
self.0.list = list.as_raw();
|
||||
for (desc, texture) in self.0.resources.iter_mut().zip(&textures) {
|
||||
desc.resource = texture.as_ref().map_or(null_mut(), Interface::as_raw);
|
||||
}
|
||||
let handle = context.handle.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut handle = *handle as *mut c_void;
|
||||
|
||||
let code = unsafe { (api.dispatch)(&mut handle, &mut self.0.header) };
|
||||
if code == OK {
|
||||
once!(info, render = ?self.0.render_size, output = ?self.0.upscale_size,
|
||||
"PC FidelityFX recorded its first host upscale");
|
||||
} else {
|
||||
once!(warn, code, "PC FidelityFX refused a host upscale dispatch");
|
||||
}
|
||||
code == OK
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn dispatch(slot: *mut *mut c_void, desc: *mut Header) -> Option<u32> {
|
||||
let api = API.get()?;
|
||||
let (key, context) = get(slot)?;
|
||||
|
||||
let Some(header) = (unsafe { desc.as_ref() }) else {
|
||||
return Some(PARAMETER);
|
||||
};
|
||||
if header.kind != DISPATCH_UPSCALE || !header.next.is_null() {
|
||||
return Some(PARAMETER);
|
||||
}
|
||||
|
||||
let mut desc = unsafe { desc.cast::<DispatchUpscale>().read() };
|
||||
let up = upscale(&desc, &context.created, key);
|
||||
desc.list = null_mut();
|
||||
for resource in &mut desc.resources {
|
||||
resource.resource = null_mut();
|
||||
}
|
||||
let dispatch = Dispatch(desc);
|
||||
let queued = streamline::record_host_upscale(up, move |list, textures| {
|
||||
dispatch.record(api, &context, list, textures)
|
||||
});
|
||||
Some(if queued { OK } else { PARAMETER })
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,839 @@
|
||||
|
||||
|
||||
use super::{
|
||||
A, B, DOWN, LEFT, LEFT_SHOULDER, LEFT_STICK, MENU, PadState, RIGHT, RIGHT_SHOULDER,
|
||||
RIGHT_STICK, UP, VIEW, X, Y,
|
||||
};
|
||||
|
||||
const GENERIC_DESKTOP: u16 = 0x01;
|
||||
const USAGE_X: u16 = 0x30;
|
||||
const AXES: usize = 6;
|
||||
const USAGE_HAT: u16 = 0x39;
|
||||
const USAGE_START: u16 = 0x3D;
|
||||
const USAGE_SELECT: u16 = 0x3E;
|
||||
const DESKTOP_BUTTONS: [(u16, u32); 6] = [
|
||||
(USAGE_START, MENU),
|
||||
(USAGE_SELECT, VIEW),
|
||||
(0x90, UP),
|
||||
(0x91, DOWN),
|
||||
(0x92, RIGHT),
|
||||
(0x93, LEFT),
|
||||
];
|
||||
|
||||
const BUTTON_PAGE: u16 = 0x09;
|
||||
|
||||
const PAD_USAGES: [u16; 2] = [0x04, 0x05];
|
||||
|
||||
pub(super) const ID: u64 = 1 << 63;
|
||||
|
||||
const AXIS_NAMES: [&str; AXES] = ["X", "Y", "Z", "Rx", "Ry", "Rz"];
|
||||
|
||||
const TARGETS: [u32; 16] = [
|
||||
A,
|
||||
B,
|
||||
X,
|
||||
Y,
|
||||
LEFT_SHOULDER,
|
||||
RIGHT_SHOULDER,
|
||||
0,
|
||||
0,
|
||||
VIEW,
|
||||
MENU,
|
||||
LEFT_STICK,
|
||||
RIGHT_STICK,
|
||||
UP,
|
||||
DOWN,
|
||||
LEFT,
|
||||
RIGHT,
|
||||
];
|
||||
const LEFT_TRIGGER: usize = 6;
|
||||
const RIGHT_TRIGGER: usize = 7;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) struct Layout([u16; 16]);
|
||||
|
||||
impl Layout {
|
||||
|
||||
const PLAYSTATION: Layout = Layout([3, 2, 4, 1, 5, 6, 7, 8, 9, 10, 11, 12, 0, 0, 0, 0]);
|
||||
|
||||
const DIRECTINPUT: Layout = Layout([2, 3, 1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 0, 0, 0]);
|
||||
|
||||
const NINTENDO: Layout = Layout([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 0, 0, 0]);
|
||||
|
||||
fn for_pad(vendor: u16) -> Layout {
|
||||
match vendor {
|
||||
0x046D => Layout::DIRECTINPUT,
|
||||
0x057E => Layout::NINTENDO,
|
||||
_ => Layout::PLAYSTATION,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse(text: &str) -> Option<Layout> {
|
||||
let numbers = text
|
||||
.split(',')
|
||||
.map(|n| n.trim().parse::<u16>().ok())
|
||||
.collect::<Option<Vec<u16>>>()?;
|
||||
if numbers.len() != 12 && numbers.len() != 16 {
|
||||
return None;
|
||||
}
|
||||
let mut layout = [0; 16];
|
||||
layout[..numbers.len()].copy_from_slice(&numbers);
|
||||
Some(Layout(layout))
|
||||
}
|
||||
|
||||
fn text(&self) -> String {
|
||||
let end = if self.0[12..].iter().all(|&n| n == 0) {
|
||||
12
|
||||
} else {
|
||||
16
|
||||
};
|
||||
let numbers: Vec<String> = self.0[..end].iter().map(u16::to_string).collect();
|
||||
numbers.join(",")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) struct Range {
|
||||
min: i64,
|
||||
max: i64,
|
||||
|
||||
signed: bool,
|
||||
bits: u32,
|
||||
}
|
||||
|
||||
impl Range {
|
||||
|
||||
fn new(min: i32, max: i32, bits: u16) -> Option<Range> {
|
||||
let bits = u32::from(bits).clamp(1, 32);
|
||||
let mask = (1i64 << bits) - 1;
|
||||
let (mut min, mut max, mut signed) = (i64::from(min), i64::from(max), min < 0);
|
||||
if max < min {
|
||||
(min, max, signed) = (min & mask, max & mask, false);
|
||||
}
|
||||
(max > min).then_some(Range {
|
||||
min,
|
||||
max,
|
||||
signed,
|
||||
bits,
|
||||
})
|
||||
}
|
||||
|
||||
fn value(self, raw: u32) -> i64 {
|
||||
let raw = i64::from(raw) & ((1i64 << self.bits) - 1);
|
||||
if self.signed && raw >> (self.bits - 1) & 1 != 0 {
|
||||
raw - (1i64 << self.bits)
|
||||
} else {
|
||||
raw
|
||||
}
|
||||
}
|
||||
|
||||
fn stick(self, value: i64) -> f32 {
|
||||
let span = (self.max - self.min) as f64;
|
||||
((2.0 * (value - self.min) as f64 / span - 1.0) as f32).clamp(-1.0, 1.0)
|
||||
}
|
||||
|
||||
fn trigger(self, value: i64) -> f32 {
|
||||
let span = (self.max - self.min) as f64;
|
||||
(((value - self.min) as f64 / span) as f32).clamp(0.0, 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub(super) struct Shape {
|
||||
axes: [Option<Range>; AXES],
|
||||
hat: Option<Range>,
|
||||
}
|
||||
|
||||
impl Shape {
|
||||
|
||||
fn describe(&self) -> String {
|
||||
let mut names: Vec<&str> = AXIS_NAMES
|
||||
.iter()
|
||||
.zip(self.axes)
|
||||
.filter_map(|(name, range)| range.map(|_| *name))
|
||||
.collect();
|
||||
if self.hat.is_some() {
|
||||
names.push("hat");
|
||||
}
|
||||
if names.is_empty() {
|
||||
"no axes".to_owned()
|
||||
} else {
|
||||
names.join(" ")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub(super) struct Raw {
|
||||
axes: [Option<i64>; AXES],
|
||||
hat: Option<i64>,
|
||||
buttons: Vec<u16>,
|
||||
desktop: Vec<u16>,
|
||||
}
|
||||
|
||||
fn hat(range: Range, value: i64) -> u32 {
|
||||
if value < range.min || value > range.max {
|
||||
return 0;
|
||||
}
|
||||
let step = value - range.min;
|
||||
let eighths = if range.max - range.min + 1 == 4 {
|
||||
step * 2
|
||||
} else {
|
||||
step
|
||||
};
|
||||
match eighths {
|
||||
0 => UP,
|
||||
1 => UP | RIGHT,
|
||||
2 => RIGHT,
|
||||
3 => RIGHT | DOWN,
|
||||
4 => DOWN,
|
||||
5 => DOWN | LEFT,
|
||||
6 => LEFT,
|
||||
7 => LEFT | UP,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn centred(shape: &Shape) -> [bool; AXES] {
|
||||
let triggers = shape.axes[2].is_some() && shape.axes[5].is_some();
|
||||
std::array::from_fn(|i| shape.axes[i].is_some() && !(triggers && (i == 3 || i == 4)))
|
||||
}
|
||||
|
||||
pub(super) fn off_centre(shape: &Shape, axis: usize, value: i64) -> bool {
|
||||
centred(shape)[axis] && shape.axes[axis].is_some_and(|r| r.stick(value).abs() > 0.5)
|
||||
}
|
||||
|
||||
pub(super) fn state(shape: &Shape, raw: &Raw, layout: &Layout) -> PadState {
|
||||
let has = |i: usize| shape.axes[i].is_some();
|
||||
let stick = |i: usize| Some(shape.axes[i]?.stick(raw.axes[i]?));
|
||||
let trigger = |i: usize| Some(shape.axes[i]?.trigger(raw.axes[i]?));
|
||||
let (right, (left_trigger, right_trigger)) = if has(2) && has(5) {
|
||||
let triggers = (trigger(3).unwrap_or(0.0), trigger(4).unwrap_or(0.0));
|
||||
((stick(2), stick(5)), triggers)
|
||||
} else {
|
||||
let z = stick(2).unwrap_or(0.0);
|
||||
((stick(3), stick(4)), (z.max(0.0), (-z).max(0.0)))
|
||||
};
|
||||
let held = |n: u16| n != 0 && raw.buttons.contains(&n);
|
||||
let mut buttons = shape.hat.zip(raw.hat).map_or(0, |(range, v)| hat(range, v));
|
||||
for (&n, bit) in layout.0.iter().zip(TARGETS) {
|
||||
if held(n) {
|
||||
buttons |= bit;
|
||||
}
|
||||
}
|
||||
for (usage, bit) in DESKTOP_BUTTONS {
|
||||
if raw.desktop.contains(&usage) {
|
||||
buttons |= bit;
|
||||
}
|
||||
}
|
||||
let pressed = |n: u16| if held(n) { 1.0 } else { 0.0 };
|
||||
PadState {
|
||||
buttons,
|
||||
left_trigger: left_trigger.max(pressed(layout.0[LEFT_TRIGGER])),
|
||||
right_trigger: right_trigger.max(pressed(layout.0[RIGHT_TRIGGER])),
|
||||
left_x: stick(0).unwrap_or(0.0),
|
||||
left_y: -stick(1).unwrap_or(0.0),
|
||||
right_x: right.0.unwrap_or(0.0),
|
||||
right_y: -right.1.unwrap_or(0.0),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn enabled() -> bool {
|
||||
std::env::var_os("EONACAT_XS_GENERIC_PADS").is_none_or(|v| v != "0")
|
||||
}
|
||||
|
||||
fn layout(vendor: u16) -> Layout {
|
||||
let set = std::env::var("EONACAT_XS_PAD_BUTTONS")
|
||||
.ok()
|
||||
.filter(|t| !t.trim().is_empty());
|
||||
match set.as_deref().map(|t| (t, Layout::parse(t))) {
|
||||
Some((_, Some(layout))) => layout,
|
||||
Some((text, None)) => {
|
||||
tracing::warn!(
|
||||
text,
|
||||
"EONACAT_XS_PAD_BUTTONS: not 12 or 16 button numbers; the pad's own layout is used"
|
||||
);
|
||||
Layout::for_pad(vendor)
|
||||
}
|
||||
None => Layout::for_pad(vendor),
|
||||
}
|
||||
}
|
||||
|
||||
fn names(pad: &PadState) -> String {
|
||||
const NAMES: [(u32, &str); 14] = [
|
||||
(A, "A"),
|
||||
(B, "B"),
|
||||
(X, "X"),
|
||||
(Y, "Y"),
|
||||
(LEFT_SHOULDER, "LB"),
|
||||
(RIGHT_SHOULDER, "RB"),
|
||||
(VIEW, "View"),
|
||||
(MENU, "Menu"),
|
||||
(LEFT_STICK, "LS"),
|
||||
(RIGHT_STICK, "RS"),
|
||||
(UP, "Up"),
|
||||
(DOWN, "Down"),
|
||||
(LEFT, "Left"),
|
||||
(RIGHT, "Right"),
|
||||
];
|
||||
let mut held: Vec<String> = NAMES
|
||||
.iter()
|
||||
.filter(|(bit, _)| pad.buttons & bit != 0)
|
||||
.map(|(_, name)| (*name).to_owned())
|
||||
.collect();
|
||||
for (name, value) in [("LT", pad.left_trigger), ("RT", pad.right_trigger)] {
|
||||
if value > 0.05 {
|
||||
held.push(format!("{name} {value:.2}"));
|
||||
}
|
||||
}
|
||||
if held.is_empty() {
|
||||
"-".to_owned()
|
||||
} else {
|
||||
held.join(" ")
|
||||
}
|
||||
}
|
||||
|
||||
fn line(shape: &Shape, raw: &Raw, pad: &PadState) -> String {
|
||||
let mut parts = vec![format!("buttons {:?}", raw.buttons)];
|
||||
for ((name, range), value) in AXIS_NAMES.iter().zip(shape.axes).zip(raw.axes) {
|
||||
if let (Some(range), Some(value)) = (range, value) {
|
||||
parts.push(format!("{name} {:+.2}", range.stick(value)));
|
||||
}
|
||||
}
|
||||
if let (Some(_), Some(value)) = (shape.hat, raw.hat) {
|
||||
parts.push(format!("hat {value}"));
|
||||
}
|
||||
if !raw.desktop.is_empty() {
|
||||
parts.push(format!("desktop {:02X?}", raw.desktop));
|
||||
}
|
||||
format!(
|
||||
"{} -> {} (sticks L {:+.2} {:+.2} R {:+.2} {:+.2})",
|
||||
parts.join(", "),
|
||||
names(pad),
|
||||
pad.left_x,
|
||||
pad.left_y,
|
||||
pad.right_x,
|
||||
pad.right_y
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(super) use host::{monitor, pads};
|
||||
|
||||
#[cfg(windows)]
|
||||
mod host {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{LazyLock, Mutex, PoisonError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use windows_sys::Win32::Devices::HumanInterfaceDevice::{
|
||||
HIDD_ATTRIBUTES, HIDP_CAPS, HIDP_STATUS_SUCCESS, HIDP_VALUE_CAPS, HidD_FreePreparsedData,
|
||||
HidD_GetAttributes, HidD_GetPreparsedData, HidD_GetProductString, HidP_GetCaps,
|
||||
HidP_GetUsageValue, HidP_GetUsages, HidP_GetValueCaps, HidP_Input, HidP_MaxUsageListLength,
|
||||
PHIDP_PREPARSED_DATA,
|
||||
};
|
||||
use windows_sys::Win32::Foundation::{CloseHandle, GENERIC_READ, HANDLE, INVALID_HANDLE_VALUE};
|
||||
use windows_sys::Win32::Storage::FileSystem::{
|
||||
CreateFileW, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING, ReadFile,
|
||||
};
|
||||
|
||||
use super::super::playstation::{Sony, hid_paths};
|
||||
use super::{
|
||||
AXES, AXIS_NAMES, BUTTON_PAGE, GENERIC_DESKTOP, ID, Layout, PAD_USAGES, PadState, Range,
|
||||
Raw, Shape, USAGE_HAT, USAGE_X, layout, line, off_centre, state,
|
||||
};
|
||||
|
||||
const SCAN: Duration = Duration::from_secs(2);
|
||||
|
||||
struct Pad {
|
||||
|
||||
id: u64,
|
||||
path: Vec<u16>,
|
||||
name: String,
|
||||
shape: Shape,
|
||||
|
||||
buttons: usize,
|
||||
layout: Layout,
|
||||
raw: Raw,
|
||||
|
||||
state: Option<PadState>,
|
||||
}
|
||||
|
||||
static PADS: Mutex<Vec<Pad>> = Mutex::new(Vec::new());
|
||||
|
||||
fn lock() -> std::sync::MutexGuard<'static, Vec<Pad>> {
|
||||
PADS.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
static OTHERS: Mutex<Vec<Vec<u16>>> = Mutex::new(Vec::new());
|
||||
|
||||
fn others() -> std::sync::MutexGuard<'static, Vec<Vec<u16>>> {
|
||||
OTHERS.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
pub(in super::super) fn pads() -> Vec<(u64, PadState)> {
|
||||
static STARTED: LazyLock<()> = LazyLock::new(|| {
|
||||
let started = std::thread::Builder::new()
|
||||
.name("generic pad scan".into())
|
||||
.spawn(|| {
|
||||
loop {
|
||||
scan();
|
||||
std::thread::sleep(SCAN);
|
||||
}
|
||||
});
|
||||
if let Err(error) = started {
|
||||
tracing::warn!(%error, "no generic pads: the thread looking for them could not start");
|
||||
}
|
||||
});
|
||||
LazyLock::force(&STARTED);
|
||||
lock()
|
||||
.iter()
|
||||
.filter_map(|pad| Some((pad.id, pad.state?)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
struct Handle(HANDLE);
|
||||
|
||||
unsafe impl Send for Handle {}
|
||||
|
||||
impl Drop for Handle {
|
||||
fn drop(&mut self) {
|
||||
|
||||
unsafe { CloseHandle(self.0) };
|
||||
}
|
||||
}
|
||||
|
||||
impl Handle {
|
||||
|
||||
fn open(path: &[u16], access: u32) -> Option<Handle> {
|
||||
let mut name = path.to_vec();
|
||||
name.push(0);
|
||||
|
||||
let handle = unsafe {
|
||||
CreateFileW(
|
||||
name.as_ptr(),
|
||||
access,
|
||||
FILE_SHARE_READ | FILE_SHARE_WRITE,
|
||||
std::ptr::null(),
|
||||
OPEN_EXISTING,
|
||||
0,
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
(handle != INVALID_HANDLE_VALUE).then_some(Handle(handle))
|
||||
}
|
||||
}
|
||||
|
||||
struct Parser(PHIDP_PREPARSED_DATA);
|
||||
|
||||
unsafe impl Send for Parser {}
|
||||
|
||||
impl Drop for Parser {
|
||||
fn drop(&mut self) {
|
||||
|
||||
unsafe { HidD_FreePreparsedData(self.0) };
|
||||
}
|
||||
}
|
||||
|
||||
impl Parser {
|
||||
fn of(handle: &Handle) -> Option<Parser> {
|
||||
let mut data = 0;
|
||||
|
||||
unsafe { HidD_GetPreparsedData(handle.0, &mut data) }.then_some(Parser(data))
|
||||
}
|
||||
|
||||
fn value(&self, usage: u16, report: &[u8]) -> Option<u32> {
|
||||
let mut value = 0;
|
||||
|
||||
let status = unsafe {
|
||||
HidP_GetUsageValue(
|
||||
HidP_Input,
|
||||
GENERIC_DESKTOP,
|
||||
0,
|
||||
usage,
|
||||
&mut value,
|
||||
self.0,
|
||||
report.as_ptr(),
|
||||
report.len() as u32,
|
||||
)
|
||||
};
|
||||
(status == HIDP_STATUS_SUCCESS).then_some(value)
|
||||
}
|
||||
|
||||
fn usages(&self, page: u16, report: &mut [u8], list: &mut [u16]) -> Option<Vec<u16>> {
|
||||
if list.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut count = list.len() as u32;
|
||||
|
||||
let status = unsafe {
|
||||
HidP_GetUsages(
|
||||
HidP_Input,
|
||||
page,
|
||||
0,
|
||||
list.as_mut_ptr(),
|
||||
&mut count,
|
||||
self.0,
|
||||
report.as_mut_ptr(),
|
||||
report.len() as u32,
|
||||
)
|
||||
};
|
||||
(status == HIDP_STATUS_SUCCESS).then(|| {
|
||||
let mut held = list[..count as usize].to_vec();
|
||||
held.sort_unstable();
|
||||
held
|
||||
})
|
||||
}
|
||||
|
||||
fn buttons(&self, page: u16) -> usize {
|
||||
|
||||
unsafe { HidP_MaxUsageListLength(HidP_Input, page, self.0) as usize }
|
||||
}
|
||||
|
||||
fn shape(&self, caps: &HIDP_CAPS) -> Shape {
|
||||
let mut count = caps.NumberInputValueCaps;
|
||||
let mut values = vec![HIDP_VALUE_CAPS::default(); usize::from(count)];
|
||||
|
||||
let status =
|
||||
unsafe { HidP_GetValueCaps(HidP_Input, values.as_mut_ptr(), &mut count, self.0) };
|
||||
let mut shape = Shape::default();
|
||||
if status != HIDP_STATUS_SUCCESS {
|
||||
return shape;
|
||||
}
|
||||
values.truncate(usize::from(count));
|
||||
for cap in values.iter().filter(|cap| cap.UsagePage == GENERIC_DESKTOP) {
|
||||
|
||||
let (first, last) = unsafe {
|
||||
if cap.IsRange {
|
||||
(cap.Anonymous.Range.UsageMin, cap.Anonymous.Range.UsageMax)
|
||||
} else {
|
||||
(cap.Anonymous.NotRange.Usage, cap.Anonymous.NotRange.Usage)
|
||||
}
|
||||
};
|
||||
let Some(range) = Range::new(cap.LogicalMin, cap.LogicalMax, cap.BitSize) else {
|
||||
continue;
|
||||
};
|
||||
for usage in first..=last {
|
||||
let slot = match usage {
|
||||
USAGE_HAT => &mut shape.hat,
|
||||
_ if (USAGE_X..USAGE_X + AXES as u16).contains(&usage) => {
|
||||
&mut shape.axes[usize::from(usage - USAGE_X)]
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
|
||||
slot.get_or_insert(range);
|
||||
}
|
||||
}
|
||||
shape
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
enum Found {
|
||||
|
||||
Other,
|
||||
|
||||
Unknown,
|
||||
Pad {
|
||||
handle: Handle,
|
||||
parser: Parser,
|
||||
name: String,
|
||||
vendor: u16,
|
||||
product: u16,
|
||||
input: usize,
|
||||
shape: Shape,
|
||||
},
|
||||
}
|
||||
|
||||
fn look(path: &[u16]) -> Found {
|
||||
|
||||
let Some(query) = Handle::open(path, 0) else {
|
||||
return Found::Unknown;
|
||||
};
|
||||
let mut attributes = HIDD_ATTRIBUTES {
|
||||
Size: size_of::<HIDD_ATTRIBUTES>() as u32,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
if !unsafe { HidD_GetAttributes(query.0, &mut attributes) } {
|
||||
return Found::Unknown;
|
||||
}
|
||||
let (vendor, product) = (attributes.VendorID, attributes.ProductID);
|
||||
|
||||
if Sony::of(vendor, product).is_some() {
|
||||
return Found::Other;
|
||||
}
|
||||
let Some(parser) = Parser::of(&query) else {
|
||||
return Found::Unknown;
|
||||
};
|
||||
let mut caps = HIDP_CAPS::default();
|
||||
|
||||
if unsafe { HidP_GetCaps(parser.0, &mut caps) } != HIDP_STATUS_SUCCESS {
|
||||
return Found::Unknown;
|
||||
}
|
||||
if caps.UsagePage != GENERIC_DESKTOP
|
||||
|| !PAD_USAGES.contains(&caps.Usage)
|
||||
|| caps.InputReportByteLength == 0
|
||||
{
|
||||
return Found::Other;
|
||||
}
|
||||
let mut name = [0u16; 128];
|
||||
|
||||
let named = unsafe {
|
||||
HidD_GetProductString(query.0, name.as_mut_ptr().cast(), size_of_val(&name) as u32)
|
||||
};
|
||||
let end = name.iter().position(|&c| c == 0).unwrap_or(name.len());
|
||||
let name = if named {
|
||||
String::from_utf16_lossy(&name[..end])
|
||||
.split_whitespace()
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let shape = parser.shape(&caps);
|
||||
let Some(handle) = Handle::open(path, GENERIC_READ) else {
|
||||
return Found::Unknown;
|
||||
};
|
||||
Found::Pad {
|
||||
handle,
|
||||
parser,
|
||||
name,
|
||||
vendor,
|
||||
product,
|
||||
input: usize::from(caps.InputReportByteLength),
|
||||
shape,
|
||||
}
|
||||
}
|
||||
|
||||
fn scan() {
|
||||
let paths = hid_paths();
|
||||
others().retain(|path| paths.contains(path));
|
||||
|
||||
if paths.is_empty() {
|
||||
return;
|
||||
}
|
||||
lock().retain(|pad| {
|
||||
let present = paths.contains(&pad.path);
|
||||
if !present {
|
||||
tracing::info!(name = %pad.name, "generic pad gone");
|
||||
}
|
||||
present
|
||||
});
|
||||
for path in paths {
|
||||
|
||||
let lower = String::from_utf16_lossy(&path).to_ascii_lowercase();
|
||||
if lower.contains("ig_")
|
||||
|| lock().iter().any(|pad| pad.path == path)
|
||||
|| others().contains(&path)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let (handle, parser, name, vendor, product, input, shape) = match look(&path) {
|
||||
Found::Other => {
|
||||
others().push(path);
|
||||
continue;
|
||||
}
|
||||
Found::Unknown => continue,
|
||||
Found::Pad {
|
||||
handle,
|
||||
parser,
|
||||
name,
|
||||
vendor,
|
||||
product,
|
||||
input,
|
||||
shape,
|
||||
} => (handle, parser, name, vendor, product, input, shape),
|
||||
};
|
||||
let layout = layout(vendor);
|
||||
static NEXT_ID: AtomicU64 = AtomicU64::new(0);
|
||||
let id = ID | NEXT_ID.fetch_add(1, Ordering::Relaxed);
|
||||
let buttons = parser.buttons(BUTTON_PAGE);
|
||||
tracing::info!(
|
||||
path = %lower,
|
||||
name = %name,
|
||||
id = %format!("{vendor:04X}:{product:04X}"),
|
||||
values = %shape.describe(),
|
||||
buttons,
|
||||
layout = %layout.text(),
|
||||
"generic pad connected (EONACAT_XS_PAD_BUTTONS sets another layout; `eonacat-xsbox pads` shows its buttons)"
|
||||
);
|
||||
lock().push(Pad {
|
||||
id,
|
||||
path: path.clone(),
|
||||
name: format!("{name} ({vendor:04X}:{product:04X})"),
|
||||
shape,
|
||||
buttons,
|
||||
layout,
|
||||
raw: Raw::default(),
|
||||
state: None,
|
||||
});
|
||||
let reader = Reader {
|
||||
id,
|
||||
handle,
|
||||
parser,
|
||||
input,
|
||||
shape,
|
||||
layout,
|
||||
};
|
||||
if let Err(error) = std::thread::Builder::new()
|
||||
.name("generic pad reader".into())
|
||||
.spawn(move || reader.run())
|
||||
{
|
||||
lock().retain(|pad| pad.id != id);
|
||||
tracing::warn!(%error, "could not start a generic pad reader");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Reader {
|
||||
id: u64,
|
||||
handle: Handle,
|
||||
parser: Parser,
|
||||
input: usize,
|
||||
shape: Shape,
|
||||
layout: Layout,
|
||||
}
|
||||
|
||||
impl Reader {
|
||||
|
||||
fn run(self) {
|
||||
let mut report = vec![0u8; self.input];
|
||||
let mut buttons = vec![0u16; self.parser.buttons(BUTTON_PAGE)];
|
||||
let mut desktop = vec![0u16; self.parser.buttons(GENERIC_DESKTOP)];
|
||||
let mut raw = Raw::default();
|
||||
|
||||
let (mut seen, mut off) = ([false; AXES], [false; AXES]);
|
||||
let why = loop {
|
||||
let mut got = 0;
|
||||
|
||||
let read = unsafe {
|
||||
ReadFile(
|
||||
self.handle.0,
|
||||
report.as_mut_ptr(),
|
||||
report.len() as u32,
|
||||
&mut got,
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if read == 0 {
|
||||
break "read failed";
|
||||
}
|
||||
if got == 0 {
|
||||
break "read nothing";
|
||||
}
|
||||
|
||||
let got = (got as usize).min(report.len());
|
||||
report[got..].fill(0);
|
||||
let report = report.as_mut_slice();
|
||||
for (i, range) in self.shape.axes.iter().enumerate() {
|
||||
if let Some(range) = range
|
||||
&& let Some(value) = self.parser.value(USAGE_X + i as u16, report)
|
||||
{
|
||||
let value = range.value(value);
|
||||
raw.axes[i] = Some(value);
|
||||
if !seen[i] {
|
||||
seen[i] = true;
|
||||
off[i] = off_centre(&self.shape, i, value);
|
||||
if off[i] {
|
||||
tracing::warn!(
|
||||
axis = AXIS_NAMES[i],
|
||||
"generic pad: an axis that should rest at its centre does not \
|
||||
(a throttle or a pedal?); it is not read until the pad reconnects"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(range) = self.shape.hat
|
||||
&& let Some(value) = self.parser.value(USAGE_HAT, report)
|
||||
{
|
||||
raw.hat = Some(range.value(value));
|
||||
}
|
||||
if let Some(held) = self.parser.usages(BUTTON_PAGE, report, &mut buttons) {
|
||||
raw.buttons = held;
|
||||
}
|
||||
if let Some(held) = self.parser.usages(GENERIC_DESKTOP, report, &mut desktop) {
|
||||
raw.desktop = held;
|
||||
}
|
||||
let mut read = raw.clone();
|
||||
for (value, off) in read.axes.iter_mut().zip(off) {
|
||||
if off {
|
||||
*value = None;
|
||||
}
|
||||
}
|
||||
let state = state(&self.shape, &read, &self.layout);
|
||||
let mut pads = lock();
|
||||
let Some(pad) = pads.iter_mut().find(|pad| pad.id == self.id) else {
|
||||
break "forgotten";
|
||||
};
|
||||
pad.state = Some(state);
|
||||
if pad.raw != raw {
|
||||
pad.raw = raw.clone();
|
||||
}
|
||||
};
|
||||
let name = lock()
|
||||
.iter()
|
||||
.find(|pad| pad.id == self.id)
|
||||
.map(|pad| pad.name.clone())
|
||||
.unwrap_or_default();
|
||||
tracing::info!(why, name = %name, "generic pad disconnected");
|
||||
lock().retain(|pad| pad.id != self.id);
|
||||
}
|
||||
}
|
||||
|
||||
pub(in super::super) fn monitor(seconds: u64) {
|
||||
let found = Instant::now();
|
||||
pads();
|
||||
while lock().is_empty() && found.elapsed() < Duration::from_secs(3) {
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
{
|
||||
let pads = lock();
|
||||
if pads.is_empty() {
|
||||
println!("Generic HID pads: none found.");
|
||||
return;
|
||||
}
|
||||
println!("Generic HID pads:");
|
||||
for (n, pad) in pads.iter().enumerate() {
|
||||
println!(
|
||||
" pad {}: {}, {}, {} buttons, EONACAT_XS_PAD_BUTTONS={}",
|
||||
n + 1,
|
||||
pad.name,
|
||||
pad.shape.describe(),
|
||||
pad.buttons,
|
||||
pad.layout.text()
|
||||
);
|
||||
}
|
||||
}
|
||||
println!(
|
||||
"\nPress each button and move each stick ({seconds} s; Ctrl+C ends).\n\
|
||||
EONACAT_XS_PAD_BUTTONS lists the button numbers for A,B,X,Y,LB,RB,LT,RT,View,Menu,LS,RS\n\
|
||||
(Xbox names, by position: A south, B east, X west, Y north).\n"
|
||||
);
|
||||
let end = Instant::now() + Duration::from_secs(seconds);
|
||||
let mut last: Vec<(u64, String)> = Vec::new();
|
||||
while Instant::now() < end {
|
||||
let now: Vec<(u64, String)> = lock()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(n, pad)| {
|
||||
let state = pad.state?;
|
||||
Some((
|
||||
pad.id,
|
||||
format!("pad {}: {}", n + 1, line(&pad.shape, &pad.raw, &state)),
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
for entry in &now {
|
||||
if !last.contains(entry) {
|
||||
println!("{}", entry.1);
|
||||
}
|
||||
}
|
||||
last = now;
|
||||
std::thread::sleep(Duration::from_millis(30));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
use eonacat_xsbox_gpu::SettingsPadMode;
|
||||
|
||||
use super::{A, B, DOWN, LEFT, LEFT_STICK, PadState, RIGHT, RIGHT_STICK, UP};
|
||||
|
||||
const STICKS: u32 = LEFT_STICK | RIGHT_STICK;
|
||||
const NAVIGATION: u32 = UP | DOWN | LEFT | RIGHT | A | B;
|
||||
const CHORD_WINDOW: Duration = Duration::from_millis(250);
|
||||
const TOGGLE: u16 = 0x78;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct MenuPad {
|
||||
previous: Option<u32>,
|
||||
chord_armed: bool,
|
||||
first_click: Option<Instant>,
|
||||
captured: u32,
|
||||
}
|
||||
|
||||
impl MenuPad {
|
||||
|
||||
pub(super) fn disconnected(&mut self, notify: impl FnOnce(Option<u16>)) {
|
||||
if self.previous.take().is_some() {
|
||||
notify(None);
|
||||
}
|
||||
self.captured = 0;
|
||||
}
|
||||
|
||||
fn shortcut(&mut self, sticks: u32, previous: u32, clock: impl FnOnce() -> Instant) -> bool {
|
||||
if sticks == 0 {
|
||||
self.chord_armed = true;
|
||||
self.first_click = None;
|
||||
} else if self.chord_armed && sticks != previous {
|
||||
if sticks != STICKS {
|
||||
self.first_click = Some(clock());
|
||||
} else {
|
||||
self.chord_armed = false;
|
||||
return self.first_click.is_none_or(|first| {
|
||||
clock().saturating_duration_since(first) <= CHORD_WINDOW
|
||||
});
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub(super) fn filter(
|
||||
&mut self,
|
||||
pad: &mut Option<PadState>,
|
||||
mode: SettingsPadMode,
|
||||
context: impl FnOnce() -> (bool, bool, bool),
|
||||
clock: impl FnOnce() -> Instant,
|
||||
notify: impl FnOnce(Option<u16>),
|
||||
) {
|
||||
if mode == SettingsPadMode::Off {
|
||||
return;
|
||||
}
|
||||
let Some(pad) = pad else {
|
||||
self.disconnected(notify);
|
||||
return;
|
||||
};
|
||||
let (focused, open, pending) = context();
|
||||
if !focused {
|
||||
self.disconnected(notify);
|
||||
return;
|
||||
}
|
||||
let buttons = pad.buttons;
|
||||
let sticks = buttons & STICKS;
|
||||
let Some(previous) = self.previous.replace(buttons) else {
|
||||
self.first_click = None;
|
||||
self.chord_armed = sticks == 0;
|
||||
return;
|
||||
};
|
||||
let pressed = buttons & !previous & NAVIGATION;
|
||||
self.captured &= buttons;
|
||||
if mode == SettingsPadMode::StickShortcut && self.shortcut(sticks, previous & STICKS, clock) {
|
||||
notify(Some(TOGGLE));
|
||||
} else if open && !pending && pressed != 0 {
|
||||
self.captured |= pressed;
|
||||
|
||||
let key = match buttons & NAVIGATION {
|
||||
UP => Some(0x26),
|
||||
DOWN => Some(0x28),
|
||||
LEFT => Some(0x25),
|
||||
RIGHT => Some(0x27),
|
||||
A => Some(0x0d),
|
||||
B => Some(0x1b),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(key) = key {
|
||||
notify(Some(key));
|
||||
}
|
||||
}
|
||||
pad.buttons &= !self.captured;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,751 @@
|
||||
|
||||
|
||||
use super::{
|
||||
A, B, DOWN, LEFT, LEFT_SHOULDER, LEFT_STICK, MENU, PadState, RIGHT, RIGHT_SHOULDER,
|
||||
RIGHT_STICK, UP, VIEW, X, Y,
|
||||
};
|
||||
|
||||
const SONY: u16 = 0x054C;
|
||||
|
||||
const DONGLE: u16 = 0x0BA0;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum Sony {
|
||||
DualShock4,
|
||||
DualSense,
|
||||
}
|
||||
|
||||
impl Sony {
|
||||
|
||||
pub(super) fn of(vendor: u16, product: u16) -> Option<Sony> {
|
||||
match (vendor, product) {
|
||||
|
||||
(SONY, 0x05C4 | 0x09CC | DONGLE) => Some(Sony::DualShock4),
|
||||
|
||||
(SONY, 0x0CE6 | 0x0DF2) => Some(Sony::DualSense),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn full_reports_feature(self) -> u8 {
|
||||
match self {
|
||||
Sony::DualShock4 => 0x02,
|
||||
Sony::DualSense => 0x05,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn pairing_feature(self) -> u8 {
|
||||
match self {
|
||||
Sony::DualShock4 => 0x12,
|
||||
Sony::DualSense => 0x09,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Sony::DualShock4 => "DualShock 4",
|
||||
Sony::DualSense => "DualSense",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn hat(value: u8) -> u32 {
|
||||
match value & 0xF {
|
||||
0 => UP,
|
||||
1 => UP | RIGHT,
|
||||
2 => RIGHT,
|
||||
3 => RIGHT | DOWN,
|
||||
4 => DOWN,
|
||||
5 => DOWN | LEFT,
|
||||
6 => LEFT,
|
||||
7 => LEFT | UP,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
const BUTTONS: [(usize, u8, u32); 11] = [
|
||||
(0, 0x10, X),
|
||||
(0, 0x20, A),
|
||||
(0, 0x40, B),
|
||||
(0, 0x80, Y),
|
||||
(1, 0x01, LEFT_SHOULDER),
|
||||
(1, 0x02, RIGHT_SHOULDER),
|
||||
(1, 0x10, VIEW),
|
||||
(1, 0x20, MENU),
|
||||
(1, 0x40, LEFT_STICK),
|
||||
(1, 0x80, RIGHT_STICK),
|
||||
(2, 0x02, VIEW),
|
||||
];
|
||||
|
||||
pub(super) fn parse(pad: Sony, report: &[u8], bluetooth: bool) -> Option<PadState> {
|
||||
|
||||
let (sticks, triggers, buttons) = match (pad, report.first()?, bluetooth) {
|
||||
(Sony::DualSense, 0x01, false) => (1, 5, 8),
|
||||
(Sony::DualSense, 0x31, true) => (2, 6, 9),
|
||||
(Sony::DualSense, 0x01, true) => (1, 8, 5),
|
||||
(Sony::DualShock4, 0x01, _) => (1, 8, 5),
|
||||
(Sony::DualShock4, 0x11, _) => (3, 10, 7),
|
||||
_ => return None,
|
||||
};
|
||||
if report.len() < sticks + 4 || report.len() < triggers + 2 || report.len() < buttons + 3 {
|
||||
return None;
|
||||
}
|
||||
let bytes = &report[buttons..buttons + 3];
|
||||
|
||||
let axis = |v: u8| ((f32::from(v) - 127.5) / 127.5).clamp(-1.0, 1.0);
|
||||
Some(PadState {
|
||||
buttons: BUTTONS
|
||||
.iter()
|
||||
.filter(|&&(byte, mask, _)| bytes[byte] & mask != 0)
|
||||
.fold(hat(bytes[0]), |all, &(_, _, bit)| all | bit),
|
||||
left_trigger: f32::from(report[triggers]) / 255.0,
|
||||
right_trigger: f32::from(report[triggers + 1]) / 255.0,
|
||||
left_x: axis(report[sticks]),
|
||||
left_y: -axis(report[sticks + 1]),
|
||||
right_x: axis(report[sticks + 2]),
|
||||
right_y: -axis(report[sticks + 3]),
|
||||
})
|
||||
}
|
||||
|
||||
fn mac(pairing: &[u8]) -> Option<[u8; 6]> {
|
||||
let mac: [u8; 6] = pairing.get(1..7)?.try_into().ok()?;
|
||||
(mac != [0; 6]).then_some(mac)
|
||||
}
|
||||
|
||||
fn serial_mac(serial: &str) -> Option<[u8; 6]> {
|
||||
let digits: Vec<u8> = serial
|
||||
.bytes()
|
||||
.filter(|c| !matches!(c, b':' | b'-'))
|
||||
.map(|c| char::from(c).to_digit(16).map(|d| d as u8))
|
||||
.collect::<Option<_>>()?;
|
||||
if digits.len() != 12 {
|
||||
return None;
|
||||
}
|
||||
let mut mac = [0u8; 6];
|
||||
|
||||
for (byte, pair) in mac.iter_mut().rev().zip(digits.chunks(2)) {
|
||||
*byte = pair[0] << 4 | pair[1];
|
||||
}
|
||||
(mac != [0; 6]).then_some(mac)
|
||||
}
|
||||
|
||||
fn dongle_empty(report: &[u8]) -> bool {
|
||||
report.len() >= 64 && report[0] == 0x01 && report[31] & 0x04 != 0
|
||||
}
|
||||
|
||||
fn crc32(parts: &[&[u8]]) -> u32 {
|
||||
let mut crc = !0u32;
|
||||
for byte in parts.iter().flat_map(|p| p.iter()) {
|
||||
crc ^= u32::from(*byte);
|
||||
for _ in 0..8 {
|
||||
crc = (crc >> 1) ^ (0xEDB8_8320 & (crc & 1).wrapping_neg());
|
||||
}
|
||||
}
|
||||
!crc
|
||||
}
|
||||
|
||||
pub(super) fn rumble_report(
|
||||
pad: Sony,
|
||||
bluetooth: bool,
|
||||
length: usize,
|
||||
low: u16,
|
||||
high: u16,
|
||||
) -> Vec<u8> {
|
||||
let (low, high) = ((low >> 8) as u8, (high >> 8) as u8);
|
||||
let mut r = vec![0u8; if bluetooth { 78 } else { length.max(32) }];
|
||||
|
||||
let common = match (pad, bluetooth) {
|
||||
(Sony::DualSense, false) => {
|
||||
r[0] = 0x02;
|
||||
1
|
||||
}
|
||||
(Sony::DualSense, true) => {
|
||||
r[0] = 0x31;
|
||||
r[1] = 0x00;
|
||||
r[2] = 0x10;
|
||||
3
|
||||
}
|
||||
(Sony::DualShock4, false) => {
|
||||
r[0] = 0x05;
|
||||
1
|
||||
}
|
||||
(Sony::DualShock4, true) => {
|
||||
r[0] = 0x11;
|
||||
r[1] = 0xC0;
|
||||
3
|
||||
}
|
||||
};
|
||||
|
||||
r[common] = match pad {
|
||||
Sony::DualSense => 0x03,
|
||||
Sony::DualShock4 => 0x01,
|
||||
};
|
||||
let motors = match pad {
|
||||
Sony::DualSense => common + 2,
|
||||
Sony::DualShock4 => common + 3,
|
||||
};
|
||||
r[motors] = high;
|
||||
r[motors + 1] = low;
|
||||
if bluetooth {
|
||||
let crc = crc32(&[&[0xA2], &r[..74]]);
|
||||
r[74..].copy_from_slice(&crc.to_le_bytes());
|
||||
r.resize(length.max(78), 0);
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(super) use host::{hid_paths, pads, rumble, stop_rumble};
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum Mode {
|
||||
Off,
|
||||
Auto,
|
||||
Both,
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(super) fn mode() -> Mode {
|
||||
static MODE: std::sync::LazyLock<Mode> =
|
||||
std::sync::LazyLock::new(|| match std::env::var("EONACAT_XS_DUALSENSE").as_deref() {
|
||||
Ok("0") => Mode::Off,
|
||||
Ok("1") => Mode::Both,
|
||||
_ => Mode::Auto,
|
||||
});
|
||||
*MODE
|
||||
}
|
||||
|
||||
pub(super) fn slots(
|
||||
mode: Mode,
|
||||
mut xinput: [Option<PadState>; super::PADS],
|
||||
assigned: &mut [Option<u64>; super::PADS],
|
||||
hid: impl FnOnce() -> Vec<(u64, PadState)>,
|
||||
) -> [Option<PadState>; super::PADS] {
|
||||
if mode == Mode::Off || mode == Mode::Auto && xinput.iter().any(Option::is_some) {
|
||||
assigned.fill(None);
|
||||
return xinput;
|
||||
}
|
||||
let pads = hid();
|
||||
for (slot, owner) in xinput.iter_mut().zip(assigned.iter_mut()) {
|
||||
if slot.is_none()
|
||||
&& let Some((_, state)) = pads.iter().find(|(id, _)| Some(*id) == *owner)
|
||||
{
|
||||
*slot = Some(*state);
|
||||
} else {
|
||||
*owner = None;
|
||||
}
|
||||
}
|
||||
for (id, state) in pads {
|
||||
if assigned.contains(&Some(id)) {
|
||||
continue;
|
||||
}
|
||||
let Some(slot) = xinput.iter().position(Option::is_none) else {
|
||||
break;
|
||||
};
|
||||
xinput[slot] = Some(state);
|
||||
assigned[slot] = Some(id);
|
||||
}
|
||||
xinput
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod host {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{LazyLock, Mutex, PoisonError};
|
||||
use std::time::Duration;
|
||||
|
||||
use windows_sys::Win32::Devices::DeviceAndDriverInstallation::{
|
||||
DIGCF_DEVICEINTERFACE, DIGCF_PRESENT, SP_DEVICE_INTERFACE_DATA,
|
||||
SP_DEVICE_INTERFACE_DETAIL_DATA_W, SetupDiDestroyDeviceInfoList,
|
||||
SetupDiEnumDeviceInterfaces, SetupDiGetClassDevsW, SetupDiGetDeviceInterfaceDetailW,
|
||||
};
|
||||
use windows_sys::Win32::Devices::HumanInterfaceDevice::{
|
||||
HIDD_ATTRIBUTES, HIDP_CAPS, HIDP_STATUS_SUCCESS, HidD_FreePreparsedData,
|
||||
HidD_GetAttributes, HidD_GetFeature, HidD_GetHidGuid, HidD_GetPreparsedData,
|
||||
HidD_GetSerialNumberString, HidP_GetCaps,
|
||||
};
|
||||
use windows_sys::Win32::Foundation::{
|
||||
CloseHandle, ERROR_IO_PENDING, GENERIC_READ, GENERIC_WRITE, GetLastError, HANDLE,
|
||||
INVALID_HANDLE_VALUE, WAIT_TIMEOUT,
|
||||
};
|
||||
use windows_sys::Win32::Storage::FileSystem::{
|
||||
CreateFileW, FILE_FLAG_OVERLAPPED, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING,
|
||||
ReadFile, WriteFile,
|
||||
};
|
||||
use windows_sys::Win32::System::IO::{
|
||||
CancelIoEx, GetOverlappedResult, GetOverlappedResultEx, OVERLAPPED,
|
||||
};
|
||||
use windows_sys::Win32::System::Threading::CreateEventW;
|
||||
|
||||
use super::{
|
||||
DONGLE, PadState, SONY, Sony, dongle_empty, mac, parse, rumble_report, serial_mac,
|
||||
};
|
||||
|
||||
const SCAN: Duration = Duration::from_secs(2);
|
||||
|
||||
const QUIET_MS: u32 = 500;
|
||||
|
||||
const WRITE_MS: u32 = 100;
|
||||
|
||||
struct Pad {
|
||||
|
||||
id: u64,
|
||||
path: Vec<u16>,
|
||||
|
||||
mac: Option<[u8; 6]>,
|
||||
|
||||
state: Option<PadState>,
|
||||
|
||||
rumble: (u16, u16),
|
||||
}
|
||||
|
||||
static PADS: Mutex<Vec<Pad>> = Mutex::new(Vec::new());
|
||||
|
||||
fn lock() -> std::sync::MutexGuard<'static, Vec<Pad>> {
|
||||
PADS.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
static TWINS: Mutex<Vec<(Vec<u16>, [u8; 6])>> = Mutex::new(Vec::new());
|
||||
|
||||
pub(in super::super) fn pads() -> Vec<(u64, PadState)> {
|
||||
static STARTED: LazyLock<()> = LazyLock::new(|| {
|
||||
std::thread::spawn(|| {
|
||||
loop {
|
||||
scan();
|
||||
std::thread::sleep(SCAN);
|
||||
}
|
||||
});
|
||||
});
|
||||
LazyLock::force(&STARTED);
|
||||
lock()
|
||||
.iter()
|
||||
.filter_map(|pad| Some((pad.id, pad.state?)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(in super::super) fn rumble(id: u64, low: u16, high: u16) {
|
||||
if let Some(pad) = lock().iter_mut().find(|pad| pad.id == id) {
|
||||
pad.rumble = (low, high);
|
||||
}
|
||||
}
|
||||
|
||||
pub(in super::super) fn stop_rumble() -> bool {
|
||||
let mut pads = lock();
|
||||
let any = pads.iter().any(|pad| pad.rumble != (0, 0));
|
||||
for pad in pads.iter_mut() {
|
||||
pad.rumble = (0, 0);
|
||||
}
|
||||
any
|
||||
}
|
||||
|
||||
struct Reports {
|
||||
input: Vec<u8>,
|
||||
feature: Vec<u8>,
|
||||
output: usize,
|
||||
}
|
||||
|
||||
impl Reports {
|
||||
fn for_device(handle: HANDLE) -> Option<Self> {
|
||||
let mut data = 0;
|
||||
|
||||
if !unsafe { HidD_GetPreparsedData(handle, &mut data) } {
|
||||
return None;
|
||||
}
|
||||
let mut caps = HIDP_CAPS::default();
|
||||
|
||||
let status = unsafe { HidP_GetCaps(data, &mut caps) };
|
||||
unsafe { HidD_FreePreparsedData(data) };
|
||||
if status != HIDP_STATUS_SUCCESS
|
||||
|| caps.InputReportByteLength == 0
|
||||
|| caps.FeatureReportByteLength == 0
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(Self {
|
||||
input: vec![0; usize::from(caps.InputReportByteLength)],
|
||||
feature: vec![0; usize::from(caps.FeatureReportByteLength)],
|
||||
output: usize::from(caps.OutputReportByteLength),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn feature(handle: HANDLE, id: u8, buffer: &mut [u8]) -> bool {
|
||||
buffer.fill(0);
|
||||
buffer[0] = id;
|
||||
|
||||
unsafe { HidD_GetFeature(handle, buffer.as_mut_ptr().cast(), buffer.len() as u32) }
|
||||
}
|
||||
|
||||
fn full_reports(handle: HANDLE, pad: Sony, buffer: &mut [u8]) -> bool {
|
||||
feature(handle, pad.full_reports_feature(), buffer)
|
||||
}
|
||||
|
||||
fn address(handle: HANDLE, pad: Sony, bluetooth: bool, buffer: &mut [u8]) -> Option<[u8; 6]> {
|
||||
if pad == Sony::DualShock4 && bluetooth {
|
||||
let mut serial = [0u16; 128];
|
||||
|
||||
let ok = unsafe {
|
||||
HidD_GetSerialNumberString(
|
||||
handle,
|
||||
serial.as_mut_ptr().cast(),
|
||||
size_of_val(&serial) as u32,
|
||||
)
|
||||
};
|
||||
let end = serial.iter().position(|&c| c == 0).unwrap_or(serial.len());
|
||||
return ok
|
||||
.then(|| serial_mac(&String::from_utf16_lossy(&serial[..end])))
|
||||
.flatten();
|
||||
}
|
||||
feature(handle, pad.pairing_feature(), buffer)
|
||||
.then(|| mac(buffer))
|
||||
.flatten()
|
||||
}
|
||||
|
||||
fn write(handle: HANDLE, event: HANDLE, report: &[u8]) -> bool {
|
||||
|
||||
let mut overlapped: OVERLAPPED = unsafe { std::mem::zeroed() };
|
||||
overlapped.hEvent = event;
|
||||
let mut put = 0;
|
||||
|
||||
let started = unsafe {
|
||||
WriteFile(
|
||||
handle,
|
||||
report.as_ptr(),
|
||||
report.len() as u32,
|
||||
std::ptr::null_mut(),
|
||||
&mut overlapped,
|
||||
)
|
||||
};
|
||||
|
||||
if started == 0 && unsafe { GetLastError() } != ERROR_IO_PENDING {
|
||||
return false;
|
||||
}
|
||||
|
||||
if unsafe { GetOverlappedResultEx(handle, &overlapped, &mut put, WRITE_MS, 0) } != 0 {
|
||||
return true;
|
||||
}
|
||||
|
||||
unsafe {
|
||||
CancelIoEx(handle, &overlapped);
|
||||
GetOverlappedResult(handle, &overlapped, &mut put, 1);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn scan() {
|
||||
let paths = hid_paths();
|
||||
{
|
||||
let pads = lock();
|
||||
|
||||
TWINS
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.retain(|(path, mac)| {
|
||||
paths.contains(path) && pads.iter().any(|pad| pad.mac == Some(*mac))
|
||||
});
|
||||
}
|
||||
for path in paths {
|
||||
|
||||
let lower = String::from_utf16_lossy(&path).to_ascii_lowercase();
|
||||
if !lower.contains("054c") {
|
||||
continue;
|
||||
}
|
||||
if lock().iter().any(|pad| pad.path == path)
|
||||
|| TWINS
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.iter()
|
||||
.any(|(twin, _)| *twin == path)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Some((handle, mut reports, pad, dongle)) = open(&path) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let bluetooth = lower.contains("{00001124-") || reports.input.len() > 64;
|
||||
let link = Link {
|
||||
pad,
|
||||
dongle,
|
||||
bluetooth,
|
||||
};
|
||||
let name = pad.name();
|
||||
|
||||
if !full_reports(handle, pad, &mut reports.feature) {
|
||||
tracing::debug!(path = %lower, pad = name, "PlayStation pad listed but not answering");
|
||||
|
||||
unsafe { CloseHandle(handle) };
|
||||
continue;
|
||||
}
|
||||
let mac = address(handle, pad, bluetooth, &mut reports.feature);
|
||||
static NEXT_ID: AtomicU64 = AtomicU64::new(0);
|
||||
let id = {
|
||||
let mut pads = lock();
|
||||
let twin = mac.is_some() && pads.iter().any(|pad| pad.mac == mac);
|
||||
(!twin).then(|| {
|
||||
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
|
||||
pads.push(Pad {
|
||||
id,
|
||||
path: path.clone(),
|
||||
mac,
|
||||
state: None,
|
||||
rumble: (0, 0),
|
||||
});
|
||||
id
|
||||
})
|
||||
};
|
||||
let Some(id) = id else {
|
||||
tracing::info!(path = %lower, pad = name, bluetooth, "PlayStation pad already open over the other transport");
|
||||
if let Some(mac) = mac {
|
||||
TWINS
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.push((path, mac));
|
||||
}
|
||||
|
||||
unsafe { CloseHandle(handle) };
|
||||
continue;
|
||||
};
|
||||
tracing::info!(path = %lower, pad = name, bluetooth, "PlayStation pad connected");
|
||||
let raw = handle as usize;
|
||||
if let Err(error) = std::thread::Builder::new()
|
||||
.name("PlayStation pad reader".into())
|
||||
.spawn(move || read(raw as HANDLE, id, link, reports))
|
||||
{
|
||||
lock().retain(|pad| pad.id != id);
|
||||
|
||||
unsafe { CloseHandle(handle) };
|
||||
tracing::warn!(%error, "could not start a PlayStation pad reader");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Link {
|
||||
pad: Sony,
|
||||
|
||||
dongle: bool,
|
||||
bluetooth: bool,
|
||||
}
|
||||
|
||||
fn read(handle: HANDLE, id: u64, link: Link, mut reports: Reports) {
|
||||
let Link {
|
||||
pad: kind,
|
||||
dongle,
|
||||
bluetooth,
|
||||
} = link;
|
||||
|
||||
let set = |state: Option<PadState>| {
|
||||
lock().iter_mut().find(|pad| pad.id == id).map(|pad| {
|
||||
pad.state = state;
|
||||
pad.rumble
|
||||
})
|
||||
};
|
||||
|
||||
let (event, wrote) = unsafe {
|
||||
(
|
||||
CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()),
|
||||
CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()),
|
||||
)
|
||||
};
|
||||
|
||||
let (mut sent, mut wanted) = ((0, 0), (0, 0));
|
||||
let mut write_failed = false;
|
||||
let why = 'pad: loop {
|
||||
if event.is_null() {
|
||||
break 'pad "no event";
|
||||
}
|
||||
if wanted != sent && reports.output > 0 && !wrote.is_null() {
|
||||
sent = wanted;
|
||||
let report = rumble_report(kind, bluetooth, reports.output, wanted.0, wanted.1);
|
||||
if !write(handle, wrote, &report) && !write_failed {
|
||||
write_failed = true;
|
||||
tracing::info!(
|
||||
pad = kind.name(),
|
||||
bluetooth,
|
||||
"a PlayStation pad rumble report did not go out"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let mut overlapped: OVERLAPPED = unsafe { std::mem::zeroed() };
|
||||
overlapped.hEvent = event;
|
||||
let mut got = 0;
|
||||
|
||||
let started = unsafe {
|
||||
ReadFile(
|
||||
handle,
|
||||
reports.input.as_mut_ptr(),
|
||||
reports.input.len() as u32,
|
||||
std::ptr::null_mut(),
|
||||
&mut overlapped,
|
||||
)
|
||||
};
|
||||
|
||||
if started == 0 && unsafe { GetLastError() } != ERROR_IO_PENDING {
|
||||
break 'pad "read failed";
|
||||
}
|
||||
loop {
|
||||
|
||||
let done =
|
||||
unsafe { GetOverlappedResultEx(handle, &overlapped, &mut got, QUIET_MS, 0) };
|
||||
if done != 0 {
|
||||
if got == 0 {
|
||||
break 'pad "read nothing";
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
if unsafe { GetLastError() } != WAIT_TIMEOUT {
|
||||
break 'pad "read failed";
|
||||
}
|
||||
|
||||
set(None);
|
||||
if !full_reports(handle, kind, &mut reports.feature) {
|
||||
|
||||
unsafe {
|
||||
CancelIoEx(handle, &overlapped);
|
||||
GetOverlappedResult(handle, &overlapped, &mut got, 1);
|
||||
}
|
||||
break 'pad "not answering";
|
||||
}
|
||||
}
|
||||
let report = &reports.input[..got as usize];
|
||||
|
||||
let state = if dongle && dongle_empty(report) {
|
||||
Some(None)
|
||||
} else {
|
||||
parse(kind, report, bluetooth).map(Some)
|
||||
};
|
||||
if let Some(state) = state
|
||||
&& let Some(asked) = set(state)
|
||||
{
|
||||
wanted = asked;
|
||||
}
|
||||
};
|
||||
tracing::info!(
|
||||
why,
|
||||
pad = kind.name(),
|
||||
bluetooth,
|
||||
"PlayStation pad disconnected"
|
||||
);
|
||||
lock().retain(|pad| pad.id != id);
|
||||
|
||||
unsafe {
|
||||
for event in [event, wrote] {
|
||||
if !event.is_null() {
|
||||
CloseHandle(event);
|
||||
}
|
||||
}
|
||||
CloseHandle(handle);
|
||||
}
|
||||
}
|
||||
|
||||
fn open(path: &[u16]) -> Option<(HANDLE, Reports, Sony, bool)> {
|
||||
let mut name = path.to_vec();
|
||||
name.push(0);
|
||||
|
||||
let handle = unsafe {
|
||||
CreateFileW(
|
||||
name.as_ptr(),
|
||||
GENERIC_READ | GENERIC_WRITE,
|
||||
FILE_SHARE_READ | FILE_SHARE_WRITE,
|
||||
std::ptr::null(),
|
||||
OPEN_EXISTING,
|
||||
FILE_FLAG_OVERLAPPED,
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if handle == INVALID_HANDLE_VALUE {
|
||||
return None;
|
||||
}
|
||||
let mut attributes = HIDD_ATTRIBUTES {
|
||||
Size: size_of::<HIDD_ATTRIBUTES>() as u32,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let ours = unsafe { HidD_GetAttributes(handle, &mut attributes) }
|
||||
.then(|| Sony::of(attributes.VendorID, attributes.ProductID))
|
||||
.flatten();
|
||||
if let Some(pad) = ours
|
||||
&& let Some(reports) = Reports::for_device(handle)
|
||||
{
|
||||
let dongle = attributes.VendorID == SONY && attributes.ProductID == DONGLE;
|
||||
return Some((handle, reports, pad, dongle));
|
||||
}
|
||||
|
||||
unsafe { CloseHandle(handle) };
|
||||
None
|
||||
}
|
||||
|
||||
pub(in super::super) fn hid_paths() -> Vec<Vec<u16>> {
|
||||
let mut paths = Vec::new();
|
||||
|
||||
unsafe {
|
||||
let mut guid = std::mem::zeroed();
|
||||
HidD_GetHidGuid(&mut guid);
|
||||
let set = SetupDiGetClassDevsW(
|
||||
&guid,
|
||||
std::ptr::null(),
|
||||
std::ptr::null_mut(),
|
||||
DIGCF_PRESENT | DIGCF_DEVICEINTERFACE,
|
||||
);
|
||||
if set == INVALID_HANDLE_VALUE as isize {
|
||||
return paths;
|
||||
}
|
||||
for index in 0.. {
|
||||
let mut interface = SP_DEVICE_INTERFACE_DATA {
|
||||
cbSize: size_of::<SP_DEVICE_INTERFACE_DATA>() as u32,
|
||||
..std::mem::zeroed()
|
||||
};
|
||||
if SetupDiEnumDeviceInterfaces(set, std::ptr::null(), &guid, index, &mut interface)
|
||||
== 0
|
||||
{
|
||||
break;
|
||||
}
|
||||
let mut size = 0;
|
||||
SetupDiGetDeviceInterfaceDetailW(
|
||||
set,
|
||||
&interface,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
&mut size,
|
||||
std::ptr::null_mut(),
|
||||
);
|
||||
if size == 0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut buffer = vec![0u64; (size as usize).div_ceil(8)];
|
||||
let detail = buffer
|
||||
.as_mut_ptr()
|
||||
.cast::<SP_DEVICE_INTERFACE_DETAIL_DATA_W>();
|
||||
(*detail).cbSize = size_of::<SP_DEVICE_INTERFACE_DETAIL_DATA_W>() as u32;
|
||||
if SetupDiGetDeviceInterfaceDetailW(
|
||||
set,
|
||||
&interface,
|
||||
detail,
|
||||
size,
|
||||
std::ptr::null_mut(),
|
||||
std::ptr::null_mut(),
|
||||
) == 0
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let start = std::ptr::addr_of!((*detail).DevicePath).cast::<u16>();
|
||||
let room = (size as usize
|
||||
- std::mem::offset_of!(SP_DEVICE_INTERFACE_DETAIL_DATA_W, DevicePath))
|
||||
/ 2;
|
||||
let wide = std::slice::from_raw_parts(start, room);
|
||||
let end = wide.iter().position(|&c| c == 0).unwrap_or(room);
|
||||
paths.push(wide[..end].to_vec());
|
||||
}
|
||||
SetupDiDestroyDeviceInfoList(set);
|
||||
}
|
||||
paths
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,434 @@
|
||||
|
||||
|
||||
#![allow(non_snake_case)]
|
||||
|
||||
use std::sync::{Mutex, Once};
|
||||
use std::time::Duration;
|
||||
|
||||
use windows_sys::Win32::Devices::DeviceAndDriverInstallation::{
|
||||
DIGCF_DEVICEINTERFACE, DIGCF_PRESENT, HDEVINFO, SP_DEVICE_INTERFACE_DATA,
|
||||
SP_DEVICE_INTERFACE_DETAIL_DATA_W, SetupDiDestroyDeviceInfoList, SetupDiEnumDeviceInterfaces,
|
||||
SetupDiGetClassDevsW, SetupDiGetDeviceInterfaceDetailW,
|
||||
};
|
||||
use windows_sys::Win32::Devices::HumanInterfaceDevice::{
|
||||
GUID_DEVINTERFACE_HID, HID_USAGE_GENERIC_HATSWITCH, HID_USAGE_GENERIC_RX, HID_USAGE_GENERIC_RY,
|
||||
HID_USAGE_GENERIC_RZ, HID_USAGE_GENERIC_X, HID_USAGE_GENERIC_Y, HID_USAGE_GENERIC_Z,
|
||||
HID_USAGE_PAGE_BUTTON, HID_USAGE_PAGE_GENERIC, HIDD_ATTRIBUTES, HIDP_CAPS, HIDP_STATUS_SUCCESS,
|
||||
HidD_FreePreparsedData, HidD_GetAttributes, HidD_GetPreparsedData, HidD_GetProductString,
|
||||
HidP_GetCaps, HidP_GetUsageValue, HidP_GetUsages, HidP_Input,
|
||||
};
|
||||
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE};
|
||||
use windows_sys::Win32::Storage::FileSystem::{
|
||||
CreateFileW, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING, ReadFile,
|
||||
};
|
||||
|
||||
use super::{
|
||||
A, B, DOWN, LEFT, LEFT_SHOULDER, LEFT_STICK, MENU, PadState, RIGHT, RIGHT_SHOULDER,
|
||||
RIGHT_STICK, UP, VIEW, X, Y,
|
||||
};
|
||||
|
||||
const GOOGLE: u16 = 0x18d1;
|
||||
const STADIA: u16 = 0x9400;
|
||||
|
||||
const PAGE_SIMULATION: u16 = 0x02;
|
||||
const USAGE_ACCELERATOR: u16 = 0xc4;
|
||||
const USAGE_BRAKE: u16 = 0xc5;
|
||||
|
||||
const GENERIC_READ: u32 = 0x8000_0000;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
struct Reading {
|
||||
buttons: u32,
|
||||
left_trigger: f32,
|
||||
right_trigger: f32,
|
||||
left_x: f32,
|
||||
left_y: f32,
|
||||
right_x: f32,
|
||||
right_y: f32,
|
||||
}
|
||||
|
||||
static READING: Mutex<Option<Reading>> = Mutex::new(None);
|
||||
static START: Once = Once::new();
|
||||
|
||||
fn wanted() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("EONACAT_XS_HID_PADS").is_none_or(|v| v != "0"))
|
||||
}
|
||||
|
||||
pub(super) fn latest() -> Option<PadState> {
|
||||
if !wanted() {
|
||||
return None;
|
||||
}
|
||||
START.call_once(|| {
|
||||
let _ = std::thread::Builder::new()
|
||||
.name("stadia".into())
|
||||
.spawn(reader);
|
||||
});
|
||||
let r = (*READING.lock().unwrap_or_else(|e| e.into_inner()))?;
|
||||
Some(PadState {
|
||||
buttons: r.buttons,
|
||||
left_trigger: r.left_trigger,
|
||||
right_trigger: r.right_trigger,
|
||||
left_x: r.left_x,
|
||||
left_y: r.left_y,
|
||||
right_x: r.right_x,
|
||||
right_y: r.right_y,
|
||||
})
|
||||
}
|
||||
|
||||
struct Pad {
|
||||
handle: HANDLE,
|
||||
preparsed: isize,
|
||||
input_len: usize,
|
||||
}
|
||||
|
||||
impl Drop for Pad {
|
||||
fn drop(&mut self) {
|
||||
|
||||
unsafe {
|
||||
HidD_FreePreparsedData(self.preparsed);
|
||||
CloseHandle(self.handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn reader() {
|
||||
loop {
|
||||
if let Some(pad) = open_pad() {
|
||||
read_reports(&pad, None);
|
||||
}
|
||||
*READING.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
|
||||
std::thread::sleep(Duration::from_secs(2));
|
||||
}
|
||||
}
|
||||
|
||||
fn read_reports(pad: &Pad, until: Option<std::time::Instant>) {
|
||||
let mut buf = vec![0u8; pad.input_len.max(64)];
|
||||
let log = std::env::var_os("EONACAT_XS_PAD_LOG").is_some_and(|v| v != "0");
|
||||
let mut last: Option<Reading> = None;
|
||||
let mut last_usages: Vec<u16> = Vec::new();
|
||||
loop {
|
||||
if until.is_some_and(|t| std::time::Instant::now() > t) {
|
||||
return;
|
||||
}
|
||||
let mut read = 0u32;
|
||||
|
||||
let ok = unsafe {
|
||||
ReadFile(
|
||||
pad.handle,
|
||||
buf.as_mut_ptr().cast(),
|
||||
buf.len() as u32,
|
||||
&mut read,
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if ok == 0 || read == 0 {
|
||||
return;
|
||||
}
|
||||
let report = &buf[..read as usize];
|
||||
let usages = usage_buttons(pad.preparsed, report);
|
||||
let reading = parse(pad.preparsed, report, &usages);
|
||||
if (log || until.is_some()) && usages != last_usages {
|
||||
let raw: Vec<String> = report.iter().map(|b| format!("{b:02x}")).collect();
|
||||
let text = format!(
|
||||
"Stadia report: usages {usages:?} -> buttons {:#x}; left {:.2},{:.2} right {:.2},{:.2} triggers {:.2},{:.2}; raw {}",
|
||||
reading.buttons,
|
||||
reading.left_x,
|
||||
reading.left_y,
|
||||
reading.right_x,
|
||||
reading.right_y,
|
||||
reading.left_trigger,
|
||||
reading.right_trigger,
|
||||
raw.join(" ")
|
||||
);
|
||||
if until.is_some() {
|
||||
println!("{text}");
|
||||
} else {
|
||||
tracing::info!("{text}");
|
||||
}
|
||||
}
|
||||
last_usages = usages;
|
||||
if last == Some(reading) {
|
||||
continue;
|
||||
}
|
||||
last = Some(reading);
|
||||
*READING.lock().unwrap_or_else(|e| e.into_inner()) = Some(reading);
|
||||
}
|
||||
}
|
||||
|
||||
fn is_stadia(handle: HANDLE, attributes: &HIDD_ATTRIBUTES) -> bool {
|
||||
if attributes.VendorID == GOOGLE && attributes.ProductID == STADIA {
|
||||
return true;
|
||||
}
|
||||
let mut name = [0u16; 128];
|
||||
|
||||
let ok =
|
||||
unsafe { HidD_GetProductString(handle, name.as_mut_ptr().cast(), (name.len() * 2) as u32) };
|
||||
if !ok {
|
||||
return false;
|
||||
}
|
||||
let len = name.iter().position(|&c| c == 0).unwrap_or(name.len());
|
||||
String::from_utf16_lossy(&name[..len])
|
||||
.to_ascii_lowercase()
|
||||
.contains("stadia")
|
||||
}
|
||||
|
||||
fn open_pad() -> Option<Pad> {
|
||||
for path in device_paths() {
|
||||
let mut wide = path.clone();
|
||||
wide.push(0);
|
||||
|
||||
let handle = unsafe {
|
||||
CreateFileW(
|
||||
wide.as_ptr(),
|
||||
GENERIC_READ,
|
||||
FILE_SHARE_READ | FILE_SHARE_WRITE,
|
||||
std::ptr::null(),
|
||||
OPEN_EXISTING,
|
||||
0,
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if handle == INVALID_HANDLE_VALUE {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut attributes: HIDD_ATTRIBUTES = unsafe { std::mem::zeroed() };
|
||||
attributes.Size = std::mem::size_of::<HIDD_ATTRIBUTES>() as u32;
|
||||
|
||||
let known = unsafe { HidD_GetAttributes(handle, &mut attributes) };
|
||||
if known && is_stadia(handle, &attributes) {
|
||||
let mut preparsed: isize = 0;
|
||||
|
||||
if !unsafe { HidD_GetPreparsedData(handle, &mut preparsed) } {
|
||||
|
||||
unsafe { CloseHandle(handle) };
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut caps: HIDP_CAPS = unsafe { std::mem::zeroed() };
|
||||
|
||||
let status = unsafe { HidP_GetCaps(preparsed, &mut caps) };
|
||||
|
||||
const GAMEPAD: u16 = 0x05;
|
||||
const JOYSTICK: u16 = 0x04;
|
||||
if status != HIDP_STATUS_SUCCESS
|
||||
|| caps.UsagePage != HID_USAGE_PAGE_GENERIC
|
||||
|| !matches!(caps.Usage, GAMEPAD | JOYSTICK)
|
||||
{
|
||||
|
||||
unsafe {
|
||||
HidD_FreePreparsedData(preparsed);
|
||||
CloseHandle(handle);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let input_len = usize::from(caps.InputReportByteLength).max(1);
|
||||
tracing::info!(
|
||||
vendor = format_args!("{:#06x}", attributes.VendorID),
|
||||
product = format_args!("{:#06x}", attributes.ProductID),
|
||||
report = input_len,
|
||||
"Stadia controller connected over HID"
|
||||
);
|
||||
return Some(Pad {
|
||||
handle,
|
||||
preparsed,
|
||||
input_len,
|
||||
});
|
||||
}
|
||||
|
||||
unsafe { CloseHandle(handle) };
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn device_paths() -> Vec<Vec<u16>> {
|
||||
let mut paths = Vec::new();
|
||||
|
||||
let set: HDEVINFO = unsafe {
|
||||
SetupDiGetClassDevsW(
|
||||
&GUID_DEVINTERFACE_HID,
|
||||
std::ptr::null(),
|
||||
std::ptr::null_mut(),
|
||||
DIGCF_PRESENT | DIGCF_DEVICEINTERFACE,
|
||||
)
|
||||
};
|
||||
if set == -1 {
|
||||
return paths;
|
||||
}
|
||||
let mut index = 0u32;
|
||||
loop {
|
||||
|
||||
let mut interface: SP_DEVICE_INTERFACE_DATA = unsafe { std::mem::zeroed() };
|
||||
interface.cbSize = std::mem::size_of::<SP_DEVICE_INTERFACE_DATA>() as u32;
|
||||
|
||||
if unsafe {
|
||||
SetupDiEnumDeviceInterfaces(
|
||||
set,
|
||||
std::ptr::null(),
|
||||
&GUID_DEVINTERFACE_HID,
|
||||
index,
|
||||
&mut interface,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
break;
|
||||
}
|
||||
index += 1;
|
||||
let mut required = 0u32;
|
||||
|
||||
unsafe {
|
||||
SetupDiGetDeviceInterfaceDetailW(
|
||||
set,
|
||||
&interface,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
&mut required,
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if required == 0 {
|
||||
continue;
|
||||
}
|
||||
let mut buffer = vec![0u8; required as usize];
|
||||
let detail = buffer
|
||||
.as_mut_ptr()
|
||||
.cast::<SP_DEVICE_INTERFACE_DETAIL_DATA_W>();
|
||||
|
||||
unsafe {
|
||||
(*detail).cbSize = std::mem::size_of::<SP_DEVICE_INTERFACE_DETAIL_DATA_W>() as u32;
|
||||
if SetupDiGetDeviceInterfaceDetailW(
|
||||
set,
|
||||
&interface,
|
||||
detail,
|
||||
required,
|
||||
std::ptr::null_mut(),
|
||||
std::ptr::null_mut(),
|
||||
) == 0
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
let words = (buffer.len() - 4) / 2;
|
||||
|
||||
let path =
|
||||
unsafe { std::slice::from_raw_parts(buffer.as_ptr().add(4).cast::<u16>(), words) };
|
||||
let len = path.iter().position(|&c| c == 0).unwrap_or(words);
|
||||
paths.push(path[..len].to_vec());
|
||||
}
|
||||
|
||||
unsafe { SetupDiDestroyDeviceInfoList(set) };
|
||||
paths
|
||||
}
|
||||
|
||||
fn usage_value(preparsed: isize, report: &[u8], page: u16, usage: u16) -> Option<u32> {
|
||||
let mut value = 0u32;
|
||||
|
||||
let status = unsafe {
|
||||
HidP_GetUsageValue(
|
||||
HidP_Input,
|
||||
page,
|
||||
0,
|
||||
usage,
|
||||
&mut value,
|
||||
preparsed,
|
||||
report.as_ptr(),
|
||||
report.len() as u32,
|
||||
)
|
||||
};
|
||||
(status == HIDP_STATUS_SUCCESS).then_some(value)
|
||||
}
|
||||
|
||||
fn usage_buttons(preparsed: isize, report: &[u8]) -> Vec<u16> {
|
||||
let mut usages = [0u16; 32];
|
||||
let mut len = usages.len() as u32;
|
||||
|
||||
let status = unsafe {
|
||||
HidP_GetUsages(
|
||||
HidP_Input,
|
||||
HID_USAGE_PAGE_BUTTON,
|
||||
0,
|
||||
usages.as_mut_ptr(),
|
||||
&mut len,
|
||||
preparsed,
|
||||
report.as_ptr() as *mut u8,
|
||||
report.len() as u32,
|
||||
)
|
||||
};
|
||||
if status == HIDP_STATUS_SUCCESS {
|
||||
usages[..len as usize].to_vec()
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
fn parse(preparsed: isize, report: &[u8], usages: &[u16]) -> Reading {
|
||||
let generic = |usage| usage_value(preparsed, report, HID_USAGE_PAGE_GENERIC, usage);
|
||||
let axis = |usage| generic(usage).unwrap_or(128);
|
||||
|
||||
let trigger = |simulation: u16, generic_usage: u16| {
|
||||
usage_value(preparsed, report, PAGE_SIMULATION, simulation)
|
||||
.or_else(|| generic(generic_usage))
|
||||
.unwrap_or(0)
|
||||
};
|
||||
state(
|
||||
[
|
||||
axis(HID_USAGE_GENERIC_X),
|
||||
axis(HID_USAGE_GENERIC_Y),
|
||||
axis(HID_USAGE_GENERIC_Z),
|
||||
axis(HID_USAGE_GENERIC_RZ),
|
||||
],
|
||||
[
|
||||
trigger(USAGE_BRAKE, HID_USAGE_GENERIC_RX),
|
||||
trigger(USAGE_ACCELERATOR, HID_USAGE_GENERIC_RY),
|
||||
],
|
||||
generic(HID_USAGE_GENERIC_HATSWITCH).unwrap_or(15),
|
||||
usages,
|
||||
)
|
||||
}
|
||||
|
||||
fn state(sticks: [u32; 4], triggers: [u32; 2], hat: u32, usages: &[u16]) -> Reading {
|
||||
let centered = |v: u32| ((f32::from(v.min(255) as u8) - 127.5) / 127.5).clamp(-1.0, 1.0);
|
||||
let mut buttons = 0u32;
|
||||
for usage in usages {
|
||||
buttons |= match usage {
|
||||
1 => A,
|
||||
2 => B,
|
||||
4 => X,
|
||||
5 => Y,
|
||||
7 => LEFT_SHOULDER,
|
||||
8 => RIGHT_SHOULDER,
|
||||
11 => VIEW,
|
||||
12 => MENU,
|
||||
13 => MENU,
|
||||
14 => LEFT_STICK,
|
||||
15 => RIGHT_STICK,
|
||||
_ => 0,
|
||||
};
|
||||
}
|
||||
|
||||
buttons |= match hat {
|
||||
0 => UP,
|
||||
1 => UP | RIGHT,
|
||||
2 => RIGHT,
|
||||
3 => DOWN | RIGHT,
|
||||
4 => DOWN,
|
||||
5 => DOWN | LEFT,
|
||||
6 => LEFT,
|
||||
7 => UP | LEFT,
|
||||
_ => 0,
|
||||
};
|
||||
Reading {
|
||||
buttons,
|
||||
left_trigger: f32::from(triggers[0].min(255) as u8) / 255.0,
|
||||
right_trigger: f32::from(triggers[1].min(255) as u8) / 255.0,
|
||||
left_x: centered(sticks[0]),
|
||||
|
||||
left_y: -centered(sticks[1]),
|
||||
right_x: centered(sticks[2]),
|
||||
right_y: -centered(sticks[3]),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum XInputRoute {
|
||||
Gameplay,
|
||||
MenuOnly,
|
||||
Off,
|
||||
}
|
||||
|
||||
impl XInputRoute {
|
||||
pub(super) fn for_poll(dualsense_only: bool, native_mouse: bool, mnk_bindings: bool) -> Self {
|
||||
if dualsense_only {
|
||||
Self::Off
|
||||
} else if !native_mouse && mnk_bindings {
|
||||
Self::MenuOnly
|
||||
} else {
|
||||
Self::Gameplay
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,311 @@
|
||||
|
||||
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
const LOGOS: [(&str, u32); 3] = [
|
||||
("Square44x44Logo", 44),
|
||||
("Square150x150Logo", 150),
|
||||
("Square480x480Logo", 480),
|
||||
];
|
||||
|
||||
const LAST_RESORT: (&str, u32) = ("StoreLogo", 50);
|
||||
|
||||
fn element_attributes(xml: &str, element: &str) -> Vec<(String, String)> {
|
||||
let open = format!("<{element}");
|
||||
let mut from = 0;
|
||||
let start = loop {
|
||||
let Some(at) = xml[from..].find(&open) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let after = from + at + open.len();
|
||||
match xml[after..].chars().next() {
|
||||
Some(c) if c.is_whitespace() || c == '/' || c == '>' => break after,
|
||||
_ => from = after,
|
||||
}
|
||||
};
|
||||
let mut quote = None;
|
||||
let mut end = xml.len();
|
||||
for (i, c) in xml[start..].char_indices() {
|
||||
match (quote, c) {
|
||||
(None, '"' | '\'') => quote = Some(c),
|
||||
(Some(q), _) if c == q => quote = None,
|
||||
(None, '>') => {
|
||||
end = start + i;
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut rest = &xml[start..end];
|
||||
let mut out = Vec::new();
|
||||
while let Some(eq) = rest.find('=') {
|
||||
let name = rest[..eq].trim().to_owned();
|
||||
let value = rest[eq + 1..].trim_start();
|
||||
let Some(q) = value.chars().next().filter(|c| *c == '"' || *c == '\'') else {
|
||||
break;
|
||||
};
|
||||
let Some(close) = value[1..].find(q) else { break };
|
||||
out.push((name, value[1..1 + close].replace("&", "&")));
|
||||
rest = &value[close + 2..];
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn logos_from_manifest(xml: &str) -> Vec<(u32, String)> {
|
||||
let attrs = element_attributes(xml, "ShellVisuals");
|
||||
let get = |key: &str| {
|
||||
attrs
|
||||
.iter()
|
||||
.find(|(k, v)| k == key && !v.trim().is_empty())
|
||||
.map(|(_, v)| v.trim().to_owned())
|
||||
};
|
||||
let mut found: Vec<(u32, String)> = LOGOS
|
||||
.iter()
|
||||
.filter_map(|(key, size)| get(key).map(|v| (*size, v)))
|
||||
.collect();
|
||||
if found.is_empty()
|
||||
&& let Some(v) = get(LAST_RESORT.0)
|
||||
{
|
||||
found.push((LAST_RESORT.1, v));
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
fn safe_relative(relative: &str) -> Option<PathBuf> {
|
||||
let text = relative.trim().replace('/', "\\");
|
||||
if text.is_empty() || text.starts_with('\\') || text.contains(':') {
|
||||
return None;
|
||||
}
|
||||
let path = PathBuf::from(&text);
|
||||
path.components()
|
||||
.all(|c| matches!(c, Component::Normal(_) | Component::CurDir))
|
||||
.then_some(path)
|
||||
}
|
||||
|
||||
fn pick_source(sizes: &[u32], want: u32) -> Option<usize> {
|
||||
sizes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, s)| **s >= want)
|
||||
.min_by_key(|(_, s)| **s)
|
||||
.or_else(|| sizes.iter().enumerate().max_by_key(|(_, s)| **s))
|
||||
.map(|(i, _)| i)
|
||||
}
|
||||
|
||||
fn find_manifest(dir: &Path) -> Option<PathBuf> {
|
||||
std::fs::read_dir(dir).ok()?.flatten().find_map(|e| {
|
||||
e.file_name()
|
||||
.to_str()
|
||||
.is_some_and(|n| n.eq_ignore_ascii_case("MicrosoftGame.config"))
|
||||
.then(|| e.path())
|
||||
})
|
||||
}
|
||||
|
||||
fn game_logos(dir: &Path) -> Vec<(u32, PathBuf)> {
|
||||
let Some(text) = find_manifest(dir).and_then(|p| std::fs::read(p).ok()) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let text = String::from_utf8_lossy(&text);
|
||||
let text = text.trim_start_matches('\u{feff}');
|
||||
let root = dir.canonicalize().ok();
|
||||
logos_from_manifest(text)
|
||||
.into_iter()
|
||||
.filter_map(|(size, rel)| {
|
||||
let Some(rel) = safe_relative(&rel) else {
|
||||
tracing::warn!("icon: the manifest names a path outside the game folder; skipped");
|
||||
return None;
|
||||
};
|
||||
let full = dir.join(rel).canonicalize().ok()?;
|
||||
|
||||
root.as_ref().is_some_and(|r| full.starts_with(r)).then_some((size, full))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub use imp::{is_ours, start};
|
||||
|
||||
#[cfg(windows)]
|
||||
mod imp {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicIsize, Ordering};
|
||||
use windows::Win32::Foundation::GENERIC_READ;
|
||||
use windows::Win32::Graphics::Imaging::{
|
||||
CLSID_WICImagingFactory, GUID_WICPixelFormat32bppBGRA, GUID_WICPixelFormat32bppPBGRA,
|
||||
IWICBitmapSource, IWICImagingFactory, IWICPalette, WICBitmapDitherTypeNone,
|
||||
WICBitmapInterpolationModeFant, WICBitmapPaletteTypeCustom, WICDecodeMetadataCacheOnDemand,
|
||||
};
|
||||
use windows::Win32::System::Com::{CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx};
|
||||
use windows::core::{Interface, PCWSTR};
|
||||
use windows_sys::Win32::Foundation::{HWND, LPARAM, WPARAM};
|
||||
use windows_sys::Win32::Graphics::Gdi::{
|
||||
BI_RGB, BITMAPINFO, CreateBitmap, CreateDIBSection, DIB_RGB_COLORS, DeleteObject, GetDC, ReleaseDC,
|
||||
};
|
||||
use windows_sys::Win32::UI::HiDpi::{GetDpiForWindow, GetSystemMetricsForDpi};
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging as wm;
|
||||
|
||||
static BIG: AtomicIsize = AtomicIsize::new(0);
|
||||
static SMALL: AtomicIsize = AtomicIsize::new(0);
|
||||
|
||||
pub fn is_ours(icon: LPARAM) -> bool {
|
||||
icon != 0 && (icon == BIG.load(Ordering::Relaxed) || icon == SMALL.load(Ordering::Relaxed))
|
||||
}
|
||||
|
||||
fn game_dir() -> Option<PathBuf> {
|
||||
let base = crate::hle::runtime::main_image()?;
|
||||
crate::hle::runtime::image_path(base)?.parent().map(Path::to_path_buf)
|
||||
}
|
||||
|
||||
pub fn start(hwnd: HWND) {
|
||||
let setting = std::env::var_os("EONACAT_XS_ICON");
|
||||
let setting = setting.as_deref().and_then(|s| s.to_str()).map(str::trim);
|
||||
let source = match setting {
|
||||
Some("0") => return,
|
||||
None | Some("") | Some("game") => None,
|
||||
Some(path) => Some(PathBuf::from(path)),
|
||||
};
|
||||
let hwnd = hwnd as usize;
|
||||
let spawned = std::thread::Builder::new().name("eonacat-xs-icon".into()).spawn(move || {
|
||||
if let Err(why) = run(hwnd as HWND, source) {
|
||||
tracing::warn!("icon: not set ({why})");
|
||||
}
|
||||
});
|
||||
if let Err(e) = spawned {
|
||||
tracing::warn!("icon: no thread ({e})");
|
||||
}
|
||||
}
|
||||
|
||||
fn run(hwnd: HWND, file: Option<PathBuf>) -> Result<(), String> {
|
||||
|
||||
let dpi = unsafe { GetDpiForWindow(hwnd) }.max(96);
|
||||
|
||||
let (big, small) = unsafe {
|
||||
(
|
||||
GetSystemMetricsForDpi(wm::SM_CXICON, dpi).max(16) as u32,
|
||||
GetSystemMetricsForDpi(wm::SM_CXSMICON, dpi).max(16) as u32,
|
||||
)
|
||||
};
|
||||
let (big_icon, small_icon) = match file {
|
||||
Some(path) if path.extension().is_some_and(|e| e.eq_ignore_ascii_case("ico")) => {
|
||||
(load_ico(&path, big)?, load_ico(&path, small)?)
|
||||
}
|
||||
Some(path) => {
|
||||
let sources = vec![(0, path)];
|
||||
(png_icon(&sources, big)?, png_icon(&sources, small)?)
|
||||
}
|
||||
None => {
|
||||
let dir = game_dir().ok_or("no game folder")?;
|
||||
let sources = game_logos(&dir);
|
||||
if sources.is_empty() {
|
||||
return Err("the manifest names no usable logo".into());
|
||||
}
|
||||
(png_icon(&sources, big)?, png_icon(&sources, small)?)
|
||||
}
|
||||
};
|
||||
BIG.store(big_icon, Ordering::Relaxed);
|
||||
SMALL.store(small_icon, Ordering::Relaxed);
|
||||
|
||||
unsafe {
|
||||
wm::PostMessageW(hwnd, wm::WM_SETICON, wm::ICON_BIG as WPARAM, big_icon);
|
||||
wm::PostMessageW(hwnd, wm::WM_SETICON, wm::ICON_SMALL as WPARAM, small_icon);
|
||||
}
|
||||
tracing::info!(big, small, dpi, "icon set");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_ico(path: &Path, size: u32) -> Result<isize, String> {
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
let wide: Vec<u16> = path.as_os_str().encode_wide().chain([0]).collect();
|
||||
|
||||
let icon = unsafe {
|
||||
wm::LoadImageW(
|
||||
std::ptr::null_mut(),
|
||||
wide.as_ptr(),
|
||||
wm::IMAGE_ICON,
|
||||
size as i32,
|
||||
size as i32,
|
||||
wm::LR_LOADFROMFILE,
|
||||
)
|
||||
};
|
||||
if icon.is_null() { Err("the .ico file did not load".into()) } else { Ok(icon as isize) }
|
||||
}
|
||||
|
||||
fn png_icon(sources: &[(u32, PathBuf)], size: u32) -> Result<isize, String> {
|
||||
let sizes: Vec<u32> = sources.iter().map(|(s, _)| *s).collect();
|
||||
let (_, path) = &sources[pick_source(&sizes, size).ok_or("no source")?];
|
||||
let pixels = decode(path, size).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
make_icon(&pixels, size)
|
||||
}
|
||||
|
||||
fn decode(path: &Path, size: u32) -> windows::core::Result<Vec<u8>> {
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
let wide: Vec<u16> = path.as_os_str().encode_wide().chain([0]).collect();
|
||||
|
||||
unsafe {
|
||||
|
||||
let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
|
||||
let factory: IWICImagingFactory = CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER)?;
|
||||
let decoder = factory.CreateDecoderFromFilename(
|
||||
PCWSTR(wide.as_ptr()),
|
||||
None,
|
||||
GENERIC_READ,
|
||||
WICDecodeMetadataCacheOnDemand,
|
||||
)?;
|
||||
let frame = decoder.GetFrame(0)?;
|
||||
|
||||
let to_pre = factory.CreateFormatConverter()?;
|
||||
to_pre.Initialize(
|
||||
&frame,
|
||||
&GUID_WICPixelFormat32bppPBGRA,
|
||||
WICBitmapDitherTypeNone,
|
||||
None::<&IWICPalette>,
|
||||
0.0,
|
||||
WICBitmapPaletteTypeCustom,
|
||||
)?;
|
||||
let scaler = factory.CreateBitmapScaler()?;
|
||||
scaler.Initialize(&to_pre, size, size, WICBitmapInterpolationModeFant)?;
|
||||
let to_straight = factory.CreateFormatConverter()?;
|
||||
to_straight.Initialize(
|
||||
&scaler,
|
||||
&GUID_WICPixelFormat32bppBGRA,
|
||||
WICBitmapDitherTypeNone,
|
||||
None::<&IWICPalette>,
|
||||
0.0,
|
||||
WICBitmapPaletteTypeCustom,
|
||||
)?;
|
||||
let source: IWICBitmapSource = to_straight.cast()?;
|
||||
let mut pixels = vec![0u8; (size * size * 4) as usize];
|
||||
source.CopyPixels(std::ptr::null(), size * 4, &mut pixels)?;
|
||||
Ok(pixels)
|
||||
}
|
||||
}
|
||||
|
||||
fn make_icon(bgra: &[u8], size: u32) -> Result<isize, String> {
|
||||
|
||||
unsafe {
|
||||
let mut info: BITMAPINFO = std::mem::zeroed();
|
||||
info.bmiHeader.biSize = std::mem::size_of_val(&info.bmiHeader) as u32;
|
||||
info.bmiHeader.biWidth = size as i32;
|
||||
info.bmiHeader.biHeight = -(size as i32);
|
||||
info.bmiHeader.biPlanes = 1;
|
||||
info.bmiHeader.biBitCount = 32;
|
||||
info.bmiHeader.biCompression = BI_RGB;
|
||||
let dc = GetDC(std::ptr::null_mut());
|
||||
let mut bits = std::ptr::null_mut();
|
||||
let colour = CreateDIBSection(dc, &info, DIB_RGB_COLORS, &mut bits, std::ptr::null_mut(), 0);
|
||||
ReleaseDC(std::ptr::null_mut(), dc);
|
||||
if colour.is_null() || bits.is_null() {
|
||||
return Err("no DIB section".into());
|
||||
}
|
||||
std::ptr::copy_nonoverlapping(bgra.as_ptr(), bits.cast::<u8>(), bgra.len());
|
||||
let mask = CreateBitmap(size as i32, size as i32, 1, 1, std::ptr::null());
|
||||
let icon_info = wm::ICONINFO { fIcon: 1, xHotspot: 0, yHotspot: 0, hbmMask: mask, hbmColor: colour };
|
||||
let icon = wm::CreateIconIndirect(&icon_info);
|
||||
|
||||
DeleteObject(colour);
|
||||
DeleteObject(mask);
|
||||
if icon.is_null() { Err("CreateIconIndirect failed".into()) } else { Ok(icon as isize) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,653 @@
|
||||
|
||||
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::ffi::c_void;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
|
||||
use super::files;
|
||||
use super::xasync::E_NOTIMPL;
|
||||
use super::xgameruntime::{HRESULT, S_OK};
|
||||
use crate::hle::{HleModule};
|
||||
use crate::hle_export;
|
||||
|
||||
const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32;
|
||||
const E_POINTER: HRESULT = 0x8000_4003_u32 as i32;
|
||||
|
||||
const UNSUPPORTED_SCHEME: HRESULT = 0xC00D_36C3_u32 as i32;
|
||||
|
||||
const IID_IUNKNOWN: [u8; 16] = guid(0x0000_0000, 0x0000, 0x0000, [0xC0, 0, 0, 0, 0, 0, 0, 0x46]);
|
||||
const IID_RESOLVER: [u8; 16] = guid(
|
||||
0xFBE5_A32D,
|
||||
0xA497,
|
||||
0x4B61,
|
||||
[0xBB, 0x85, 0x97, 0xB1, 0xA8, 0x48, 0xA6, 0xE3],
|
||||
);
|
||||
|
||||
const fn guid(a: u32, b: u16, c: u16, d: [u8; 8]) -> [u8; 16] {
|
||||
let (a, b, c) = (a.to_le_bytes(), b.to_le_bytes(), c.to_le_bytes());
|
||||
[
|
||||
a[0], a[1], a[2], a[3], b[0], b[1], c[0], c[1], d[0], d[1], d[2], d[3], d[4], d[5], d[6],
|
||||
d[7],
|
||||
]
|
||||
}
|
||||
|
||||
fn local(url: &[u16]) -> Result<Vec<u16>, (String, String)> {
|
||||
let text = String::from_utf16_lossy(url);
|
||||
let drive = |s: &str| {
|
||||
let b = s.as_bytes();
|
||||
b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':'
|
||||
};
|
||||
let host_of = |rest: &str| rest.split(['/', '\\']).next().unwrap_or("").to_string();
|
||||
|
||||
let share = |s: &str| {
|
||||
let b = s.as_bytes();
|
||||
b.len() >= 2 && b[..2].iter().all(|c| b"/\\".contains(c))
|
||||
};
|
||||
let path = if let Some(rest) = text.strip_prefix(r"\\?\") {
|
||||
if !drive(rest) {
|
||||
return Err(("unc".into(), host_of(rest.trim_start_matches("UNC\\"))));
|
||||
}
|
||||
text.clone()
|
||||
} else if let Some(rest) = text.strip_prefix(r"\??\") {
|
||||
|
||||
if !drive(rest) {
|
||||
return Err(("unc".into(), host_of(rest.trim_start_matches("UNC\\"))));
|
||||
}
|
||||
return Ok(with_nul(url));
|
||||
} else if share(&text) {
|
||||
return Err(("unc".into(), host_of(&text[2..])));
|
||||
} else if drive(&text) {
|
||||
text.clone()
|
||||
} else if let Some((scheme, rest)) = text.split_once(':').filter(|(s, _)| {
|
||||
s.len() > 1
|
||||
&& s.bytes()
|
||||
.all(|c| c.is_ascii_alphanumeric() || b"+-.".contains(&c))
|
||||
}) {
|
||||
let scheme = scheme.to_ascii_lowercase();
|
||||
let authority = rest.strip_prefix("//");
|
||||
if scheme != "file" {
|
||||
return Err((scheme, authority.map(host_of).unwrap_or_default()));
|
||||
}
|
||||
let (path, this_machine) = match authority {
|
||||
Some(rest) => {
|
||||
let host = host_of(rest);
|
||||
if !host.is_empty() && !host.eq_ignore_ascii_case("localhost") {
|
||||
return Err((scheme, host));
|
||||
}
|
||||
(&rest[host.len()..], !host.is_empty())
|
||||
}
|
||||
None => (rest, false),
|
||||
};
|
||||
let whole = percent_decode(path);
|
||||
let path = percent_decode(path.trim_start_matches(['/', '\\'])).replace('/', "\\");
|
||||
if !drive(&path) {
|
||||
|
||||
if !this_machine && share(&whole) {
|
||||
return Err((scheme, host_of(whole.trim_start_matches(['/', '\\']))));
|
||||
}
|
||||
|
||||
return Ok(with_nul(url));
|
||||
}
|
||||
path
|
||||
} else {
|
||||
|
||||
return Ok(with_nul(url));
|
||||
};
|
||||
let wide: Vec<u16> = path.encode_utf16().collect();
|
||||
Ok(files::translate(&wide).unwrap_or_else(|| with_nul(&wide)))
|
||||
}
|
||||
|
||||
fn with_nul(s: &[u16]) -> Vec<u16> {
|
||||
s.iter().copied().chain([0]).collect()
|
||||
}
|
||||
|
||||
fn percent_decode(s: &str) -> String {
|
||||
let b = s.as_bytes();
|
||||
let mut out = Vec::with_capacity(b.len());
|
||||
let mut i = 0;
|
||||
while i < b.len() {
|
||||
|
||||
let hex = b
|
||||
.get(i + 1..i + 3)
|
||||
.filter(|h| h.iter().all(|c| c.is_ascii_hexdigit()))
|
||||
.and_then(|h| std::str::from_utf8(h).ok());
|
||||
match (b[i], hex.and_then(|h| u8::from_str_radix(h, 16).ok())) {
|
||||
(b'%', Some(v)) => {
|
||||
out.push(v);
|
||||
i += 3;
|
||||
}
|
||||
(c, _) => {
|
||||
out.push(c);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
fn units<'a>(s: *const u16) -> &'a [u16] {
|
||||
|
||||
let len = (0..).take_while(|&i| unsafe { s.add(i).read() } != 0).count();
|
||||
|
||||
unsafe { std::slice::from_raw_parts(s, len) }
|
||||
}
|
||||
|
||||
fn checked(url: *const u16) -> Result<Vec<u16>, HRESULT> {
|
||||
if url.is_null() {
|
||||
return Err(E_POINTER);
|
||||
}
|
||||
local(units(url)).map_err(|(scheme, host)| {
|
||||
static REFUSED: Mutex<Option<HashSet<(String, String)>>> = Mutex::new(None);
|
||||
let mut refused = REFUSED.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if refused
|
||||
.get_or_insert_with(HashSet::new)
|
||||
.insert((scheme.clone(), host.clone()))
|
||||
{
|
||||
tracing::warn!(
|
||||
scheme,
|
||||
host,
|
||||
"media: refused a URL that is not a local file"
|
||||
);
|
||||
}
|
||||
UNSUPPORTED_SCHEME
|
||||
})
|
||||
}
|
||||
|
||||
fn kept(s: Vec<u16>) -> *const u16 {
|
||||
static KEPT: Mutex<Option<HashSet<Box<[u16]>>>> = Mutex::new(None);
|
||||
let mut kept = KEPT.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let kept = kept.get_or_insert_with(HashSet::new);
|
||||
if let Some(s) = kept.get(&s[..]) {
|
||||
return s.as_ptr();
|
||||
}
|
||||
let s = s.into_boxed_slice();
|
||||
|
||||
let ptr = s.as_ptr();
|
||||
kept.insert(s);
|
||||
ptr
|
||||
}
|
||||
|
||||
fn file_path(path: *const u16) -> Option<Vec<u16>> {
|
||||
if path.is_null() {
|
||||
return None;
|
||||
}
|
||||
files::translate(units(path))
|
||||
}
|
||||
|
||||
const PROC_NOT_FOUND: HRESULT = 0x8007_007F_u32 as i32;
|
||||
|
||||
macro_rules! host_or_return {
|
||||
($dll:literal, $name:literal: $ty:ty) => {{
|
||||
static ADDRESS: OnceLock<Option<usize>> = OnceLock::new();
|
||||
match *ADDRESS.get_or_init(|| crate::hle::host::function($dll, $name)) {
|
||||
|
||||
Some(address) => unsafe { std::mem::transmute::<usize, $ty>(address) },
|
||||
None => return PROC_NOT_FOUND,
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
fn clear(out: *mut Unknown) {
|
||||
if !out.is_null() {
|
||||
|
||||
unsafe { out.write(std::ptr::null_mut()) };
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct Host {
|
||||
vtable: *const usize,
|
||||
}
|
||||
|
||||
impl Host {
|
||||
|
||||
unsafe fn method<F: Copy>(this: *mut Host, n: usize) -> F {
|
||||
|
||||
unsafe { std::mem::transmute_copy(&*(*this).vtable.add(n)) }
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct Resolver {
|
||||
vtable: &'static Methods,
|
||||
host: *mut Host,
|
||||
refs: AtomicU32,
|
||||
}
|
||||
|
||||
type Unknown = *mut c_void;
|
||||
|
||||
extern "system" fn beyond<const SLOT: usize>(_: *mut Resolver) -> HRESULT {
|
||||
tracing::warn!(
|
||||
slot = format_args!("{SLOT:#x}"),
|
||||
"source resolver method not implemented"
|
||||
);
|
||||
E_NOTIMPL
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct Methods {
|
||||
query_interface:
|
||||
extern "system" fn(*mut Resolver, *const [u8; 16], *mut *mut c_void) -> HRESULT,
|
||||
add_ref: extern "system" fn(*mut Resolver) -> u32,
|
||||
release: extern "system" fn(*mut Resolver) -> u32,
|
||||
create_from_url: extern "system" fn(
|
||||
*mut Resolver,
|
||||
*const u16,
|
||||
u32,
|
||||
Unknown,
|
||||
*mut u32,
|
||||
*mut Unknown,
|
||||
) -> HRESULT,
|
||||
create_from_stream: extern "system" fn(
|
||||
*mut Resolver,
|
||||
Unknown,
|
||||
*const u16,
|
||||
u32,
|
||||
Unknown,
|
||||
*mut u32,
|
||||
*mut Unknown,
|
||||
) -> HRESULT,
|
||||
begin_from_url: extern "system" fn(
|
||||
*mut Resolver,
|
||||
*const u16,
|
||||
u32,
|
||||
Unknown,
|
||||
*mut Unknown,
|
||||
Unknown,
|
||||
Unknown,
|
||||
) -> HRESULT,
|
||||
end_from_url: extern "system" fn(*mut Resolver, Unknown, *mut u32, *mut Unknown) -> HRESULT,
|
||||
begin_from_stream: extern "system" fn(
|
||||
*mut Resolver,
|
||||
Unknown,
|
||||
*const u16,
|
||||
u32,
|
||||
Unknown,
|
||||
*mut Unknown,
|
||||
Unknown,
|
||||
Unknown,
|
||||
) -> HRESULT,
|
||||
end_from_stream: extern "system" fn(*mut Resolver, Unknown, *mut u32, *mut Unknown) -> HRESULT,
|
||||
cancel: extern "system" fn(*mut Resolver, Unknown) -> HRESULT,
|
||||
|
||||
spare: [extern "system" fn(*mut Resolver) -> HRESULT; 8],
|
||||
}
|
||||
|
||||
static METHODS: Methods = Methods {
|
||||
query_interface,
|
||||
add_ref,
|
||||
release,
|
||||
create_from_url,
|
||||
create_from_stream,
|
||||
begin_from_url,
|
||||
end_from_url,
|
||||
begin_from_stream,
|
||||
end_from_stream,
|
||||
cancel,
|
||||
spare: [
|
||||
beyond::<0x50>,
|
||||
beyond::<0x58>,
|
||||
beyond::<0x60>,
|
||||
beyond::<0x68>,
|
||||
beyond::<0x70>,
|
||||
beyond::<0x78>,
|
||||
beyond::<0x80>,
|
||||
beyond::<0x88>,
|
||||
],
|
||||
};
|
||||
|
||||
fn host(this: *mut Resolver) -> *mut Host {
|
||||
|
||||
unsafe { (*this).host }
|
||||
}
|
||||
|
||||
extern "system" fn query_interface(
|
||||
this: *mut Resolver,
|
||||
iid: *const [u8; 16],
|
||||
out: *mut *mut c_void,
|
||||
) -> HRESULT {
|
||||
if iid.is_null() || out.is_null() {
|
||||
return E_POINTER;
|
||||
}
|
||||
|
||||
let iid = unsafe { *iid };
|
||||
let found = iid == IID_IUNKNOWN || iid == IID_RESOLVER;
|
||||
|
||||
unsafe {
|
||||
out.write(if found {
|
||||
this.cast()
|
||||
} else {
|
||||
std::ptr::null_mut()
|
||||
})
|
||||
};
|
||||
if !found {
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
add_ref(this);
|
||||
S_OK
|
||||
}
|
||||
|
||||
extern "system" fn add_ref(this: *mut Resolver) -> u32 {
|
||||
|
||||
unsafe { (*this).refs.fetch_add(1, Ordering::Relaxed) + 1 }
|
||||
}
|
||||
|
||||
extern "system" fn release(this: *mut Resolver) -> u32 {
|
||||
|
||||
let left = unsafe { (*this).refs.fetch_sub(1, Ordering::AcqRel) } - 1;
|
||||
if left == 0 {
|
||||
|
||||
let proxy = unsafe { Box::from_raw(this) };
|
||||
|
||||
let release: extern "system" fn(*mut Host) -> u32 = unsafe { Host::method(proxy.host, 2) };
|
||||
release(proxy.host);
|
||||
}
|
||||
left
|
||||
}
|
||||
|
||||
extern "system" fn create_from_url(
|
||||
this: *mut Resolver,
|
||||
url: *const u16,
|
||||
flags: u32,
|
||||
props: Unknown,
|
||||
kind: *mut u32,
|
||||
object: *mut Unknown,
|
||||
) -> HRESULT {
|
||||
let url = match checked(url) {
|
||||
Ok(url) => url,
|
||||
Err(error) => {
|
||||
clear(object);
|
||||
return error;
|
||||
}
|
||||
};
|
||||
let host = host(this);
|
||||
|
||||
let f: extern "system" fn(
|
||||
*mut Host,
|
||||
*const u16,
|
||||
u32,
|
||||
Unknown,
|
||||
*mut u32,
|
||||
*mut Unknown,
|
||||
) -> HRESULT = unsafe { Host::method(host, 3) };
|
||||
f(host, url.as_ptr(), flags, props, kind, object)
|
||||
}
|
||||
|
||||
extern "system" fn begin_from_url(
|
||||
this: *mut Resolver,
|
||||
url: *const u16,
|
||||
flags: u32,
|
||||
props: Unknown,
|
||||
cookie: *mut Unknown,
|
||||
callback: Unknown,
|
||||
state: Unknown,
|
||||
) -> HRESULT {
|
||||
let url = match checked(url) {
|
||||
Ok(url) => kept(url),
|
||||
Err(error) => {
|
||||
clear(cookie);
|
||||
return error;
|
||||
}
|
||||
};
|
||||
let host = host(this);
|
||||
|
||||
let f: extern "system" fn(
|
||||
*mut Host,
|
||||
*const u16,
|
||||
u32,
|
||||
Unknown,
|
||||
*mut Unknown,
|
||||
Unknown,
|
||||
Unknown,
|
||||
) -> HRESULT = unsafe { Host::method(host, 5) };
|
||||
f(host, url, flags, props, cookie, callback, state)
|
||||
}
|
||||
|
||||
extern "system" fn create_from_stream(
|
||||
this: *mut Resolver,
|
||||
stream: Unknown,
|
||||
url: *const u16,
|
||||
flags: u32,
|
||||
props: Unknown,
|
||||
kind: *mut u32,
|
||||
object: *mut Unknown,
|
||||
) -> HRESULT {
|
||||
let host = host(this);
|
||||
|
||||
let f: extern "system" fn(
|
||||
*mut Host,
|
||||
Unknown,
|
||||
*const u16,
|
||||
u32,
|
||||
Unknown,
|
||||
*mut u32,
|
||||
*mut Unknown,
|
||||
) -> HRESULT = unsafe { Host::method(host, 4) };
|
||||
f(host, stream, url, flags, props, kind, object)
|
||||
}
|
||||
|
||||
extern "system" fn end_from_url(
|
||||
this: *mut Resolver,
|
||||
result: Unknown,
|
||||
kind: *mut u32,
|
||||
object: *mut Unknown,
|
||||
) -> HRESULT {
|
||||
let host = host(this);
|
||||
|
||||
let f: extern "system" fn(*mut Host, Unknown, *mut u32, *mut Unknown) -> HRESULT =
|
||||
unsafe { Host::method(host, 6) };
|
||||
f(host, result, kind, object)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
extern "system" fn begin_from_stream(
|
||||
this: *mut Resolver,
|
||||
stream: Unknown,
|
||||
url: *const u16,
|
||||
flags: u32,
|
||||
props: Unknown,
|
||||
cookie: *mut Unknown,
|
||||
callback: Unknown,
|
||||
state: Unknown,
|
||||
) -> HRESULT {
|
||||
let host = host(this);
|
||||
|
||||
let f: extern "system" fn(
|
||||
*mut Host,
|
||||
Unknown,
|
||||
*const u16,
|
||||
u32,
|
||||
Unknown,
|
||||
*mut Unknown,
|
||||
Unknown,
|
||||
Unknown,
|
||||
) -> HRESULT = unsafe { Host::method(host, 7) };
|
||||
f(host, stream, url, flags, props, cookie, callback, state)
|
||||
}
|
||||
|
||||
extern "system" fn end_from_stream(
|
||||
this: *mut Resolver,
|
||||
result: Unknown,
|
||||
kind: *mut u32,
|
||||
object: *mut Unknown,
|
||||
) -> HRESULT {
|
||||
let host = host(this);
|
||||
|
||||
let f: extern "system" fn(*mut Host, Unknown, *mut u32, *mut Unknown) -> HRESULT =
|
||||
unsafe { Host::method(host, 8) };
|
||||
f(host, result, kind, object)
|
||||
}
|
||||
|
||||
extern "system" fn cancel(this: *mut Resolver, cookie: Unknown) -> HRESULT {
|
||||
let host = host(this);
|
||||
|
||||
let f: extern "system" fn(*mut Host, Unknown) -> HRESULT = unsafe { Host::method(host, 9) };
|
||||
f(host, cookie)
|
||||
}
|
||||
|
||||
pub extern "system" fn MFCreateSourceResolver(out: *mut *mut Resolver) -> HRESULT {
|
||||
if out.is_null() {
|
||||
return E_POINTER;
|
||||
}
|
||||
static CREATE: OnceLock<Option<usize>> = OnceLock::new();
|
||||
let Some(create) =
|
||||
*CREATE.get_or_init(|| crate::hle::host::function("mfplat.dll", "MFCreateSourceResolver"))
|
||||
else {
|
||||
return UNSUPPORTED_SCHEME;
|
||||
};
|
||||
|
||||
let create: extern "system" fn(*mut *mut Host) -> HRESULT =
|
||||
unsafe { std::mem::transmute(create) };
|
||||
let mut host = std::ptr::null_mut();
|
||||
let hr = create(&mut host);
|
||||
if hr < 0 || host.is_null() {
|
||||
return hr;
|
||||
}
|
||||
let proxy = Box::new(Resolver {
|
||||
vtable: &METHODS,
|
||||
host,
|
||||
refs: AtomicU32::new(1),
|
||||
});
|
||||
|
||||
unsafe { out.write(Box::into_raw(proxy)) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub extern "system" fn MFCreateSourceReaderFromURL(
|
||||
url: *const u16,
|
||||
attributes: Unknown,
|
||||
reader: *mut Unknown,
|
||||
) -> HRESULT {
|
||||
let url = match checked(url) {
|
||||
Ok(url) => url,
|
||||
Err(error) => {
|
||||
clear(reader);
|
||||
return error;
|
||||
}
|
||||
};
|
||||
let create = host_or_return!("mfreadwrite.dll", "MFCreateSourceReaderFromURL":
|
||||
extern "system" fn(*const u16, Unknown, *mut Unknown) -> HRESULT);
|
||||
create(url.as_ptr(), attributes, reader)
|
||||
}
|
||||
|
||||
pub extern "system" fn MFCreateSinkWriterFromURL(
|
||||
url: *const u16,
|
||||
stream: Unknown,
|
||||
attributes: Unknown,
|
||||
writer: *mut Unknown,
|
||||
) -> HRESULT {
|
||||
let create = host_or_return!("mfreadwrite.dll", "MFCreateSinkWriterFromURL":
|
||||
extern "system" fn(*const u16, Unknown, Unknown, *mut Unknown) -> HRESULT);
|
||||
if !stream.is_null() {
|
||||
return create(url, stream, attributes, writer);
|
||||
}
|
||||
let url = match checked(url) {
|
||||
Ok(url) => url,
|
||||
Err(error) => {
|
||||
clear(writer);
|
||||
return error;
|
||||
}
|
||||
};
|
||||
create(url.as_ptr(), stream, attributes, writer)
|
||||
}
|
||||
|
||||
pub extern "system" fn MFCreateFile(
|
||||
access: u32,
|
||||
open: u32,
|
||||
flags: u32,
|
||||
path: *const u16,
|
||||
stream: *mut Unknown,
|
||||
) -> HRESULT {
|
||||
let create = host_or_return!("mfplat.dll", "MFCreateFile":
|
||||
extern "system" fn(u32, u32, u32, *const u16, *mut Unknown) -> HRESULT);
|
||||
let host = file_path(path);
|
||||
create(
|
||||
access,
|
||||
open,
|
||||
flags,
|
||||
host.as_ref().map_or(path, |p| p.as_ptr()),
|
||||
stream,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn MFBeginCreateFile(
|
||||
access: u32,
|
||||
open: u32,
|
||||
flags: u32,
|
||||
path: *const u16,
|
||||
callback: Unknown,
|
||||
state: Unknown,
|
||||
cookie: *mut Unknown,
|
||||
) -> HRESULT {
|
||||
let begin = host_or_return!("mfplat.dll", "MFBeginCreateFile":
|
||||
extern "system" fn(u32, u32, u32, *const u16, Unknown, Unknown, *mut Unknown) -> HRESULT);
|
||||
let path = file_path(path).map_or(path, kept);
|
||||
begin(access, open, flags, path, callback, state, cookie)
|
||||
}
|
||||
|
||||
const UNSUPPORTED_D3D_TYPE: HRESULT = 0xC00D_6D76_u32 as i32;
|
||||
|
||||
fn no_gpu_video(call: &'static str) {
|
||||
static SAID: Mutex<Vec<&'static str>> = Mutex::new(Vec::new());
|
||||
let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if !said.contains(&call) {
|
||||
said.push(call);
|
||||
tracing::warn!(
|
||||
call,
|
||||
"media: the title asked for video on the GPU, which is not served (its device and textures are not the host's); refused with MF_E_UNSUPPORTED_D3D_TYPE"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub extern "system" fn MFResetDXGIDeviceManagerX(manager: Unknown, device: Unknown, _token: u32) -> HRESULT {
|
||||
if manager.is_null() || device.is_null() {
|
||||
return E_POINTER;
|
||||
}
|
||||
no_gpu_video("MFResetDXGIDeviceManagerX");
|
||||
UNSUPPORTED_D3D_TYPE
|
||||
}
|
||||
|
||||
pub extern "system" fn MFCreateDXGISurfaceBufferX(
|
||||
iid: *const [u8; 16],
|
||||
surface: Unknown,
|
||||
_subresource: u32,
|
||||
_bottom_up: i32,
|
||||
buffer: *mut Unknown,
|
||||
) -> HRESULT {
|
||||
clear(buffer);
|
||||
if iid.is_null() || surface.is_null() || buffer.is_null() {
|
||||
return E_POINTER;
|
||||
}
|
||||
no_gpu_video("MFCreateDXGISurfaceBufferX");
|
||||
UNSUPPORTED_D3D_TYPE
|
||||
}
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "media",
|
||||
dlls: &["mfplat.dll"],
|
||||
exports: vec![
|
||||
hle_export!(MFCreateSourceResolver),
|
||||
hle_export!(MFCreateFile),
|
||||
hle_export!(MFBeginCreateFile),
|
||||
hle_export!(MFResetDXGIDeviceManagerX),
|
||||
hle_export!(MFCreateDXGISurfaceBufferX),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn readers() -> HleModule {
|
||||
HleModule {
|
||||
name: "media readers",
|
||||
dlls: &["mfreadwrite.dll"],
|
||||
exports: vec![
|
||||
hle_export!(MFCreateSourceReaderFromURL),
|
||||
hle_export!(MFCreateSinkWriterFromURL),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,424 @@
|
||||
use super::{
|
||||
A, B, DOWN, LEFT, LEFT_SHOULDER, LEFT_STICK, MENU, PadState, RIGHT, RIGHT_SHOULDER,
|
||||
RIGHT_STICK, UP, VIEW, X, Y,
|
||||
};
|
||||
use std::sync::atomic::{AtomicU32, Ordering::Relaxed};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
use windows_sys::Win32::{
|
||||
Foundation::{HWND, POINT, RECT},
|
||||
UI::{Input::KeyboardAndMouse::GetAsyncKeyState, WindowsAndMessaging as wm},
|
||||
};
|
||||
|
||||
fn is_mouse_button(vk: u8) -> bool {
|
||||
matches!(vk, 1..=6)
|
||||
}
|
||||
|
||||
static LATCHED: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
fn latched(vk: u8) -> bool {
|
||||
LATCHED.load(Relaxed) & (1 << vk) != 0
|
||||
}
|
||||
|
||||
pub(crate) fn forget_buttons() {
|
||||
LATCHED.store(0, Relaxed);
|
||||
}
|
||||
|
||||
pub(crate) fn note_button(message: u32, wparam: usize) -> bool {
|
||||
let (vk, held) = match message {
|
||||
wm::WM_LBUTTONDOWN => (1u8, true),
|
||||
wm::WM_LBUTTONUP => (1u8, false),
|
||||
wm::WM_RBUTTONDOWN => (2, true),
|
||||
wm::WM_RBUTTONUP => (2, false),
|
||||
wm::WM_MBUTTONDOWN => (4, true),
|
||||
wm::WM_MBUTTONUP => (4, false),
|
||||
|
||||
wm::WM_XBUTTONDOWN | wm::WM_XBUTTONUP => {
|
||||
let which = ((wparam >> 16) & 0xffff) as u16;
|
||||
(if which == 2 { 6 } else { 5 }, message == wm::WM_XBUTTONDOWN)
|
||||
}
|
||||
_ => return false,
|
||||
};
|
||||
if held {
|
||||
LATCHED.fetch_or(1 << vk, Relaxed);
|
||||
} else {
|
||||
LATCHED.fetch_and(!(1 << vk), Relaxed);
|
||||
}
|
||||
true
|
||||
}
|
||||
const BUTTONS: &[(&str, u32)] = &[
|
||||
("A", A),
|
||||
("B", B),
|
||||
("X", X),
|
||||
("Y", Y),
|
||||
("LB", LEFT_SHOULDER),
|
||||
("RB", RIGHT_SHOULDER),
|
||||
("LS", LEFT_STICK),
|
||||
("RS", RIGHT_STICK),
|
||||
("Menu", MENU),
|
||||
("View", VIEW),
|
||||
("DpadUp", UP),
|
||||
("DpadDown", DOWN),
|
||||
("DpadLeft", LEFT),
|
||||
("DpadRight", RIGHT),
|
||||
];
|
||||
const AXES: [&str; 6] = ["LT", "RT", "MoveLeft", "MoveRight", "MoveDown", "MoveUp"];
|
||||
|
||||
const WHEEL_UP: u8 = 0x0E;
|
||||
const WHEEL_DOWN: u8 = 0x0F;
|
||||
|
||||
const WHEEL_DELTA: i32 = 120;
|
||||
|
||||
const WHEEL_PULSE_MS: u64 = 70;
|
||||
const WHEEL_GAP_MS: u64 = 40;
|
||||
|
||||
const WHEEL_QUEUE_MAX: usize = 16;
|
||||
|
||||
#[derive(Default)]
|
||||
struct Wheel {
|
||||
|
||||
rest: i32,
|
||||
queue: std::collections::VecDeque<u8>,
|
||||
|
||||
now: Option<(u8, u64)>,
|
||||
|
||||
free_at: u64,
|
||||
}
|
||||
|
||||
impl Wheel {
|
||||
|
||||
fn scroll(&mut self, delta: i32) {
|
||||
if delta != 0 && self.rest != 0 && (delta < 0) != (self.rest < 0) {
|
||||
self.rest = 0;
|
||||
}
|
||||
self.rest = self.rest.saturating_add(delta);
|
||||
let key = if self.rest > 0 { WHEEL_UP } else { WHEEL_DOWN };
|
||||
let n = (self.rest / WHEEL_DELTA).unsigned_abs() as usize;
|
||||
self.rest %= WHEEL_DELTA;
|
||||
for _ in 0..n {
|
||||
if self.queue.len() < WHEEL_QUEUE_MAX {
|
||||
self.queue.push_back(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn poll(&mut self, ms: u64) -> Option<u8> {
|
||||
if let Some((key, until)) = self.now {
|
||||
if ms < until {
|
||||
return Some(key);
|
||||
}
|
||||
self.now = None;
|
||||
self.free_at = until + WHEEL_GAP_MS;
|
||||
}
|
||||
if ms >= self.free_at
|
||||
&& let Some(key) = self.queue.pop_front()
|
||||
{
|
||||
self.now = Some((key, ms + WHEEL_PULSE_MS));
|
||||
return Some(key);
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn wheel() -> std::sync::MutexGuard<'static, Wheel> {
|
||||
static WHEEL: OnceLock<Mutex<Wheel>> = OnceLock::new();
|
||||
WHEEL
|
||||
.get_or_init(Default::default)
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
pub(crate) fn wheel_scroll(hwnd: HWND, delta: i32) {
|
||||
if enabled()
|
||||
&& !eonacat_xsbox_gpu::SETTINGS_MENU_OPEN.load(Relaxed)
|
||||
&& unsafe { wm::GetForegroundWindow() } == hwnd
|
||||
{
|
||||
wheel().scroll(delta);
|
||||
}
|
||||
}
|
||||
|
||||
struct Bindings {
|
||||
buttons: Vec<(u8, u32)>,
|
||||
axes: [Vec<u8>; 6],
|
||||
sensitivity: f32,
|
||||
}
|
||||
|
||||
fn key(name: &str) -> Option<u8> {
|
||||
let name = name.trim().to_ascii_uppercase();
|
||||
if name.len() == 1 && name.as_bytes()[0].is_ascii_alphanumeric() {
|
||||
return Some(name.as_bytes()[0]);
|
||||
}
|
||||
if let Some(hex) = name.strip_prefix("0X") {
|
||||
return u8::from_str_radix(hex, 16)
|
||||
.ok()
|
||||
.filter(|v| *v > 0 && *v < 255);
|
||||
}
|
||||
Some(match name.as_str() {
|
||||
"MOUSE1" => 1,
|
||||
"MOUSE2" => 2,
|
||||
"MOUSE3" => 4,
|
||||
"MOUSE4" => 5,
|
||||
"MOUSE5" => 6,
|
||||
"WHEELUP" => WHEEL_UP,
|
||||
"WHEELDOWN" => WHEEL_DOWN,
|
||||
"BACKSPACE" => 8,
|
||||
"TAB" => 9,
|
||||
"ENTER" => 13,
|
||||
"SHIFT" => 16,
|
||||
"CTRL" => 17,
|
||||
"ALT" => 18,
|
||||
"ESC" => 27,
|
||||
"SPACE" => 32,
|
||||
"LEFT" => 37,
|
||||
"UP" => 38,
|
||||
"RIGHT" => 39,
|
||||
"DOWN" => 40,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse(file: &str) -> Result<Bindings, String> {
|
||||
let mut b = Bindings {
|
||||
buttons: Vec::new(),
|
||||
axes: Default::default(),
|
||||
sensitivity: 0.045,
|
||||
};
|
||||
for (i, line) in file.lines().enumerate() {
|
||||
let line = line.split('#').next().unwrap_or("").trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let err = || format!("Invalid binding on line {}: {}", i + 1, line);
|
||||
let (out, input) = line.split_once('=').ok_or_else(err)?;
|
||||
let out = out.trim();
|
||||
if out.eq_ignore_ascii_case("Sensitivity") {
|
||||
b.sensitivity = input
|
||||
.trim()
|
||||
.parse::<f32>()
|
||||
.ok()
|
||||
.filter(|s| s.is_finite() && *s > 0.0)
|
||||
.ok_or_else(err)?;
|
||||
continue;
|
||||
}
|
||||
let keys = input
|
||||
.split(',')
|
||||
.map(|k| key(k).ok_or_else(err))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
if let Some((_, bit)) = BUTTONS
|
||||
.iter()
|
||||
.find(|(name, _)| name.eq_ignore_ascii_case(out))
|
||||
{
|
||||
b.buttons.extend(keys.into_iter().map(|k| (k, *bit)));
|
||||
} else {
|
||||
let index = AXES
|
||||
.iter()
|
||||
.position(|s| s.eq_ignore_ascii_case(out))
|
||||
.ok_or_else(err)?;
|
||||
b.axes[index].extend(keys);
|
||||
}
|
||||
}
|
||||
Ok(b)
|
||||
}
|
||||
|
||||
fn load() -> Option<Bindings> {
|
||||
let file = std::env::var_os("EONACAT_XS_MNK_BINDINGS")?;
|
||||
match std::fs::read_to_string(file)
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|s| parse(&s))
|
||||
{
|
||||
Ok(b) => Some(b),
|
||||
Err(e) => {
|
||||
eprintln!("Mouse and keyboard disabled: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn config() -> Option<Arc<Bindings>> {
|
||||
static CONFIG: Mutex<(u32, Option<Option<Arc<Bindings>>>)> = Mutex::new((0, None));
|
||||
let changed = eonacat_xsbox_gpu::MNK_BINDINGS_CHANGED.load(Relaxed);
|
||||
let mut c = CONFIG.lock().unwrap_or_else(|e| e.into_inner());
|
||||
refresh(&mut c, changed, load)
|
||||
}
|
||||
|
||||
fn refresh<B>(state: &mut (u32, Option<Option<Arc<B>>>), changed: u32, load: impl FnOnce() -> Option<B>) -> Option<Arc<B>> {
|
||||
match &state.1 {
|
||||
None => *state = (changed, Some(load().map(Arc::new))),
|
||||
Some(_) if state.0 != changed => {
|
||||
state.0 = changed;
|
||||
if let Some(b) = load() {
|
||||
state.1 = Some(Some(Arc::new(b)));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
state.1.clone().flatten()
|
||||
}
|
||||
|
||||
pub(crate) fn bound_buttons() -> Option<Vec<(u8, u32)>> {
|
||||
config().map(|b| b.buttons.clone())
|
||||
}
|
||||
|
||||
pub(crate) fn enabled() -> bool {
|
||||
config().is_some()
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Mouse {
|
||||
window: usize,
|
||||
velocity: [f32; 2],
|
||||
stick: [f32; 2],
|
||||
last: Option<Instant>,
|
||||
last_motion: Option<Instant>,
|
||||
centered: bool,
|
||||
}
|
||||
fn mouse() -> std::sync::MutexGuard<'static, Mouse> {
|
||||
static STATE: OnceLock<Mutex<Mouse>> = OnceLock::new();
|
||||
STATE.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
fn recenter(hwnd: HWND, centered: bool) -> Option<[i32; 2]> {
|
||||
if crate::hle::modules::lifecycle::mouse_dragging() {
|
||||
return None;
|
||||
}
|
||||
let mut rect = RECT::default();
|
||||
let mut cursor = POINT::default();
|
||||
unsafe {
|
||||
if wm::GetClientRect(hwnd, &mut rect) == 0 || rect.right <= 0 || rect.bottom <= 0 {
|
||||
return None;
|
||||
}
|
||||
let mut top_left = POINT { x: 0, y: 0 };
|
||||
let mut bottom_right = POINT {
|
||||
x: rect.right,
|
||||
y: rect.bottom,
|
||||
};
|
||||
if windows_sys::Win32::Graphics::Gdi::ClientToScreen(hwnd, &mut top_left) == 0
|
||||
|| windows_sys::Win32::Graphics::Gdi::ClientToScreen(hwnd, &mut bottom_right) == 0
|
||||
|| wm::GetCursorPos(&mut cursor) == 0
|
||||
|| wm::GetForegroundWindow() != hwnd
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
if !centered
|
||||
&& (cursor.x < top_left.x
|
||||
|| cursor.x >= bottom_right.x
|
||||
|| cursor.y < top_left.y
|
||||
|| cursor.y >= bottom_right.y)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let center = POINT {
|
||||
x: top_left.x + (bottom_right.x - top_left.x) / 2,
|
||||
y: top_left.y + (bottom_right.y - top_left.y) / 2,
|
||||
};
|
||||
let delta = [cursor.x - center.x, cursor.y - center.y];
|
||||
if delta != [0, 0] && wm::SetCursorPos(center.x, center.y) == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(delta)
|
||||
}
|
||||
}
|
||||
|
||||
impl Mouse {
|
||||
fn update_look(&mut self, delta: [i32; 2], now: Instant, elapsed: Duration, sensitivity: f32) {
|
||||
if delta != [0, 0] {
|
||||
self.last_motion = Some(now);
|
||||
}
|
||||
if self
|
||||
.last_motion
|
||||
.is_none_or(|t| now.duration_since(t) >= Duration::from_millis(40))
|
||||
{
|
||||
self.velocity = [0.0; 2];
|
||||
self.stick = [0.0; 2];
|
||||
return;
|
||||
}
|
||||
let seconds = elapsed.as_secs_f32();
|
||||
let weight = 1.0 - (-seconds / 0.020).exp();
|
||||
|
||||
for (v, d) in self
|
||||
.velocity
|
||||
.iter_mut()
|
||||
.zip([delta[0] as f32, -(delta[1] as f32)])
|
||||
{
|
||||
let target = d * sensitivity * 0.008 / seconds;
|
||||
*v += weight * (target - *v);
|
||||
}
|
||||
let length = self.velocity[0].hypot(self.velocity[1]);
|
||||
if length <= 0.001 {
|
||||
self.stick = [0.0; 2];
|
||||
} else {
|
||||
|
||||
let gain = (0.24 + 0.76 * length.min(1.0)) / length;
|
||||
self.stick = self.velocity.map(|v| v * gain);
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) fn sample() -> Option<PadState> {
|
||||
let b = config()?;
|
||||
let mut m = mouse();
|
||||
|
||||
if eonacat_xsbox_gpu::SETTINGS_MENU_OPEN.load(Relaxed) || crate::hle::modules::lifecycle::mouse_dragging() {
|
||||
*m = Mouse::default();
|
||||
*wheel() = Wheel::default();
|
||||
return Some(PadState::default());
|
||||
}
|
||||
let hwnd = unsafe { wm::GetForegroundWindow() };
|
||||
let mut pid = 0;
|
||||
unsafe { wm::GetWindowThreadProcessId(hwnd, &mut pid) };
|
||||
if hwnd.is_null() || pid != std::process::id() {
|
||||
*m = Mouse::default();
|
||||
*wheel() = Wheel::default();
|
||||
return Some(PadState::default());
|
||||
}
|
||||
if m.window != hwnd as usize {
|
||||
*m = Mouse {
|
||||
window: hwnd as usize,
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
let now = Instant::now();
|
||||
let elapsed = m
|
||||
.last
|
||||
.map_or(Duration::from_millis(8), |last| now.duration_since(last));
|
||||
if elapsed >= Duration::from_millis(8) {
|
||||
let displacement = recenter(hwnd, m.centered);
|
||||
let delta = if m.centered {
|
||||
displacement.unwrap_or_default()
|
||||
} else {
|
||||
[0, 0]
|
||||
};
|
||||
m.centered = displacement.is_some();
|
||||
m.update_look(delta, now, elapsed, b.sensitivity);
|
||||
m.last = Some(now);
|
||||
}
|
||||
static START: OnceLock<Instant> = OnceLock::new();
|
||||
let ms = now.duration_since(*START.get_or_init(|| now)).as_millis() as u64;
|
||||
let wheel_key = wheel().poll(ms);
|
||||
|
||||
let held = |vk: u8| match vk {
|
||||
WHEEL_UP | WHEEL_DOWN => wheel_key == Some(vk),
|
||||
_ => {
|
||||
let down = (unsafe { GetAsyncKeyState(vk.into()) }) < 0;
|
||||
if is_mouse_button(vk) { down || latched(vk) } else { down }
|
||||
}
|
||||
};
|
||||
let axes = b
|
||||
.axes
|
||||
.each_ref()
|
||||
.map(|keys| u8::from(keys.iter().copied().any(held)) as f32);
|
||||
Some(PadState {
|
||||
buttons: b
|
||||
.buttons
|
||||
.iter()
|
||||
.filter(|(vk, _)| held(*vk))
|
||||
.fold(0, |v, (_, bit)| v | bit),
|
||||
left_trigger: axes[0],
|
||||
right_trigger: axes[1],
|
||||
left_x: axes[3] - axes[2],
|
||||
left_y: axes[5] - axes[4],
|
||||
right_x: m.stick[0],
|
||||
right_y: m.stick[1],
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
|
||||
|
||||
#[cfg(windows)]
|
||||
pub mod apu;
|
||||
pub mod audio;
|
||||
pub mod bink;
|
||||
pub mod d3d12x;
|
||||
pub mod display;
|
||||
pub mod dsp;
|
||||
#[cfg(windows)]
|
||||
pub mod dstorage;
|
||||
#[cfg(windows)]
|
||||
pub mod fidelityfx;
|
||||
#[cfg(windows)]
|
||||
pub mod files;
|
||||
pub mod gameinput;
|
||||
#[cfg(windows)]
|
||||
pub mod icon;
|
||||
pub mod kernel;
|
||||
#[cfg(windows)]
|
||||
pub mod lifecycle;
|
||||
#[cfg(windows)]
|
||||
pub mod media;
|
||||
#[cfg(windows)]
|
||||
pub mod net;
|
||||
pub mod rpcrt4;
|
||||
pub mod speech;
|
||||
#[cfg(windows)]
|
||||
pub mod theme;
|
||||
pub mod storage;
|
||||
pub mod xasync;
|
||||
#[cfg(windows)]
|
||||
pub mod xboxbvh;
|
||||
pub mod xg;
|
||||
#[cfg(windows)]
|
||||
pub mod xaudio2;
|
||||
pub mod xcurl;
|
||||
pub mod xgame;
|
||||
pub mod xgameruntime;
|
||||
pub mod xgamesave;
|
||||
pub mod xgameui;
|
||||
#[cfg(windows)]
|
||||
pub mod xmem;
|
||||
pub mod xnetworking;
|
||||
pub mod xpackage;
|
||||
pub mod xstore;
|
||||
pub mod xsystem;
|
||||
pub mod xuser;
|
||||
|
||||
use crate::hle::HleModule;
|
||||
|
||||
pub(crate) fn all() -> Vec<HleModule> {
|
||||
let mut all = vec![
|
||||
kernel::module(),
|
||||
xgameruntime::module(),
|
||||
gameinput::module(),
|
||||
d3d12x::module(),
|
||||
audio::module(),
|
||||
dsp::module(),
|
||||
xg::module(),
|
||||
];
|
||||
#[cfg(windows)]
|
||||
all.push(apu::module());
|
||||
#[cfg(windows)]
|
||||
all.push(media::module());
|
||||
#[cfg(windows)]
|
||||
all.push(media::readers());
|
||||
#[cfg(windows)]
|
||||
all.push(xaudio2::module());
|
||||
all.push(xcurl::module());
|
||||
#[cfg(windows)]
|
||||
all.push(dstorage::module());
|
||||
#[cfg(windows)]
|
||||
all.push(files::module());
|
||||
#[cfg(windows)]
|
||||
all.push(lifecycle::module());
|
||||
#[cfg(windows)]
|
||||
all.push(net::module());
|
||||
all.push(rpcrt4::module());
|
||||
#[cfg(windows)]
|
||||
all.push(xmem::module());
|
||||
#[cfg(windows)]
|
||||
all.push(xsystem::module());
|
||||
|
||||
#[cfg(windows)]
|
||||
if eonacat_xsbox_gpu::hwrt::requested() {
|
||||
all.push(xboxbvh::module());
|
||||
}
|
||||
all
|
||||
}
|
||||
@@ -0,0 +1,848 @@
|
||||
|
||||
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
#![allow(clippy::too_many_arguments)]
|
||||
|
||||
use std::ffi::{CStr, c_char, c_void};
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::sync::Mutex;
|
||||
|
||||
use windows_sys::Win32::Foundation::SetLastError;
|
||||
|
||||
use crate::hle::modules::files::host;
|
||||
use crate::hle::{HleExport, HleModule};
|
||||
use crate::hle_export;
|
||||
|
||||
const SOCKET_ERROR: i32 = -1;
|
||||
const INVALID_SOCKET: Socket = !0;
|
||||
const WSAEINVAL: i32 = 10022;
|
||||
const WSAEADDRNOTAVAIL: i32 = 10049;
|
||||
const WSAENETUNREACH: i32 = 10051;
|
||||
const WSASERVICE_NOT_FOUND: i32 = 10108;
|
||||
const WSAHOST_NOT_FOUND: i32 = 11001;
|
||||
const ERROR_WINHTTP_CANNOT_CONNECT: u32 = 12029;
|
||||
const ERROR_WINHTTP_AUTODETECTION_FAILED: u32 = 12180;
|
||||
const AF_INET: u16 = 2;
|
||||
const AF_INET6: u16 = 23;
|
||||
const NI_NUMERICHOST: i32 = 0x02;
|
||||
const NI_NAMEREQD: i32 = 0x04;
|
||||
const SIO_GET_EXTENSION_FUNCTION_POINTER: u32 = 0xC800_0006;
|
||||
const SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER: u32 = 0xC800_0024;
|
||||
const WINHTTP_ACCESS_TYPE_NO_PROXY: u32 = 1;
|
||||
const WINHTTP_OPTION_PROXY: u32 = 38;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
struct Guid(u32, u16, u16, [u8; 8]);
|
||||
|
||||
const WSAID_CONNECTEX: Guid = Guid(
|
||||
0x25a2_07b9,
|
||||
0xddf3,
|
||||
0x4660,
|
||||
[0x8e, 0xe9, 0x76, 0xe5, 0x8c, 0x74, 0x06, 0x3e],
|
||||
);
|
||||
const WSAID_WSASENDMSG: Guid = Guid(
|
||||
0xa441_e712,
|
||||
0x754f,
|
||||
0x43ca,
|
||||
[0x84, 0xa7, 0x0d, 0xee, 0x44, 0xcf, 0x60, 0x6d],
|
||||
);
|
||||
|
||||
type Socket = usize;
|
||||
type Handle = *mut c_void;
|
||||
|
||||
fn once(what: &'static str, destination: String) {
|
||||
let own = ["COMPUTERNAME", "USERDOMAIN"]
|
||||
.iter()
|
||||
.filter_map(|name| std::env::var(name).ok())
|
||||
.any(|name| name.eq_ignore_ascii_case(&destination));
|
||||
let destination = if own { "<pc>".to_owned() } else { destination };
|
||||
static SEEN: Mutex<Vec<(&str, String)>> = Mutex::new(Vec::new());
|
||||
let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if !seen.iter().any(|(w, d)| *w == what && *d == destination) {
|
||||
tracing::info!(%destination, "{what}");
|
||||
seen.push((what, destination));
|
||||
}
|
||||
}
|
||||
|
||||
fn wsa_error(code: i32) {
|
||||
host!("ws2_32.dll", "WSASetLastError": extern "system" fn(i32))(code);
|
||||
}
|
||||
|
||||
fn narrow(text: *const c_char) -> Option<String> {
|
||||
(!text.is_null()).then(|| {
|
||||
|
||||
unsafe { CStr::from_ptr(text) }
|
||||
.to_string_lossy()
|
||||
.into_owned()
|
||||
})
|
||||
}
|
||||
|
||||
fn wide(text: *const u16) -> Option<String> {
|
||||
|
||||
(!text.is_null()).then(|| unsafe {
|
||||
let len = (0..).take_while(|&i| *text.add(i) != 0).count();
|
||||
String::from_utf16_lossy(std::slice::from_raw_parts(text, len))
|
||||
})
|
||||
}
|
||||
|
||||
fn socket_addr(addr: *const u8, len: i32) -> Option<SocketAddr> {
|
||||
let len = usize::try_from(len).ok()?;
|
||||
if addr.is_null() || len < 4 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let b = unsafe { std::slice::from_raw_parts(addr, len) };
|
||||
let port = u16::from_be_bytes([b[2], b[3]]);
|
||||
match u16::from_le_bytes([b[0], b[1]]) {
|
||||
AF_INET if len >= 16 => Some((<[u8; 4]>::try_from(&b[4..8]).ok()?, port).into()),
|
||||
AF_INET6 if len >= 28 => Some((<[u8; 16]>::try_from(&b[8..24]).ok()?, port).into()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn raw_ip(addr: *const c_char, len: i32, kind: i32) -> Option<IpAddr> {
|
||||
let len = usize::try_from(len).ok()?;
|
||||
if addr.is_null() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let b = unsafe { std::slice::from_raw_parts(addr.cast::<u8>(), len) };
|
||||
match (u16::try_from(kind).ok()?, len) {
|
||||
(AF_INET, 4..) => Some(<[u8; 4]>::try_from(&b[..4]).ok()?.into()),
|
||||
(AF_INET6, 16..) => Some(<[u8; 16]>::try_from(&b[..16]).ok()?.into()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn loopback(ip: IpAddr) -> bool {
|
||||
ip.to_canonical().is_loopback()
|
||||
}
|
||||
|
||||
fn loopback_name(name: &str) -> bool {
|
||||
let bare = name.trim_start_matches('[').trim_end_matches(']');
|
||||
bare.eq_ignore_ascii_case("localhost") || bare.parse().is_ok_and(loopback)
|
||||
}
|
||||
|
||||
fn shown(addr: Option<impl ToString>) -> String {
|
||||
addr.map_or_else(|| "not an IP address".into(), |a| a.to_string())
|
||||
}
|
||||
|
||||
fn reachable(what: &'static str, addr: *const u8, len: i32) -> bool {
|
||||
match socket_addr(addr, len) {
|
||||
Some(a) if loopback(a.ip()) => true,
|
||||
a => {
|
||||
once(what, shown(a));
|
||||
wsa_error(WSAENETUNREACH);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn reachable_name(name: Option<String>) -> bool {
|
||||
match name {
|
||||
Some(name) if !loopback_name(&name) => {
|
||||
let literal = name.parse::<IpAddr>().is_ok();
|
||||
once("network connect blocked", name);
|
||||
wsa_error(if literal {
|
||||
WSAENETUNREACH
|
||||
} else {
|
||||
WSAHOST_NOT_FOUND
|
||||
});
|
||||
false
|
||||
}
|
||||
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
fn resolvable(name: Option<String>) -> bool {
|
||||
match name {
|
||||
Some(name)
|
||||
if !(name.is_empty()
|
||||
|| name.eq_ignore_ascii_case("localhost")
|
||||
|| name.parse::<IpAddr>().is_ok()) =>
|
||||
{
|
||||
once("network name lookup blocked", name);
|
||||
wsa_error(WSAHOST_NOT_FOUND);
|
||||
false
|
||||
}
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
fn reverse_resolvable(ip: Option<IpAddr>) -> bool {
|
||||
match ip {
|
||||
Some(ip) if loopback(ip) => true,
|
||||
ip => {
|
||||
once("network reverse lookup blocked", shown(ip));
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn name_info_flags(sa: *const u8, len: i32, host_wanted: bool, flags: i32) -> Option<i32> {
|
||||
if !host_wanted
|
||||
|| flags & NI_NUMERICHOST != 0
|
||||
|| reverse_resolvable(socket_addr(sa, len).map(|a| a.ip()))
|
||||
{
|
||||
Some(flags)
|
||||
} else if flags & NI_NAMEREQD != 0 {
|
||||
wsa_error(WSAHOST_NOT_FOUND);
|
||||
None
|
||||
} else {
|
||||
Some(flags | NI_NUMERICHOST)
|
||||
}
|
||||
}
|
||||
|
||||
pub extern "system" fn connect(s: Socket, name: *const u8, len: i32) -> i32 {
|
||||
if !reachable("network connect blocked", name, len) {
|
||||
return SOCKET_ERROR;
|
||||
}
|
||||
host!("ws2_32.dll", "connect": extern "system" fn(Socket, *const u8, i32) -> i32)(s, name, len)
|
||||
}
|
||||
|
||||
pub extern "system" fn WSAConnect(
|
||||
s: Socket,
|
||||
name: *const u8,
|
||||
len: i32,
|
||||
caller_data: *const c_void,
|
||||
callee_data: *mut c_void,
|
||||
sqos: *const c_void,
|
||||
gqos: *const c_void,
|
||||
) -> i32 {
|
||||
if !reachable("network connect blocked", name, len) {
|
||||
return SOCKET_ERROR;
|
||||
}
|
||||
host!("ws2_32.dll", "WSAConnect": extern "system" fn(Socket, *const u8, i32, *const c_void, *mut c_void, *const c_void, *const c_void) -> i32)(
|
||||
s,
|
||||
name,
|
||||
len,
|
||||
caller_data,
|
||||
callee_data,
|
||||
sqos,
|
||||
gqos,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn WSAConnectByNameA(
|
||||
s: Socket,
|
||||
node: *const c_char,
|
||||
service: *const c_char,
|
||||
local_len: *mut u32,
|
||||
local: *mut c_void,
|
||||
remote_len: *mut u32,
|
||||
remote: *mut c_void,
|
||||
timeout: *const c_void,
|
||||
reserved: *mut c_void,
|
||||
) -> i32 {
|
||||
if !reachable_name(narrow(node)) {
|
||||
return 0;
|
||||
}
|
||||
host!("ws2_32.dll", "WSAConnectByNameA": extern "system" fn(Socket, *const c_char, *const c_char, *mut u32, *mut c_void, *mut u32, *mut c_void, *const c_void, *mut c_void) -> i32)(
|
||||
s, node, service, local_len, local, remote_len, remote, timeout, reserved,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn WSAConnectByNameW(
|
||||
s: Socket,
|
||||
node: *const u16,
|
||||
service: *const u16,
|
||||
local_len: *mut u32,
|
||||
local: *mut c_void,
|
||||
remote_len: *mut u32,
|
||||
remote: *mut c_void,
|
||||
timeout: *const c_void,
|
||||
reserved: *mut c_void,
|
||||
) -> i32 {
|
||||
if !reachable_name(wide(node)) {
|
||||
return 0;
|
||||
}
|
||||
host!("ws2_32.dll", "WSAConnectByNameW": extern "system" fn(Socket, *const u16, *const u16, *mut u32, *mut c_void, *mut u32, *mut c_void, *const c_void, *mut c_void) -> i32)(
|
||||
s, node, service, local_len, local, remote_len, remote, timeout, reserved,
|
||||
)
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct SocketAddress {
|
||||
addr: *const u8,
|
||||
len: i32,
|
||||
}
|
||||
|
||||
pub extern "system" fn WSAConnectByList(
|
||||
s: Socket,
|
||||
list: *const u8,
|
||||
local_len: *mut u32,
|
||||
local: *mut c_void,
|
||||
remote_len: *mut u32,
|
||||
remote: *mut c_void,
|
||||
timeout: *const c_void,
|
||||
reserved: *mut c_void,
|
||||
) -> i32 {
|
||||
if !list.is_null() {
|
||||
|
||||
let entries = unsafe {
|
||||
let count = usize::try_from(list.cast::<i32>().read()).unwrap_or(0);
|
||||
std::slice::from_raw_parts(list.add(8).cast::<SocketAddress>(), count)
|
||||
};
|
||||
if !entries
|
||||
.iter()
|
||||
.all(|e| reachable("network connect blocked", e.addr, e.len))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
host!("ws2_32.dll", "WSAConnectByList": extern "system" fn(Socket, *const u8, *mut u32, *mut c_void, *mut u32, *mut c_void, *const c_void, *mut c_void) -> i32)(
|
||||
s, list, local_len, local, remote_len, remote, timeout, reserved,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn WSAJoinLeaf(
|
||||
s: Socket,
|
||||
name: *const u8,
|
||||
len: i32,
|
||||
caller_data: *const c_void,
|
||||
callee_data: *mut c_void,
|
||||
sqos: *const c_void,
|
||||
gqos: *const c_void,
|
||||
flags: u32,
|
||||
) -> Socket {
|
||||
if !reachable("network connect blocked", name, len) {
|
||||
return INVALID_SOCKET;
|
||||
}
|
||||
host!("ws2_32.dll", "WSAJoinLeaf": extern "system" fn(Socket, *const u8, i32, *const c_void, *mut c_void, *const c_void, *const c_void, u32) -> Socket)(
|
||||
s,
|
||||
name,
|
||||
len,
|
||||
caller_data,
|
||||
callee_data,
|
||||
sqos,
|
||||
gqos,
|
||||
flags,
|
||||
)
|
||||
}
|
||||
|
||||
extern "system" fn connect_ex(
|
||||
s: Socket,
|
||||
name: *const u8,
|
||||
len: i32,
|
||||
send: *const c_void,
|
||||
send_len: u32,
|
||||
sent: *mut u32,
|
||||
overlapped: *mut c_void,
|
||||
) -> i32 {
|
||||
if !reachable("network connect blocked", name, len) {
|
||||
return 0;
|
||||
}
|
||||
let (mut real, mut size) = (0usize, 0u32);
|
||||
let ioctl = host!("ws2_32.dll", "WSAIoctl": extern "system" fn(Socket, u32, *const c_void, u32, *mut c_void, u32, *mut u32, *mut c_void, *const c_void) -> i32);
|
||||
let guid = WSAID_CONNECTEX;
|
||||
let found = ioctl(
|
||||
s,
|
||||
SIO_GET_EXTENSION_FUNCTION_POINTER,
|
||||
(&raw const guid).cast(),
|
||||
16,
|
||||
(&raw mut real).cast(),
|
||||
8,
|
||||
&mut size,
|
||||
std::ptr::null_mut(),
|
||||
std::ptr::null(),
|
||||
);
|
||||
if found != 0 {
|
||||
|
||||
return 0;
|
||||
}
|
||||
if real == 0 {
|
||||
|
||||
const WSAEINVAL: i32 = 10022;
|
||||
wsa_error(WSAEINVAL);
|
||||
return 0;
|
||||
}
|
||||
|
||||
let real = unsafe {
|
||||
std::mem::transmute::<
|
||||
usize,
|
||||
extern "system" fn(
|
||||
Socket,
|
||||
*const u8,
|
||||
i32,
|
||||
*const c_void,
|
||||
u32,
|
||||
*mut u32,
|
||||
*mut c_void,
|
||||
) -> i32,
|
||||
>(real)
|
||||
};
|
||||
real(s, name, len, send, send_len, sent, overlapped)
|
||||
}
|
||||
|
||||
pub extern "system" fn WSAIoctl(
|
||||
s: Socket,
|
||||
code: u32,
|
||||
input: *const c_void,
|
||||
input_len: u32,
|
||||
output: *mut c_void,
|
||||
output_len: u32,
|
||||
returned: *mut u32,
|
||||
overlapped: *mut c_void,
|
||||
completion: *const c_void,
|
||||
) -> i32 {
|
||||
if code == SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER {
|
||||
wsa_error(WSAEINVAL);
|
||||
return SOCKET_ERROR;
|
||||
}
|
||||
let result = host!("ws2_32.dll", "WSAIoctl": extern "system" fn(Socket, u32, *const c_void, u32, *mut c_void, u32, *mut u32, *mut c_void, *const c_void) -> i32)(
|
||||
s, code, input, input_len, output, output_len, returned, overlapped, completion,
|
||||
);
|
||||
if result == 0 && code == SIO_GET_EXTENSION_FUNCTION_POINTER && input_len >= 16 {
|
||||
|
||||
unsafe {
|
||||
let ours = match input.cast::<Guid>().read_unaligned() {
|
||||
WSAID_CONNECTEX => connect_ex as *const () as usize,
|
||||
WSAID_WSASENDMSG => WSASendMsg as *const () as usize,
|
||||
_ => return result,
|
||||
};
|
||||
output.cast::<usize>().write_unaligned(ours);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub extern "system" fn sendto(
|
||||
s: Socket,
|
||||
buf: *const u8,
|
||||
len: i32,
|
||||
flags: i32,
|
||||
to: *const u8,
|
||||
to_len: i32,
|
||||
) -> i32 {
|
||||
if !to.is_null() && !stream(s) && !reachable("network datagram blocked", to, to_len) {
|
||||
return SOCKET_ERROR;
|
||||
}
|
||||
host!("ws2_32.dll", "sendto": extern "system" fn(Socket, *const u8, i32, i32, *const u8, i32) -> i32)(
|
||||
s, buf, len, flags, to, to_len,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn WSASendTo(
|
||||
s: Socket,
|
||||
buffers: *const c_void,
|
||||
count: u32,
|
||||
sent: *mut u32,
|
||||
flags: u32,
|
||||
to: *const u8,
|
||||
to_len: i32,
|
||||
overlapped: *mut c_void,
|
||||
completion: *const c_void,
|
||||
) -> i32 {
|
||||
if !to.is_null() && !stream(s) && !reachable("network datagram blocked", to, to_len) {
|
||||
return SOCKET_ERROR;
|
||||
}
|
||||
host!("ws2_32.dll", "WSASendTo": extern "system" fn(Socket, *const c_void, u32, *mut u32, u32, *const u8, i32, *mut c_void, *const c_void) -> i32)(
|
||||
s, buffers, count, sent, flags, to, to_len, overlapped, completion,
|
||||
)
|
||||
}
|
||||
|
||||
fn stream(s: Socket) -> bool {
|
||||
const SOL_SOCKET: i32 = 0xffff;
|
||||
const SO_TYPE: i32 = 0x1008;
|
||||
const SOCK_STREAM: i32 = 1;
|
||||
let (mut kind, mut len) = (0i32, 4i32);
|
||||
let getsockopt = host!("ws2_32.dll", "getsockopt": extern "system" fn(Socket, i32, i32, *mut i32, *mut i32) -> i32);
|
||||
getsockopt(s, SOL_SOCKET, SO_TYPE, &mut kind, &mut len) == 0 && kind == SOCK_STREAM
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct MessageName {
|
||||
name: *const u8,
|
||||
len: i32,
|
||||
}
|
||||
|
||||
pub extern "system" fn WSASendMsg(
|
||||
s: Socket,
|
||||
message: *const c_void,
|
||||
flags: u32,
|
||||
sent: *mut u32,
|
||||
overlapped: *mut c_void,
|
||||
completion: *const c_void,
|
||||
) -> i32 {
|
||||
|
||||
if let Some(m) = unsafe { message.cast::<MessageName>().as_ref() }
|
||||
&& !m.name.is_null()
|
||||
&& !reachable("network datagram blocked", m.name, m.len)
|
||||
{
|
||||
return SOCKET_ERROR;
|
||||
}
|
||||
host!("ws2_32.dll", "WSASendMsg": extern "system" fn(Socket, *const c_void, u32, *mut u32, *mut c_void, *const c_void) -> i32)(
|
||||
s, message, flags, sent, overlapped, completion,
|
||||
)
|
||||
}
|
||||
|
||||
fn dual_stack(s: Socket) -> bool {
|
||||
const IPPROTO_IPV6: i32 = 41;
|
||||
const IPV6_V6ONLY: i32 = 27;
|
||||
let get = host!("ws2_32.dll", "getsockopt": extern "system" fn(Socket, i32, i32, *mut u8, *mut i32) -> i32);
|
||||
let (mut only, mut size) = (1u32, 4i32);
|
||||
get(s, IPPROTO_IPV6, IPV6_V6ONLY, (&raw mut only).cast(), &mut size) == 0 && only == 0
|
||||
}
|
||||
|
||||
pub extern "system" fn bind(s: Socket, name: *const u8, len: i32) -> i32 {
|
||||
let host_bind = host!("ws2_32.dll", "bind": extern "system" fn(Socket, *const u8, i32) -> i32);
|
||||
match socket_addr(name, len) {
|
||||
Some(a) if loopback(a.ip()) => host_bind(s, name, len),
|
||||
Some(a) if a.ip().is_unspecified() => {
|
||||
once("network bind narrowed to loopback", a.to_string());
|
||||
|
||||
let mut local = unsafe { std::slice::from_raw_parts(name, len as usize) }.to_vec();
|
||||
match a {
|
||||
SocketAddr::V4(_) => local[4..8].copy_from_slice(&[127, 0, 0, 1]),
|
||||
|
||||
SocketAddr::V6(_) if dual_stack(s) => {
|
||||
local[8..24].copy_from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 127, 0, 0, 1]);
|
||||
}
|
||||
SocketAddr::V6(_) => local[23] = 1,
|
||||
}
|
||||
host_bind(s, local.as_ptr(), len)
|
||||
}
|
||||
a => {
|
||||
once("network bind blocked", shown(a));
|
||||
wsa_error(WSAEADDRNOTAVAIL);
|
||||
SOCKET_ERROR
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn blocked_lookup(result: *mut *mut c_void) -> i32 {
|
||||
if !result.is_null() {
|
||||
|
||||
unsafe { result.write(std::ptr::null_mut()) };
|
||||
}
|
||||
WSAHOST_NOT_FOUND
|
||||
}
|
||||
|
||||
pub extern "system" fn getaddrinfo(
|
||||
node: *const c_char,
|
||||
service: *const c_char,
|
||||
hints: *const c_void,
|
||||
result: *mut *mut c_void,
|
||||
) -> i32 {
|
||||
if !resolvable(narrow(node)) {
|
||||
return blocked_lookup(result);
|
||||
}
|
||||
host!("ws2_32.dll", "getaddrinfo": extern "system" fn(*const c_char, *const c_char, *const c_void, *mut *mut c_void) -> i32)(
|
||||
node, service, hints, result,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn GetAddrInfoW(
|
||||
node: *const u16,
|
||||
service: *const u16,
|
||||
hints: *const c_void,
|
||||
result: *mut *mut c_void,
|
||||
) -> i32 {
|
||||
if !resolvable(wide(node)) {
|
||||
return blocked_lookup(result);
|
||||
}
|
||||
host!("ws2_32.dll", "GetAddrInfoW": extern "system" fn(*const u16, *const u16, *const c_void, *mut *mut c_void) -> i32)(
|
||||
node, service, hints, result,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn GetAddrInfoExA(
|
||||
name: *const c_char,
|
||||
service: *const c_char,
|
||||
namespace: u32,
|
||||
provider: *const c_void,
|
||||
hints: *const c_void,
|
||||
result: *mut *mut c_void,
|
||||
timeout: *const c_void,
|
||||
overlapped: *mut c_void,
|
||||
completion: *const c_void,
|
||||
handle: *mut Handle,
|
||||
) -> i32 {
|
||||
if !resolvable(narrow(name)) {
|
||||
return blocked_lookup(result);
|
||||
}
|
||||
host!("ws2_32.dll", "GetAddrInfoExA": extern "system" fn(*const c_char, *const c_char, u32, *const c_void, *const c_void, *mut *mut c_void, *const c_void, *mut c_void, *const c_void, *mut Handle) -> i32)(
|
||||
name, service, namespace, provider, hints, result, timeout, overlapped, completion, handle,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn GetAddrInfoExW(
|
||||
name: *const u16,
|
||||
service: *const u16,
|
||||
namespace: u32,
|
||||
provider: *const c_void,
|
||||
hints: *const c_void,
|
||||
result: *mut *mut c_void,
|
||||
timeout: *const c_void,
|
||||
overlapped: *mut c_void,
|
||||
completion: *const c_void,
|
||||
handle: *mut Handle,
|
||||
) -> i32 {
|
||||
if !resolvable(wide(name)) {
|
||||
return blocked_lookup(result);
|
||||
}
|
||||
host!("ws2_32.dll", "GetAddrInfoExW": extern "system" fn(*const u16, *const u16, u32, *const c_void, *const c_void, *mut *mut c_void, *const c_void, *mut c_void, *const c_void, *mut Handle) -> i32)(
|
||||
name, service, namespace, provider, hints, result, timeout, overlapped, completion, handle,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn gethostbyname(name: *const c_char) -> *mut c_void {
|
||||
if !resolvable(narrow(name)) {
|
||||
return std::ptr::null_mut();
|
||||
}
|
||||
host!("ws2_32.dll", "gethostbyname": extern "system" fn(*const c_char) -> *mut c_void)(name)
|
||||
}
|
||||
|
||||
pub extern "system" fn WSAAsyncGetHostByName(
|
||||
window: Handle,
|
||||
message: u32,
|
||||
name: *const c_char,
|
||||
buf: *mut c_char,
|
||||
buf_len: i32,
|
||||
) -> Handle {
|
||||
if !resolvable(narrow(name)) {
|
||||
return std::ptr::null_mut();
|
||||
}
|
||||
host!("ws2_32.dll", "WSAAsyncGetHostByName": extern "system" fn(Handle, u32, *const c_char, *mut c_char, i32) -> Handle)(
|
||||
window, message, name, buf, buf_len,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn WSALookupServiceBeginA(
|
||||
_restrictions: *const c_void,
|
||||
_flags: u32,
|
||||
_lookup: *mut Handle,
|
||||
) -> i32 {
|
||||
once("network name-space query blocked", "any".into());
|
||||
wsa_error(WSASERVICE_NOT_FOUND);
|
||||
SOCKET_ERROR
|
||||
}
|
||||
|
||||
pub extern "system" fn WSALookupServiceBeginW(
|
||||
restrictions: *const c_void,
|
||||
flags: u32,
|
||||
lookup: *mut Handle,
|
||||
) -> i32 {
|
||||
WSALookupServiceBeginA(restrictions, flags, lookup)
|
||||
}
|
||||
|
||||
pub extern "system" fn gethostbyaddr(addr: *const c_char, len: i32, kind: i32) -> *mut c_void {
|
||||
if !reverse_resolvable(raw_ip(addr, len, kind)) {
|
||||
wsa_error(WSAHOST_NOT_FOUND);
|
||||
return std::ptr::null_mut();
|
||||
}
|
||||
host!("ws2_32.dll", "gethostbyaddr": extern "system" fn(*const c_char, i32, i32) -> *mut c_void)(
|
||||
addr, len, kind,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn WSAAsyncGetHostByAddr(
|
||||
window: Handle,
|
||||
message: u32,
|
||||
addr: *const c_char,
|
||||
len: i32,
|
||||
kind: i32,
|
||||
buf: *mut c_char,
|
||||
buf_len: i32,
|
||||
) -> Handle {
|
||||
if !reverse_resolvable(raw_ip(addr, len, kind)) {
|
||||
wsa_error(WSAHOST_NOT_FOUND);
|
||||
return std::ptr::null_mut();
|
||||
}
|
||||
host!("ws2_32.dll", "WSAAsyncGetHostByAddr": extern "system" fn(Handle, u32, *const c_char, i32, i32, *mut c_char, i32) -> Handle)(
|
||||
window, message, addr, len, kind, buf, buf_len,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn getnameinfo(
|
||||
sa: *const u8,
|
||||
sa_len: i32,
|
||||
host: *mut c_char,
|
||||
host_len: u32,
|
||||
serv: *mut c_char,
|
||||
serv_len: u32,
|
||||
flags: i32,
|
||||
) -> i32 {
|
||||
let Some(flags) = name_info_flags(sa, sa_len, !host.is_null(), flags) else {
|
||||
return WSAHOST_NOT_FOUND;
|
||||
};
|
||||
host!("ws2_32.dll", "getnameinfo": extern "system" fn(*const u8, i32, *mut c_char, u32, *mut c_char, u32, i32) -> i32)(
|
||||
sa, sa_len, host, host_len, serv, serv_len, flags,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn GetNameInfoW(
|
||||
sa: *const u8,
|
||||
sa_len: i32,
|
||||
host: *mut u16,
|
||||
host_len: u32,
|
||||
serv: *mut u16,
|
||||
serv_len: u32,
|
||||
flags: i32,
|
||||
) -> i32 {
|
||||
let Some(flags) = name_info_flags(sa, sa_len, !host.is_null(), flags) else {
|
||||
return WSAHOST_NOT_FOUND;
|
||||
};
|
||||
host!("ws2_32.dll", "GetNameInfoW": extern "system" fn(*const u8, i32, *mut u16, u32, *mut u16, u32, i32) -> i32)(
|
||||
sa, sa_len, host, host_len, serv, serv_len, flags,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn WinHttpConnect(
|
||||
session: Handle,
|
||||
server: *const u16,
|
||||
port: u16,
|
||||
reserved: u32,
|
||||
) -> Handle {
|
||||
if let Some(name) = wide(server)
|
||||
&& !loopback_name(&name)
|
||||
{
|
||||
once("HTTP connection blocked", format!("{name}:{port}"));
|
||||
|
||||
unsafe { SetLastError(ERROR_WINHTTP_CANNOT_CONNECT) };
|
||||
return std::ptr::null_mut();
|
||||
}
|
||||
host!("winhttp.dll", "WinHttpConnect": extern "system" fn(Handle, *const u16, u16, u32) -> Handle)(
|
||||
session, server, port, reserved,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn WinHttpOpen(
|
||||
agent: *const u16,
|
||||
access: u32,
|
||||
_proxy: *const u16,
|
||||
_bypass: *const u16,
|
||||
flags: u32,
|
||||
) -> Handle {
|
||||
if access != WINHTTP_ACCESS_TYPE_NO_PROXY {
|
||||
once("HTTP proxy ignored", format!("access type {access}"));
|
||||
}
|
||||
host!("winhttp.dll", "WinHttpOpen": extern "system" fn(*const u16, u32, *const u16, *const u16, u32) -> Handle)(
|
||||
agent,
|
||||
WINHTTP_ACCESS_TYPE_NO_PROXY,
|
||||
std::ptr::null(),
|
||||
std::ptr::null(),
|
||||
flags,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn WinHttpSetOption(
|
||||
handle: Handle,
|
||||
option: u32,
|
||||
buffer: *const c_void,
|
||||
len: u32,
|
||||
) -> i32 {
|
||||
if option == WINHTTP_OPTION_PROXY {
|
||||
once("HTTP proxy ignored", "WINHTTP_OPTION_PROXY".into());
|
||||
return 1;
|
||||
}
|
||||
host!("winhttp.dll", "WinHttpSetOption": extern "system" fn(Handle, u32, *const c_void, u32) -> i32)(
|
||||
handle, option, buffer, len,
|
||||
)
|
||||
}
|
||||
|
||||
fn no_auto_proxy() -> u32 {
|
||||
once("HTTP proxy auto-detection blocked", "WPAD/PAC".into());
|
||||
ERROR_WINHTTP_AUTODETECTION_FAILED
|
||||
}
|
||||
|
||||
pub extern "system" fn WinHttpDetectAutoProxyConfigUrl(_flags: u32, _url: *mut *mut u16) -> i32 {
|
||||
|
||||
unsafe { SetLastError(no_auto_proxy()) };
|
||||
0
|
||||
}
|
||||
|
||||
pub extern "system" fn WinHttpGetProxyForUrl(
|
||||
_session: Handle,
|
||||
_url: *const u16,
|
||||
_options: *const c_void,
|
||||
_info: *mut c_void,
|
||||
) -> i32 {
|
||||
|
||||
unsafe { SetLastError(no_auto_proxy()) };
|
||||
0
|
||||
}
|
||||
|
||||
pub extern "system" fn WinHttpGetProxyForUrlEx(
|
||||
_resolver: Handle,
|
||||
_url: *const u16,
|
||||
_options: *const c_void,
|
||||
_context: usize,
|
||||
) -> u32 {
|
||||
no_auto_proxy()
|
||||
}
|
||||
|
||||
pub extern "system" fn WinHttpGetProxyForUrlEx2(
|
||||
_resolver: Handle,
|
||||
_url: *const u16,
|
||||
_options: *const c_void,
|
||||
_selection_len: u32,
|
||||
_selection: *const u8,
|
||||
_context: usize,
|
||||
) -> u32 {
|
||||
no_auto_proxy()
|
||||
}
|
||||
|
||||
pub extern "system" fn WinHttpGetProxySettingsEx(
|
||||
_resolver: Handle,
|
||||
_kind: i32,
|
||||
_params: *const c_void,
|
||||
_context: usize,
|
||||
) -> u32 {
|
||||
no_auto_proxy()
|
||||
}
|
||||
|
||||
fn ordinal(name: &'static str, f: usize) -> HleExport {
|
||||
HleExport { name, address: f }
|
||||
}
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "net",
|
||||
dlls: &["ws2_32.dll", "winhttp.dll"],
|
||||
exports: vec![
|
||||
hle_export!(connect),
|
||||
hle_export!(WSAConnect),
|
||||
hle_export!(WSAConnectByNameA),
|
||||
hle_export!(WSAConnectByNameW),
|
||||
hle_export!(WSAConnectByList),
|
||||
hle_export!(WSAJoinLeaf),
|
||||
hle_export!(WSAIoctl),
|
||||
hle_export!(sendto),
|
||||
hle_export!(WSASendTo),
|
||||
hle_export!(WSASendMsg),
|
||||
hle_export!(bind),
|
||||
hle_export!(getaddrinfo),
|
||||
hle_export!(GetAddrInfoW),
|
||||
hle_export!(GetAddrInfoExA),
|
||||
hle_export!(GetAddrInfoExW),
|
||||
hle_export!(gethostbyname),
|
||||
hle_export!(WSAAsyncGetHostByName),
|
||||
hle_export!(WSALookupServiceBeginA),
|
||||
hle_export!(WSALookupServiceBeginW),
|
||||
hle_export!(gethostbyaddr),
|
||||
hle_export!(WSAAsyncGetHostByAddr),
|
||||
hle_export!(getnameinfo),
|
||||
hle_export!(GetNameInfoW),
|
||||
hle_export!(WinHttpConnect),
|
||||
hle_export!(WinHttpOpen),
|
||||
hle_export!(WinHttpSetOption),
|
||||
hle_export!(WinHttpDetectAutoProxyConfigUrl),
|
||||
hle_export!(WinHttpGetProxyForUrl),
|
||||
hle_export!(WinHttpGetProxyForUrlEx),
|
||||
hle_export!(WinHttpGetProxyForUrlEx2),
|
||||
hle_export!(WinHttpGetProxySettingsEx),
|
||||
ordinal("#2", bind as *const () as usize),
|
||||
ordinal("#4", connect as *const () as usize),
|
||||
ordinal("#20", sendto as *const () as usize),
|
||||
ordinal("#51", gethostbyaddr as *const () as usize),
|
||||
ordinal("#52", gethostbyname as *const () as usize),
|
||||
ordinal("#102", WSAAsyncGetHostByAddr as *const () as usize),
|
||||
ordinal("#103", WSAAsyncGetHostByName as *const () as usize),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
|
||||
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::{c_char, c_void};
|
||||
|
||||
use super::xgameruntime::Guid;
|
||||
|
||||
const OK: i32 = 0;
|
||||
|
||||
const INVALID_STRING_UUID: i32 = 1705;
|
||||
|
||||
const OUT_OF_MEMORY: i32 = 14;
|
||||
|
||||
extern "system" fn UuidCreate(uuid: *mut Guid) -> i32 {
|
||||
create(uuid, false)
|
||||
}
|
||||
|
||||
extern "system" fn UuidCreateSequential(uuid: *mut Guid) -> i32 {
|
||||
create(uuid, true)
|
||||
}
|
||||
|
||||
fn create(uuid: *mut Guid, _sequential: bool) -> i32 {
|
||||
if uuid.is_null() {
|
||||
return INVALID_STRING_UUID;
|
||||
}
|
||||
let mut bytes = [0u8; 16];
|
||||
if !random(&mut bytes) {
|
||||
return OUT_OF_MEMORY;
|
||||
}
|
||||
|
||||
bytes[7] = (bytes[7] & 0x0f) | 0x40;
|
||||
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
||||
|
||||
unsafe { uuid.write(from_bytes(bytes)) };
|
||||
OK
|
||||
}
|
||||
|
||||
fn random(bytes: &mut [u8; 16]) -> bool {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use windows_sys::Win32::Security::Cryptography::{
|
||||
BCRYPT_USE_SYSTEM_PREFERRED_RNG, BCryptGenRandom,
|
||||
};
|
||||
|
||||
let status = unsafe {
|
||||
BCryptGenRandom(
|
||||
std::ptr::null_mut(),
|
||||
bytes.as_mut_ptr(),
|
||||
bytes.len() as u32,
|
||||
BCRYPT_USE_SYSTEM_PREFERRED_RNG,
|
||||
)
|
||||
};
|
||||
status >= 0
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static N: AtomicU64 = AtomicU64::new(0);
|
||||
let n = N.fetch_add(1, Ordering::Relaxed)
|
||||
^ std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_nanos() as u64);
|
||||
for (i, b) in bytes.iter_mut().enumerate() {
|
||||
*b = (n >> (8 * (i % 8))) as u8 ^ (i as u8).wrapping_mul(31);
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
extern "system" fn UuidFromStringA(text: *const c_char, uuid: *mut Guid) -> i32 {
|
||||
if text.is_null() || uuid.is_null() {
|
||||
return INVALID_STRING_UUID;
|
||||
}
|
||||
|
||||
let bytes = unsafe { std::ffi::CStr::from_ptr(text.cast()) }.to_bytes();
|
||||
match parse(bytes.iter().copied()) {
|
||||
|
||||
Some(g) => unsafe {
|
||||
uuid.write(g);
|
||||
OK
|
||||
},
|
||||
None => INVALID_STRING_UUID,
|
||||
}
|
||||
}
|
||||
|
||||
extern "system" fn UuidFromStringW(text: *const u16, uuid: *mut Guid) -> i32 {
|
||||
if text.is_null() || uuid.is_null() {
|
||||
return INVALID_STRING_UUID;
|
||||
}
|
||||
let mut units = Vec::new();
|
||||
|
||||
unsafe {
|
||||
let mut at = text;
|
||||
while *at != 0 {
|
||||
units.push(*at);
|
||||
at = at.add(1);
|
||||
}
|
||||
}
|
||||
match parse(units.into_iter().map(|u| u as u32)) {
|
||||
|
||||
Some(g) => unsafe {
|
||||
uuid.write(g);
|
||||
OK
|
||||
},
|
||||
None => INVALID_STRING_UUID,
|
||||
}
|
||||
}
|
||||
|
||||
extern "system" fn UuidToStringA(uuid: *const Guid, out: *mut *mut c_char) -> i32 {
|
||||
|
||||
let Some(g) = (unsafe { uuid.as_ref() }) else {
|
||||
return INVALID_STRING_UUID;
|
||||
};
|
||||
if out.is_null() {
|
||||
return INVALID_STRING_UUID;
|
||||
}
|
||||
let text = format(g);
|
||||
let mut bytes = Vec::with_capacity(37);
|
||||
bytes.extend_from_slice(&text);
|
||||
bytes.push(0);
|
||||
|
||||
unsafe { out.write(allocate(&bytes).cast()) };
|
||||
OK
|
||||
}
|
||||
|
||||
extern "system" fn UuidToStringW(uuid: *const Guid, out: *mut *mut u16) -> i32 {
|
||||
|
||||
let Some(g) = (unsafe { uuid.as_ref() }) else {
|
||||
return INVALID_STRING_UUID;
|
||||
};
|
||||
if out.is_null() {
|
||||
return INVALID_STRING_UUID;
|
||||
}
|
||||
let text = format(g);
|
||||
let mut units: Vec<u16> = text.iter().map(|&b| u16::from(b)).collect();
|
||||
units.push(0);
|
||||
let bytes: Vec<u8> = units.iter().flat_map(|u| u.to_le_bytes()).collect();
|
||||
|
||||
unsafe { out.write(allocate(&bytes).cast()) };
|
||||
OK
|
||||
}
|
||||
|
||||
extern "system" fn RpcStringFreeA(string: *mut *mut c_char) -> i32 {
|
||||
free(string.cast());
|
||||
OK
|
||||
}
|
||||
|
||||
extern "system" fn RpcStringFreeW(string: *mut *mut u16) -> i32 {
|
||||
free(string.cast());
|
||||
OK
|
||||
}
|
||||
|
||||
fn from_bytes(b: [u8; 16]) -> Guid {
|
||||
Guid {
|
||||
data1: u32::from_le_bytes([b[0], b[1], b[2], b[3]]),
|
||||
data2: u16::from_le_bytes([b[4], b[5]]),
|
||||
data3: u16::from_le_bytes([b[6], b[7]]),
|
||||
data4: [b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]],
|
||||
}
|
||||
}
|
||||
|
||||
fn format(g: &Guid) -> [u8; 36] {
|
||||
const HEX: &[u8; 16] = b"0123456789abcdef";
|
||||
let mut text = [b'-'; 36];
|
||||
let pairs = [
|
||||
(0, g.data1 as u64, 8),
|
||||
(9, g.data2 as u64, 4),
|
||||
(14, g.data3 as u64, 4),
|
||||
(19, g.data4[0] as u64, 2),
|
||||
(21, g.data4[1] as u64, 2),
|
||||
(24, g.data4[2] as u64, 2),
|
||||
(26, g.data4[3] as u64, 2),
|
||||
(28, g.data4[4] as u64, 2),
|
||||
(30, g.data4[5] as u64, 2),
|
||||
(32, g.data4[6] as u64, 2),
|
||||
(34, g.data4[7] as u64, 2),
|
||||
];
|
||||
for (at, value, digits) in pairs {
|
||||
for i in 0..digits {
|
||||
let shift = 4 * (digits - 1 - i);
|
||||
text[at + i] = HEX[((value >> shift) & 0xf) as usize];
|
||||
}
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
fn parse(mut chars: impl Iterator<Item = impl Into<u32>>) -> Option<Guid> {
|
||||
let mut digits = [0u8; 32];
|
||||
let mut n = 0;
|
||||
for c in &mut chars {
|
||||
let c = c.into();
|
||||
if n == 32 {
|
||||
|
||||
return (c == u32::from(b'}')).then(|| assemble(&digits));
|
||||
}
|
||||
if c == u32::from(b'-') || (n == 0 && c == u32::from(b'{')) {
|
||||
continue;
|
||||
}
|
||||
let digit = match c {
|
||||
0x30..=0x39 => c - 0x30,
|
||||
0x61..=0x66 => c - 0x61 + 10,
|
||||
0x41..=0x46 => c - 0x41 + 10,
|
||||
_ => return None,
|
||||
};
|
||||
digits[n] = digit as u8;
|
||||
n += 1;
|
||||
}
|
||||
(n == 32).then(|| assemble(&digits))
|
||||
}
|
||||
|
||||
fn assemble(digits: &[u8; 32]) -> Guid {
|
||||
let byte = |i: usize| (digits[2 * i] << 4) | digits[2 * i + 1];
|
||||
|
||||
Guid {
|
||||
data1: u32::from_be_bytes([byte(0), byte(1), byte(2), byte(3)]),
|
||||
data2: u16::from_be_bytes([byte(4), byte(5)]),
|
||||
data3: u16::from_be_bytes([byte(6), byte(7)]),
|
||||
data4: [
|
||||
byte(8),
|
||||
byte(9),
|
||||
byte(10),
|
||||
byte(11),
|
||||
byte(12),
|
||||
byte(13),
|
||||
byte(14),
|
||||
byte(15),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
fn allocate(bytes: &[u8]) -> *mut u8 {
|
||||
let len = 8 + bytes.len();
|
||||
let layout = std::alloc::Layout::from_size_align(len, 8).expect("a small allocation");
|
||||
|
||||
unsafe {
|
||||
let base = std::alloc::alloc(layout);
|
||||
if base.is_null() {
|
||||
return std::ptr::null_mut();
|
||||
}
|
||||
base.cast::<u64>().write_unaligned(bytes.len() as u64);
|
||||
std::ptr::copy_nonoverlapping(bytes.as_ptr(), base.add(8), bytes.len());
|
||||
base.add(8)
|
||||
}
|
||||
}
|
||||
|
||||
fn free(pointer: *mut *mut c_void) {
|
||||
if pointer.is_null() {
|
||||
return;
|
||||
}
|
||||
|
||||
unsafe {
|
||||
let at = pointer.read();
|
||||
if at.is_null() {
|
||||
return;
|
||||
}
|
||||
let base = at.cast::<u8>().sub(8);
|
||||
let len = base.cast::<u64>().read_unaligned() as usize;
|
||||
let layout = std::alloc::Layout::from_size_align(8 + len, 8).expect("a small allocation");
|
||||
std::alloc::dealloc(base, layout);
|
||||
pointer.write(std::ptr::null_mut());
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn module() -> crate::hle::HleModule {
|
||||
crate::hle::HleModule {
|
||||
name: "rpcrt4",
|
||||
dlls: &["rpcrt4.dll"],
|
||||
exports: vec![
|
||||
crate::hle_export!(UuidCreate),
|
||||
crate::hle_export!(UuidCreateSequential),
|
||||
crate::hle_export!(UuidFromStringA),
|
||||
crate::hle_export!(UuidFromStringW),
|
||||
crate::hle_export!(UuidToStringA),
|
||||
crate::hle_export!(UuidToStringW),
|
||||
crate::hle_export!(RpcStringFreeA),
|
||||
crate::hle_export!(RpcStringFreeW),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
|
||||
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::{c_char, c_void};
|
||||
|
||||
use super::xgameruntime::{
|
||||
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text, with_spare,
|
||||
};
|
||||
|
||||
pub const PROVIDER: Guid = Guid::new(
|
||||
0x3e24_1977,
|
||||
0x6237,
|
||||
0x41e9,
|
||||
[0x85, 0x59, 0x10, 0x2c, 0x2d, 0x99, 0x83, 0xf1],
|
||||
);
|
||||
|
||||
pub const IID: Guid = Guid::new(
|
||||
0xd722_b373,
|
||||
0x8c4d,
|
||||
0x4692,
|
||||
[0x9e, 0x51, 0xd6, 0xad, 0x9b, 0x37, 0xaa, 0x7d],
|
||||
);
|
||||
|
||||
pub static OBJECT: Object = Object::new("accessibility", &VTABLE);
|
||||
pub const INTERFACES: &[Interface] = &[(PROVIDER, IID, &OBJECT)];
|
||||
|
||||
const SILENCE: [u8; 44] =
|
||||
*b"RIFF\x24\0\0\0WAVEfmt \x10\0\0\0\x01\0\x01\0\x80\x3e\0\0\0\x7d\0\0\x02\0\x10\0data\0\0\0\0";
|
||||
|
||||
static SYNTHESIZER: u8 = 0;
|
||||
static STREAM: u8 = 0;
|
||||
|
||||
type This = *const Object;
|
||||
|
||||
extern "system" fn enumerate_voices(
|
||||
_: This,
|
||||
_context: *mut c_void,
|
||||
_callback: *const c_void,
|
||||
) -> HRESULT {
|
||||
S_OK
|
||||
}
|
||||
extern "system" fn create(_: This, out: *mut *const u8) -> HRESULT {
|
||||
put(out, &raw const SYNTHESIZER)
|
||||
}
|
||||
extern "system" fn close(_: This, _: *const u8) -> HRESULT {
|
||||
S_OK
|
||||
}
|
||||
extern "system" fn set_default_voice(_: This, _: *const u8) -> HRESULT {
|
||||
S_OK
|
||||
}
|
||||
extern "system" fn set_custom_voice(_: This, _: *const u8, _voice: *const c_char) -> HRESULT {
|
||||
S_OK
|
||||
}
|
||||
extern "system" fn create_stream(
|
||||
_: This,
|
||||
_: *const u8,
|
||||
words: *const c_char,
|
||||
out: *mut *const u8,
|
||||
) -> HRESULT {
|
||||
tracing::debug!(text = text(words).unwrap_or_default(), "speech (silent)");
|
||||
put(out, &raw const STREAM)
|
||||
}
|
||||
extern "system" fn stream_size(_: This, _: *const u8, out: *mut usize) -> HRESULT {
|
||||
put(out, SILENCE.len())
|
||||
}
|
||||
extern "system" fn stream_data(
|
||||
_: This,
|
||||
_: *const u8,
|
||||
size: usize,
|
||||
buffer: *mut u8,
|
||||
used: *mut usize,
|
||||
) -> HRESULT {
|
||||
if buffer.is_null() || size < SILENCE.len() {
|
||||
return super::xasync::E_NOT_SUFFICIENT_BUFFER;
|
||||
}
|
||||
|
||||
unsafe { buffer.copy_from_nonoverlapping(SILENCE.as_ptr(), SILENCE.len()) };
|
||||
if !used.is_null() {
|
||||
|
||||
unsafe { used.write(SILENCE.len()) };
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
static VTABLE: Methods<30> = with_spare([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
missing::<3> as *const (),
|
||||
missing::<4> as *const (),
|
||||
missing::<5> as *const (),
|
||||
missing::<6> as *const (),
|
||||
missing::<7> as *const (),
|
||||
enumerate_voices as *const (),
|
||||
create as *const (),
|
||||
close as *const (),
|
||||
set_default_voice as *const (),
|
||||
set_custom_voice as *const (),
|
||||
create_stream as *const (),
|
||||
close as *const (),
|
||||
stream_size as *const (),
|
||||
stream_data as *const (),
|
||||
missing::<17> as *const (),
|
||||
missing::<18> as *const (),
|
||||
missing::<19> as *const (),
|
||||
missing::<20> as *const (),
|
||||
create_stream as *const (),
|
||||
]);
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
|
||||
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use super::xasync::{self, AsyncBlock, E_ABORT};
|
||||
use super::xgameruntime::{
|
||||
Guid, HRESULT, Interface, Methods, NOT_SUPPORTED, Object, S_OK, add_ref, missing, put,
|
||||
put_string, with_spare,
|
||||
};
|
||||
use crate::hle::runtime;
|
||||
|
||||
pub const PROVIDER: Guid = Guid::new(
|
||||
0xf4fa_f4d4,
|
||||
0x2d04,
|
||||
0x4fce,
|
||||
[0xb3, 0xe0, 0x47, 0x4a, 0x71, 0x3a, 0x3e, 0x84],
|
||||
);
|
||||
pub const IID: Guid = Guid::new(
|
||||
0xd294_11df,
|
||||
0x0794,
|
||||
0x4553,
|
||||
[0x8b, 0x27, 0x95, 0xfc, 0x02, 0xd0, 0xf7, 0x5d],
|
||||
);
|
||||
|
||||
pub const IID_2026: Guid = Guid::new(
|
||||
0x41a4_e10c,
|
||||
0x5a7e,
|
||||
0x41d9,
|
||||
[0x8c, 0x37, 0x37, 0xbd, 0xe6, 0x2a, 0x07, 0xd6],
|
||||
);
|
||||
|
||||
pub static OBJECT: Object = Object::new("persistent local storage", &VTABLE);
|
||||
pub const INTERFACES: &[Interface] = &[(PROVIDER, IID, &OBJECT), (PROVIDER, IID_2026, &OBJECT)];
|
||||
|
||||
const E_FAIL: HRESULT = 0x8000_4005_u32 as i32;
|
||||
|
||||
type This = *const Object;
|
||||
|
||||
fn folder() -> Option<String> {
|
||||
let storage = runtime::title().storage;
|
||||
if storage.as_os_str().is_empty() {
|
||||
return None;
|
||||
}
|
||||
#[cfg(windows)]
|
||||
return super::files::mount(&storage).map(|letter| format!("{letter}:\\"));
|
||||
#[cfg(not(windows))]
|
||||
None
|
||||
}
|
||||
|
||||
extern "system" fn path_size(_: This, out: *mut usize) -> HRESULT {
|
||||
match folder() {
|
||||
Some(path) => put(out, path.len() + 1),
|
||||
None => NOT_SUPPORTED,
|
||||
}
|
||||
}
|
||||
|
||||
extern "system" fn path(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT {
|
||||
match folder() {
|
||||
Some(path) if size <= path.len() => E_FAIL,
|
||||
Some(path) => put_string(&path, size, buffer, used),
|
||||
None => NOT_SUPPORTED,
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct SpaceInfo {
|
||||
|
||||
pub available_free: u64,
|
||||
|
||||
pub total_free: u64,
|
||||
pub used: u64,
|
||||
|
||||
pub total: u64,
|
||||
}
|
||||
|
||||
pub(crate) fn used_bytes(dir: &Path) -> u64 {
|
||||
let mut pending = vec![dir.to_owned()];
|
||||
let mut bytes = 0u64;
|
||||
while let Some(dir) = pending.pop() {
|
||||
let Ok(metadata) = std::fs::symlink_metadata(&dir) else {
|
||||
continue;
|
||||
};
|
||||
if !metadata.is_dir() || metadata.file_type().is_symlink() {
|
||||
continue;
|
||||
}
|
||||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||
continue;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
let Ok(metadata) = std::fs::symlink_metadata(&path) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
if metadata.file_type().is_symlink() {
|
||||
continue;
|
||||
}
|
||||
if metadata.is_dir() {
|
||||
pending.push(path);
|
||||
} else {
|
||||
bytes = bytes.saturating_add(metadata.len());
|
||||
}
|
||||
}
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
pub(crate) fn disk_free(dir: &Path) -> u64 {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
let wide: Vec<u16> = dir.as_os_str().encode_wide().chain([0]).collect();
|
||||
let mut free = 0;
|
||||
let null = std::ptr::null_mut();
|
||||
|
||||
let ok = unsafe {
|
||||
windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW(
|
||||
wide.as_ptr(),
|
||||
&mut free,
|
||||
null,
|
||||
null,
|
||||
)
|
||||
};
|
||||
if ok != 0 {
|
||||
return free;
|
||||
}
|
||||
let error = std::io::Error::last_os_error();
|
||||
static WARNED: std::sync::Once = std::sync::Once::new();
|
||||
WARNED.call_once(|| {
|
||||
tracing::warn!(
|
||||
path = %dir.display(),
|
||||
%error,
|
||||
"could not query free storage space; treating it as unlimited"
|
||||
);
|
||||
});
|
||||
}
|
||||
let _ = dir;
|
||||
u64::MAX
|
||||
}
|
||||
|
||||
fn space() -> SpaceInfo {
|
||||
let title = runtime::title();
|
||||
let used = used_bytes(&title.storage);
|
||||
let free = title.storage_bytes.saturating_sub(used);
|
||||
SpaceInfo {
|
||||
|
||||
available_free: free.min(disk_free(&title.storage)),
|
||||
total_free: free,
|
||||
used,
|
||||
total: title.storage_bytes,
|
||||
}
|
||||
}
|
||||
|
||||
extern "system" fn space_info(_: This, out: *mut SpaceInfo) -> HRESULT {
|
||||
put(out, space())
|
||||
}
|
||||
|
||||
static PROMPT: u8 = 0;
|
||||
|
||||
fn prompt_status(bytes: u64, space: SpaceInfo) -> HRESULT {
|
||||
if bytes <= space.available_free {
|
||||
S_OK
|
||||
} else {
|
||||
E_ABORT
|
||||
}
|
||||
}
|
||||
|
||||
extern "system" fn prompt_for_space(_: This, bytes: u64, block: *mut AsyncBlock) -> HRESULT {
|
||||
let hr = prompt_status(bytes, space());
|
||||
xasync::finished(block, (&raw const PROMPT).cast(), hr)
|
||||
}
|
||||
|
||||
extern "system" fn prompt_result(_: This, block: *mut AsyncBlock) -> HRESULT {
|
||||
let none = std::ptr::null_mut();
|
||||
xasync::XAsyncGetResult(block, (&raw const PROMPT).cast(), 0, none, none.cast())
|
||||
}
|
||||
|
||||
static VTABLE: Methods<17> = with_spare([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
path_size as *const (),
|
||||
path as *const (),
|
||||
space_info as *const (),
|
||||
prompt_for_space as *const (),
|
||||
prompt_result as *const (),
|
||||
missing::<8> as *const (),
|
||||
]);
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Mode {
|
||||
Auto,
|
||||
Dark,
|
||||
Off,
|
||||
}
|
||||
|
||||
impl Mode {
|
||||
fn parse(text: Option<&str>) -> Mode {
|
||||
match text.map(str::trim) {
|
||||
Some("1") => Mode::Dark,
|
||||
Some("0") => Mode::Off,
|
||||
_ => Mode::Auto,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn apps_use_dark(value: Option<u32>) -> bool {
|
||||
value == Some(0)
|
||||
}
|
||||
|
||||
fn wants_dark(mode: Mode, apps_use_light_theme: Option<u32>) -> Option<bool> {
|
||||
match mode {
|
||||
Mode::Off => None,
|
||||
Mode::Dark => Some(true),
|
||||
Mode::Auto => Some(apps_use_dark(apps_use_light_theme)),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_theme_setting(text: &[u16]) -> bool {
|
||||
text.iter().copied().eq("ImmersiveColorSet".encode_utf16())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(crate) use imp::{apply, apply_for_setting};
|
||||
|
||||
#[cfg(windows)]
|
||||
mod imp {
|
||||
use super::*;
|
||||
use windows_sys::Win32::Foundation::{HWND, LPARAM};
|
||||
use windows_sys::Win32::Graphics::Dwm::{DWMWA_USE_IMMERSIVE_DARK_MODE, DwmSetWindowAttribute};
|
||||
use windows_sys::Win32::System::Registry::{HKEY_CURRENT_USER, RRF_RT_REG_DWORD, RegGetValueW};
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging as wm;
|
||||
use windows_sys::core::w;
|
||||
|
||||
fn apps_use_light_theme() -> Option<u32> {
|
||||
let mut value = 0u32;
|
||||
let mut size = 4u32;
|
||||
|
||||
let status = unsafe {
|
||||
RegGetValueW(
|
||||
HKEY_CURRENT_USER,
|
||||
w!("Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"),
|
||||
w!("AppsUseLightTheme"),
|
||||
RRF_RT_REG_DWORD,
|
||||
std::ptr::null_mut(),
|
||||
std::ptr::addr_of_mut!(value).cast(),
|
||||
&mut size,
|
||||
)
|
||||
};
|
||||
(status == 0).then_some(value)
|
||||
}
|
||||
|
||||
pub(crate) fn apply(hwnd: HWND) {
|
||||
let setting = std::env::var("EONACAT_XS_DARK_TITLE").ok();
|
||||
let Some(dark) = wants_dark(Mode::parse(setting.as_deref()), apps_use_light_theme()) else {
|
||||
return;
|
||||
};
|
||||
let value = i32::from(dark);
|
||||
|
||||
let ok = unsafe {
|
||||
let set = |attribute: u32| {
|
||||
DwmSetWindowAttribute(hwnd, attribute, std::ptr::addr_of!(value).cast(), 4) >= 0
|
||||
};
|
||||
|
||||
set(DWMWA_USE_IMMERSIVE_DARK_MODE as u32) || set(19)
|
||||
};
|
||||
if !ok {
|
||||
tracing::warn!("title bar theme: the window manager refused the attribute");
|
||||
return;
|
||||
}
|
||||
|
||||
unsafe {
|
||||
wm::SetWindowPos(
|
||||
hwnd,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
wm::SWP_FRAMECHANGED | wm::SWP_NOMOVE | wm::SWP_NOSIZE | wm::SWP_NOZORDER | wm::SWP_NOACTIVATE,
|
||||
);
|
||||
}
|
||||
tracing::debug!(dark, "title bar theme applied");
|
||||
}
|
||||
|
||||
pub(crate) fn apply_for_setting(hwnd: HWND, lparam: LPARAM) {
|
||||
if lparam == 0 {
|
||||
return;
|
||||
}
|
||||
let text = lparam as *const u16;
|
||||
|
||||
let seen: Vec<u16> = (0..32).map(|i| unsafe { *text.add(i) }).take_while(|c| *c != 0).collect();
|
||||
if is_theme_setting(&seen) {
|
||||
apply(hwnd);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,444 @@
|
||||
|
||||
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
#![allow(clippy::too_many_arguments)]
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::ffi::c_void;
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
use eonacat_xsbox_gpu::formats::xma;
|
||||
|
||||
use super::xgameruntime::HRESULT;
|
||||
use crate::hle::{HleExport, HleModule};
|
||||
use crate::hle_export;
|
||||
|
||||
type Ptr = *mut c_void;
|
||||
|
||||
macro_rules! once {
|
||||
($level:ident, $($arg:tt)*) => {{
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
ONCE.call_once(|| tracing::$level!($($arg)*));
|
||||
}};
|
||||
}
|
||||
|
||||
const WAVE_FORMAT_PCM: u16 = 1;
|
||||
const WAVE_FORMAT_XMA2: u16 = 0x166;
|
||||
|
||||
const XBOX_FLAGS: u32 = 0x0400 | 0x0800 | 0x4000;
|
||||
|
||||
const NO_SAMPLES_PLAYED: u32 = 0x0100;
|
||||
const E_INVALIDARG: HRESULT = 0x8007_0057_u32 as i32;
|
||||
const E_POINTER: HRESULT = 0x8000_4003_u32 as i32;
|
||||
const PROC_NOT_FOUND: HRESULT = 0x8007_007F_u32 as i32;
|
||||
|
||||
#[repr(C, packed)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct WaveFormat {
|
||||
tag: u16,
|
||||
channels: u16,
|
||||
rate: u32,
|
||||
bytes_per_second: u32,
|
||||
block_align: u16,
|
||||
bits: u16,
|
||||
extra: u16,
|
||||
}
|
||||
|
||||
#[repr(C, packed)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Xma2Format {
|
||||
wfx: WaveFormat,
|
||||
streams: u16,
|
||||
channel_mask: u32,
|
||||
samples_encoded: u32,
|
||||
bytes_per_block: u32,
|
||||
play_begin: u32,
|
||||
play_length: u32,
|
||||
loop_begin: u32,
|
||||
loop_length: u32,
|
||||
loop_count: u8,
|
||||
encoder_version: u8,
|
||||
blocks: u16,
|
||||
}
|
||||
|
||||
#[repr(C, packed)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Buffer {
|
||||
flags: u32,
|
||||
bytes: u32,
|
||||
data: *const u8,
|
||||
play_begin: u32,
|
||||
play_length: u32,
|
||||
loop_begin: u32,
|
||||
loop_length: u32,
|
||||
loop_count: u32,
|
||||
context: Ptr,
|
||||
}
|
||||
|
||||
#[repr(C, packed)]
|
||||
struct VoiceState {
|
||||
context: Ptr,
|
||||
queued: u32,
|
||||
samples_played: u64,
|
||||
}
|
||||
|
||||
const ENGINE_METHODS: usize = 13;
|
||||
const CREATE_SOURCE_VOICE: usize = 5;
|
||||
const CREATE_SUBMIX_VOICE: usize = 6;
|
||||
const CREATE_MASTERING_VOICE: usize = 7;
|
||||
|
||||
const SOURCE_METHODS: usize = 29;
|
||||
const DESTROY_VOICE: usize = 18;
|
||||
const SUBMIT_SOURCE_BUFFER: usize = 21;
|
||||
const FLUSH_SOURCE_BUFFERS: usize = 22;
|
||||
const GET_STATE: usize = 25;
|
||||
|
||||
fn table(object: Ptr) -> *const usize {
|
||||
|
||||
unsafe { *object.cast::<*const usize>() }
|
||||
}
|
||||
|
||||
fn patch(object: Ptr, methods: usize, ours: &[(usize, usize)]) {
|
||||
static COPIES: Mutex<Option<HashMap<(usize, usize), usize>>> = Mutex::new(None);
|
||||
let host = table(object);
|
||||
let mut copies = COPIES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let copy = *copies.get_or_insert_with(HashMap::new).entry((host as usize, methods)).or_insert_with(|| {
|
||||
|
||||
let mut copy: Vec<usize> = (0..methods).map(|i| unsafe { *host.add(i) }).collect();
|
||||
for &(slot, f) in ours {
|
||||
copy[slot] = f;
|
||||
}
|
||||
copy.push(host as usize);
|
||||
Box::leak(copy.into_boxed_slice()).as_ptr() as usize
|
||||
});
|
||||
|
||||
unsafe { object.cast::<usize>().write(copy) };
|
||||
}
|
||||
|
||||
unsafe fn original<F: Copy>(object: Ptr, methods: usize, slot: usize) -> F {
|
||||
|
||||
unsafe {
|
||||
let host = *table(object).add(methods) as *const usize;
|
||||
std::mem::transmute_copy(&*host.add(slot))
|
||||
}
|
||||
}
|
||||
|
||||
extern "system" fn create_source_voice(
|
||||
this: Ptr,
|
||||
voice: *mut Ptr,
|
||||
format: *const WaveFormat,
|
||||
flags: u32,
|
||||
max_ratio: f32,
|
||||
callback: Ptr,
|
||||
sends: Ptr,
|
||||
effects: Ptr,
|
||||
) -> HRESULT {
|
||||
|
||||
let create: extern "system" fn(Ptr, *mut Ptr, *const WaveFormat, u32, f32, Ptr, Ptr, Ptr) -> HRESULT =
|
||||
unsafe { original(this, ENGINE_METHODS, CREATE_SOURCE_VOICE) };
|
||||
let flags = flags & !XBOX_FLAGS;
|
||||
|
||||
let tag = (!format.is_null()).then(|| unsafe { format.read_unaligned() }.tag);
|
||||
if tag != Some(WAVE_FORMAT_XMA2) {
|
||||
return create(this, voice, format, flags, max_ratio, callback, sends, effects);
|
||||
}
|
||||
|
||||
let xma2 = unsafe { format.cast::<Xma2Format>().read_unaligned() };
|
||||
let Some(streams) = streams(xma2.wfx.channels, xma2.streams) else {
|
||||
let (channels, streams) = (xma2.wfx.channels, xma2.streams);
|
||||
tracing::warn!(channels, streams, "XAudio2: an XMA2 format with channels and streams that do not fit");
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
let (channels, rate) = (xma2.wfx.channels, xma2.wfx.rate);
|
||||
let pcm = WaveFormat {
|
||||
tag: WAVE_FORMAT_PCM,
|
||||
channels,
|
||||
rate,
|
||||
bytes_per_second: rate * u32::from(channels) * 2,
|
||||
block_align: channels * 2,
|
||||
bits: 16,
|
||||
extra: 0,
|
||||
};
|
||||
let hr = create(this, voice, &pcm, flags, max_ratio, callback, sends, effects);
|
||||
if hr < 0 || voice.is_null() {
|
||||
return hr;
|
||||
}
|
||||
|
||||
let made = unsafe { *voice };
|
||||
if made.is_null() {
|
||||
return hr;
|
||||
}
|
||||
patch(
|
||||
made,
|
||||
SOURCE_METHODS,
|
||||
&[
|
||||
(DESTROY_VOICE, destroy_voice as *const () as usize),
|
||||
(SUBMIT_SOURCE_BUFFER, submit_source_buffer as *const () as usize),
|
||||
(FLUSH_SOURCE_BUFFERS, flush_source_buffers as *const () as usize),
|
||||
],
|
||||
);
|
||||
let decoders = streams.iter().map(|&c| (xma::Decoder::new(c, rate), c)).collect();
|
||||
voices().insert(made as usize, Arc::new(Mutex::new(Xma { decoders, channels: channels.into(), kept: VecDeque::new() })));
|
||||
once!(info, channels, rate, "XAudio2: an XMA2 source voice, decoded here into a PCM voice");
|
||||
hr
|
||||
}
|
||||
|
||||
extern "system" fn create_submix_voice(
|
||||
this: Ptr,
|
||||
voice: *mut Ptr,
|
||||
channels: u32,
|
||||
rate: u32,
|
||||
flags: u32,
|
||||
stage: u32,
|
||||
sends: Ptr,
|
||||
effects: Ptr,
|
||||
) -> HRESULT {
|
||||
|
||||
let create: extern "system" fn(Ptr, *mut Ptr, u32, u32, u32, u32, Ptr, Ptr) -> HRESULT =
|
||||
unsafe { original(this, ENGINE_METHODS, CREATE_SUBMIX_VOICE) };
|
||||
create(this, voice, channels, rate, flags & !XBOX_FLAGS, stage, sends, effects)
|
||||
}
|
||||
|
||||
extern "system" fn create_mastering_voice(
|
||||
this: Ptr,
|
||||
voice: *mut Ptr,
|
||||
channels: u32,
|
||||
rate: u32,
|
||||
flags: u32,
|
||||
device: *const u16,
|
||||
effects: Ptr,
|
||||
category: u32,
|
||||
) -> HRESULT {
|
||||
|
||||
let create: extern "system" fn(Ptr, *mut Ptr, u32, u32, u32, *const u16, Ptr, u32) -> HRESULT =
|
||||
unsafe { original(this, ENGINE_METHODS, CREATE_MASTERING_VOICE) };
|
||||
create(this, voice, channels, rate, flags & !XBOX_FLAGS, device, effects, category)
|
||||
}
|
||||
|
||||
fn streams(channels: u16, streams: u16) -> Option<Vec<usize>> {
|
||||
let (channels, streams) = (usize::from(channels), usize::from(streams));
|
||||
if channels == 0 || streams == 0 || channels > 2 * streams || channels < streams {
|
||||
return None;
|
||||
}
|
||||
if channels == streams {
|
||||
return Some(vec![1; streams]);
|
||||
}
|
||||
let last = channels.checked_sub(2 * (streams - 1)).filter(|c| (1..=2).contains(c))?;
|
||||
Some((0..streams).map(|s| if s + 1 == streams { last } else { 2 }).collect())
|
||||
}
|
||||
|
||||
struct Xma {
|
||||
|
||||
decoders: Vec<(xma::Decoder, usize)>,
|
||||
channels: usize,
|
||||
|
||||
kept: VecDeque<Box<[i16]>>,
|
||||
}
|
||||
|
||||
type Voices = HashMap<usize, Arc<Mutex<Xma>>>;
|
||||
|
||||
fn voices() -> std::sync::MutexGuard<'static, Voices> {
|
||||
static VOICES: std::sync::LazyLock<Mutex<Voices>> = std::sync::LazyLock::new(Default::default);
|
||||
VOICES.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
fn voice(this: Ptr) -> Option<Arc<Mutex<Xma>>> {
|
||||
voices().get(&(this as usize)).cloned()
|
||||
}
|
||||
|
||||
fn lock(v: &Mutex<Xma>) -> std::sync::MutexGuard<'_, Xma> {
|
||||
v.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
fn decode(voice: &mut Xma, data: &[u8]) -> Vec<i16> {
|
||||
let mut outs = Vec::with_capacity(voice.decoders.len());
|
||||
let mut bad = 0;
|
||||
for (s, (decoder, _)) in voice.decoders.iter_mut().enumerate() {
|
||||
let mut out = Vec::new();
|
||||
if let Some(packet) = xma::packet(data, s) {
|
||||
let mut at = s * xma::PACKET_BYTES * 8 + 32 + packet.first_frame_bit as usize;
|
||||
while let Some(frame) = xma::read_frame(data, at) {
|
||||
bad += usize::from(decoder.decode(&frame.data, frame.bits, &mut out).is_err());
|
||||
match frame.next {
|
||||
Some(next) if next > at => at = next,
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
outs.push(out);
|
||||
}
|
||||
if bad > 0 {
|
||||
once!(warn, bad, "XAudio2: XMA2 frames that did not decode (silence in their place)");
|
||||
}
|
||||
let frames = outs.iter().zip(&voice.decoders).map(|(o, (_, c))| o.len() / c).min().unwrap_or(0);
|
||||
let mut pcm = Vec::with_capacity(frames * voice.channels);
|
||||
for f in 0..frames {
|
||||
for (out, (_, c)) in outs.iter().zip(&voice.decoders) {
|
||||
pcm.extend_from_slice(&out[f * c..f * c + c]);
|
||||
}
|
||||
}
|
||||
pcm
|
||||
}
|
||||
|
||||
fn fit(buffer: &Buffer, frames: u32) -> Buffer {
|
||||
let mut b = *buffer;
|
||||
if b.play_begin >= frames || b.play_begin.saturating_add(b.play_length) > frames {
|
||||
(b.play_begin, b.play_length) = (0, 0);
|
||||
}
|
||||
let play_end = if b.play_length == 0 { frames } else { b.play_begin + b.play_length };
|
||||
let loop_end = if b.loop_length == 0 { play_end } else { b.loop_begin.saturating_add(b.loop_length) };
|
||||
if b.loop_count != 0 && (b.loop_begin >= play_end || loop_end > play_end) {
|
||||
(b.loop_begin, b.loop_length, b.loop_count) = (0, 0, 0);
|
||||
}
|
||||
if b.loop_count == 0 {
|
||||
(b.loop_begin, b.loop_length) = (0, 0);
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
extern "system" fn submit_source_buffer(this: Ptr, buffer: *const Buffer, wma: Ptr) -> HRESULT {
|
||||
|
||||
let submit: extern "system" fn(Ptr, *const Buffer, Ptr) -> HRESULT =
|
||||
unsafe { original(this, SOURCE_METHODS, SUBMIT_SOURCE_BUFFER) };
|
||||
let Some(voice) = voice(this) else {
|
||||
return submit(this, buffer, wma);
|
||||
};
|
||||
if buffer.is_null() {
|
||||
return E_POINTER;
|
||||
}
|
||||
|
||||
let asked = unsafe { buffer.read_unaligned() };
|
||||
let data: &[u8] = if asked.data.is_null() || asked.bytes == 0 {
|
||||
&[]
|
||||
} else {
|
||||
|
||||
unsafe { std::slice::from_raw_parts(asked.data, asked.bytes as usize) }
|
||||
};
|
||||
let (pcm, channels) = {
|
||||
let mut v = lock(&voice);
|
||||
let mut pcm = decode(&mut v, data);
|
||||
if pcm.is_empty() {
|
||||
|
||||
pcm = vec![0; xma::SUBFRAME_SAMPLES * v.channels];
|
||||
}
|
||||
(pcm.into_boxed_slice(), v.channels)
|
||||
};
|
||||
let frames = (pcm.len() / channels) as u32;
|
||||
let mut shown = fit(&asked, frames);
|
||||
shown.bytes = (pcm.len() * 2) as u32;
|
||||
shown.data = pcm.as_ptr().cast();
|
||||
|
||||
let hr = submit(this, &shown, std::ptr::null_mut());
|
||||
if hr < 0 {
|
||||
return hr;
|
||||
}
|
||||
lock(&voice).kept.push_back(pcm);
|
||||
|
||||
let get_state: extern "system" fn(Ptr, *mut VoiceState, u32) =
|
||||
unsafe { original(this, SOURCE_METHODS, GET_STATE) };
|
||||
let mut state = VoiceState { context: std::ptr::null_mut(), queued: u32::MAX, samples_played: 0 };
|
||||
get_state(this, &mut state, NO_SAMPLES_PLAYED);
|
||||
let mut v = lock(&voice);
|
||||
|
||||
while v.kept.len() > state.queued as usize + 1 {
|
||||
v.kept.pop_front();
|
||||
}
|
||||
hr
|
||||
}
|
||||
|
||||
extern "system" fn flush_source_buffers(this: Ptr) -> HRESULT {
|
||||
|
||||
let flush: extern "system" fn(Ptr) -> HRESULT = unsafe { original(this, SOURCE_METHODS, FLUSH_SOURCE_BUFFERS) };
|
||||
let hr = flush(this);
|
||||
if let Some(voice) = voice(this) {
|
||||
|
||||
for (decoder, _) in &mut lock(&voice).decoders {
|
||||
decoder.reset();
|
||||
}
|
||||
}
|
||||
hr
|
||||
}
|
||||
|
||||
extern "system" fn destroy_voice(this: Ptr) {
|
||||
|
||||
let destroy: extern "system" fn(Ptr) = unsafe { original(this, SOURCE_METHODS, DESTROY_VOICE) };
|
||||
destroy(this);
|
||||
voices().remove(&(this as usize));
|
||||
}
|
||||
|
||||
fn engine(out: *mut Ptr, hr: HRESULT) -> HRESULT {
|
||||
if hr >= 0 && !out.is_null() {
|
||||
|
||||
let made = unsafe { *out };
|
||||
if !made.is_null() {
|
||||
patch(
|
||||
made,
|
||||
ENGINE_METHODS,
|
||||
&[
|
||||
(CREATE_SOURCE_VOICE, create_source_voice as *const () as usize),
|
||||
(CREATE_SUBMIX_VOICE, create_submix_voice as *const () as usize),
|
||||
(CREATE_MASTERING_VOICE, create_mastering_voice as *const () as usize),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
hr
|
||||
}
|
||||
|
||||
fn keep_com() {
|
||||
static KEPT: OnceLock<()> = OnceLock::new();
|
||||
KEPT.get_or_init(|| {
|
||||
let hr = crate::hle::host::function("ole32.dll", "CoIncrementMTAUsage").map_or(PROC_NOT_FOUND, |f| {
|
||||
|
||||
let keep: extern "system" fn(*mut usize) -> HRESULT = unsafe { std::mem::transmute(f) };
|
||||
keep(&mut 0)
|
||||
});
|
||||
if hr < 0 {
|
||||
tracing::warn!(hr = format_args!("{hr:#x}"), "XAudio2: the multithreaded apartment was not kept; a mastering voice may fail");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn host_create(out: *mut Ptr, flags: u32, processor: u32) -> HRESULT {
|
||||
keep_com();
|
||||
static CREATE: OnceLock<Option<usize>> = OnceLock::new();
|
||||
let Some(create) = *CREATE.get_or_init(|| crate::hle::host::function("xaudio2_9.dll", "XAudio2Create")) else {
|
||||
return PROC_NOT_FOUND;
|
||||
};
|
||||
|
||||
let create: extern "system" fn(*mut Ptr, u32, u32) -> HRESULT = unsafe { std::mem::transmute(create) };
|
||||
engine(out, create(out, flags & !XBOX_FLAGS, processor))
|
||||
}
|
||||
|
||||
pub extern "system" fn XAudio2Create(out: *mut Ptr, flags: u32, processor: u32) -> HRESULT {
|
||||
host_create(out, flags, processor)
|
||||
}
|
||||
|
||||
pub extern "system" fn XAudio2CreateWithVersionInfo(out: *mut Ptr, flags: u32, processor: u32, _ntddi: u32) -> HRESULT {
|
||||
host_create(out, flags, processor)
|
||||
}
|
||||
|
||||
pub extern "system" fn XAudio2CreateWithSharedContexts(
|
||||
out: *mut Ptr,
|
||||
flags: u32,
|
||||
processor: u32,
|
||||
_contexts: Ptr,
|
||||
) -> HRESULT {
|
||||
host_create(out, flags, processor)
|
||||
}
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "xaudio2",
|
||||
dlls: &["xaudio2_9.dll"],
|
||||
exports: vec![
|
||||
hle_export!(XAudio2Create),
|
||||
|
||||
HleExport { name: "#1", address: XAudio2Create as *const () as usize },
|
||||
hle_export!(XAudio2CreateWithVersionInfo),
|
||||
hle_export!(XAudio2CreateWithSharedContexts),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
|
||||
|
||||
use std::ffi::c_void;
|
||||
|
||||
use eonacat_xsbox_gpu::hwrt::{
|
||||
XboxBatchedBuildDesc2, XboxBuildDesc, XboxBuildInputs, XboxPostbuildDesc, XboxPrebuildInfo,
|
||||
};
|
||||
use eonacat_xsbox_gpu::object::{HRESULT, Object, S_OK};
|
||||
|
||||
type This = *const Object;
|
||||
|
||||
use crate::hle::{HleExport, HleModule};
|
||||
|
||||
extern "system" fn ctor(
|
||||
this: *mut [usize; 3],
|
||||
_device: This,
|
||||
rehydrate_only: bool,
|
||||
) -> *mut [usize; 3] {
|
||||
if !this.is_null() {
|
||||
|
||||
unsafe { *this = [0, 0, 0] };
|
||||
}
|
||||
tracing::info!(rehydrate_only, "HLE XboxBvhBuilder constructed (hardware DXR 1.1)");
|
||||
this
|
||||
}
|
||||
|
||||
extern "system" fn dtor(this: *mut [usize; 3]) {
|
||||
if !this.is_null() {
|
||||
|
||||
unsafe { *this = [0, 0, 0] };
|
||||
}
|
||||
}
|
||||
|
||||
extern "system" fn set_64bit_morton(_this: *mut c_void, _enable: bool) {}
|
||||
|
||||
extern "system" fn get_prebuild_info(
|
||||
_this: *mut c_void,
|
||||
inputs: *const XboxBuildInputs,
|
||||
stream_desc: *const u8,
|
||||
out: *mut XboxPrebuildInfo,
|
||||
) {
|
||||
eonacat_xsbox_gpu::hwrt::prebuild_info(inputs, stream_desc, out);
|
||||
}
|
||||
|
||||
extern "system" fn build_single(
|
||||
_this: *mut c_void,
|
||||
list: This,
|
||||
desc: *const XboxBuildDesc,
|
||||
num_postbuild: u32,
|
||||
postbuild: *const XboxPostbuildDesc,
|
||||
) {
|
||||
eonacat_xsbox_gpu::hwrt::build_single(list, desc, num_postbuild, postbuild);
|
||||
}
|
||||
|
||||
extern "system" fn build_batched2(
|
||||
_this: *mut c_void,
|
||||
list: This,
|
||||
num_descs: u32,
|
||||
descs: *const XboxBatchedBuildDesc2,
|
||||
) {
|
||||
eonacat_xsbox_gpu::hwrt::build_batched2(list, num_descs, descs);
|
||||
}
|
||||
|
||||
extern "system" fn copy_as(
|
||||
_this: *mut c_void,
|
||||
list: This,
|
||||
dest_va: u64,
|
||||
src_va: u64,
|
||||
mode: u32,
|
||||
) {
|
||||
eonacat_xsbox_gpu::hwrt::copy_as(list, dest_va, src_va, mode);
|
||||
}
|
||||
|
||||
extern "system" fn rehydrate_batched2(
|
||||
_this: *mut c_void,
|
||||
list: This,
|
||||
num_descs: u32,
|
||||
descs: *const XboxBuildDesc,
|
||||
src_vas: *const u64,
|
||||
) -> HRESULT {
|
||||
eonacat_xsbox_gpu::hwrt::rehydrate_batched2(list, num_descs, descs, src_vas)
|
||||
}
|
||||
|
||||
extern "system" fn rehydrate_batched(
|
||||
_this: *mut c_void,
|
||||
list: This,
|
||||
num_descs: u32,
|
||||
descs: *const XboxBuildDesc,
|
||||
) -> HRESULT {
|
||||
eonacat_xsbox_gpu::hwrt::rehydrate_batched2(list, num_descs, descs, std::ptr::null())
|
||||
}
|
||||
|
||||
extern "system" fn rehydrate_cpu(
|
||||
_this: *mut c_void,
|
||||
_device: This,
|
||||
_desc: *const XboxBuildDesc,
|
||||
) -> HRESULT {
|
||||
S_OK
|
||||
}
|
||||
|
||||
extern "system" fn validate_rehydrate(_this: *mut c_void, _desc: *const XboxBuildDesc) -> HRESULT {
|
||||
S_OK
|
||||
}
|
||||
|
||||
extern "system" fn cpu_validate(_this: *mut c_void, _list: This, _desc: *const XboxBuildDesc) {}
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "xboxbvh",
|
||||
dlls: &["xboxbvhbuilder.dll"],
|
||||
exports: vec![
|
||||
HleExport {
|
||||
name: "??0XboxBvhBuilder@@QEAA@PEAUID3D12Device11@@_N@Z",
|
||||
address: ctor as *const () as usize,
|
||||
},
|
||||
HleExport {
|
||||
name: "??1XboxBvhBuilder@@QEAA@XZ",
|
||||
address: dtor as *const () as usize,
|
||||
},
|
||||
HleExport {
|
||||
name: "?Set64BitMortonCodes@XboxBvhBuilder@@QEAAX_N@Z",
|
||||
address: set_64bit_morton as *const () as usize,
|
||||
},
|
||||
HleExport {
|
||||
name: "?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z",
|
||||
address: get_prebuild_info as *const () as usize,
|
||||
},
|
||||
HleExport {
|
||||
name: "?BuildRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@PEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@IPEBUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC@@@Z",
|
||||
address: build_single as *const () as usize,
|
||||
},
|
||||
HleExport {
|
||||
name: "?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z",
|
||||
address: build_batched2 as *const () as usize,
|
||||
},
|
||||
HleExport {
|
||||
name: "?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE@@@Z",
|
||||
address: copy_as as *const () as usize,
|
||||
},
|
||||
HleExport {
|
||||
name: "?RehydrateRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z",
|
||||
address: rehydrate_batched2 as *const () as usize,
|
||||
},
|
||||
HleExport {
|
||||
name: "?RehydrateRaytracingAccelerationStructureBatchedX@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@@Z",
|
||||
address: rehydrate_batched as *const () as usize,
|
||||
},
|
||||
HleExport {
|
||||
name: "?RehydrateRaytracingAccelerationStructureX@XboxBvhBuilder@@QEAAJPEAUID3D12Device11@@PEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@@Z",
|
||||
address: rehydrate_cpu as *const () as usize,
|
||||
},
|
||||
HleExport {
|
||||
name: "?ValidateRehydrateAccelerationStructureBuildDesc@XboxBvhBuilder@@QEAAJPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@@Z",
|
||||
address: validate_rehydrate as *const () as usize,
|
||||
},
|
||||
HleExport {
|
||||
name: "?CpuValidateResultX@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@PEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@@Z",
|
||||
address: cpu_validate as *const () as usize,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,787 @@
|
||||
|
||||
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::ffi::{CStr, c_char, c_int, c_long, c_uint, c_void};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use crate::hle::{HleModule};
|
||||
use crate::hle_export;
|
||||
|
||||
type Code = c_int;
|
||||
const CURLE_OK: Code = 0;
|
||||
const CURLE_COULDNT_RESOLVE_HOST: Code = 6;
|
||||
const CURLE_BAD_FUNCTION_ARGUMENT: Code = 43;
|
||||
const CURL_ERROR_SIZE: usize = 256;
|
||||
|
||||
const CURLOPT_URL: c_int = 10_002;
|
||||
const CURLOPT_ERRORBUFFER: c_int = 10_010;
|
||||
const CURLOPT_PRIVATE: c_int = 10_103;
|
||||
const CURLINFO_TYPEMASK: c_int = 0xf0_0000;
|
||||
const CURLINFO_STRING: c_int = 0x10_0000;
|
||||
const CURLINFO_LONG: c_int = 0x20_0000;
|
||||
const CURLINFO_DOUBLE: c_int = 0x30_0000;
|
||||
const CURLINFO_PTR: c_int = 0x40_0000;
|
||||
const CURLINFO_SOCKET: c_int = 0x50_0000;
|
||||
const CURLINFO_OFF_T: c_int = 0x60_0000;
|
||||
const CURLINFO_EFFECTIVE_URL: c_int = CURLINFO_STRING + 1;
|
||||
const CURLINFO_PRIVATE: c_int = CURLINFO_STRING + 21;
|
||||
|
||||
const OFFLINE: &CStr = c"Could not resolve host: the console is offline";
|
||||
|
||||
fn text(s: *const c_char) -> Option<&'static CStr> {
|
||||
|
||||
(!s.is_null()).then(|| unsafe { CStr::from_ptr(s) })
|
||||
}
|
||||
|
||||
fn give(bytes: &[u8]) -> *mut c_char {
|
||||
let mut b = Vec::with_capacity(8 + bytes.len() + 1);
|
||||
b.extend_from_slice(&(bytes.len() + 1).to_le_bytes());
|
||||
b.extend_from_slice(bytes);
|
||||
b.push(0);
|
||||
let b = Box::leak(b.into_boxed_slice());
|
||||
|
||||
unsafe { b.as_mut_ptr().add(8).cast() }
|
||||
}
|
||||
|
||||
pub extern "C" fn curl_free(p: *mut c_void) {
|
||||
if p.is_null() {
|
||||
return;
|
||||
}
|
||||
|
||||
unsafe {
|
||||
let base = p.cast::<u8>().sub(8);
|
||||
let len = usize::from_le_bytes(base.cast::<[u8; 8]>().read());
|
||||
drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut(base, 8 + len)));
|
||||
}
|
||||
}
|
||||
|
||||
pub extern "C" fn curl_global_init(_flags: c_long) -> Code {
|
||||
tracing::info!("XCurl: initialized (offline: every transfer fails to resolve its host)");
|
||||
CURLE_OK
|
||||
}
|
||||
pub extern "C" fn curl_global_init_mem(_flags: c_long, _m: Ptr, _f: Ptr, _r: Ptr, _s: Ptr, _c: Ptr) -> Code {
|
||||
curl_global_init(0)
|
||||
}
|
||||
pub extern "C" fn xcurl_global_init_mem(_flags: c_long, _m: Ptr, _f: Ptr, _r: Ptr, _s: Ptr, _c: Ptr) -> Code {
|
||||
curl_global_init(0)
|
||||
}
|
||||
pub extern "C" fn curl_global_cleanup() {}
|
||||
pub extern "C" fn xcurl_global_suspend() {}
|
||||
pub extern "C" fn xcurl_global_resume() {}
|
||||
pub extern "C" fn xcurl_global_set_request_limit(_limit: c_uint) {}
|
||||
|
||||
pub extern "C" fn curl_global_sslset(_id: c_int, _name: *const c_char, avail: *mut *const c_void) -> c_int {
|
||||
if !avail.is_null() {
|
||||
|
||||
unsafe { avail.write(EMPTY.as_ptr().cast()) };
|
||||
}
|
||||
0
|
||||
}
|
||||
static EMPTY: [usize; 1] = [0];
|
||||
|
||||
type Ptr = *const c_void;
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub struct Easy {
|
||||
private: usize,
|
||||
error_buffer: usize,
|
||||
url: Option<Box<CStr>>,
|
||||
}
|
||||
|
||||
fn easy<'a>(h: *mut Easy) -> Option<&'a mut Easy> {
|
||||
|
||||
unsafe { h.as_mut() }
|
||||
}
|
||||
|
||||
pub extern "C" fn curl_easy_init() -> *mut Easy {
|
||||
Box::into_raw(Box::default())
|
||||
}
|
||||
pub extern "C" fn curl_easy_cleanup(h: *mut Easy) {
|
||||
if !h.is_null() {
|
||||
|
||||
drop(unsafe { Box::from_raw(h) });
|
||||
}
|
||||
}
|
||||
pub extern "C" fn curl_easy_duphandle(h: *mut Easy) -> *mut Easy {
|
||||
easy(h).map_or(std::ptr::null_mut(), |e| Box::into_raw(Box::new(e.clone())))
|
||||
}
|
||||
pub extern "C" fn curl_easy_reset(h: *mut Easy) {
|
||||
if let Some(e) = easy(h) {
|
||||
*e = Easy::default();
|
||||
}
|
||||
}
|
||||
|
||||
pub extern "C" fn curl_easy_setopt(h: *mut Easy, option: c_int, value: usize) -> Code {
|
||||
let Some(e) = easy(h) else {
|
||||
return CURLE_BAD_FUNCTION_ARGUMENT;
|
||||
};
|
||||
match option {
|
||||
CURLOPT_PRIVATE => e.private = value,
|
||||
CURLOPT_ERRORBUFFER => e.error_buffer = value,
|
||||
CURLOPT_URL => e.url = text(value as *const c_char).map(Box::from),
|
||||
_ => {}
|
||||
}
|
||||
CURLE_OK
|
||||
}
|
||||
|
||||
pub extern "C" fn curl_easy_perform(h: *mut Easy) -> Code {
|
||||
let Some(e) = easy(h) else {
|
||||
return CURLE_BAD_FUNCTION_ARGUMENT;
|
||||
};
|
||||
fail(e)
|
||||
}
|
||||
|
||||
fn fail(e: &Easy) -> Code {
|
||||
tracing::debug!(url = ?e.url, "XCurl: transfer refused (offline)");
|
||||
if e.error_buffer != 0 {
|
||||
let message = OFFLINE.to_bytes_with_nul();
|
||||
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(message.as_ptr(), e.error_buffer as *mut u8, message.len().min(CURL_ERROR_SIZE));
|
||||
}
|
||||
}
|
||||
CURLE_COULDNT_RESOLVE_HOST
|
||||
}
|
||||
|
||||
pub extern "C" fn curl_easy_getinfo(h: *mut Easy, info: c_int, out: *mut c_void) -> Code {
|
||||
let Some(e) = easy(h) else {
|
||||
return CURLE_BAD_FUNCTION_ARGUMENT;
|
||||
};
|
||||
if out.is_null() {
|
||||
return CURLE_BAD_FUNCTION_ARGUMENT;
|
||||
}
|
||||
|
||||
unsafe {
|
||||
match (info, info & CURLINFO_TYPEMASK) {
|
||||
(CURLINFO_PRIVATE, _) => out.cast::<usize>().write(e.private),
|
||||
(CURLINFO_EFFECTIVE_URL, _) => {
|
||||
out.cast::<*const c_char>().write(e.url.as_deref().map_or(c"".as_ptr(), CStr::as_ptr));
|
||||
}
|
||||
(_, CURLINFO_STRING) => out.cast::<*const c_char>().write(c"".as_ptr()),
|
||||
(_, CURLINFO_LONG) => out.cast::<c_long>().write(0),
|
||||
(_, CURLINFO_DOUBLE) => out.cast::<f64>().write(0.0),
|
||||
(_, CURLINFO_PTR) => out.cast::<usize>().write(0),
|
||||
(_, CURLINFO_SOCKET) => out.cast::<usize>().write(usize::MAX),
|
||||
(_, CURLINFO_OFF_T) => out.cast::<i64>().write(0),
|
||||
_ => return CURLE_BAD_FUNCTION_ARGUMENT,
|
||||
}
|
||||
}
|
||||
CURLE_OK
|
||||
}
|
||||
|
||||
pub extern "C" fn curl_easy_strerror(code: Code) -> *const c_char {
|
||||
match code {
|
||||
CURLE_OK => c"No error",
|
||||
CURLE_COULDNT_RESOLVE_HOST => c"Couldn't resolve host name",
|
||||
CURLE_BAD_FUNCTION_ARGUMENT => c"A libcurl function was given a bad argument",
|
||||
_ => c"Error (XCurl offline)",
|
||||
}
|
||||
.as_ptr()
|
||||
}
|
||||
|
||||
fn escape(bytes: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(bytes.len() * 3);
|
||||
for &b in bytes {
|
||||
if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
|
||||
out.push(b);
|
||||
} else {
|
||||
out.extend_from_slice(format!("%{b:02X}").as_bytes());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn unescape(bytes: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
let hex = bytes.get(i + 1..i + 3).filter(|h| h.iter().all(u8::is_ascii_hexdigit));
|
||||
match (bytes[i], hex) {
|
||||
(b'%', Some(h)) => {
|
||||
out.push(u8::from_str_radix(std::str::from_utf8(h).unwrap_or("0"), 16).unwrap_or(0));
|
||||
i += 3;
|
||||
}
|
||||
(b, _) => {
|
||||
out.push(b);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn input<'a>(s: *const c_char, len: c_int) -> Option<&'a [u8]> {
|
||||
if s.is_null() {
|
||||
return None;
|
||||
}
|
||||
Some(match usize::try_from(len).unwrap_or(0) {
|
||||
0 => text(s)?.to_bytes(),
|
||||
|
||||
n => unsafe { std::slice::from_raw_parts(s.cast(), n) },
|
||||
})
|
||||
}
|
||||
|
||||
pub extern "C" fn curl_easy_escape(_h: *mut Easy, s: *const c_char, len: c_int) -> *mut c_char {
|
||||
input(s, len).map_or(std::ptr::null_mut(), |b| give(&escape(b)))
|
||||
}
|
||||
pub extern "C" fn curl_escape(s: *const c_char, len: c_int) -> *mut c_char {
|
||||
curl_easy_escape(std::ptr::null_mut(), s, len)
|
||||
}
|
||||
pub extern "C" fn curl_easy_unescape(_h: *mut Easy, s: *const c_char, len: c_int, out_len: *mut c_int) -> *mut c_char {
|
||||
let Some(b) = input(s, len) else {
|
||||
return std::ptr::null_mut();
|
||||
};
|
||||
let plain = unescape(b);
|
||||
if !out_len.is_null() {
|
||||
|
||||
unsafe { out_len.write(plain.len() as c_int) };
|
||||
}
|
||||
give(&plain)
|
||||
}
|
||||
pub extern "C" fn curl_unescape(s: *const c_char, len: c_int) -> *mut c_char {
|
||||
curl_easy_unescape(std::ptr::null_mut(), s, len, std::ptr::null_mut())
|
||||
}
|
||||
|
||||
pub extern "C" fn curl_getdate(_s: *const c_char, _unused: *const i64) -> i64 {
|
||||
-1
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct Slist {
|
||||
data: *mut c_char,
|
||||
next: *mut Slist,
|
||||
}
|
||||
|
||||
pub extern "C" fn curl_slist_append(list: *mut Slist, s: *const c_char) -> *mut Slist {
|
||||
let Some(s) = text(s) else {
|
||||
return std::ptr::null_mut();
|
||||
};
|
||||
let node = Box::into_raw(Box::new(Slist { data: give(s.to_bytes()), next: std::ptr::null_mut() }));
|
||||
if list.is_null() {
|
||||
return node;
|
||||
}
|
||||
let mut at = list;
|
||||
|
||||
unsafe {
|
||||
while !(*at).next.is_null() {
|
||||
at = (*at).next;
|
||||
}
|
||||
(*at).next = node;
|
||||
}
|
||||
list
|
||||
}
|
||||
|
||||
pub extern "C" fn curl_slist_free_all(list: *mut Slist) {
|
||||
let mut at = list;
|
||||
while !at.is_null() {
|
||||
|
||||
let node = unsafe { Box::from_raw(at) };
|
||||
curl_free(node.data.cast());
|
||||
at = node.next;
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Mime {
|
||||
|
||||
#[allow(clippy::vec_box)]
|
||||
parts: Vec<Box<u8>>,
|
||||
}
|
||||
|
||||
pub extern "C" fn curl_mime_init(_h: *mut Easy) -> *mut Mime {
|
||||
Box::into_raw(Box::new(Mime { parts: Vec::new() }))
|
||||
}
|
||||
pub extern "C" fn curl_mime_free(m: *mut Mime) {
|
||||
if !m.is_null() {
|
||||
|
||||
drop(unsafe { Box::from_raw(m) });
|
||||
}
|
||||
}
|
||||
pub extern "C" fn curl_mime_addpart(m: *mut Mime) -> *mut c_void {
|
||||
|
||||
let Some(m) = (unsafe { m.as_mut() }) else {
|
||||
return std::ptr::null_mut();
|
||||
};
|
||||
m.parts.push(Box::new(0));
|
||||
let part: &mut u8 = m.parts.last_mut().expect("just pushed");
|
||||
(part as *mut u8).cast()
|
||||
}
|
||||
|
||||
pub extern "C" fn curl_mime_name(_p: Ptr, _s: *const c_char) -> Code {
|
||||
CURLE_OK
|
||||
}
|
||||
pub extern "C" fn curl_mime_filename(_p: Ptr, _s: *const c_char) -> Code {
|
||||
CURLE_OK
|
||||
}
|
||||
pub extern "C" fn curl_mime_type(_p: Ptr, _s: *const c_char) -> Code {
|
||||
CURLE_OK
|
||||
}
|
||||
pub extern "C" fn curl_mime_encoder(_p: Ptr, _s: *const c_char) -> Code {
|
||||
CURLE_OK
|
||||
}
|
||||
pub extern "C" fn curl_mime_filedata(_p: Ptr, _s: *const c_char) -> Code {
|
||||
CURLE_OK
|
||||
}
|
||||
pub extern "C" fn curl_mime_data(_p: Ptr, _data: *const c_char, _size: usize) -> Code {
|
||||
CURLE_OK
|
||||
}
|
||||
pub extern "C" fn curl_mime_data_cb(_p: Ptr, _size: i64, _read: Ptr, _seek: Ptr, _free: Ptr, _arg: Ptr) -> Code {
|
||||
CURLE_OK
|
||||
}
|
||||
|
||||
pub extern "C" fn curl_mime_subparts(_p: Ptr, _m: *mut Mime) -> Code {
|
||||
CURLE_OK
|
||||
}
|
||||
pub extern "C" fn curl_mime_headers(_p: Ptr, _headers: *mut Slist, _take: c_int) -> Code {
|
||||
CURLE_OK
|
||||
}
|
||||
|
||||
pub extern "C" fn curl_formadd(_post: *mut Ptr, _last: *mut Ptr, _option: c_int) -> c_int {
|
||||
7
|
||||
}
|
||||
pub extern "C" fn curl_formget(_form: Ptr, _arg: Ptr, _append: Ptr) -> c_int {
|
||||
0
|
||||
}
|
||||
pub extern "C" fn curl_formfree(_form: Ptr) {}
|
||||
|
||||
type MultiCode = c_int;
|
||||
const CURLM_OK: MultiCode = 0;
|
||||
const CURLM_BAD_HANDLE: MultiCode = 1;
|
||||
const CURLM_BAD_EASY_HANDLE: MultiCode = 2;
|
||||
const CURLM_ADDED_ALREADY: MultiCode = 7;
|
||||
const CURLMSG_DONE: c_int = 1;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Message {
|
||||
msg: c_int,
|
||||
easy: *mut Easy,
|
||||
result: usize,
|
||||
}
|
||||
|
||||
pub struct Multi {
|
||||
|
||||
handles: Vec<(*mut Easy, bool)>,
|
||||
messages: VecDeque<Message>,
|
||||
|
||||
current: Message,
|
||||
}
|
||||
|
||||
fn multi<'a>(m: *mut Multi) -> Option<&'a mut Multi> {
|
||||
|
||||
unsafe { m.as_mut() }
|
||||
}
|
||||
|
||||
pub extern "C" fn curl_multi_init() -> *mut Multi {
|
||||
Box::into_raw(Box::new(Multi {
|
||||
handles: Vec::new(),
|
||||
messages: VecDeque::new(),
|
||||
current: Message { msg: 0, easy: std::ptr::null_mut(), result: 0 },
|
||||
}))
|
||||
}
|
||||
pub extern "C" fn curl_multi_cleanup(m: *mut Multi) -> MultiCode {
|
||||
if m.is_null() {
|
||||
return CURLM_BAD_HANDLE;
|
||||
}
|
||||
|
||||
drop(unsafe { Box::from_raw(m) });
|
||||
CURLM_OK
|
||||
}
|
||||
pub extern "C" fn curl_multi_add_handle(m: *mut Multi, e: *mut Easy) -> MultiCode {
|
||||
let Some(m) = multi(m) else {
|
||||
return CURLM_BAD_HANDLE;
|
||||
};
|
||||
if e.is_null() {
|
||||
return CURLM_BAD_EASY_HANDLE;
|
||||
}
|
||||
if m.handles.iter().any(|(h, _)| *h == e) {
|
||||
return CURLM_ADDED_ALREADY;
|
||||
}
|
||||
m.handles.push((e, false));
|
||||
CURLM_OK
|
||||
}
|
||||
pub extern "C" fn curl_multi_remove_handle(m: *mut Multi, e: *mut Easy) -> MultiCode {
|
||||
let Some(m) = multi(m) else {
|
||||
return CURLM_BAD_HANDLE;
|
||||
};
|
||||
m.handles.retain(|(h, _)| *h != e);
|
||||
m.messages.retain(|msg| msg.easy != e);
|
||||
CURLM_OK
|
||||
}
|
||||
|
||||
pub extern "C" fn curl_multi_perform(m: *mut Multi, running: *mut c_int) -> MultiCode {
|
||||
let Some(m) = multi(m) else {
|
||||
return CURLM_BAD_HANDLE;
|
||||
};
|
||||
for (e, done) in &mut m.handles {
|
||||
if !*done {
|
||||
*done = true;
|
||||
let result = easy(*e).map_or(CURLE_COULDNT_RESOLVE_HOST, |e| fail(e));
|
||||
m.messages.push_back(Message { msg: CURLMSG_DONE, easy: *e, result: result as usize });
|
||||
}
|
||||
}
|
||||
if !running.is_null() {
|
||||
|
||||
unsafe { running.write(0) };
|
||||
}
|
||||
CURLM_OK
|
||||
}
|
||||
pub extern "C" fn curl_multi_info_read(m: *mut Multi, left: *mut c_int) -> *mut Message {
|
||||
let Some(m) = multi(m) else {
|
||||
return std::ptr::null_mut();
|
||||
};
|
||||
let next = m.messages.pop_front();
|
||||
if !left.is_null() {
|
||||
|
||||
unsafe { left.write(m.messages.len() as c_int) };
|
||||
}
|
||||
match next {
|
||||
Some(msg) => {
|
||||
m.current = msg;
|
||||
&raw mut m.current
|
||||
}
|
||||
None => std::ptr::null_mut(),
|
||||
}
|
||||
}
|
||||
|
||||
pub extern "C" fn curl_multi_wait(m: *mut Multi, _fds: Ptr, _n: c_uint, _timeout_ms: c_int, ready: *mut c_int) -> MultiCode {
|
||||
if m.is_null() {
|
||||
return CURLM_BAD_HANDLE;
|
||||
}
|
||||
if !ready.is_null() {
|
||||
|
||||
unsafe { ready.write(0) };
|
||||
}
|
||||
CURLM_OK
|
||||
}
|
||||
pub extern "C" fn curl_multi_poll(m: *mut Multi, fds: Ptr, n: c_uint, timeout_ms: c_int, ready: *mut c_int) -> MultiCode {
|
||||
curl_multi_wait(m, fds, n, timeout_ms, ready)
|
||||
}
|
||||
pub extern "C" fn curl_multi_wakeup(m: *mut Multi) -> MultiCode {
|
||||
if m.is_null() { CURLM_BAD_HANDLE } else { CURLM_OK }
|
||||
}
|
||||
pub extern "C" fn curl_multi_setopt(m: *mut Multi, _option: c_int, _value: usize) -> MultiCode {
|
||||
if m.is_null() { CURLM_BAD_HANDLE } else { CURLM_OK }
|
||||
}
|
||||
pub extern "C" fn curl_multi_strerror(code: MultiCode) -> *const c_char {
|
||||
match code {
|
||||
CURLM_OK => c"No error",
|
||||
CURLM_BAD_HANDLE => c"Invalid multi handle",
|
||||
CURLM_BAD_EASY_HANDLE => c"Invalid easy handle",
|
||||
CURLM_ADDED_ALREADY => c"The easy handle is already added to a multi handle",
|
||||
_ => c"Error (XCurl offline)",
|
||||
}
|
||||
.as_ptr()
|
||||
}
|
||||
|
||||
pub extern "C" fn curl_share_init() -> *mut u8 {
|
||||
Box::into_raw(Box::new(0u8))
|
||||
}
|
||||
pub extern "C" fn curl_share_setopt(s: *mut u8, _option: c_int, _value: usize) -> c_int {
|
||||
|
||||
if s.is_null() { 3 } else { 0 }
|
||||
}
|
||||
pub extern "C" fn curl_share_cleanup(s: *mut u8) -> c_int {
|
||||
if s.is_null() {
|
||||
return 3;
|
||||
}
|
||||
|
||||
drop(unsafe { Box::from_raw(s) });
|
||||
0
|
||||
}
|
||||
pub extern "C" fn curl_share_strerror(code: c_int) -> *const c_char {
|
||||
if code == 0 { c"No error" } else { c"Invalid share handle" }.as_ptr()
|
||||
}
|
||||
|
||||
type UrlCode = c_int;
|
||||
const CURLUE_OK: UrlCode = 0;
|
||||
const CURLUE_BAD_HANDLE: UrlCode = 1;
|
||||
const CURLUE_BAD_PARTPOINTER: UrlCode = 2;
|
||||
const CURLUE_MALFORMED_INPUT: UrlCode = 3;
|
||||
const CURLUE_UNKNOWN_PART: UrlCode = 9;
|
||||
|
||||
fn no_part(index: usize) -> UrlCode {
|
||||
match index {
|
||||
1..=6 => 9 + index as UrlCode,
|
||||
8 => 16,
|
||||
9 => 17,
|
||||
_ => 13,
|
||||
}
|
||||
}
|
||||
|
||||
const URL: c_int = 0;
|
||||
const PARTS: usize = 11;
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub struct Url {
|
||||
|
||||
parts: [Option<String>; PARTS],
|
||||
}
|
||||
|
||||
impl Url {
|
||||
|
||||
fn parse(&mut self, url: &str) -> bool {
|
||||
let Some((scheme, rest)) = url.split_once("://") else {
|
||||
return false;
|
||||
};
|
||||
let (rest, fragment) = rest.split_once('#').map_or((rest, None), |(a, b)| (a, Some(b)));
|
||||
let (rest, query) = rest.split_once('?').map_or((rest, None), |(a, b)| (a, Some(b)));
|
||||
let (authority, path) = rest.find('/').map_or((rest, "/"), |i| (&rest[..i], &rest[i..]));
|
||||
let (user_info, host_port) = authority.rsplit_once('@').map_or((None, authority), |(a, b)| (Some(a), b));
|
||||
let (user, password) = match user_info {
|
||||
Some(u) => u.split_once(':').map_or((Some(u), None), |(a, b)| (Some(a), Some(b))),
|
||||
None => (None, None),
|
||||
};
|
||||
let (host, port) = match host_port.rsplit_once(':') {
|
||||
Some((h, p)) if !p.contains(']') && p.bytes().all(|b| b.is_ascii_digit()) => (h, Some(p)),
|
||||
_ => (host_port, None),
|
||||
};
|
||||
if host.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let owned = |s: Option<&str>| s.map(str::to_owned);
|
||||
self.parts = Default::default();
|
||||
self.parts[1] = Some(scheme.to_owned());
|
||||
self.parts[2] = owned(user);
|
||||
self.parts[3] = owned(password);
|
||||
self.parts[5] = Some(host.to_owned());
|
||||
self.parts[6] = owned(port);
|
||||
self.parts[7] = Some(path.to_owned());
|
||||
self.parts[8] = owned(query);
|
||||
self.parts[9] = owned(fragment);
|
||||
true
|
||||
}
|
||||
|
||||
fn whole(&self) -> Option<String> {
|
||||
let p = &self.parts;
|
||||
let mut out = format!("{}://", p[1].as_deref()?);
|
||||
if let Some(user) = &p[2] {
|
||||
out.push_str(user);
|
||||
if let Some(password) = &p[3] {
|
||||
out.push(':');
|
||||
out.push_str(password);
|
||||
}
|
||||
out.push('@');
|
||||
}
|
||||
out.push_str(p[5].as_deref()?);
|
||||
if let Some(port) = &p[6] {
|
||||
out.push(':');
|
||||
out.push_str(port);
|
||||
}
|
||||
out.push_str(p[7].as_deref().unwrap_or("/"));
|
||||
if let Some(query) = &p[8] {
|
||||
out.push('?');
|
||||
out.push_str(query);
|
||||
}
|
||||
if let Some(fragment) = &p[9] {
|
||||
out.push('#');
|
||||
out.push_str(fragment);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
}
|
||||
|
||||
fn url<'a>(u: *mut Url) -> Option<&'a mut Url> {
|
||||
|
||||
unsafe { u.as_mut() }
|
||||
}
|
||||
|
||||
pub extern "C" fn curl_url() -> *mut Url {
|
||||
Box::into_raw(Box::default())
|
||||
}
|
||||
pub extern "C" fn curl_url_cleanup(u: *mut Url) {
|
||||
if !u.is_null() {
|
||||
|
||||
drop(unsafe { Box::from_raw(u) });
|
||||
}
|
||||
}
|
||||
pub extern "C" fn curl_url_dup(u: *mut Url) -> *mut Url {
|
||||
url(u).map_or(std::ptr::null_mut(), |u| Box::into_raw(Box::new(u.clone())))
|
||||
}
|
||||
|
||||
pub extern "C" fn curl_url_set(u: *mut Url, what: c_int, content: *const c_char, _flags: c_uint) -> UrlCode {
|
||||
let Some(u) = url(u) else {
|
||||
return CURLUE_BAD_HANDLE;
|
||||
};
|
||||
let Some(index) = usize::try_from(what).ok().filter(|&i| i < PARTS) else {
|
||||
return CURLUE_UNKNOWN_PART;
|
||||
};
|
||||
let value = text(content).map(|c| c.to_string_lossy().into_owned());
|
||||
if what == URL {
|
||||
return match value {
|
||||
Some(v) if u.parse(&v) => CURLUE_OK,
|
||||
Some(_) => CURLUE_MALFORMED_INPUT,
|
||||
None => {
|
||||
*u = Url::default();
|
||||
CURLUE_OK
|
||||
}
|
||||
};
|
||||
}
|
||||
u.parts[index] = value;
|
||||
CURLUE_OK
|
||||
}
|
||||
|
||||
pub extern "C" fn curl_url_get(u: *mut Url, what: c_int, out: *mut *mut c_char, _flags: c_uint) -> UrlCode {
|
||||
let Some(u) = url(u) else {
|
||||
return CURLUE_BAD_HANDLE;
|
||||
};
|
||||
if out.is_null() {
|
||||
return CURLUE_BAD_PARTPOINTER;
|
||||
}
|
||||
let Some(index) = usize::try_from(what).ok().filter(|&i| i < PARTS) else {
|
||||
return CURLUE_UNKNOWN_PART;
|
||||
};
|
||||
let value = match what {
|
||||
URL => u.whole(),
|
||||
|
||||
7 => Some(u.parts[7].clone().unwrap_or_else(|| "/".into())),
|
||||
_ => u.parts[index].clone(),
|
||||
};
|
||||
|
||||
unsafe { out.write(std::ptr::null_mut()) };
|
||||
match value {
|
||||
Some(v) => {
|
||||
|
||||
unsafe { out.write(give(v.as_bytes())) };
|
||||
CURLUE_OK
|
||||
}
|
||||
None if what == URL => CURLUE_MALFORMED_INPUT,
|
||||
None => no_part(index),
|
||||
}
|
||||
}
|
||||
|
||||
pub extern "C" fn curl_version() -> *const c_char {
|
||||
c"libcurl/7.76.0 (eonacat-xs, offline)".as_ptr()
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct VersionInfo {
|
||||
age: c_int,
|
||||
version: *const c_char,
|
||||
version_num: c_uint,
|
||||
host: *const c_char,
|
||||
features: c_int,
|
||||
ssl_version: *const c_char,
|
||||
ssl_version_num: c_long,
|
||||
libz_version: *const c_char,
|
||||
protocols: *const *const c_char,
|
||||
ares: *const c_char,
|
||||
ares_num: c_int,
|
||||
libidn: *const c_char,
|
||||
iconv_ver_num: c_int,
|
||||
libssh_version: *const c_char,
|
||||
brotli_ver_num: c_uint,
|
||||
brotli_version: *const c_char,
|
||||
nghttp2_ver_num: c_uint,
|
||||
nghttp2_version: *const c_char,
|
||||
quic_version: *const c_char,
|
||||
}
|
||||
|
||||
struct Shared<T>(T);
|
||||
|
||||
unsafe impl<T> Sync for Shared<T> {}
|
||||
|
||||
unsafe impl<T> Send for Shared<T> {}
|
||||
|
||||
pub extern "C" fn curl_version_info(_age: c_int) -> *const VersionInfo {
|
||||
static PROTOCOLS: Shared<[*const c_char; 3]> = Shared([c"http".as_ptr(), c"https".as_ptr(), std::ptr::null()]);
|
||||
static INFO: OnceLock<Shared<VersionInfo>> = OnceLock::new();
|
||||
let null = std::ptr::null();
|
||||
let info = INFO.get_or_init(|| {
|
||||
Shared(VersionInfo {
|
||||
age: 5,
|
||||
version: c"7.76.0".as_ptr(),
|
||||
version_num: 0x07_4c_00,
|
||||
host: c"x86_64-pc-win32".as_ptr(),
|
||||
features: 1 << 0 | 1 << 9,
|
||||
ssl_version: null,
|
||||
ssl_version_num: 0,
|
||||
libz_version: null,
|
||||
protocols: PROTOCOLS.0.as_ptr(),
|
||||
ares: null,
|
||||
ares_num: 0,
|
||||
libidn: null,
|
||||
iconv_ver_num: 0,
|
||||
libssh_version: null,
|
||||
brotli_ver_num: 0,
|
||||
brotli_version: null,
|
||||
nghttp2_ver_num: 0,
|
||||
nghttp2_version: null,
|
||||
quic_version: null,
|
||||
})
|
||||
});
|
||||
&info.0
|
||||
}
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "xcurl",
|
||||
dlls: &["xcurl.dll"],
|
||||
exports: vec![
|
||||
hle_export!(curl_easy_cleanup),
|
||||
hle_export!(curl_easy_duphandle),
|
||||
hle_export!(curl_easy_escape),
|
||||
hle_export!(curl_easy_getinfo),
|
||||
hle_export!(curl_easy_init),
|
||||
hle_export!(curl_easy_perform),
|
||||
hle_export!(curl_easy_reset),
|
||||
hle_export!(curl_easy_setopt),
|
||||
hle_export!(curl_easy_strerror),
|
||||
hle_export!(curl_easy_unescape),
|
||||
hle_export!(curl_escape),
|
||||
hle_export!(curl_formadd),
|
||||
hle_export!(curl_formfree),
|
||||
hle_export!(curl_formget),
|
||||
hle_export!(curl_free),
|
||||
hle_export!(curl_getdate),
|
||||
hle_export!(curl_global_cleanup),
|
||||
hle_export!(curl_global_init),
|
||||
hle_export!(curl_global_init_mem),
|
||||
hle_export!(curl_global_sslset),
|
||||
hle_export!(curl_mime_addpart),
|
||||
hle_export!(curl_mime_data),
|
||||
hle_export!(curl_mime_data_cb),
|
||||
hle_export!(curl_mime_encoder),
|
||||
hle_export!(curl_mime_filedata),
|
||||
hle_export!(curl_mime_filename),
|
||||
hle_export!(curl_mime_free),
|
||||
hle_export!(curl_mime_headers),
|
||||
hle_export!(curl_mime_init),
|
||||
hle_export!(curl_mime_name),
|
||||
hle_export!(curl_mime_subparts),
|
||||
hle_export!(curl_mime_type),
|
||||
hle_export!(curl_multi_add_handle),
|
||||
hle_export!(curl_multi_cleanup),
|
||||
hle_export!(curl_multi_info_read),
|
||||
hle_export!(curl_multi_init),
|
||||
hle_export!(curl_multi_perform),
|
||||
hle_export!(curl_multi_poll),
|
||||
hle_export!(curl_multi_remove_handle),
|
||||
hle_export!(curl_multi_setopt),
|
||||
hle_export!(curl_multi_strerror),
|
||||
hle_export!(curl_multi_wait),
|
||||
hle_export!(curl_multi_wakeup),
|
||||
hle_export!(curl_share_cleanup),
|
||||
hle_export!(curl_share_init),
|
||||
hle_export!(curl_share_setopt),
|
||||
hle_export!(curl_share_strerror),
|
||||
hle_export!(curl_slist_append),
|
||||
hle_export!(curl_slist_free_all),
|
||||
hle_export!(curl_unescape),
|
||||
hle_export!(curl_url),
|
||||
hle_export!(curl_url_cleanup),
|
||||
hle_export!(curl_url_dup),
|
||||
hle_export!(curl_url_get),
|
||||
hle_export!(curl_url_set),
|
||||
hle_export!(curl_version),
|
||||
hle_export!(curl_version_info),
|
||||
hle_export!(xcurl_global_init_mem),
|
||||
hle_export!(xcurl_global_resume),
|
||||
hle_export!(xcurl_global_set_request_limit),
|
||||
hle_export!(xcurl_global_suspend),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,275 @@
|
||||
|
||||
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::{CStr, c_char, c_void};
|
||||
|
||||
use super::xasync::E_INVALIDARG;
|
||||
use super::xgameruntime::{
|
||||
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text, token, with_spare,
|
||||
};
|
||||
use crate::hle::runtime;
|
||||
|
||||
pub const TITLE_PROVIDER: Guid = Guid::new(
|
||||
0x973a_344e,
|
||||
0x24bf,
|
||||
0x4d0f,
|
||||
[0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29],
|
||||
);
|
||||
|
||||
pub const TITLE_IID: Guid = Guid::new(
|
||||
0x2549_f142,
|
||||
0x6419,
|
||||
0x4a06,
|
||||
[0x97, 0xb5, 0x93, 0x1a, 0xab, 0x7c, 0x2f, 0x34],
|
||||
);
|
||||
|
||||
pub const FEATURES: Guid = Guid::new(
|
||||
0x8836_fe87,
|
||||
0xedb9,
|
||||
0x4fe3,
|
||||
[0x8d, 0xad, 0x05, 0xf0, 0xd2, 0xcd, 0x5b, 0x40],
|
||||
);
|
||||
pub const INVITES: Guid = Guid::new(
|
||||
0x0651_aae2,
|
||||
0x4012,
|
||||
0x4077,
|
||||
[0xbf, 0x84, 0x8b, 0x90, 0x97, 0x09, 0x0e, 0x2c],
|
||||
);
|
||||
pub const EVENTS: Guid = Guid::new(
|
||||
0xbbfb_dcc7,
|
||||
0xbfe7,
|
||||
0x409b,
|
||||
[0xa5, 0xca, 0xed, 0xf0, 0x54, 0x96, 0x0b, 0x4d],
|
||||
);
|
||||
|
||||
pub const PENDING_INVITES_IID: Guid = Guid::new(
|
||||
0x014d_1cc3,
|
||||
0xbcfe,
|
||||
0x41ff,
|
||||
[0xb2, 0xf0, 0xe1, 0xef, 0x07, 0x15, 0x58, 0x28],
|
||||
);
|
||||
|
||||
pub const ACTIVATION_PROVIDER: Guid = Guid::new(
|
||||
0x7f0f_e8b8,
|
||||
0xe075,
|
||||
0x49ab,
|
||||
[0x9a, 0xa7, 0xa1, 0xe0, 0x65, 0x48, 0x9a, 0x9e],
|
||||
);
|
||||
pub const ACTIVATION_IID: Guid = Guid::new(
|
||||
0x2e4f_76fe,
|
||||
0x0fc7,
|
||||
0x461e,
|
||||
[0xab, 0x4d, 0xa4, 0x49, 0x94, 0x34, 0xc3, 0xcf],
|
||||
);
|
||||
|
||||
pub const PROTOCOL_PROVIDER: Guid = Guid::new(
|
||||
0x95fd_18d2,
|
||||
0x74dd,
|
||||
0x4d7c,
|
||||
[0xaa, 0x1b, 0x0b, 0x51, 0x82, 0x76, 0x65, 0xd6],
|
||||
);
|
||||
pub const PROTOCOL_IID: Guid = Guid::new(
|
||||
0x026b_010c,
|
||||
0x06c3,
|
||||
0x4cdd,
|
||||
[0xbb, 0xcb, 0x43, 0xf2, 0x29, 0xdb, 0x1c, 0xff],
|
||||
);
|
||||
|
||||
pub static TITLE_OBJECT: Object = Object::new("title", &TITLE_VTABLE);
|
||||
pub static ACTIVATION_OBJECT: Object = Object::new("activation", &ACTIVATION_VTABLE);
|
||||
pub static PROTOCOL_OBJECT: Object = Object::new("protocol activation", &PROTOCOL_VTABLE);
|
||||
pub static FEATURES_OBJECT: Object = Object::new("features", &FEATURES_VTABLE);
|
||||
pub static INVITES_OBJECT: Object = Object::new("invites", &INVITES_VTABLE);
|
||||
pub static EVENTS_OBJECT: Object = Object::new("events", &EVENTS_VTABLE);
|
||||
|
||||
pub const INTERFACES: &[Interface] = &[
|
||||
(TITLE_PROVIDER, TITLE_IID, &TITLE_OBJECT),
|
||||
(FEATURES, FEATURES, &FEATURES_OBJECT),
|
||||
(INVITES, INVITES, &INVITES_OBJECT),
|
||||
(INVITES, PENDING_INVITES_IID, &INVITES_OBJECT),
|
||||
(EVENTS, EVENTS, &EVENTS_OBJECT),
|
||||
(ACTIVATION_PROVIDER, ACTIVATION_IID, &ACTIVATION_OBJECT),
|
||||
(PROTOCOL_PROVIDER, PROTOCOL_IID, &PROTOCOL_OBJECT),
|
||||
];
|
||||
|
||||
type This = *const Object;
|
||||
|
||||
extern "system" fn title_id(_: This, out: *mut u32) -> HRESULT {
|
||||
put(out, runtime::title().id)
|
||||
}
|
||||
|
||||
extern "system" fn launch_new_game(
|
||||
_: This,
|
||||
exe: *const c_char,
|
||||
args: *const c_char,
|
||||
_user: *const c_void,
|
||||
) {
|
||||
let (exe, args) = (text(exe).unwrap_or_default(), text(args).unwrap_or_default());
|
||||
tracing::info!(exe, args, "XLaunchNewGame");
|
||||
let current = runtime::main_image()
|
||||
.and_then(runtime::image_path)
|
||||
.unwrap_or_default();
|
||||
let ours: Vec<_> = std::env::args_os().skip(1).collect();
|
||||
let command = relaunch_args(ours, current.as_os_str(), &exe, &args);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
super::lifecycle::end_title(
|
||||
"XLaunchNewGame",
|
||||
Box::new(move || super::lifecycle::relaunch(command)),
|
||||
);
|
||||
loop {
|
||||
std::thread::park();
|
||||
}
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = command;
|
||||
}
|
||||
|
||||
fn relaunch_args(
|
||||
ours: Vec<std::ffi::OsString>,
|
||||
current: &std::ffi::OsStr,
|
||||
exe: &str,
|
||||
args: &str,
|
||||
) -> Vec<std::ffi::OsString> {
|
||||
let mut out: Vec<_> = ours.into_iter().take_while(|a| a != "--").collect();
|
||||
|
||||
if !exe.is_empty()
|
||||
&& let Some(slot) = out.iter_mut().find(|a| {
|
||||
a.as_os_str() == current
|
||||
|| std::path::absolute(a).is_ok_and(|p| p.as_os_str() == current)
|
||||
})
|
||||
{
|
||||
*slot = exe.into();
|
||||
}
|
||||
if !args.trim().is_empty() {
|
||||
out.push("--".into());
|
||||
out.extend(split_args(args).into_iter().map(Into::into));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn split_args(args: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut current = String::new();
|
||||
let mut quoted = false;
|
||||
let mut started = false;
|
||||
for c in args.chars() {
|
||||
match c {
|
||||
'"' => {
|
||||
quoted = !quoted;
|
||||
started = true;
|
||||
}
|
||||
c if !quoted && c.is_whitespace() => {
|
||||
if started {
|
||||
out.push(std::mem::take(&mut current));
|
||||
started = false;
|
||||
}
|
||||
}
|
||||
c => {
|
||||
current.push(c);
|
||||
started = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if started {
|
||||
out.push(current);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
const AVAILABLE: [u32; 20] = [
|
||||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20,
|
||||
];
|
||||
|
||||
extern "system" fn is_feature_available(_: This, feature: u32) -> bool {
|
||||
AVAILABLE.contains(&feature)
|
||||
}
|
||||
|
||||
extern "system" fn register(
|
||||
_: This,
|
||||
_queue: *const c_void,
|
||||
_context: *mut c_void,
|
||||
_callback: *const c_void,
|
||||
out: *mut u64,
|
||||
) -> HRESULT {
|
||||
put(out, token())
|
||||
}
|
||||
extern "system" fn unregister(_: This, _token: u64, _wait: bool) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
extern "system" fn accept_pending_invite(_: This, uri: *const c_char) -> HRESULT {
|
||||
tracing::info!(
|
||||
uri = text(uri).unwrap_or_default(),
|
||||
"an invite accepted: none is pending offline"
|
||||
);
|
||||
E_INVALIDARG
|
||||
}
|
||||
|
||||
extern "system" fn write_event(
|
||||
_: This,
|
||||
_user: *const c_void,
|
||||
_service_config: *const c_char,
|
||||
_session: *const c_char,
|
||||
name: *const c_char,
|
||||
_dimensions: *const c_char,
|
||||
_measurements: *const c_char,
|
||||
) -> HRESULT {
|
||||
if !name.is_null() {
|
||||
|
||||
let name = unsafe { CStr::from_ptr(name) }.to_string_lossy();
|
||||
tracing::debug!(%name, "game event dropped");
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
static TITLE_VTABLE: Methods<14> = with_spare([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
title_id as *const (),
|
||||
launch_new_game as *const (),
|
||||
missing::<5> as *const (),
|
||||
]);
|
||||
|
||||
static FEATURES_VTABLE: Methods<12> = with_spare([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
is_feature_available as *const (),
|
||||
]);
|
||||
|
||||
static INVITES_VTABLE: Methods<16> = with_spare([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
register as *const (),
|
||||
unregister as *const (),
|
||||
register as *const (),
|
||||
unregister as *const (),
|
||||
accept_pending_invite as *const (),
|
||||
]);
|
||||
static ACTIVATION_VTABLE: Methods<6> = Methods([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
register as *const (),
|
||||
unregister as *const (),
|
||||
accept_pending_invite as *const (),
|
||||
]);
|
||||
static PROTOCOL_VTABLE: Methods<5> = Methods([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
register as *const (),
|
||||
unregister as *const (),
|
||||
]);
|
||||
|
||||
static EVENTS_VTABLE: Methods<12> = with_spare([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
write_event as *const (),
|
||||
]);
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
|
||||
|
||||
#![allow(non_snake_case)]
|
||||
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::{CStr, c_char, c_void};
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use super::{
|
||||
display, speech, storage, xasync, xgame, xgamesave, xgameui, xnetworking, xpackage, xstore,
|
||||
xsystem, xuser,
|
||||
};
|
||||
use crate::hle::{HleModule};
|
||||
use crate::hle_export;
|
||||
|
||||
pub type HRESULT = i32;
|
||||
pub const S_OK: HRESULT = 0;
|
||||
|
||||
pub const NOT_SUPPORTED: HRESULT = 0x8007_0032_u32 as i32;
|
||||
|
||||
pub const E_POINTER: HRESULT = 0x8000_4003_u32 as i32;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Guid {
|
||||
pub data1: u32,
|
||||
pub data2: u16,
|
||||
pub data3: u16,
|
||||
pub data4: [u8; 8],
|
||||
}
|
||||
|
||||
impl Guid {
|
||||
pub const fn new(data1: u32, data2: u16, data3: u16, data4: [u8; 8]) -> Guid {
|
||||
Guid {
|
||||
data1,
|
||||
data2,
|
||||
data3,
|
||||
data4,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Guid {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let d = self.data4;
|
||||
write!(
|
||||
f,
|
||||
"{:08x}-{:04x}-{:04x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
|
||||
self.data1, self.data2, self.data3, d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct Object {
|
||||
vtable: *const *const (),
|
||||
|
||||
area: &'static str,
|
||||
|
||||
slots: usize,
|
||||
}
|
||||
|
||||
unsafe impl Sync for Object {}
|
||||
|
||||
impl Object {
|
||||
pub const fn new<const N: usize>(area: &'static str, methods: &'static Methods<N>) -> Object {
|
||||
Object {
|
||||
vtable: methods.0.as_ptr(),
|
||||
area,
|
||||
slots: N,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Methods<const N: usize>(pub [*const (); N]);
|
||||
|
||||
unsafe impl<const N: usize> Sync for Methods<N> {}
|
||||
|
||||
macro_rules! spare {
|
||||
($($slot:literal)*) => { [$(missing::<$slot> as *const ()),*] };
|
||||
}
|
||||
|
||||
pub const fn with_spare<const K: usize, const N: usize>(known: [*const (); K]) -> Methods<N> {
|
||||
let spare = spare!(
|
||||
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
||||
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
||||
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
||||
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
|
||||
);
|
||||
assert!(K <= N && N <= spare.len());
|
||||
let mut table = [std::ptr::null(); N];
|
||||
let mut i = 0;
|
||||
while i < N {
|
||||
table[i] = if i < K { known[i] } else { spare[i] };
|
||||
i += 1;
|
||||
}
|
||||
Methods(table)
|
||||
}
|
||||
|
||||
pub type Interface = (Guid, Guid, &'static Object);
|
||||
|
||||
const AREAS: &[&[Interface]] = &[
|
||||
xasync::INTERFACES,
|
||||
xuser::INTERFACES,
|
||||
xsystem::INTERFACES,
|
||||
xgame::INTERFACES,
|
||||
storage::INTERFACES,
|
||||
xnetworking::INTERFACES,
|
||||
xpackage::INTERFACES,
|
||||
display::INTERFACES,
|
||||
xgamesave::INTERFACES,
|
||||
xstore::INTERFACES,
|
||||
xgameui::INTERFACES,
|
||||
speech::INTERFACES,
|
||||
ERROR_INTERFACES,
|
||||
];
|
||||
|
||||
pub extern "system" fn add_ref(_: *const Object) -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
pub extern "system" fn missing<const SLOT: usize>(this: *const Object) -> HRESULT {
|
||||
|
||||
let area = unsafe { (*this).area };
|
||||
tracing::warn!(
|
||||
area,
|
||||
slot = format_args!("{:#x}", SLOT * 8),
|
||||
"runtime method not implemented"
|
||||
);
|
||||
xasync::E_NOTIMPL
|
||||
}
|
||||
|
||||
pub fn put<T>(out: *mut T, value: T) -> HRESULT {
|
||||
if out.is_null() {
|
||||
return xasync::E_INVALIDARG;
|
||||
}
|
||||
|
||||
unsafe { out.write(value) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub fn put_string(text: &str, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT {
|
||||
let len = text.len() + 1;
|
||||
if buffer.is_null() || size < len {
|
||||
return xasync::E_NOT_SUFFICIENT_BUFFER;
|
||||
}
|
||||
|
||||
unsafe {
|
||||
buffer.copy_from_nonoverlapping(text.as_ptr(), text.len());
|
||||
buffer.add(text.len()).write(0);
|
||||
}
|
||||
if !used.is_null() {
|
||||
|
||||
unsafe { used.write(len) };
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub fn text(s: *const c_char) -> Option<String> {
|
||||
|
||||
(!s.is_null()).then(|| unsafe { CStr::from_ptr(s) }.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
pub fn token() -> u64 {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(1);
|
||||
NEXT.fetch_add(1, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub extern "system" fn XGameRuntimeInitialize() -> HRESULT {
|
||||
tracing::info!("XGameRuntimeInitialize");
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub extern "system" fn XGameRuntimeUninitialize() {
|
||||
tracing::info!("XGameRuntimeUninitialize");
|
||||
}
|
||||
|
||||
static RUNTIME_BUILD: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
pub fn runtime_build() -> u64 {
|
||||
RUNTIME_BUILD.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn note_build(build: u64) {
|
||||
let _ = RUNTIME_BUILD.compare_exchange(0, build, Ordering::Relaxed, Ordering::Relaxed);
|
||||
eonacat_xsbox_gpu::device::note_runtime_build(build);
|
||||
}
|
||||
|
||||
pub extern "system" fn InitializeApiImpl(version: u64, build: u64) -> HRESULT {
|
||||
tracing::info!(version, build, "InitializeApiImpl");
|
||||
note_build(build);
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub extern "system" fn InitializeApiImplEx(version: u64, build: u64, flags: u64) -> HRESULT {
|
||||
tracing::info!(version, build, flags, "InitializeApiImplEx");
|
||||
note_build(build);
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub extern "system" fn InitializeApiImplEx2(
|
||||
version: u64,
|
||||
build: u64,
|
||||
flags: u64,
|
||||
options: *const c_void,
|
||||
) -> HRESULT {
|
||||
tracing::info!(version, build, flags, ?options, "InitializeApiImplEx2");
|
||||
note_build(build);
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub extern "system" fn UninitializeApiImpl() {
|
||||
tracing::info!("UninitializeApiImpl");
|
||||
}
|
||||
|
||||
pub extern "system" fn QueryApiImpl(
|
||||
provider: *const Guid,
|
||||
iid: *const Guid,
|
||||
out: *mut *mut c_void,
|
||||
) -> HRESULT {
|
||||
|
||||
static QUERIED: Mutex<Vec<(Guid, Guid, u64)>> = Mutex::new(Vec::new());
|
||||
if out.is_null() {
|
||||
return E_POINTER;
|
||||
}
|
||||
|
||||
let (Some(&provider), Some(&iid)) = (unsafe { provider.as_ref() }, unsafe { iid.as_ref() })
|
||||
else {
|
||||
return NOT_SUPPORTED;
|
||||
};
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if tracing::enabled!(tracing::Level::DEBUG) {
|
||||
|
||||
static CALLS: Mutex<Vec<String>> = Mutex::new(Vec::new());
|
||||
let from = super::kernel::callers();
|
||||
let mut calls = CALLS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if !calls.contains(&from) {
|
||||
tracing::debug!(%provider, %iid, %from, "runtime call");
|
||||
calls.push(from);
|
||||
}
|
||||
}
|
||||
let found = AREAS
|
||||
.iter()
|
||||
.flat_map(|area| area.iter())
|
||||
.find(|(p, i, _)| (*p, *i) == (provider, iid));
|
||||
if let Some(&(_, _, object)) = found {
|
||||
|
||||
unsafe { out.write((object as *const Object).cast_mut().cast()) };
|
||||
return S_OK;
|
||||
}
|
||||
let mut queried = QUERIED.lock().unwrap_or_else(|e| e.into_inner());
|
||||
match queried.iter_mut().find(|(p, i, _)| (*p, *i) == (provider, iid)) {
|
||||
None => {
|
||||
queried.push((provider, iid, 1));
|
||||
tracing::warn!(%provider, %iid, "runtime API area not implemented");
|
||||
}
|
||||
|
||||
Some((_, _, calls)) => {
|
||||
*calls += 1;
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if calls.is_power_of_two() {
|
||||
tracing::info!(%provider, %iid, calls = *calls, "runtime API area not implemented, asked again");
|
||||
}
|
||||
}
|
||||
}
|
||||
NOT_SUPPORTED
|
||||
}
|
||||
|
||||
pub extern "system" fn XErrorReport(hr: HRESULT, message: *const c_char) {
|
||||
let text = if message.is_null() {
|
||||
"".into()
|
||||
} else {
|
||||
|
||||
unsafe { CStr::from_ptr(message) }.to_string_lossy()
|
||||
};
|
||||
tracing::warn!(hr = format_args!("{:#010x}", hr as u32), message = %text, "XErrorReport");
|
||||
let callback = *ERROR_CALLBACK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some((callback, context)) = callback {
|
||||
|
||||
let callback: ErrorCallback = unsafe { std::mem::transmute(callback) };
|
||||
let message = if message.is_null() {
|
||||
c"".as_ptr()
|
||||
} else {
|
||||
message
|
||||
};
|
||||
callback(hr, message, context as *mut c_void);
|
||||
}
|
||||
}
|
||||
|
||||
type ErrorCallback = extern "system" fn(HRESULT, *const c_char, *mut c_void) -> bool;
|
||||
|
||||
static ERROR_CALLBACK: Mutex<Option<(usize, usize)>> = Mutex::new(None);
|
||||
|
||||
pub const ERROR_AREA: Guid = Guid::new(
|
||||
0x8ca4_67f7,
|
||||
0x22e8,
|
||||
0x4096,
|
||||
[0x84, 0x56, 0xbb, 0x8a, 0xa1, 0x3f, 0x79, 0xd8],
|
||||
);
|
||||
static ERROR_OBJECT: Object = Object::new("errors", &ERROR_METHODS);
|
||||
const ERROR_INTERFACES: &[Interface] = &[(ERROR_AREA, ERROR_AREA, &ERROR_OBJECT)];
|
||||
|
||||
extern "system" fn error_report(_: *const Object, hr: HRESULT, message: *const c_char) {
|
||||
XErrorReport(hr, message);
|
||||
}
|
||||
|
||||
extern "system" fn error_set_callback(
|
||||
_: *const Object,
|
||||
callback: Option<ErrorCallback>,
|
||||
context: *mut c_void,
|
||||
) {
|
||||
*ERROR_CALLBACK.lock().unwrap_or_else(|e| e.into_inner()) =
|
||||
callback.map(|c| (c as usize, context as usize));
|
||||
}
|
||||
|
||||
extern "system" fn error_set_options(_: *const Object, debugger: u32, no_debugger: u32) {
|
||||
tracing::info!(debugger, no_debugger, "XErrorSetOptions: logged only");
|
||||
}
|
||||
static ERROR_METHODS: Methods<6> = Methods([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
error_report as *const (),
|
||||
error_set_callback as *const (),
|
||||
error_set_options as *const (),
|
||||
]);
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "xgameruntime",
|
||||
dlls: &["xgameruntime.dll"],
|
||||
exports: vec![
|
||||
hle_export!(XGameRuntimeInitialize),
|
||||
hle_export!(XGameRuntimeUninitialize),
|
||||
hle_export!(InitializeApiImpl),
|
||||
hle_export!(InitializeApiImplEx),
|
||||
hle_export!(InitializeApiImplEx2),
|
||||
hle_export!(UninitializeApiImpl),
|
||||
hle_export!(QueryApiImpl),
|
||||
hle_export!(XErrorReport),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,636 @@
|
||||
|
||||
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::{c_char, c_void};
|
||||
|
||||
use super::xasync::{self, AsyncBlock, E_ABORT};
|
||||
use super::xgameruntime::{
|
||||
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text, with_spare,
|
||||
};
|
||||
|
||||
pub const PROVIDER: Guid = Guid::new(
|
||||
0xdfcd_4649,
|
||||
0x4ff8,
|
||||
0x4043,
|
||||
[0xba, 0x07, 0x35, 0xd6, 0x07, 0xdf, 0x98, 0xb0],
|
||||
);
|
||||
|
||||
pub const IID_2026: Guid = Guid::new(
|
||||
0xeaf6_69df,
|
||||
0x5542,
|
||||
0x4590,
|
||||
[0x99, 0xa3, 0x8d, 0xc0, 0x61, 0xf8, 0x37, 0xcc],
|
||||
);
|
||||
|
||||
pub static OBJECT: Object = Object::new("game ui", &VTABLE);
|
||||
pub const INTERFACES: &[Interface] = &[(PROVIDER, IID_2026, &OBJECT)];
|
||||
|
||||
type This = *const Object;
|
||||
|
||||
static PROFILE: u8 = 0;
|
||||
static TEXT: u8 = 0;
|
||||
|
||||
extern "system" fn profile_card_async(
|
||||
_: This,
|
||||
block: *mut AsyncBlock,
|
||||
_user: *const c_void,
|
||||
xuid: u64,
|
||||
) -> HRESULT {
|
||||
tracing::info!(xuid, "profile card: nothing to show");
|
||||
xasync::finished(block, (&raw const PROFILE).cast(), S_OK)
|
||||
}
|
||||
extern "system" fn profile_card_result(_: This, block: *mut AsyncBlock) -> HRESULT {
|
||||
let none = std::ptr::null_mut();
|
||||
xasync::XAsyncGetResult(block, (&raw const PROFILE).cast(), 0, none, none.cast())
|
||||
}
|
||||
|
||||
extern "system" fn text_entry_async(
|
||||
_: This,
|
||||
block: *mut AsyncBlock,
|
||||
title: *const c_char,
|
||||
description: *const c_char,
|
||||
default: *const c_char,
|
||||
scope: u32,
|
||||
max_length: u32,
|
||||
) -> HRESULT {
|
||||
let [title, description, default] =
|
||||
[title, description, default].map(|t| text(t).unwrap_or_default());
|
||||
let max_length = max_length_for(scope, max_length);
|
||||
|
||||
let password = scope == PASSWORD;
|
||||
tracing::info!(title, description, max_length, password, "text entry");
|
||||
xasync::pending_with(block, (&raw const TEXT).cast(), move || {
|
||||
match ask(&title, &description, &default, max_length, password) {
|
||||
Some(typed) => {
|
||||
tracing::info!(length = typed.chars().count(), "text entry: done");
|
||||
let mut bytes = limit(&typed, max_length).into_bytes();
|
||||
bytes.push(0);
|
||||
Ok(bytes)
|
||||
}
|
||||
None => {
|
||||
tracing::info!("text entry: cancelled");
|
||||
Err(E_ABORT)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
extern "system" fn text_entry_size(_: This, block: *mut AsyncBlock, out: *mut u32) -> HRESULT {
|
||||
let mut size = 0;
|
||||
let hr = xasync::XAsyncGetResultSize(block, &mut size);
|
||||
if hr < 0 {
|
||||
return hr;
|
||||
}
|
||||
put(out, size as u32)
|
||||
}
|
||||
extern "system" fn text_entry_result(
|
||||
_: This,
|
||||
block: *mut AsyncBlock,
|
||||
size: u32,
|
||||
buffer: *mut c_char,
|
||||
used: *mut u32,
|
||||
) -> HRESULT {
|
||||
let mut written = 0;
|
||||
let identity = (&raw const TEXT).cast();
|
||||
let hr = xasync::XAsyncGetResult(block, identity, size as usize, buffer.cast(), &mut written);
|
||||
if hr < 0 || used.is_null() {
|
||||
return hr;
|
||||
}
|
||||
put(used, written as u32)
|
||||
}
|
||||
|
||||
static MESSAGE: u8 = 0;
|
||||
static ERROR: u8 = 0;
|
||||
static CLOSED: u8 = 0;
|
||||
static PICKER: u8 = 0;
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
extern "system" fn message_dialog_async(
|
||||
_: This,
|
||||
block: *mut AsyncBlock,
|
||||
title: *const c_char,
|
||||
content: *const c_char,
|
||||
first: *const c_char,
|
||||
second: *const c_char,
|
||||
third: *const c_char,
|
||||
default: u32,
|
||||
cancel: u32,
|
||||
) -> HRESULT {
|
||||
let [title, content] = [title, content].map(|t| text(t).unwrap_or_default());
|
||||
|
||||
let buttons: Vec<(u32, String)> = [first, second, third]
|
||||
.into_iter()
|
||||
.zip(0..)
|
||||
.filter_map(|(label, i)| text(label).filter(|l| !l.is_empty()).map(|l| (i, l)))
|
||||
.collect();
|
||||
if buttons.is_empty() {
|
||||
return xasync::E_INVALIDARG;
|
||||
}
|
||||
tracing::info!(title, buttons = buttons.len(), "message dialog");
|
||||
xasync::pending_with(block, (&raw const MESSAGE).cast(), move || {
|
||||
let chosen = choose(&title, &content, &buttons, default, cancel);
|
||||
tracing::info!(chosen, "message dialog: done");
|
||||
Ok(chosen.to_le_bytes().to_vec())
|
||||
})
|
||||
}
|
||||
extern "system" fn message_dialog_result(
|
||||
_: This,
|
||||
block: *mut AsyncBlock,
|
||||
out: *mut u32,
|
||||
) -> HRESULT {
|
||||
xasync::result(block, (&raw const MESSAGE).cast(), out)
|
||||
}
|
||||
|
||||
extern "system" fn error_dialog_async(
|
||||
_: This,
|
||||
block: *mut AsyncBlock,
|
||||
error: HRESULT,
|
||||
context: *const c_char,
|
||||
) -> HRESULT {
|
||||
let context = text(context).unwrap_or_default();
|
||||
tracing::warn!(
|
||||
error = format_args!("{:#010x}", error as u32),
|
||||
context,
|
||||
"error dialog"
|
||||
);
|
||||
xasync::pending_with(block, (&raw const ERROR).cast(), move || {
|
||||
show_error(error, &context);
|
||||
Ok(Vec::new())
|
||||
})
|
||||
}
|
||||
extern "system" fn error_dialog_result(_: This, block: *mut AsyncBlock) -> HRESULT {
|
||||
let none = std::ptr::null_mut();
|
||||
xasync::XAsyncGetResult(block, (&raw const ERROR).cast(), 0, none, none.cast())
|
||||
}
|
||||
|
||||
extern "system" fn achievements_async(
|
||||
_: This,
|
||||
block: *mut AsyncBlock,
|
||||
_user: *const c_void,
|
||||
title_id: u32,
|
||||
) -> HRESULT {
|
||||
tracing::info!(title_id, "achievements: nothing to show");
|
||||
xasync::finished(block, (&raw const CLOSED).cast(), S_OK)
|
||||
}
|
||||
|
||||
fn dismissed(block: *mut AsyncBlock, what: &str) -> HRESULT {
|
||||
tracing::info!(what, "a page for other players: dismissed offline");
|
||||
xasync::finished(block, (&raw const CLOSED).cast(), E_ABORT)
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
extern "system" fn send_invite_async(
|
||||
_: This,
|
||||
block: *mut AsyncBlock,
|
||||
_user: *const c_void,
|
||||
_configuration: *const c_char,
|
||||
_template: *const c_char,
|
||||
_session: *const c_char,
|
||||
_text: *const c_char,
|
||||
_context: *const c_char,
|
||||
) -> HRESULT {
|
||||
dismissed(block, "send game invite")
|
||||
}
|
||||
extern "system" fn activity_invite_async(
|
||||
_: This,
|
||||
block: *mut AsyncBlock,
|
||||
_user: *const c_void,
|
||||
) -> HRESULT {
|
||||
dismissed(block, "multiplayer activity invite")
|
||||
}
|
||||
extern "system" fn state_share_async(
|
||||
_: This,
|
||||
block: *mut AsyncBlock,
|
||||
_user: *const c_void,
|
||||
_link: *const c_char,
|
||||
) -> HRESULT {
|
||||
dismissed(block, "state share")
|
||||
}
|
||||
|
||||
extern "system" fn closed_result(_: This, block: *mut AsyncBlock) -> HRESULT {
|
||||
let none = std::ptr::null_mut();
|
||||
xasync::XAsyncGetResult(block, (&raw const CLOSED).cast(), 0, none, none.cast())
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
extern "system" fn player_picker_async(
|
||||
_: This,
|
||||
block: *mut AsyncBlock,
|
||||
_user: *const c_void,
|
||||
_prompt: *const c_char,
|
||||
_count: u32,
|
||||
_players: *const u64,
|
||||
_preselected_count: u32,
|
||||
_preselected: *const u64,
|
||||
minimum: u32,
|
||||
_maximum: u32,
|
||||
) -> HRESULT {
|
||||
let result = if minimum == 0 {
|
||||
Ok(Vec::new())
|
||||
} else {
|
||||
Err(E_ABORT)
|
||||
};
|
||||
xasync::finished_with(block, (&raw const PICKER).cast(), result)
|
||||
}
|
||||
extern "system" fn player_picker_count(_: This, block: *mut AsyncBlock, out: *mut u32) -> HRESULT {
|
||||
let mut size = 0;
|
||||
let hr = xasync::XAsyncGetResultSize(block, &mut size);
|
||||
if hr < 0 {
|
||||
return hr;
|
||||
}
|
||||
put(out, (size / 8) as u32)
|
||||
}
|
||||
extern "system" fn player_picker_result(
|
||||
_: This,
|
||||
block: *mut AsyncBlock,
|
||||
count: u32,
|
||||
players: *mut u64,
|
||||
used: *mut u32,
|
||||
) -> HRESULT {
|
||||
let mut written = 0;
|
||||
let identity = (&raw const PICKER).cast();
|
||||
let hr = xasync::XAsyncGetResult(
|
||||
block,
|
||||
identity,
|
||||
count as usize * 8,
|
||||
players.cast(),
|
||||
&mut written,
|
||||
);
|
||||
if hr < 0 || used.is_null() {
|
||||
return hr;
|
||||
}
|
||||
put(used, (written / 8) as u32)
|
||||
}
|
||||
|
||||
extern "system" fn notification_position(_: This, _position: u32) -> HRESULT {
|
||||
S_OK
|
||||
}
|
||||
|
||||
extern "system" fn set_ui_callbacks(_: This, _callbacks: *const c_void, system: bool) -> HRESULT {
|
||||
tracing::info!(system, "XGameUiSetUiCallbacks: our dialogs show");
|
||||
S_OK
|
||||
}
|
||||
|
||||
fn choose(title: &str, content: &str, buttons: &[(u32, String)], default: u32, cancel: u32) -> u32 {
|
||||
dialog::choose(title, content, buttons, default, cancel)
|
||||
}
|
||||
|
||||
fn show_error(error: HRESULT, context: &str) {
|
||||
dialog::show_error(error, context);
|
||||
}
|
||||
|
||||
const MAX_LENGTH: u32 = 1024;
|
||||
|
||||
const PASSWORD: u32 = 31;
|
||||
|
||||
fn max_length_for(scope: u32, max: u32) -> u32 {
|
||||
if max == 0 || scope == PASSWORD {
|
||||
MAX_LENGTH
|
||||
} else {
|
||||
max.min(MAX_LENGTH)
|
||||
}
|
||||
}
|
||||
|
||||
fn limit(typed: &str, max: u32) -> String {
|
||||
typed.chars().take(max as usize).collect()
|
||||
}
|
||||
|
||||
fn ask(title: &str, description: &str, default: &str, max: u32, password: bool) -> Option<String> {
|
||||
dialog::ask(title, description, default, max, password)
|
||||
}
|
||||
|
||||
mod dialog {
|
||||
use windows_sys::Win32::Foundation::{HWND, LPARAM, WPARAM};
|
||||
use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW;
|
||||
use windows_sys::Win32::UI::Input::KeyboardAndMouse::SetFocus;
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::{self as wm, DLGTEMPLATE};
|
||||
|
||||
const EDIT: i32 = 100;
|
||||
|
||||
const EM_SETSEL: u32 = 0xb1;
|
||||
const EM_LIMITTEXT: u32 = 0xc5;
|
||||
|
||||
struct Entry {
|
||||
max: u32,
|
||||
typed: Option<String>,
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub(super) fn ask(
|
||||
title: &str,
|
||||
description: &str,
|
||||
default: &str,
|
||||
max: u32,
|
||||
password: bool,
|
||||
) -> Option<String> {
|
||||
let mut t: Vec<u16> = Vec::new();
|
||||
fn dword(t: &mut Vec<u16>, v: u32) {
|
||||
t.extend([v as u16, (v >> 16) as u16]);
|
||||
}
|
||||
fn text(t: &mut Vec<u16>, s: &str) {
|
||||
t.extend(s.encode_utf16().filter(|&c| c != 0));
|
||||
t.push(0);
|
||||
}
|
||||
let style = wm::WS_POPUP | wm::WS_CAPTION | wm::WS_SYSMENU;
|
||||
let flags = (wm::DS_MODALFRAME | wm::DS_CENTER | wm::DS_SETFOREGROUND) as u32;
|
||||
dword(&mut t, style | flags);
|
||||
dword(&mut t, wm::WS_EX_TOPMOST);
|
||||
t.extend([4, 0, 0, 240, 62, 0, 0]);
|
||||
text(&mut t, title);
|
||||
let mut item = |style: u32, rect: [u16; 4], id: u16, class: u16, caption: &str| {
|
||||
if t.len() % 2 == 1 {
|
||||
t.push(0);
|
||||
}
|
||||
dword(&mut t, wm::WS_CHILD | wm::WS_VISIBLE | style);
|
||||
dword(&mut t, 0);
|
||||
t.extend(rect);
|
||||
t.extend([id, 0xffff, class]);
|
||||
text(&mut t, caption);
|
||||
t.push(0);
|
||||
};
|
||||
let (button, edit, label) = (0x80, 0x81, 0x82);
|
||||
let tab = wm::WS_TABSTOP;
|
||||
item(0, [7, 7, 226, 10], 0xffff, label, description);
|
||||
let mut edit_style = wm::WS_BORDER | tab | wm::ES_AUTOHSCROLL as u32;
|
||||
if password {
|
||||
edit_style |= wm::ES_PASSWORD as u32;
|
||||
}
|
||||
item(edit_style, [7, 20, 226, 12], EDIT as u16, edit, default);
|
||||
let ok = wm::BS_DEFPUSHBUTTON as u32 | tab;
|
||||
item(ok, [129, 40, 50, 14], wm::IDOK as u16, button, "OK");
|
||||
let cancel = wm::BS_PUSHBUTTON as u32 | tab;
|
||||
item(
|
||||
cancel,
|
||||
[183, 40, 50, 14],
|
||||
wm::IDCANCEL as u16,
|
||||
button,
|
||||
"Cancel",
|
||||
);
|
||||
|
||||
let template: Vec<u32> = t
|
||||
.chunks(2)
|
||||
.map(|c| u32::from(c[0]) | u32::from(c.get(1).copied().unwrap_or(0)) << 16)
|
||||
.collect();
|
||||
let mut entry = Entry { max, typed: None };
|
||||
|
||||
unsafe {
|
||||
wm::DialogBoxIndirectParamW(
|
||||
GetModuleHandleW(std::ptr::null()),
|
||||
template.as_ptr().cast::<DLGTEMPLATE>(),
|
||||
std::ptr::null_mut(),
|
||||
Some(procedure),
|
||||
(&raw mut entry) as LPARAM,
|
||||
);
|
||||
}
|
||||
entry.typed
|
||||
}
|
||||
|
||||
extern "system" fn procedure(
|
||||
dialog: HWND,
|
||||
message: u32,
|
||||
wparam: WPARAM,
|
||||
lparam: LPARAM,
|
||||
) -> isize {
|
||||
|
||||
unsafe {
|
||||
let edit = wm::GetDlgItem(dialog, EDIT);
|
||||
match message {
|
||||
wm::WM_INITDIALOG => {
|
||||
wm::SetWindowLongPtrW(dialog, wm::GWLP_USERDATA, lparam);
|
||||
let entry = &*(lparam as *const Entry);
|
||||
wm::SendMessageW(edit, EM_LIMITTEXT, entry.max as WPARAM, 0);
|
||||
wm::SendMessageW(edit, EM_SETSEL, 0, -1);
|
||||
SetFocus(edit);
|
||||
0
|
||||
}
|
||||
wm::WM_COMMAND => {
|
||||
let user_data = wm::GetWindowLongPtrW(dialog, wm::GWLP_USERDATA);
|
||||
if user_data == 0 {
|
||||
return 0;
|
||||
}
|
||||
let entry = &mut *(user_data as *mut Entry);
|
||||
match (wparam & 0xffff) as i32 {
|
||||
wm::IDOK => {
|
||||
let mut buffer =
|
||||
vec![0u16; wm::GetWindowTextLengthW(edit) as usize + 1];
|
||||
let n =
|
||||
wm::GetWindowTextW(edit, buffer.as_mut_ptr(), buffer.len() as i32);
|
||||
entry.typed =
|
||||
Some(String::from_utf16_lossy(&buffer[..n.max(0) as usize]));
|
||||
wm::EndDialog(dialog, 1);
|
||||
}
|
||||
wm::IDCANCEL => {
|
||||
wm::EndDialog(dialog, 0);
|
||||
}
|
||||
_ => return 0,
|
||||
}
|
||||
1
|
||||
}
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Template(Vec<u16>);
|
||||
|
||||
impl Template {
|
||||
fn new(title: &str, items: u16, size: [u16; 2]) -> Template {
|
||||
let mut t = Template(Vec::new());
|
||||
let style = wm::WS_POPUP | wm::WS_CAPTION | wm::WS_SYSMENU;
|
||||
let flags = (wm::DS_MODALFRAME | wm::DS_CENTER | wm::DS_SETFOREGROUND) as u32;
|
||||
t.dword(style | flags);
|
||||
t.dword(wm::WS_EX_TOPMOST);
|
||||
|
||||
t.0.extend([items, 0, 0, size[0], size[1], 0, 0]);
|
||||
t.text(title);
|
||||
t
|
||||
}
|
||||
fn dword(&mut self, v: u32) {
|
||||
self.0.extend([v as u16, (v >> 16) as u16]);
|
||||
}
|
||||
fn text(&mut self, s: &str) {
|
||||
self.0.extend(s.encode_utf16().filter(|&c| c != 0));
|
||||
self.0.push(0);
|
||||
}
|
||||
|
||||
fn item(&mut self, style: u32, rect: [u16; 4], id: u16, class: u16, caption: &str) {
|
||||
if self.0.len() % 2 == 1 {
|
||||
self.0.push(0);
|
||||
}
|
||||
self.dword(wm::WS_CHILD | wm::WS_VISIBLE | style);
|
||||
self.dword(0);
|
||||
self.0.extend(rect);
|
||||
self.0.extend([id, 0xffff, class]);
|
||||
self.text(caption);
|
||||
self.0.push(0);
|
||||
}
|
||||
fn words(&self) -> Vec<u32> {
|
||||
self.0
|
||||
.chunks(2)
|
||||
.map(|c| u32::from(c[0]) | (u32::from(c.get(1).copied().unwrap_or(0)) << 16))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
const FIRST_BUTTON: i32 = 1000;
|
||||
|
||||
struct Choice {
|
||||
default: u32,
|
||||
cancel: u32,
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub(super) fn choose(
|
||||
title: &str,
|
||||
content: &str,
|
||||
buttons: &[(u32, String)],
|
||||
default: u32,
|
||||
cancel: u32,
|
||||
) -> u32 {
|
||||
const WIDTH: u16 = 260;
|
||||
const BUTTON: u16 = 70;
|
||||
let mut t = Template::new(title, 1 + buttons.len() as u16, [WIDTH, 96]);
|
||||
t.item(0, [7, 7, WIDTH - 14, 60], 0xffff, 0x82, content);
|
||||
let mut x = WIDTH - 7 - (BUTTON + 4) * buttons.len() as u16 + 4;
|
||||
for (number, label) in buttons {
|
||||
let kind = if *number == default {
|
||||
wm::BS_DEFPUSHBUTTON
|
||||
} else {
|
||||
wm::BS_PUSHBUTTON
|
||||
};
|
||||
let id = (FIRST_BUTTON + *number as i32) as u16;
|
||||
t.item(
|
||||
kind as u32 | wm::WS_TABSTOP,
|
||||
[x, 74, BUTTON, 14],
|
||||
id,
|
||||
0x80,
|
||||
label,
|
||||
);
|
||||
x += BUTTON + 4;
|
||||
}
|
||||
let template = t.words();
|
||||
let mut choice = Choice { default, cancel };
|
||||
|
||||
let ended = unsafe {
|
||||
wm::DialogBoxIndirectParamW(
|
||||
GetModuleHandleW(std::ptr::null()),
|
||||
template.as_ptr().cast::<DLGTEMPLATE>(),
|
||||
std::ptr::null_mut(),
|
||||
Some(buttons_procedure),
|
||||
(&raw mut choice) as LPARAM,
|
||||
)
|
||||
};
|
||||
u32::try_from(ended).unwrap_or(cancel)
|
||||
}
|
||||
|
||||
extern "system" fn buttons_procedure(
|
||||
dialog: HWND,
|
||||
message: u32,
|
||||
wparam: WPARAM,
|
||||
lparam: LPARAM,
|
||||
) -> isize {
|
||||
|
||||
unsafe {
|
||||
match message {
|
||||
wm::WM_INITDIALOG => {
|
||||
wm::SetWindowLongPtrW(dialog, wm::GWLP_USERDATA, lparam);
|
||||
let choice = &*(lparam as *const Choice);
|
||||
let default = wm::GetDlgItem(dialog, FIRST_BUTTON + choice.default as i32);
|
||||
if default.is_null() {
|
||||
return 1;
|
||||
}
|
||||
SetFocus(default);
|
||||
0
|
||||
}
|
||||
wm::WM_COMMAND => {
|
||||
let user_data = wm::GetWindowLongPtrW(dialog, wm::GWLP_USERDATA);
|
||||
if user_data == 0 {
|
||||
return 0;
|
||||
}
|
||||
let choice = &*(user_data as *const Choice);
|
||||
match (wparam & 0xffff) as i32 {
|
||||
id @ FIRST_BUTTON..=1002 => {
|
||||
wm::EndDialog(dialog, (id - FIRST_BUTTON) as isize);
|
||||
}
|
||||
wm::IDCANCEL => {
|
||||
wm::EndDialog(dialog, choice.cancel as isize);
|
||||
}
|
||||
_ => return 0,
|
||||
}
|
||||
1
|
||||
}
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub(super) fn show_error(error: i32, context: &str) {
|
||||
let text = if context.is_empty() {
|
||||
format!("Error {:#010x}", error as u32)
|
||||
} else {
|
||||
format!("{context}\n\nError {:#010x}", error as u32)
|
||||
};
|
||||
let wide = |s: &str| s.encode_utf16().chain([0]).collect::<Vec<u16>>();
|
||||
let (text, caption) = (wide(&text), wide("Error"));
|
||||
let style = wm::MB_OK | wm::MB_ICONERROR | wm::MB_TOPMOST | wm::MB_SETFOREGROUND;
|
||||
|
||||
unsafe { wm::MessageBoxW(std::ptr::null_mut(), text.as_ptr(), caption.as_ptr(), style) };
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static VTABLE: Methods<59> = with_spare([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
message_dialog_async as *const (),
|
||||
message_dialog_result as *const (),
|
||||
send_invite_async as *const (),
|
||||
closed_result as *const (),
|
||||
profile_card_async as *const (),
|
||||
profile_card_result as *const (),
|
||||
achievements_async as *const (),
|
||||
closed_result as *const (),
|
||||
player_picker_async as *const (),
|
||||
player_picker_count as *const (),
|
||||
player_picker_result as *const (),
|
||||
error_dialog_async as *const (),
|
||||
error_dialog_result as *const (),
|
||||
notification_position as *const (),
|
||||
text_entry_async as *const (),
|
||||
text_entry_size as *const (),
|
||||
text_entry_result as *const (),
|
||||
missing::<20> as *const (),
|
||||
missing::<21> as *const (),
|
||||
missing::<22> as *const (),
|
||||
missing::<23> as *const (),
|
||||
missing::<24> as *const (),
|
||||
missing::<25> as *const (),
|
||||
missing::<26> as *const (),
|
||||
missing::<27> as *const (),
|
||||
missing::<28> as *const (),
|
||||
missing::<29> as *const (),
|
||||
activity_invite_async as *const (),
|
||||
closed_result as *const (),
|
||||
missing::<32> as *const (),
|
||||
missing::<33> as *const (),
|
||||
missing::<34> as *const (),
|
||||
missing::<35> as *const (),
|
||||
missing::<36> as *const (),
|
||||
missing::<37> as *const (),
|
||||
missing::<38> as *const (),
|
||||
missing::<39> as *const (),
|
||||
state_share_async as *const (),
|
||||
closed_result as *const (),
|
||||
set_ui_callbacks as *const (),
|
||||
missing::<43> as *const (),
|
||||
missing::<44> as *const (),
|
||||
missing::<45> as *const (),
|
||||
missing::<46> as *const (),
|
||||
missing::<47> as *const (),
|
||||
missing::<48> as *const (),
|
||||
missing::<49> as *const (),
|
||||
missing::<50> as *const (),
|
||||
]);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,207 @@
|
||||
|
||||
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::{c_char, c_void};
|
||||
|
||||
use super::xasync::{self, AsyncBlock};
|
||||
use super::xgameruntime::{
|
||||
Guid, HRESULT, Interface, Methods, Object, add_ref, missing, put, text, token, with_spare,
|
||||
};
|
||||
|
||||
pub const PROVIDER: Guid = Guid::new(
|
||||
0x37e5_6907,
|
||||
0x2f10,
|
||||
0x41e8,
|
||||
[0xb7, 0x2f, 0x36, 0xed, 0xb1, 0x85, 0x33, 0x1a],
|
||||
);
|
||||
|
||||
pub const IID_2026: Guid = Guid::new(
|
||||
0xbf23_46b2,
|
||||
0x39af,
|
||||
0x4658,
|
||||
[0xb5, 0xea, 0x44, 0x71, 0x3c, 0x7e, 0x83, 0xb3],
|
||||
);
|
||||
|
||||
pub static OBJECT: Object = Object::new("networking", &VTABLE);
|
||||
pub const INTERFACES: &[Interface] =
|
||||
&[(PROVIDER, PROVIDER, &OBJECT), (PROVIDER, IID_2026, &OBJECT)];
|
||||
|
||||
pub const UNREACHABLE: HRESULT = 0x8007_04CF_u32 as i32;
|
||||
|
||||
const UDP_PORT: u16 = 3074;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct ConnectivityHint {
|
||||
pub level: u32,
|
||||
pub cost: u32,
|
||||
pub interface_type: u32,
|
||||
pub initialized: bool,
|
||||
pub approaching_data_limit: bool,
|
||||
pub over_data_limit: bool,
|
||||
pub roaming: bool,
|
||||
}
|
||||
|
||||
const OFFLINE: ConnectivityHint = ConnectivityHint {
|
||||
level: 1,
|
||||
cost: 0,
|
||||
interface_type: 0,
|
||||
initialized: true,
|
||||
approaching_data_limit: false,
|
||||
over_data_limit: false,
|
||||
roaming: false,
|
||||
};
|
||||
|
||||
type This = *const Object;
|
||||
|
||||
extern "system" fn udp_port(_: This, out: *mut u16) -> HRESULT {
|
||||
put(out, UDP_PORT)
|
||||
}
|
||||
|
||||
static PORT: u8 = 0;
|
||||
|
||||
extern "system" fn udp_port_async(_: This, block: *mut AsyncBlock) -> HRESULT {
|
||||
xasync::finished_with(block, (&raw const PORT).cast(), Ok(xasync::bytes(UDP_PORT)))
|
||||
}
|
||||
extern "system" fn udp_port_result(_: This, block: *mut AsyncBlock, out: *mut u16) -> HRESULT {
|
||||
xasync::result(block, (&raw const PORT).cast(), out)
|
||||
}
|
||||
|
||||
static SECURITY: u8 = 0;
|
||||
|
||||
fn wide(text: *const u16) -> Option<String> {
|
||||
|
||||
(!text.is_null()).then(|| unsafe {
|
||||
let len = (0..).take_while(|&i| *text.add(i) != 0).count();
|
||||
String::from_utf16_lossy(std::slice::from_raw_parts(text, len))
|
||||
})
|
||||
}
|
||||
|
||||
extern "system" fn security_info_async(
|
||||
_: This,
|
||||
url: *const c_char,
|
||||
block: *mut AsyncBlock,
|
||||
) -> HRESULT {
|
||||
tracing::debug!(
|
||||
url = text(url).unwrap_or_default(),
|
||||
"security information: offline"
|
||||
);
|
||||
xasync::finished(block, (&raw const SECURITY).cast(), UNREACHABLE)
|
||||
}
|
||||
extern "system" fn security_info_utf16_async(
|
||||
_: This,
|
||||
url: *const u16,
|
||||
block: *mut AsyncBlock,
|
||||
) -> HRESULT {
|
||||
tracing::debug!(
|
||||
url = wide(url).unwrap_or_default(),
|
||||
"security information (utf16): offline"
|
||||
);
|
||||
xasync::finished(block, (&raw const SECURITY).cast(), UNREACHABLE)
|
||||
}
|
||||
extern "system" fn security_info_size(_: This, block: *mut AsyncBlock, out: *mut usize) -> HRESULT {
|
||||
xasync::XAsyncGetResultSize(block, out)
|
||||
}
|
||||
extern "system" fn security_info_result(
|
||||
_: This,
|
||||
block: *mut AsyncBlock,
|
||||
size: usize,
|
||||
used: *mut usize,
|
||||
buffer: *mut u8,
|
||||
_info: *mut *const c_void,
|
||||
) -> HRESULT {
|
||||
xasync::XAsyncGetResult(
|
||||
block,
|
||||
(&raw const SECURITY).cast(),
|
||||
size,
|
||||
buffer.cast(),
|
||||
used,
|
||||
)
|
||||
}
|
||||
|
||||
extern "system" fn verify_certificate(
|
||||
_: This,
|
||||
_request: *mut c_void,
|
||||
_info: *const c_void,
|
||||
) -> HRESULT {
|
||||
UNREACHABLE
|
||||
}
|
||||
|
||||
extern "system" fn connectivity_hint(_: This, out: *mut ConnectivityHint) -> HRESULT {
|
||||
put(out, OFFLINE)
|
||||
}
|
||||
|
||||
extern "system" fn register(
|
||||
_: This,
|
||||
_queue: *const c_void,
|
||||
_context: *mut c_void,
|
||||
_callback: *const c_void,
|
||||
out: *mut u64,
|
||||
) -> HRESULT {
|
||||
put(out, token())
|
||||
}
|
||||
extern "system" fn unregister(_: This, _token: u64, _wait: bool) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
static SETTINGS: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
|
||||
|
||||
extern "system" fn query_setting(_: This, setting: u32, out: *mut u64) -> HRESULT {
|
||||
match SETTINGS.get(setting as usize) {
|
||||
Some(value) => put(out, value.load(std::sync::atomic::Ordering::Relaxed)),
|
||||
None => xasync::E_INVALIDARG,
|
||||
}
|
||||
}
|
||||
|
||||
extern "system" fn set_setting(_: This, setting: u32, value: u64) -> HRESULT {
|
||||
match SETTINGS.get(setting as usize) {
|
||||
Some(kept) => {
|
||||
kept.store(value, std::sync::atomic::Ordering::Relaxed);
|
||||
super::xgameruntime::S_OK
|
||||
}
|
||||
None => xasync::E_INVALIDARG,
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct TcpQueueStatistics {
|
||||
pub queued: u64,
|
||||
pub peak: u64,
|
||||
pub total: u64,
|
||||
pub dropped_over_max: u64,
|
||||
pub dropped_on_failure: u64,
|
||||
}
|
||||
|
||||
extern "system" fn query_statistics(_: This, kind: u32, out: *mut TcpQueueStatistics) -> HRESULT {
|
||||
if kind > 2 {
|
||||
return xasync::E_INVALIDARG;
|
||||
}
|
||||
put(out, TcpQueueStatistics::default())
|
||||
}
|
||||
|
||||
static VTABLE: Methods<29> = with_spare([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
udp_port as *const (),
|
||||
udp_port_async as *const (),
|
||||
udp_port_result as *const (),
|
||||
register as *const (),
|
||||
unregister as *const (),
|
||||
security_info_async as *const (),
|
||||
security_info_size as *const (),
|
||||
security_info_result as *const (),
|
||||
security_info_utf16_async as *const (),
|
||||
security_info_size as *const (),
|
||||
security_info_result as *const (),
|
||||
verify_certificate as *const (),
|
||||
connectivity_hint as *const (),
|
||||
register as *const (),
|
||||
unregister as *const (),
|
||||
query_setting as *const (),
|
||||
set_setting as *const (),
|
||||
query_statistics as *const (),
|
||||
]);
|
||||
|
||||
@@ -0,0 +1,454 @@
|
||||
|
||||
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::{c_char, c_void};
|
||||
use std::path::Path;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use super::xasync::{self, AsyncBlock};
|
||||
use super::xgameruntime::{
|
||||
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, put_string, text,
|
||||
token, with_spare,
|
||||
};
|
||||
use crate::hle::runtime;
|
||||
|
||||
pub const PROVIDER: Guid = Guid::new(
|
||||
0xaf40_6016,
|
||||
0xe850,
|
||||
0x4aa8,
|
||||
[0xa8, 0x8d, 0x2f, 0x3d, 0xcb, 0x9d, 0xac, 0x7e],
|
||||
);
|
||||
|
||||
pub const IID_2026: Guid = Guid::new(
|
||||
0x0b9d_556e,
|
||||
0xab70,
|
||||
0x43f4,
|
||||
[0xba, 0xa0, 0x99, 0x99, 0xac, 0x4c, 0xb0, 0x40],
|
||||
);
|
||||
|
||||
pub static OBJECT: Object = Object::new("package", &VTABLE);
|
||||
pub const INTERFACES: &[Interface] = &[(PROVIDER, IID_2026, &OBJECT)];
|
||||
|
||||
pub const NO_PACKAGE: HRESULT = 0x8924_5208_u32 as i32;
|
||||
|
||||
pub fn identifier() -> String {
|
||||
format!("{:08X}", runtime::title().id)
|
||||
}
|
||||
|
||||
fn is_ours(id: *const c_char) -> bool {
|
||||
text(id).is_some_and(|id| id == identifier())
|
||||
}
|
||||
|
||||
fn package_bytes() -> u64 {
|
||||
fn size(dir: &Path) -> u64 {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||
return 0;
|
||||
};
|
||||
entries
|
||||
.flatten()
|
||||
.map(|e| match e.metadata() {
|
||||
Ok(m) if m.is_dir() => size(&e.path()),
|
||||
Ok(m) => m.len(),
|
||||
Err(_) => 0,
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
static BYTES: OnceLock<u64> = OnceLock::new();
|
||||
static STARTED: std::sync::Once = std::sync::Once::new();
|
||||
STARTED.call_once(|| {
|
||||
let folder = runtime::main_image()
|
||||
.and_then(runtime::image_path)
|
||||
.and_then(|exe| exe.parent().map(Path::to_path_buf));
|
||||
let counted = std::thread::Builder::new().name("package size".into()).spawn(move || {
|
||||
let _ = BYTES.set(folder.as_deref().map_or(0, size));
|
||||
});
|
||||
if counted.is_err() {
|
||||
let _ = BYTES.set(0);
|
||||
}
|
||||
});
|
||||
BYTES.get().copied().unwrap_or(0)
|
||||
}
|
||||
|
||||
type This = *const Object;
|
||||
|
||||
extern "system" fn current_identifier(_: This, size: usize, buffer: *mut u8) -> HRESULT {
|
||||
|
||||
package_bytes();
|
||||
put_string(&identifier(), size, buffer, std::ptr::null_mut())
|
||||
}
|
||||
|
||||
extern "system" fn is_packaged(_: This) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
static MONITOR: u8 = 0;
|
||||
fn monitor() -> *const c_void {
|
||||
(&raw const MONITOR).cast()
|
||||
}
|
||||
|
||||
extern "system" fn create_monitor(
|
||||
_: This,
|
||||
id: *const c_char,
|
||||
_selector_count: u32,
|
||||
_selectors: *const c_void,
|
||||
_interval_ms: u32,
|
||||
_queue: *const c_void,
|
||||
out: *mut *const c_void,
|
||||
) -> HRESULT {
|
||||
if !is_ours(id) {
|
||||
return NO_PACKAGE;
|
||||
}
|
||||
put(out, monitor())
|
||||
}
|
||||
extern "system" fn close_monitor(_: This, _: *const c_void) {}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Progress {
|
||||
pub total_bytes: u64,
|
||||
pub installed_bytes: u64,
|
||||
pub launch_bytes: u64,
|
||||
pub launchable: bool,
|
||||
pub completed: bool,
|
||||
}
|
||||
|
||||
extern "system" fn progress(_: This, _: *const c_void, out: *mut Progress) {
|
||||
let bytes = package_bytes();
|
||||
put(
|
||||
out,
|
||||
Progress {
|
||||
total_bytes: bytes,
|
||||
installed_bytes: bytes,
|
||||
launch_bytes: bytes,
|
||||
launchable: true,
|
||||
completed: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
extern "system" fn register_progress(
|
||||
_: This,
|
||||
_monitor: *const c_void,
|
||||
_context: *mut c_void,
|
||||
_callback: *const c_void,
|
||||
out: *mut u64,
|
||||
) -> HRESULT {
|
||||
put(out, token())
|
||||
}
|
||||
|
||||
extern "system" fn unregister_progress(
|
||||
_: This,
|
||||
_monitor: *const c_void,
|
||||
_token: u64,
|
||||
_wait: bool,
|
||||
) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
extern "system" fn update_monitor(_: This, _monitor: *const c_void) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
extern "system" fn register_installed(
|
||||
_: This,
|
||||
_queue: *const c_void,
|
||||
_context: *mut c_void,
|
||||
_callback: *const c_void,
|
||||
out: *mut u64,
|
||||
) -> HRESULT {
|
||||
put(out, token())
|
||||
}
|
||||
|
||||
extern "system" fn unregister_installed(_: This, _token: u64, _wait: bool) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
extern "system" fn find_availability(
|
||||
_: This,
|
||||
id: *const c_char,
|
||||
_selector_count: u32,
|
||||
_selectors: *const c_void,
|
||||
out: *mut u32,
|
||||
) -> HRESULT {
|
||||
if !is_ours(id) {
|
||||
return NO_PACKAGE;
|
||||
}
|
||||
put(out, 0)
|
||||
}
|
||||
|
||||
extern "system" fn change_order(
|
||||
_: This,
|
||||
id: *const c_char,
|
||||
_count: u32,
|
||||
_selectors: *const c_void,
|
||||
) -> HRESULT {
|
||||
if is_ours(id) { S_OK } else { NO_PACKAGE }
|
||||
}
|
||||
|
||||
static INSTALL: u8 = 0;
|
||||
|
||||
extern "system" fn install_chunks_async(
|
||||
_: This,
|
||||
id: *const c_char,
|
||||
_count: u32,
|
||||
_selectors: *const c_void,
|
||||
_interval_ms: u32,
|
||||
_suppress_confirmation: bool,
|
||||
block: *mut AsyncBlock,
|
||||
) -> HRESULT {
|
||||
let result = if is_ours(id) {
|
||||
Ok(xasync::bytes(monitor()))
|
||||
} else {
|
||||
Err(NO_PACKAGE)
|
||||
};
|
||||
xasync::finished_with(block, (&raw const INSTALL).cast(), result)
|
||||
}
|
||||
extern "system" fn install_chunks_result(
|
||||
_: This,
|
||||
block: *mut AsyncBlock,
|
||||
out: *mut *const c_void,
|
||||
) -> HRESULT {
|
||||
xasync::result(block, (&raw const INSTALL).cast(), out)
|
||||
}
|
||||
|
||||
extern "system" fn estimate_download(
|
||||
_: This,
|
||||
id: *const c_char,
|
||||
_count: u32,
|
||||
_selectors: *const c_void,
|
||||
bytes: *mut u64,
|
||||
confirm: *mut bool,
|
||||
) -> HRESULT {
|
||||
if !is_ours(id) {
|
||||
return NO_PACKAGE;
|
||||
}
|
||||
if !confirm.is_null() {
|
||||
|
||||
unsafe { confirm.write(false) };
|
||||
}
|
||||
put(bytes, 0)
|
||||
}
|
||||
|
||||
extern "system" fn uninstall_chunks(
|
||||
_: This,
|
||||
id: *const c_char,
|
||||
_count: u32,
|
||||
_selectors: *const c_void,
|
||||
) -> HRESULT {
|
||||
if is_ours(id) { S_OK } else { NO_PACKAGE }
|
||||
}
|
||||
|
||||
extern "system" fn mount_path(_: This, _: *const c_void, _: usize, _: *mut u8) -> HRESULT {
|
||||
xasync::E_INVALIDARG
|
||||
}
|
||||
extern "system" fn close_mount(_: This, _: *const c_void) {}
|
||||
|
||||
extern "system" fn uninstall_package(_: This, id: *const c_char) -> bool {
|
||||
tracing::info!(
|
||||
id = text(id).unwrap_or_default(),
|
||||
"package uninstall refused"
|
||||
);
|
||||
false
|
||||
}
|
||||
|
||||
static MOUNT: u8 = 0;
|
||||
|
||||
extern "system" fn mount_async(_: This, id: *const c_char, block: *mut AsyncBlock) -> HRESULT {
|
||||
tracing::info!(
|
||||
id = text(id).unwrap_or_default(),
|
||||
"package mount: not installed"
|
||||
);
|
||||
xasync::finished(block, (&raw const MOUNT).cast(), NO_PACKAGE)
|
||||
}
|
||||
extern "system" fn mount_result(
|
||||
_: This,
|
||||
block: *mut AsyncBlock,
|
||||
out: *mut *const c_void,
|
||||
) -> HRESULT {
|
||||
xasync::result(block, (&raw const MOUNT).cast(), out)
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Details {
|
||||
pub identifier: *const c_char,
|
||||
|
||||
pub version: [u16; 4],
|
||||
pub kind: u32,
|
||||
pub display_name: *const c_char,
|
||||
pub description: *const c_char,
|
||||
pub publisher: *const c_char,
|
||||
pub store_id: *const c_char,
|
||||
pub installing: bool,
|
||||
pub index: u32,
|
||||
pub count: u32,
|
||||
pub age_restricted: bool,
|
||||
pub title_id: *const c_char,
|
||||
}
|
||||
|
||||
type EnumerationCallback = extern "system" fn(*mut c_void, *const Details) -> bool;
|
||||
|
||||
extern "system" fn enumerate(
|
||||
_: This,
|
||||
kind: u32,
|
||||
_scope: u32,
|
||||
context: *mut c_void,
|
||||
callback: *const c_void,
|
||||
) -> HRESULT {
|
||||
if kind != 0 || callback.is_null() {
|
||||
tracing::debug!(kind, "packages enumerated: none");
|
||||
return S_OK;
|
||||
}
|
||||
let title = runtime::title();
|
||||
let text = |s: String| std::ffi::CString::new(s).unwrap_or_default();
|
||||
let (identifier, store_id, title_id, empty) =
|
||||
(text(identifier()), text(title.store_id.clone()), text(format!("{:08X}", title.id)), text(String::new()));
|
||||
let details = Details {
|
||||
identifier: identifier.as_ptr(),
|
||||
version: [0; 4],
|
||||
kind: 0,
|
||||
display_name: empty.as_ptr(),
|
||||
description: empty.as_ptr(),
|
||||
publisher: empty.as_ptr(),
|
||||
store_id: store_id.as_ptr(),
|
||||
installing: false,
|
||||
index: 0,
|
||||
count: 1,
|
||||
age_restricted: false,
|
||||
title_id: title_id.as_ptr(),
|
||||
};
|
||||
|
||||
let callback: EnumerationCallback = unsafe { std::mem::transmute(callback) };
|
||||
|
||||
callback(context, &details);
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub fn user_locale() -> String {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use windows_sys::Win32::Globalization::GetUserDefaultLocaleName;
|
||||
let mut name = [0u16; 85];
|
||||
|
||||
let len = unsafe { GetUserDefaultLocaleName(name.as_mut_ptr(), name.len() as i32) };
|
||||
if len > 1 {
|
||||
return String::from_utf16_lossy(&name[..len as usize - 1]);
|
||||
}
|
||||
}
|
||||
"en-US".into()
|
||||
}
|
||||
|
||||
extern "system" fn get_user_locale(_: This, size: usize, buffer: *mut u8) -> HRESULT {
|
||||
put_string(&user_locale(), size, buffer, std::ptr::null_mut())
|
||||
}
|
||||
|
||||
extern "system" fn enumerate_chunk_availability(
|
||||
_: This,
|
||||
id: *const c_char,
|
||||
_kind: u32,
|
||||
_context: *mut c_void,
|
||||
_callback: *const c_void,
|
||||
) -> HRESULT {
|
||||
if is_ours(id) { S_OK } else { NO_PACKAGE }
|
||||
}
|
||||
|
||||
extern "system" fn install_chunks(
|
||||
_: This,
|
||||
id: *const c_char,
|
||||
_count: u32,
|
||||
_selectors: *const c_void,
|
||||
_interval_ms: u32,
|
||||
_suppress_confirmation: bool,
|
||||
_queue: *const c_void,
|
||||
out: *mut *const c_void,
|
||||
) -> HRESULT {
|
||||
if !is_ours(id) {
|
||||
return NO_PACKAGE;
|
||||
}
|
||||
put(out, monitor())
|
||||
}
|
||||
|
||||
extern "system" fn mount_path_size(_: This, _: *const c_void, _: *mut usize) -> HRESULT {
|
||||
xasync::E_INVALIDARG
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct WriteStats {
|
||||
pub interval: u64,
|
||||
pub budget: u64,
|
||||
pub elapsed: u64,
|
||||
pub bytes_written: u64,
|
||||
}
|
||||
|
||||
extern "system" fn write_stats(_: This, out: *mut WriteStats) -> HRESULT {
|
||||
put(out, WriteStats { interval: 300, budget: 1 << 40, elapsed: 0, bytes_written: 0 })
|
||||
}
|
||||
|
||||
extern "system" fn uninstall_uwp_instance(_: This, name: *const c_char) -> HRESULT {
|
||||
tracing::info!(name = text(name).unwrap_or_default(), "UWP instance uninstall: none installed");
|
||||
NO_PACKAGE
|
||||
}
|
||||
|
||||
extern "system" fn enumerate_features(
|
||||
_: This,
|
||||
id: *const c_char,
|
||||
_context: *mut c_void,
|
||||
_callback: *const c_void,
|
||||
) -> HRESULT {
|
||||
if is_ours(id) { S_OK } else { NO_PACKAGE }
|
||||
}
|
||||
|
||||
extern "system" fn package_kind(_: This, id: *const c_char, out: *mut u32) -> HRESULT {
|
||||
if !is_ours(id) {
|
||||
return NO_PACKAGE;
|
||||
}
|
||||
put(out, 0u32)
|
||||
}
|
||||
|
||||
static VTABLE: Methods<50> = with_spare([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
current_identifier as *const (),
|
||||
is_packaged as *const (),
|
||||
create_monitor as *const (),
|
||||
close_monitor as *const (),
|
||||
progress as *const (),
|
||||
update_monitor as *const (),
|
||||
register_progress as *const (),
|
||||
unregister_progress as *const (),
|
||||
get_user_locale as *const (),
|
||||
find_availability as *const (),
|
||||
enumerate_chunk_availability as *const (),
|
||||
change_order as *const (),
|
||||
install_chunks as *const (),
|
||||
install_chunks_async as *const (),
|
||||
install_chunks_result as *const (),
|
||||
estimate_download as *const (),
|
||||
uninstall_chunks as *const (),
|
||||
missing::<20> as *const (),
|
||||
missing::<21> as *const (),
|
||||
unregister_installed as *const (),
|
||||
missing::<23> as *const (),
|
||||
mount_path_size as *const (),
|
||||
mount_path as *const (),
|
||||
close_mount as *const (),
|
||||
missing::<27> as *const (),
|
||||
missing::<28> as *const (),
|
||||
missing::<29> as *const (),
|
||||
write_stats as *const (),
|
||||
missing::<31> as *const (),
|
||||
uninstall_uwp_instance as *const (),
|
||||
enumerate_features as *const (),
|
||||
uninstall_package as *const (),
|
||||
missing::<35> as *const (),
|
||||
missing::<36> as *const (),
|
||||
mount_async as *const (),
|
||||
mount_result as *const (),
|
||||
enumerate as *const (),
|
||||
register_installed as *const (),
|
||||
package_kind as *const (),
|
||||
]);
|
||||
|
||||
@@ -0,0 +1,534 @@
|
||||
|
||||
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::{c_char, c_void};
|
||||
|
||||
use super::xasync::{self, AsyncBlock, E_ILLEGAL_METHOD_CALL, E_INVALIDARG};
|
||||
use super::xgameruntime::{
|
||||
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, put_string, text,
|
||||
token, with_spare,
|
||||
};
|
||||
use super::xpackage;
|
||||
use crate::hle::runtime;
|
||||
|
||||
pub const PROVIDER: Guid = Guid::new(
|
||||
0x0dd1_12ac,
|
||||
0x7c24,
|
||||
0x448c,
|
||||
[0xb9, 0x2b, 0x39, 0x60, 0xfb, 0x5b, 0xd3, 0x0c],
|
||||
);
|
||||
|
||||
pub const IID_2026: Guid = Guid::new(
|
||||
0xb09d_803c,
|
||||
0x2414,
|
||||
0x4a05,
|
||||
[0x82, 0xc6, 0x66, 0xdf, 0xdc, 0x9e, 0x9a, 0x44],
|
||||
);
|
||||
|
||||
pub const DURABLES_IID: Guid = Guid::new(
|
||||
0x2d42_fea5,
|
||||
0xe71d,
|
||||
0x4b76,
|
||||
[0x97, 0xcd, 0xc5, 0x0a, 0xfb, 0xb3, 0xae, 0x5d],
|
||||
);
|
||||
|
||||
pub const STORE_ID_IID: Guid = Guid::new(
|
||||
0x5c48_dedf,
|
||||
0x0b67,
|
||||
0x4492,
|
||||
[0xa4, 0xb5, 0x68, 0x29, 0xb8, 0xe7, 0x96, 0xe1],
|
||||
);
|
||||
|
||||
pub const AVAILABILITY_IID: Guid = Guid::new(
|
||||
0x60b0_9f4e,
|
||||
0x1b85,
|
||||
0x45b1,
|
||||
[0x82, 0x6c, 0x16, 0x91, 0x18, 0xe2, 0x30, 0xe1],
|
||||
);
|
||||
|
||||
pub static OBJECT: Object = Object::new("store", &VTABLE);
|
||||
|
||||
pub const INTERFACES: &[Interface] = &[
|
||||
(PROVIDER, IID_2026, &OBJECT),
|
||||
(PROVIDER, DURABLES_IID, &OBJECT),
|
||||
(PROVIDER, STORE_ID_IID, &OBJECT),
|
||||
(PROVIDER, AVAILABILITY_IID, &OBJECT),
|
||||
];
|
||||
|
||||
pub const NETWORK_ERROR: HRESULT = 0x8924_5301_u32 as i32;
|
||||
|
||||
type This = *const Object;
|
||||
type Handle = *const c_void;
|
||||
|
||||
static CONTEXT: u8 = 0;
|
||||
static QUERY: u8 = 0;
|
||||
static VALID: u8 = 0;
|
||||
static INVALID: u8 = 0;
|
||||
fn handle(of: &'static u8) -> Handle {
|
||||
(of as *const u8).cast()
|
||||
}
|
||||
|
||||
static FAILED: u8 = 0;
|
||||
static QUERY_CALL: u8 = 0;
|
||||
static LICENSE_CALL: u8 = 0;
|
||||
static GAME_LICENSE: u8 = 0;
|
||||
static ADDON_LICENSES: u8 = 0;
|
||||
|
||||
fn offline(block: *mut AsyncBlock, what: &str) -> HRESULT {
|
||||
tracing::info!(what, "store call: offline");
|
||||
xasync::finished(block, (&raw const FAILED).cast(), NETWORK_ERROR)
|
||||
}
|
||||
|
||||
extern "system" fn status(_: This, block: *mut AsyncBlock) -> HRESULT {
|
||||
xasync::XAsyncGetStatus(block, false)
|
||||
}
|
||||
|
||||
extern "system" fn create_context(_: This, _user: *const c_void, out: *mut Handle) -> HRESULT {
|
||||
put(out, handle(&CONTEXT))
|
||||
}
|
||||
extern "system" fn close(_: This, _: Handle) {}
|
||||
|
||||
extern "system" fn associated_products_async(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_kinds: u32,
|
||||
_per_page: u32,
|
||||
block: *mut AsyncBlock,
|
||||
) -> HRESULT {
|
||||
offline(block, "associated products")
|
||||
}
|
||||
|
||||
extern "system" fn entitled_products_async(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_kinds: u32,
|
||||
_per_page: u32,
|
||||
block: *mut AsyncBlock,
|
||||
) -> HRESULT {
|
||||
xasync::finished_with(
|
||||
block,
|
||||
(&raw const QUERY_CALL).cast(),
|
||||
Ok(xasync::bytes(handle(&QUERY))),
|
||||
)
|
||||
}
|
||||
extern "system" fn query_result(_: This, block: *mut AsyncBlock, out: *mut Handle) -> HRESULT {
|
||||
xasync::result(block, (&raw const QUERY_CALL).cast(), out)
|
||||
}
|
||||
|
||||
extern "system" fn enumerate_products(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_: *mut c_void,
|
||||
_: *const c_void,
|
||||
) -> HRESULT {
|
||||
S_OK
|
||||
}
|
||||
extern "system" fn has_more_pages(_: This, _: Handle) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
extern "system" fn next_page_async(_: This, _: Handle, block: *mut AsyncBlock) -> HRESULT {
|
||||
xasync::finished(block, (&raw const QUERY_CALL).cast(), E_ILLEGAL_METHOD_CALL)
|
||||
}
|
||||
|
||||
fn license_for(owned: bool, block: *mut AsyncBlock) -> HRESULT {
|
||||
let license = handle(if owned { &VALID } else { &INVALID });
|
||||
xasync::finished_with(
|
||||
block,
|
||||
(&raw const LICENSE_CALL).cast(),
|
||||
Ok(xasync::bytes(license)),
|
||||
)
|
||||
}
|
||||
|
||||
extern "system" fn license_for_package_async(
|
||||
_: This,
|
||||
_: Handle,
|
||||
package: *const c_char,
|
||||
block: *mut AsyncBlock,
|
||||
) -> HRESULT {
|
||||
let ours = text(package).is_some_and(|p| p == xpackage::identifier());
|
||||
license_for(ours, block)
|
||||
}
|
||||
|
||||
extern "system" fn license_for_durables_async(
|
||||
_: This,
|
||||
_: Handle,
|
||||
store_id: *const c_char,
|
||||
block: *mut AsyncBlock,
|
||||
) -> HRESULT {
|
||||
tracing::debug!(
|
||||
store_id = text(store_id).unwrap_or_default(),
|
||||
"durable not owned"
|
||||
);
|
||||
license_for(false, block)
|
||||
}
|
||||
extern "system" fn license_result(_: This, block: *mut AsyncBlock, out: *mut Handle) -> HRESULT {
|
||||
xasync::result(block, (&raw const LICENSE_CALL).cast(), out)
|
||||
}
|
||||
extern "system" fn is_license_valid(_: This, license: Handle) -> bool {
|
||||
license == handle(&VALID)
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct GameLicense {
|
||||
pub sku_store_id: [u8; 18],
|
||||
pub is_active: bool,
|
||||
pub is_trial_owned_by_this_user: bool,
|
||||
pub is_disc_license: bool,
|
||||
pub is_trial: bool,
|
||||
pub trial_seconds_remaining: u32,
|
||||
pub trial_unique_id: [u8; 64],
|
||||
pub expiration: i64,
|
||||
}
|
||||
|
||||
fn game_license() -> GameLicense {
|
||||
let mut sku = [0u8; 18];
|
||||
let id = format!("{}/0010", runtime::title().store_id);
|
||||
let len = id.len().min(sku.len() - 1);
|
||||
sku[..len].copy_from_slice(&id.as_bytes()[..len]);
|
||||
GameLicense {
|
||||
sku_store_id: sku,
|
||||
is_active: true,
|
||||
is_trial_owned_by_this_user: false,
|
||||
is_disc_license: false,
|
||||
is_trial: false,
|
||||
trial_seconds_remaining: 0,
|
||||
trial_unique_id: [0; 64],
|
||||
expiration: 0,
|
||||
}
|
||||
}
|
||||
|
||||
extern "system" fn game_license_async(_: This, _: Handle, block: *mut AsyncBlock) -> HRESULT {
|
||||
let license = xasync::bytes(game_license());
|
||||
xasync::finished_with(block, (&raw const GAME_LICENSE).cast(), Ok(license))
|
||||
}
|
||||
extern "system" fn game_license_result(
|
||||
_: This,
|
||||
block: *mut AsyncBlock,
|
||||
out: *mut GameLicense,
|
||||
) -> HRESULT {
|
||||
xasync::result(block, (&raw const GAME_LICENSE).cast(), out)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
extern "system" fn products_async(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_kinds: u32,
|
||||
_store_ids: *const *const c_char,
|
||||
_store_id_count: usize,
|
||||
_action_filters: *const *const c_char,
|
||||
_action_filter_count: usize,
|
||||
block: *mut AsyncBlock,
|
||||
) -> HRESULT {
|
||||
offline(block, "products")
|
||||
}
|
||||
extern "system" fn product_for_game_async(_: This, _: Handle, block: *mut AsyncBlock) -> HRESULT {
|
||||
offline(block, "product for the game")
|
||||
}
|
||||
extern "system" fn product_for_package_async(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_kinds: u32,
|
||||
_package: *const c_char,
|
||||
block: *mut AsyncBlock,
|
||||
) -> HRESULT {
|
||||
offline(block, "product for a package")
|
||||
}
|
||||
|
||||
extern "system" fn can_acquire_async(_: This, _: Handle, _id: *const c_char, block: *mut AsyncBlock) -> HRESULT {
|
||||
offline(block, "licence acquisition check")
|
||||
}
|
||||
extern "system" fn struct_status(_: This, block: *mut AsyncBlock, _out: *mut c_void) -> HRESULT {
|
||||
xasync::XAsyncGetStatus(block, false)
|
||||
}
|
||||
|
||||
extern "system" fn addon_licenses_async(_: This, _: Handle, block: *mut AsyncBlock) -> HRESULT {
|
||||
xasync::finished(block, (&raw const ADDON_LICENSES).cast(), S_OK)
|
||||
}
|
||||
extern "system" fn addon_license_count(_: This, block: *mut AsyncBlock, out: *mut u32) -> HRESULT {
|
||||
match xasync::XAsyncGetStatus(block, false) {
|
||||
S_OK => put(out, 0),
|
||||
hr => hr,
|
||||
}
|
||||
}
|
||||
extern "system" fn addon_licenses(_: This, block: *mut AsyncBlock, count: u32, _out: *mut c_void) -> HRESULT {
|
||||
match xasync::XAsyncGetStatus(block, false) {
|
||||
S_OK if count == 0 => S_OK,
|
||||
S_OK => E_INVALIDARG,
|
||||
hr => hr,
|
||||
}
|
||||
}
|
||||
|
||||
extern "system" fn consumable_balance_async(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_store_id: *const c_char,
|
||||
block: *mut AsyncBlock,
|
||||
) -> HRESULT {
|
||||
offline(block, "consumable balance")
|
||||
}
|
||||
extern "system" fn report_fulfillment_async(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_store_id: *const c_char,
|
||||
_quantity: u32,
|
||||
_tracking_id: *const c_void,
|
||||
block: *mut AsyncBlock,
|
||||
) -> HRESULT {
|
||||
offline(block, "consumable fulfillment")
|
||||
}
|
||||
|
||||
extern "system" fn user_id_async(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_ticket: *const c_char,
|
||||
_publisher_user_id: *const c_char,
|
||||
block: *mut AsyncBlock,
|
||||
) -> HRESULT {
|
||||
offline(block, "user store id")
|
||||
}
|
||||
extern "system" fn size_status(_: This, block: *mut AsyncBlock, _out: *mut usize) -> HRESULT {
|
||||
xasync::XAsyncGetStatus(block, false)
|
||||
}
|
||||
extern "system" fn string_status(
|
||||
_: This,
|
||||
block: *mut AsyncBlock,
|
||||
_: usize,
|
||||
_: *mut c_char,
|
||||
) -> HRESULT {
|
||||
xasync::XAsyncGetStatus(block, false)
|
||||
}
|
||||
extern "system" fn count_status(_: This, block: *mut AsyncBlock, _out: *mut u32) -> HRESULT {
|
||||
xasync::XAsyncGetStatus(block, false)
|
||||
}
|
||||
extern "system" fn array_status(
|
||||
_: This,
|
||||
block: *mut AsyncBlock,
|
||||
_: u32,
|
||||
_: *mut c_void,
|
||||
) -> HRESULT {
|
||||
xasync::XAsyncGetStatus(block, false)
|
||||
}
|
||||
|
||||
extern "system" fn purchase_ui_async(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_store_id: *const c_char,
|
||||
_name: *const c_char,
|
||||
_json: *const c_char,
|
||||
block: *mut AsyncBlock,
|
||||
) -> HRESULT {
|
||||
offline(block, "purchase page")
|
||||
}
|
||||
extern "system" fn product_page_ui_async(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_store_id: *const c_char,
|
||||
block: *mut AsyncBlock,
|
||||
) -> HRESULT {
|
||||
offline(block, "product page")
|
||||
}
|
||||
extern "system" fn redeem_ui_async(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_token: *const c_char,
|
||||
_allowed: *const *const c_char,
|
||||
_allowed_count: usize,
|
||||
_disallow_csv: bool,
|
||||
block: *mut AsyncBlock,
|
||||
) -> HRESULT {
|
||||
offline(block, "redeem page")
|
||||
}
|
||||
extern "system" fn updates_async(_: This, _: Handle, block: *mut AsyncBlock) -> HRESULT {
|
||||
offline(block, "update check")
|
||||
}
|
||||
|
||||
extern "system" fn install_async(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_ids: *const *const c_char,
|
||||
_count: usize,
|
||||
block: *mut AsyncBlock,
|
||||
) -> HRESULT {
|
||||
offline(block, "package download")
|
||||
}
|
||||
|
||||
extern "system" fn license_token_async(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_product_ids: *const *const c_char,
|
||||
_count: usize,
|
||||
_developer_string: *const c_char,
|
||||
block: *mut AsyncBlock,
|
||||
) -> HRESULT {
|
||||
offline(block, "licence token")
|
||||
}
|
||||
extern "system" fn rate_and_review_ui_async(_: This, _: Handle, block: *mut AsyncBlock) -> HRESULT {
|
||||
offline(block, "rate and review page")
|
||||
}
|
||||
extern "system" fn associated_products_ui_async(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_store_id: *const c_char,
|
||||
_kinds: u32,
|
||||
block: *mut AsyncBlock,
|
||||
) -> HRESULT {
|
||||
offline(block, "associated products page")
|
||||
}
|
||||
extern "system" fn gifting_ui_async(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_store_id: *const c_char,
|
||||
_name: *const c_char,
|
||||
_json: *const c_char,
|
||||
block: *mut AsyncBlock,
|
||||
) -> HRESULT {
|
||||
offline(block, "gifting page")
|
||||
}
|
||||
extern "system" fn associated_for_store_id_async(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_store_id: *const c_char,
|
||||
_kinds: u32,
|
||||
_per_page: u32,
|
||||
block: *mut AsyncBlock,
|
||||
) -> HRESULT {
|
||||
offline(block, "associated products for a store id")
|
||||
}
|
||||
extern "system" fn package_updates_async(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_ids: *const *const c_char,
|
||||
_count: usize,
|
||||
block: *mut AsyncBlock,
|
||||
) -> HRESULT {
|
||||
offline(block, "package update check")
|
||||
}
|
||||
|
||||
extern "system" fn is_purchasable(_: This, _availability: *const c_void) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
extern "system" fn out_status(_: This, block: *mut AsyncBlock, _out: *mut c_void) -> HRESULT {
|
||||
xasync::XAsyncGetStatus(block, false)
|
||||
}
|
||||
|
||||
extern "system" fn package_identifier(
|
||||
_: This,
|
||||
store_id: *const c_char,
|
||||
size: usize,
|
||||
buffer: *mut u8,
|
||||
) -> HRESULT {
|
||||
let title = runtime::title();
|
||||
match text(store_id) {
|
||||
Some(id) if !title.store_id.is_empty() && id == title.store_id => {
|
||||
put_string(&xpackage::identifier(), size, buffer, std::ptr::null_mut())
|
||||
}
|
||||
_ => E_INVALIDARG,
|
||||
}
|
||||
}
|
||||
|
||||
extern "system" fn register(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_queue: *const c_void,
|
||||
_context: *mut c_void,
|
||||
_callback: *const c_void,
|
||||
out: *mut u64,
|
||||
) -> HRESULT {
|
||||
put(out, token())
|
||||
}
|
||||
extern "system" fn unregister(_: This, _: Handle, _token: u64, _wait: bool) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
static VTABLE: Methods<92> = with_spare([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
create_context as *const (),
|
||||
close as *const (),
|
||||
associated_products_async as *const (),
|
||||
query_result as *const (),
|
||||
products_async as *const (),
|
||||
query_result as *const (),
|
||||
entitled_products_async as *const (),
|
||||
query_result as *const (),
|
||||
product_for_game_async as *const (),
|
||||
query_result as *const (),
|
||||
product_for_package_async as *const (),
|
||||
query_result as *const (),
|
||||
enumerate_products as *const (),
|
||||
has_more_pages as *const (),
|
||||
next_page_async as *const (),
|
||||
query_result as *const (),
|
||||
close as *const (),
|
||||
license_for_package_async as *const (),
|
||||
license_result as *const (),
|
||||
is_license_valid as *const (),
|
||||
close as *const (),
|
||||
can_acquire_async as *const (),
|
||||
struct_status as *const (),
|
||||
can_acquire_async as *const (),
|
||||
struct_status as *const (),
|
||||
game_license_async as *const (),
|
||||
game_license_result as *const (),
|
||||
addon_licenses_async as *const (),
|
||||
addon_license_count as *const (),
|
||||
addon_licenses as *const (),
|
||||
consumable_balance_async as *const (),
|
||||
count_status as *const (),
|
||||
report_fulfillment_async as *const (),
|
||||
count_status as *const (),
|
||||
user_id_async as *const (),
|
||||
size_status as *const (),
|
||||
string_status as *const (),
|
||||
user_id_async as *const (),
|
||||
size_status as *const (),
|
||||
string_status as *const (),
|
||||
license_token_async as *const (),
|
||||
size_status as *const (),
|
||||
string_status as *const (),
|
||||
missing::<46> as *const (),
|
||||
missing::<47> as *const (),
|
||||
missing::<48> as *const (),
|
||||
purchase_ui_async as *const (),
|
||||
status as *const (),
|
||||
rate_and_review_ui_async as *const (),
|
||||
out_status as *const (),
|
||||
redeem_ui_async as *const (),
|
||||
status as *const (),
|
||||
updates_async as *const (),
|
||||
count_status as *const (),
|
||||
array_status as *const (),
|
||||
install_async as *const (),
|
||||
status as *const (),
|
||||
install_async as *const (),
|
||||
status as *const (),
|
||||
install_async as *const (),
|
||||
count_status as *const (),
|
||||
array_status as *const (),
|
||||
package_identifier as *const (),
|
||||
register as *const (),
|
||||
unregister as *const (),
|
||||
register as *const (),
|
||||
unregister as *const (),
|
||||
is_purchasable as *const (),
|
||||
license_for_durables_async as *const (),
|
||||
license_result as *const (),
|
||||
associated_products_ui_async as *const (),
|
||||
status as *const (),
|
||||
product_page_ui_async as *const (),
|
||||
status as *const (),
|
||||
associated_for_store_id_async as *const (),
|
||||
out_status as *const (),
|
||||
package_updates_async as *const (),
|
||||
count_status as *const (),
|
||||
array_status as *const (),
|
||||
gifting_ui_async as *const (),
|
||||
status as *const (),
|
||||
]);
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
|
||||
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::c_void;
|
||||
|
||||
use super::xgameruntime::{
|
||||
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put_string, with_spare,
|
||||
};
|
||||
|
||||
pub const PROVIDER: Guid = Guid::new(
|
||||
0xe349_bd1a,
|
||||
0xfc20,
|
||||
0x4e40,
|
||||
[0xb9, 0x9c, 0x41, 0x78, 0xcc, 0x6b, 0x40, 0x9f],
|
||||
);
|
||||
|
||||
pub const IID: Guid = Guid::new(
|
||||
0x6fd7_1f09,
|
||||
0x7513,
|
||||
0x49f0,
|
||||
[0x89, 0xbc, 0xbf, 0xaf, 0x5d, 0xf6, 0xf8, 0x52],
|
||||
);
|
||||
|
||||
pub const ANALYTICS: Guid = Guid::new(
|
||||
0xb884_675d,
|
||||
0xb738,
|
||||
0x4a9c,
|
||||
[0x81, 0x5d, 0x9a, 0x9a, 0x1e, 0x0c, 0x6c, 0x9b],
|
||||
);
|
||||
|
||||
const CONSOLE_ID: &str = "00000000000000000000000000000000000001";
|
||||
|
||||
const SANDBOX: &str = "RETAIL";
|
||||
|
||||
const DEVICE_ID: &str = "VkljdG9yeSBvZmZsaW5lIGRldmljZSBpZGVudGl0eSE=";
|
||||
|
||||
pub static OBJECT: Object = Object::new("system", &VTABLE);
|
||||
pub static ANALYTICS_OBJECT: Object = Object::new("analytics", &ANALYTICS_VTABLE);
|
||||
|
||||
pub const IID_2026: Guid = Guid::new(
|
||||
0x1861_cf2e,
|
||||
0xe18b,
|
||||
0x4834,
|
||||
[0xa9, 0xf5, 0xb4, 0xa4, 0xe6, 0xef, 0xb4, 0xcf],
|
||||
);
|
||||
|
||||
pub const INTERFACES: &[Interface] = &[
|
||||
(PROVIDER, IID, &OBJECT),
|
||||
(PROVIDER, IID_2026, &OBJECT),
|
||||
(ANALYTICS, ANALYTICS, &ANALYTICS_OBJECT),
|
||||
];
|
||||
|
||||
type This = *const Object;
|
||||
|
||||
extern "system" fn console_id(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT {
|
||||
put_string(CONSOLE_ID, size, buffer, used)
|
||||
}
|
||||
extern "system" fn sandbox_id(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT {
|
||||
put_string(SANDBOX, size, buffer, used)
|
||||
}
|
||||
|
||||
extern "system" fn device_id(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT {
|
||||
put_string(DEVICE_ID, size, buffer, used)
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Version {
|
||||
pub major: u16,
|
||||
pub minor: u16,
|
||||
pub build: u16,
|
||||
pub revision: u16,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct AnalyticsInfo {
|
||||
pub os: Version,
|
||||
pub hosting_os: Version,
|
||||
|
||||
pub family: [u8; 64],
|
||||
pub form: [u8; 64],
|
||||
}
|
||||
|
||||
const OS: Version = Version {
|
||||
major: 10,
|
||||
minor: 0,
|
||||
build: 22000,
|
||||
revision: 0,
|
||||
};
|
||||
|
||||
fn text(s: &str) -> [u8; 64] {
|
||||
let mut out = [0; 64];
|
||||
out[..s.len()].copy_from_slice(s.as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
extern "system" fn analytics_info(_: This, out: *mut AnalyticsInfo) -> *mut AnalyticsInfo {
|
||||
let info = AnalyticsInfo {
|
||||
os: OS,
|
||||
hosting_os: OS,
|
||||
family: text("Xbox"),
|
||||
form: text(eonacat_xsbox_gpu::console::current().name()),
|
||||
};
|
||||
|
||||
unsafe { out.write(info) };
|
||||
out
|
||||
}
|
||||
|
||||
extern "system" fn handle_track(_: This, _callback: *const (), _context: *mut c_void) -> HRESULT {
|
||||
tracing::debug!("XSystemHandleTrack: runtime handles are not reported");
|
||||
S_OK
|
||||
}
|
||||
|
||||
extern "system" fn is_handle_valid(_: This, _handle: *const c_void) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
extern "system" fn allow_full_download_bandwidth(_: This, _enable: bool) {}
|
||||
|
||||
static VTABLE: Methods<17> = with_spare([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
console_id as *const (),
|
||||
sandbox_id as *const (),
|
||||
device_id as *const (),
|
||||
handle_track as *const (),
|
||||
is_handle_valid as *const (),
|
||||
allow_full_download_bandwidth as *const (),
|
||||
]);
|
||||
|
||||
static ANALYTICS_VTABLE: Methods<12> = with_spare([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
analytics_info as *const (),
|
||||
]);
|
||||
|
||||
#[cfg(windows)]
|
||||
mod device_type {
|
||||
#![allow(non_snake_case)]
|
||||
|
||||
use std::ffi::c_void;
|
||||
|
||||
use eonacat_xsbox_gpu::console::{self, Console};
|
||||
|
||||
use crate::hle::modules::files::host;
|
||||
use crate::hle::{HleModule};
|
||||
use crate::hle_export;
|
||||
|
||||
type Key = *mut c_void;
|
||||
const LOCAL_MACHINE: Key = 0xffff_ffff_8000_0002_u64 as Key;
|
||||
const KEY: &str = r"Software\Microsoft\Windows NT\CurrentVersion\OEM";
|
||||
const VALUE: &str = "ConsoleMode";
|
||||
const SUCCESS: u32 = 0;
|
||||
const FILE_NOT_FOUND: u32 = 2;
|
||||
const INVALID_PARAMETER: u32 = 87;
|
||||
const MORE_DATA: u32 = 234;
|
||||
const DWORD: u32 = 4;
|
||||
|
||||
static OEM: u8 = 0;
|
||||
fn oem() -> Key {
|
||||
(&raw const OEM).cast_mut().cast()
|
||||
}
|
||||
|
||||
pub(super) fn console_mode(console: Console) -> u32 {
|
||||
match console {
|
||||
Console::SeriesX => 0x64,
|
||||
Console::SeriesS => 0x60,
|
||||
}
|
||||
}
|
||||
|
||||
fn is(text: *const u16, expected: &str) -> bool {
|
||||
if text.is_null() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let text = unsafe {
|
||||
let len = (0..).take_while(|&i| *text.add(i) != 0).count();
|
||||
String::from_utf16_lossy(std::slice::from_raw_parts(text, len))
|
||||
};
|
||||
text.eq_ignore_ascii_case(expected)
|
||||
}
|
||||
|
||||
fn open(root: Key, sub: *const u16, out: *mut Key) -> Option<u32> {
|
||||
if root == oem() {
|
||||
return Some(FILE_NOT_FOUND);
|
||||
}
|
||||
if root == LOCAL_MACHINE && is(sub, KEY) && !out.is_null() {
|
||||
|
||||
unsafe { out.write(oem()) };
|
||||
return Some(SUCCESS);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub extern "system" fn RegOpenKeyW(root: Key, sub: *const u16, out: *mut Key) -> u32 {
|
||||
open(root, sub, out).unwrap_or_else(|| {
|
||||
host!("advapi32.dll", "RegOpenKeyW": extern "system" fn(Key, *const u16, *mut Key) -> u32)(
|
||||
root, sub, out,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub extern "system" fn RegOpenKeyExW(
|
||||
root: Key,
|
||||
sub: *const u16,
|
||||
options: u32,
|
||||
access: u32,
|
||||
out: *mut Key,
|
||||
) -> u32 {
|
||||
open(root, sub, out).unwrap_or_else(|| {
|
||||
host!("advapi32.dll", "RegOpenKeyExW": extern "system" fn(
|
||||
Key, *const u16, u32, u32, *mut Key,
|
||||
) -> u32)(root, sub, options, access, out)
|
||||
})
|
||||
}
|
||||
|
||||
pub extern "system" fn RegQueryValueExW(
|
||||
key: Key,
|
||||
name: *const u16,
|
||||
reserved: *mut u32,
|
||||
kind: *mut u32,
|
||||
data: *mut u8,
|
||||
size: *mut u32,
|
||||
) -> u32 {
|
||||
if key != oem() {
|
||||
return host!("advapi32.dll", "RegQueryValueExW": extern "system" fn(
|
||||
Key, *const u16, *mut u32, *mut u32, *mut u8, *mut u32,
|
||||
) -> u32)(key, name, reserved, kind, data, size);
|
||||
}
|
||||
if !is(name, VALUE) {
|
||||
return FILE_NOT_FOUND;
|
||||
}
|
||||
if !data.is_null() && size.is_null() {
|
||||
return INVALID_PARAMETER;
|
||||
}
|
||||
|
||||
unsafe {
|
||||
if !kind.is_null() {
|
||||
kind.write(DWORD);
|
||||
}
|
||||
if size.is_null() {
|
||||
return SUCCESS;
|
||||
}
|
||||
let room = size.read();
|
||||
size.write(4);
|
||||
if data.is_null() {
|
||||
return SUCCESS;
|
||||
}
|
||||
if room < 4 {
|
||||
return MORE_DATA;
|
||||
}
|
||||
data.cast::<u32>()
|
||||
.write_unaligned(console_mode(console::current()));
|
||||
}
|
||||
tracing::debug!(console = console::current().name(), "device type read");
|
||||
SUCCESS
|
||||
}
|
||||
|
||||
pub extern "system" fn RegCloseKey(key: Key) -> u32 {
|
||||
if key == oem() {
|
||||
return SUCCESS;
|
||||
}
|
||||
host!("advapi32.dll", "RegCloseKey": extern "system" fn(Key) -> u32)(key)
|
||||
}
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "device type",
|
||||
|
||||
dlls: &[
|
||||
"advapi32.dll",
|
||||
"kernelbase.dll",
|
||||
"api-ms-win-core-registry-*",
|
||||
],
|
||||
exports: vec![
|
||||
hle_export!(RegOpenKeyW),
|
||||
hle_export!(RegOpenKeyExW),
|
||||
hle_export!(RegQueryValueExW),
|
||||
hle_export!(RegCloseKey),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
#[cfg(windows)]
|
||||
pub(crate) use device_type::module;
|
||||
|
||||
@@ -0,0 +1,388 @@
|
||||
|
||||
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::{c_char, c_void};
|
||||
|
||||
use super::xasync::{self, AsyncBlock, ProviderData};
|
||||
use super::xgameruntime::{
|
||||
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, put_string, text,
|
||||
token, with_spare,
|
||||
};
|
||||
|
||||
pub const PROVIDER: Guid = Guid {
|
||||
data1: 0x01ac_d177,
|
||||
data2: 0x91f9,
|
||||
data3: 0x4763,
|
||||
data4: [0xa3, 0x8e, 0xcc, 0xbb, 0x55, 0xce, 0x32, 0xe0],
|
||||
};
|
||||
|
||||
pub const IID: Guid = Guid {
|
||||
data1: 0xeb9b_f948,
|
||||
data2: 0x18dc,
|
||||
data3: 0x4d82,
|
||||
data4: [0xbb, 0xcc, 0x40, 0xe0, 0xa8, 0x09, 0xc4, 0xc0],
|
||||
};
|
||||
|
||||
pub const GAMERTAG_IID: Guid = Guid {
|
||||
data1: 0xcef4_fac0,
|
||||
data2: 0x7676,
|
||||
data3: 0x4a94,
|
||||
data4: [0xa1, 0x19, 0x4c, 0x43, 0xf9, 0xeb, 0x5b, 0x74],
|
||||
};
|
||||
|
||||
pub const DEVICE_PROVIDER: Guid = Guid::new(
|
||||
0x7d82_4997,
|
||||
0x10dc,
|
||||
0x45ab,
|
||||
[0x86, 0xb7, 0x27, 0x37, 0x76, 0x7c, 0x0b, 0xf1],
|
||||
);
|
||||
|
||||
pub const DEVICE_IID: Guid = Guid::new(
|
||||
0x0cc6_a956,
|
||||
0xe7e1,
|
||||
0x4fdf,
|
||||
[0x93, 0x41, 0x9d, 0x5d, 0xa6, 0x49, 0xeb, 0xc8],
|
||||
);
|
||||
|
||||
pub const USER_NOT_FOUND: HRESULT = 0x8924_5104_u32 as i32;
|
||||
|
||||
pub const XUID: u64 = 0x0009_0000_0000_0001;
|
||||
pub const LOCAL_ID: u64 = 1;
|
||||
const GAMERTAG: &str = "Player";
|
||||
|
||||
pub struct User;
|
||||
static USER: User = User;
|
||||
type Handle = *const User;
|
||||
|
||||
fn user() -> Handle {
|
||||
&USER
|
||||
}
|
||||
|
||||
fn found(found: bool, out: *mut Handle) -> HRESULT {
|
||||
if found {
|
||||
put(out, user())
|
||||
} else {
|
||||
USER_NOT_FOUND
|
||||
}
|
||||
}
|
||||
|
||||
pub static OBJECT: Object = Object::new("user", &VTABLE);
|
||||
pub static GAMERTAG_OBJECT: Object = Object::new("user gamertag", &GAMERTAG_VTABLE);
|
||||
pub static DEVICE_OBJECT: Object = Object::new("user devices", &DEVICE_VTABLE);
|
||||
|
||||
pub const INTERFACES: &[Interface] = &[
|
||||
(PROVIDER, IID, &OBJECT),
|
||||
|
||||
(PROVIDER, PROVIDER, &OBJECT),
|
||||
(PROVIDER, GAMERTAG_IID, &GAMERTAG_OBJECT),
|
||||
(DEVICE_PROVIDER, DEVICE_IID, &DEVICE_OBJECT),
|
||||
];
|
||||
|
||||
type This = *const Object;
|
||||
extern "system" fn duplicate(_: This, _: Handle, out: *mut Handle) -> HRESULT {
|
||||
put(out, user())
|
||||
}
|
||||
extern "system" fn close(_: This, _: Handle) {}
|
||||
extern "system" fn compare(_: This, a: Handle, b: Handle) -> i32 {
|
||||
i32::from(a != b)
|
||||
}
|
||||
|
||||
extern "system" fn add_provider(op: u32, data: *const ProviderData) -> HRESULT {
|
||||
const BEGIN: u32 = 0;
|
||||
const GET_RESULT: u32 = 2;
|
||||
|
||||
let data = unsafe { &*data };
|
||||
match op {
|
||||
BEGIN => xasync::XAsyncComplete(data.block, S_OK, size_of::<Handle>()),
|
||||
GET_RESULT => return put(data.buffer.cast::<Handle>(), user()),
|
||||
_ => {}
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
static ADD: u8 = 0;
|
||||
|
||||
extern "system" fn add_async(_: This, options: u32, block: *mut AsyncBlock) -> HRESULT {
|
||||
tracing::info!(options, "XUserAddAsync: the offline local user");
|
||||
xasync::XAsyncBegin(
|
||||
block,
|
||||
std::ptr::null_mut(),
|
||||
(&raw const ADD).cast(),
|
||||
std::ptr::null(),
|
||||
Some(add_provider),
|
||||
)
|
||||
}
|
||||
extern "system" fn add_result(_: This, block: *mut AsyncBlock, out: *mut Handle) -> HRESULT {
|
||||
xasync::XAsyncGetResult(
|
||||
block,
|
||||
(&raw const ADD).cast(),
|
||||
size_of::<Handle>(),
|
||||
out.cast(),
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
}
|
||||
extern "system" fn get_local_id(_: This, _: Handle, out: *mut u64) -> HRESULT {
|
||||
put(out, LOCAL_ID)
|
||||
}
|
||||
extern "system" fn find_by_local_id(_: This, id: u64, out: *mut Handle) -> HRESULT {
|
||||
found(id == LOCAL_ID, out)
|
||||
}
|
||||
extern "system" fn get_id(_: This, _: Handle, out: *mut u64) -> HRESULT {
|
||||
put(out, XUID)
|
||||
}
|
||||
extern "system" fn find_by_id(_: This, id: u64, out: *mut Handle) -> HRESULT {
|
||||
found(id == XUID, out)
|
||||
}
|
||||
extern "system" fn get_is_guest(_: This, _: Handle, out: *mut bool) -> HRESULT {
|
||||
put(out, false)
|
||||
}
|
||||
|
||||
extern "system" fn get_state(_: This, _: Handle, out: *mut u32) -> HRESULT {
|
||||
put(out, 0)
|
||||
}
|
||||
|
||||
extern "system" fn get_gamertag(
|
||||
_: This,
|
||||
_: Handle,
|
||||
component: u32,
|
||||
size: usize,
|
||||
buffer: *mut u8,
|
||||
used: *mut usize,
|
||||
) -> HRESULT {
|
||||
const MODERN_SUFFIX: u32 = 2;
|
||||
let text = match component {
|
||||
MODERN_SUFFIX => "",
|
||||
_ => GAMERTAG,
|
||||
};
|
||||
put_string(text, size, buffer, used)
|
||||
}
|
||||
|
||||
extern "system" fn check_privilege(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_options: u32,
|
||||
_privilege: u32,
|
||||
has: *mut bool,
|
||||
reason: *mut u32,
|
||||
) -> HRESULT {
|
||||
if !reason.is_null() {
|
||||
|
||||
unsafe { reason.write(0) };
|
||||
}
|
||||
put(has, true)
|
||||
}
|
||||
|
||||
extern "system" fn get_age_group(_: This, _: Handle, out: *mut u32) -> HRESULT {
|
||||
put(out, 3)
|
||||
}
|
||||
|
||||
static RESOLVE: u8 = 0;
|
||||
static TOKEN: u8 = 0;
|
||||
|
||||
extern "system" fn resolve_privilege_async(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_options: u32,
|
||||
_privilege: u32,
|
||||
block: *mut AsyncBlock,
|
||||
) -> HRESULT {
|
||||
xasync::finished(block, (&raw const RESOLVE).cast(), S_OK)
|
||||
}
|
||||
extern "system" fn resolve_privilege_result(_: This, block: *mut AsyncBlock) -> HRESULT {
|
||||
let none = std::ptr::null_mut();
|
||||
xasync::XAsyncGetResult(block, (&raw const RESOLVE).cast(), 0, none, none.cast())
|
||||
}
|
||||
|
||||
pub const FAILED_TO_GET_TOKEN: HRESULT = 0x8924_5111_u32 as i32;
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
extern "system" fn token_async(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_options: u32,
|
||||
_method: *const c_char,
|
||||
url: *const c_char,
|
||||
_header_count: usize,
|
||||
_headers: *const c_void,
|
||||
_body_size: usize,
|
||||
_body: *const c_void,
|
||||
block: *mut AsyncBlock,
|
||||
) -> HRESULT {
|
||||
tracing::info!(
|
||||
url = text(url).unwrap_or_default(),
|
||||
"token and signature: offline"
|
||||
);
|
||||
xasync::finished(block, (&raw const TOKEN).cast(), FAILED_TO_GET_TOKEN)
|
||||
}
|
||||
extern "system" fn token_size(_: This, block: *mut AsyncBlock, out: *mut usize) -> HRESULT {
|
||||
xasync::XAsyncGetResultSize(block, out)
|
||||
}
|
||||
extern "system" fn token_result(
|
||||
_: This,
|
||||
block: *mut AsyncBlock,
|
||||
size: usize,
|
||||
buffer: *mut c_void,
|
||||
_data: *mut *const c_void,
|
||||
used: *mut usize,
|
||||
) -> HRESULT {
|
||||
xasync::XAsyncGetResult(block, (&raw const TOKEN).cast(), size, buffer, used)
|
||||
}
|
||||
|
||||
extern "system" fn max_users(_: This, out: *mut u32) -> HRESULT {
|
||||
put(out, 1)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
extern "system" fn token_utf16_async(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_options: u32,
|
||||
_method: *const u16,
|
||||
_url: *const u16,
|
||||
_header_count: usize,
|
||||
_headers: *const c_void,
|
||||
_body_size: usize,
|
||||
_body: *const c_void,
|
||||
block: *mut AsyncBlock,
|
||||
) -> HRESULT {
|
||||
tracing::info!("token and signature (UTF-16): offline");
|
||||
xasync::finished(block, (&raw const TOKEN).cast(), FAILED_TO_GET_TOKEN)
|
||||
}
|
||||
|
||||
extern "system" fn resolve_issue_async(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_url: *const c_void,
|
||||
block: *mut AsyncBlock,
|
||||
) -> HRESULT {
|
||||
xasync::finished(block, (&raw const RESOLVE).cast(), S_OK)
|
||||
}
|
||||
|
||||
const NO_PICTURE: HRESULT = 0x8000_4005_u32 as i32;
|
||||
static PICTURE: u8 = 0;
|
||||
|
||||
extern "system" fn picture_async(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_size: u32,
|
||||
block: *mut AsyncBlock,
|
||||
) -> HRESULT {
|
||||
xasync::finished(block, (&raw const PICTURE).cast(), NO_PICTURE)
|
||||
}
|
||||
extern "system" fn picture_size(_: This, block: *mut AsyncBlock, out: *mut usize) -> HRESULT {
|
||||
xasync::XAsyncGetResultSize(block, out)
|
||||
}
|
||||
extern "system" fn picture_result(
|
||||
_: This,
|
||||
block: *mut AsyncBlock,
|
||||
size: usize,
|
||||
buffer: *mut c_void,
|
||||
used: *mut usize,
|
||||
) -> HRESULT {
|
||||
xasync::XAsyncGetResult(block, (&raw const PICTURE).cast(), size, buffer, used)
|
||||
}
|
||||
|
||||
pub const DEFERRAL_NOT_AVAILABLE: HRESULT = 0x8924_5103_u32 as i32;
|
||||
|
||||
extern "system" fn sign_out_deferral(_: This, out: *mut *const c_void) -> HRESULT {
|
||||
if !out.is_null() {
|
||||
|
||||
unsafe { out.write(std::ptr::null()) };
|
||||
}
|
||||
DEFERRAL_NOT_AVAILABLE
|
||||
}
|
||||
extern "system" fn close_deferral(_: This, _deferral: *const c_void) {}
|
||||
|
||||
extern "system" fn add_by_id_async(this: This, id: u64, block: *mut AsyncBlock) -> HRESULT {
|
||||
if id == XUID {
|
||||
add_async(this, 0, block)
|
||||
} else {
|
||||
xasync::finished(block, (&raw const ADD).cast(), USER_NOT_FOUND)
|
||||
}
|
||||
}
|
||||
|
||||
extern "system" fn register(
|
||||
_: This,
|
||||
_queue: *const c_void,
|
||||
_context: *mut c_void,
|
||||
_callback: *const c_void,
|
||||
out: *mut u64,
|
||||
) -> HRESULT {
|
||||
put(out, token())
|
||||
}
|
||||
extern "system" fn unregister(_: This, _token: u64, _wait: bool) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
extern "system" fn find_for_device(_: This, device: *const [u8; 32], out: *mut Handle) -> HRESULT {
|
||||
|
||||
match unsafe { device.as_ref() } {
|
||||
Some(id) => found(super::gameinput::is_device_id(id), out),
|
||||
None => xasync::E_INVALIDARG,
|
||||
}
|
||||
}
|
||||
|
||||
static VTABLE: Methods<47> = with_spare([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
duplicate as *const (),
|
||||
close as *const (),
|
||||
compare as *const (),
|
||||
max_users as *const (),
|
||||
add_async as *const (),
|
||||
add_result as *const (),
|
||||
get_local_id as *const (),
|
||||
find_by_local_id as *const (),
|
||||
get_id as *const (),
|
||||
find_by_id as *const (),
|
||||
get_is_guest as *const (),
|
||||
get_state as *const (),
|
||||
get_gamertag as *const (),
|
||||
picture_async as *const (),
|
||||
picture_size as *const (),
|
||||
picture_result as *const (),
|
||||
get_age_group as *const (),
|
||||
check_privilege as *const (),
|
||||
resolve_privilege_async as *const (),
|
||||
resolve_privilege_result as *const (),
|
||||
token_async as *const (),
|
||||
token_size as *const (),
|
||||
token_result as *const (),
|
||||
token_utf16_async as *const (),
|
||||
token_size as *const (),
|
||||
token_result as *const (),
|
||||
resolve_issue_async as *const (),
|
||||
resolve_privilege_result as *const (),
|
||||
resolve_issue_async as *const (),
|
||||
resolve_privilege_result as *const (),
|
||||
register as *const (),
|
||||
unregister as *const (),
|
||||
sign_out_deferral as *const (),
|
||||
close_deferral as *const (),
|
||||
add_by_id_async as *const (),
|
||||
add_result as *const (),
|
||||
]);
|
||||
|
||||
static GAMERTAG_VTABLE: Methods<12> = with_spare([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
get_gamertag as *const (),
|
||||
]);
|
||||
|
||||
static DEVICE_VTABLE: Methods<19> = with_spare([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
find_for_device as *const (),
|
||||
register as *const (),
|
||||
unregister as *const (),
|
||||
missing::<6> as *const (),
|
||||
register as *const (),
|
||||
unregister as *const (),
|
||||
missing::<9> as *const (),
|
||||
missing::<10> as *const (),
|
||||
]);
|
||||
|
||||
Reference in new issue
Block a user