Initial
This commit is contained in:
1 parent
2cff35f215
commit
49e10bb398
357 files changed
+253936
-74
No files matched your search
@@ -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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user