Skip to content

armgit / gecko

Public Imported from GitHub
0

A GameCube/Wii emulator and debugger written in Rust.

faster rom loading in gecko-app, support all textures, unified decoding

Layle237f0176fb33
diff --git a/Cargo.lock b/Cargo.lock
index eec2abc..d72bec2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -42,6 +42,17 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+[[package]]
+name = "aes"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
+dependencies = [
+ "cfg-if",
+ "cipher",
+ "cpufeatures",
+]
+
[[package]]
name = "ahash"
version = "0.8.12"
@@ -558,6 +569,12 @@ dependencies = [
"windows-link",
]
+[[package]]
+name = "base16ct"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf"
+
[[package]]
name = "base64"
version = "0.22.1"
@@ -652,6 +669,15 @@ dependencies = [
"generic-array",
]
+[[package]]
+name = "block-padding"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"
+dependencies = [
+ "generic-array",
+]
+
[[package]]
name = "block2"
version = "0.5.1"
@@ -812,6 +838,15 @@ dependencies = [
"rustversion",
]
+[[package]]
+name = "cbc"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6"
+dependencies = [
+ "cipher",
+]
+
[[package]]
name = "cc"
version = "1.2.62"
@@ -895,6 +930,16 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901"
+[[package]]
+name = "cipher"
+version = "0.4.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
+dependencies = [
+ "crypto-common",
+ "inout",
+]
+
[[package]]
name = "clap"
version = "4.6.1"
@@ -2329,7 +2374,9 @@ dependencies = [
"iced",
"iced_aw",
"image 0.1.0",
+ "indexed_deflate",
"mimalloc",
+ "nod",
"reqwest",
"rfd",
"ringbuf",
@@ -2343,6 +2390,8 @@ dependencies = [
"walkdir",
"webbrowser",
"wgpu",
+ "zerocopy",
+ "zip",
]
[[package]]
@@ -2530,6 +2579,15 @@ dependencies = [
"svg_fmt",
]
+[[package]]
+name = "gzip-header"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "86848f4fd157d91041a62c78046fb7b248bcc2dce78376d436a1756e9a038577"
+dependencies = [
+ "crc32fast",
+]
+
[[package]]
name = "h2"
version = "0.4.14"
@@ -3224,6 +3282,17 @@ version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "964de6e86d545b246d84badc0fef527924ace5134f30641c203ef52ba83f58d5"
+[[package]]
+name = "indexed_deflate"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df94285e6105b4fd185b5a9672737911a793c3a0b23ad7ac939b4ff9f9c2c637"
+dependencies = [
+ "gzip-header",
+ "miniz_oxide",
+ "thiserror 2.0.18",
+]
+
[[package]]
name = "indexmap"
version = "2.14.0"
@@ -3245,6 +3314,16 @@ dependencies = [
"rustversion",
]
+[[package]]
+name = "inout"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
+dependencies = [
+ "block-padding",
+ "generic-array",
+]
+
[[package]]
name = "instability"
version = "0.3.12"
@@ -4097,6 +4176,27 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "nod"
+version = "1.4.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9fbe592a5e74ed882c6d7373b4cc6beca6e84cf6b7f9fe5cba5d600255d965b5"
+dependencies = [
+ "aes",
+ "base16ct",
+ "cbc",
+ "digest",
+ "dyn-clone",
+ "encoding_rs",
+ "itertools 0.13.0",
+ "log",
+ "rayon",
+ "sha1",
+ "thiserror 1.0.69",
+ "zerocopy",
+ "zstd",
+]
+
[[package]]
name = "nohash-hasher"
version = "0.2.0"
@@ -6075,6 +6175,17 @@ dependencies = [
"serde_core",
]
+[[package]]
+name = "sha1"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest",
+]
+
[[package]]
name = "sha3"
version = "0.10.9"
@@ -8559,18 +8670,18 @@ checksum = "6df3dc4292935e51816d896edcd52aa30bc297907c26167fec31e2b0c6a32524"
[[package]]
name = "zerocopy"
-version = "0.8.48"
+version = "0.8.57"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9"
+checksum = "d35102a9f36d089ccae9e4c6802bc118be4487b80aaffc0ab4e0cf5ce92d2873"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
-version = "0.8.48"
+version = "0.8.57"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4"
+checksum = "146c01f5ab44258da43cf276c74a2763db2ff3969c9c652c3f2de07041d0b2bc"
dependencies = [
"proc-macro2",
"quote",
diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml
index 8cd119e..b1d1d8e 100644
--- a/crates/app/Cargo.toml
+++ b/crates/app/Cargo.toml
@@ -9,6 +9,10 @@ path = "src/main.rs"
[dependencies]
image = { path = "../image" }
+nod = { version = "1.4.4", default-features = false, features = ["compress-zstd"] }
+zip = { version = "8.6.0", default-features = false, features = ["deflate"] }
+indexed_deflate = "0.1.0"
+zerocopy = "0.8.57"
gecko = { path = "../gecko", features = ["fps-counter"] }
hostinput = { path = "../hostinput" }
backend-wgpu = { path = "../backend-wgpu" }
diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs
index a03b2a2..40c0671 100644
--- a/crates/app/src/app.rs
+++ b/crates/app/src/app.rs
@@ -309,9 +309,12 @@ impl App {
self.insert_game_sorted(*game);
Task::none()
}
+ Message::ScanProgress(ScanProgress::Checkpoint(cache)) => {
+ self.cache = *cache;
+ Task::none()
+ }
Message::ScanProgress(ScanProgress::Finished(cache)) => {
self.cache = *cache;
- self.persist_cache();
self.scanning = false;
tracing::info!(total = self.games.len(), "scan finished");
Task::none()
@@ -379,7 +382,7 @@ impl App {
Task::perform(
async move {
- tokio::task::spawn_blocking(move || library::load_one(&path, format).map(Box::new))
+ tokio::task::spawn_blocking(move || library::load_header(&path, format).map(Box::new))
.await
.unwrap_or_else(|err| Err(err.to_string()))
},
@@ -927,14 +930,15 @@ impl App {
}
}
- fn persist_cache(&self) {
- let path = cache::cache_path();
- if let Err(err) = cache::save(&path, &self.cache) {
- tracing::warn!(%err, path = %path.display(), "failed to persist library cache");
+ fn insert_game_sorted(&mut self, game: Game) {
+ if let Some(index) = self.games.iter().position(|existing| existing.path == game.path) {
+ if self.games[index].title_lc == game.title_lc {
+ self.games[index] = game;
+ return;
+ }
+ self.games.remove(index);
}
- }
- fn insert_game_sorted(&mut self, game: Game) {
let pos = self
.games
.binary_search_by(|g| g.title_lc.cmp(&game.title_lc))
diff --git a/crates/app/src/banner.rs b/crates/app/src/banner.rs
new file mode 100644
index 0000000..0cd85cf
--- /dev/null
+++ b/crates/app/src/banner.rs
@@ -0,0 +1,53 @@
+use gecko::flipper::gx::draw::{TextureDescriptor, TextureFormat, TlutFormat};
+use gecko::flipper::gx::regs::{MagFilter, MinFilter, WrapMode};
+use gecko::flipper::gx::texture;
+
+pub fn decode(encoded: image::banner::Texture<'_>) -> Option<Vec<u8>> {
+ let format = match encoded.format {
+ 0 => TextureFormat::I4,
+ 1 => TextureFormat::I8,
+ 2 => TextureFormat::IA4,
+ 3 => TextureFormat::IA8,
+ 4 => TextureFormat::RGB565,
+ 5 => TextureFormat::RGB5A3,
+ 6 => TextureFormat::RGBA8,
+ 8 => TextureFormat::CI4,
+ 9 => TextureFormat::CI8,
+ 10 => TextureFormat::CI14,
+ 14 => TextureFormat::CMPR,
+ _ => return None,
+ };
+
+ let size = texture::raw_data_size(encoded.width, encoded.height, format);
+ let pixels = encoded.pixels.get(..size)?;
+
+ let (palette, tlut) = match encoded.palette {
+ Some(palette) => {
+ let tlut = match palette.format {
+ 0 => TlutFormat::IA8,
+ 1 => TlutFormat::RGB565,
+ 2 => TlutFormat::RGB5A3,
+ _ => return None,
+ };
+ let entries = palette
+ .entries
+ .chunks_exact(2)
+ .map(|p| u16::from_be_bytes([p[0], p[1]]))
+ .collect::<Vec<_>>();
+ (entries, tlut)
+ }
+ None => (Vec::new(), TlutFormat::IA8),
+ };
+
+ let desc = TextureDescriptor {
+ ram_addr: 0,
+ width: encoded.width,
+ height: encoded.height,
+ format,
+ wrap_s: WrapMode::Clamp,
+ wrap_t: WrapMode::Clamp,
+ mag_filter: MagFilter::Nearest,
+ min_filter: MinFilter::Nearest,
+ };
+ Some(texture::decode_to_rgba(pixels, &desc, &palette, tlut))
+}
diff --git a/crates/app/src/cache.rs b/crates/app/src/cache.rs
index 4af742b..dad231d 100644
--- a/crates/app/src/cache.rs
+++ b/crates/app/src/cache.rs
@@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize};
use crate::config;
use crate::game::Game;
-const CACHE_VERSION: u32 = 1;
+const CACHE_VERSION: u32 = 3;
const CACHE_DIR: &str = "cache";
const CACHE_FILE: &str = "library.bin";
@@ -37,6 +37,7 @@ impl FileFingerprint {
pub struct CacheEntry {
pub fingerprint: FileFingerprint,
pub game: Game,
+ pub banner_scanned: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
diff --git a/crates/app/src/game.rs b/crates/app/src/game.rs
index c433c8d..0977dec 100644
--- a/crates/app/src/game.rs
+++ b/crates/app/src/game.rs
@@ -3,7 +3,7 @@ use std::sync::{Arc, OnceLock};
use backend_wgpu::sink::TargetAspect;
use iced::widget::image::Handle;
-use image::Dvd;
+use image::dvd::Header;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -180,8 +180,7 @@ pub struct Game {
}
impl Game {
- pub fn from_dvd(path: &Path, dvd: &dyn Dvd, format: Format) -> Self {
- let hdr = dvd.header();
+ pub fn from_metadata(path: &Path, hdr: &Header, banner: Option<image::banner::Banner>, format: Format) -> Self {
let title = self::decode_cstring(&hdr.game_name);
let game_id = String::from_utf8_lossy(&hdr.game_code).into_owned();
let maker_code = String::from_utf8_lossy(&hdr.maker_code).into_owned();
@@ -189,7 +188,7 @@ impl Game {
let region = Region::from_game_code(hdr.game_code);
let platform = if hdr.is_wii() { Platform::Wii } else { Platform::Gcn };
- let banner = image::banner::extract(dvd).map(BannerData::from).map(Arc::new);
+ let banner = banner.map(BannerData::from).map(Arc::new);
let title_lc = title.to_lowercase();
let file_name_lc = file_name.to_lowercase();
diff --git a/crates/app/src/library.rs b/crates/app/src/library.rs
index 162c2f8..c3571dd 100644
--- a/crates/app/src/library.rs
+++ b/crates/app/src/library.rs
@@ -1,17 +1,20 @@
-use std::panic::AssertUnwindSafe;
use std::path::{Path, PathBuf};
+use std::time::{Duration, Instant};
use futures::channel::mpsc;
-use futures::stream::Stream;
+use futures::stream::{self, Stream, StreamExt};
use walkdir::WalkDir;
use crate::cache::{CacheEntry, FileFingerprint, LibraryCache};
use crate::game::{Format, Game, Platform};
+const CHECKPOINT_INTERVAL: Duration = Duration::from_secs(5);
+
#[derive(Debug, Clone)]
pub enum ScanProgress {
Started { cached: Vec<Game>, pending: usize },
Loaded(Box<Game>),
+ Checkpoint(Box<LibraryCache>),
Finished(Box<LibraryCache>),
Error(String),
}
@@ -25,7 +28,7 @@ pub fn scan_library_stream(
rx
}
-async fn run_scan(roots: Vec<PathBuf>, prior: LibraryCache, tx: mpsc::UnboundedSender<ScanProgress>) {
+async fn run_scan(roots: Vec<PathBuf>, mut prior: LibraryCache, tx: mpsc::UnboundedSender<ScanProgress>) {
let enumerated = match tokio::task::spawn_blocking(move || self::enumerate_many(&roots)).await {
Ok(Ok(v)) => v,
Ok(Err(err)) => {
@@ -39,66 +42,121 @@ async fn run_scan(roots: Vec<PathBuf>, prior: LibraryCache, tx: mpsc::UnboundedS
};
let mut cache = LibraryCache::default();
- let mut cached_games: Vec<Game> = Vec::new();
- let mut todo: Vec<(PathBuf, Format, FileFingerprint)> = Vec::new();
-
- for (path, format, fp) in enumerated {
- match prior.entries.get(&path) {
- Some(entry) if entry.fingerprint == fp => {
- let game = entry.game.clone();
- cache.entries.insert(
- path.clone(),
- CacheEntry {
- fingerprint: fp,
- game: game.clone(),
- },
- );
- cached_games.push(game);
+ let mut cached_games = Vec::new();
+ let mut headers = Vec::new();
+ let mut banners = Vec::new();
+
+ for (path, format, fingerprint) in enumerated {
+ match prior.entries.remove(&path) {
+ Some(entry) if entry.fingerprint == fingerprint => {
+ if !entry.banner_scanned {
+ banners.push((path.clone(), format, fingerprint));
+ }
+ cached_games.push(entry.game.clone());
+ cache.entries.insert(path, entry);
}
- _ => todo.push((path, format, fp)),
+ _ => headers.push((path, format, fingerprint)),
}
}
- let _ = tx.unbounded_send(ScanProgress::Started {
+ let started = ScanProgress::Started {
cached: cached_games,
- pending: todo.len(),
- });
+ pending: headers.len() + banners.len(),
+ };
+ if tx.unbounded_send(started).is_err() {
+ return;
+ }
- for (path, format, fp) in todo {
- let path_for_task = path.clone();
- let join = tokio::task::spawn_blocking(move || {
- tracing::info!(path = %path_for_task.display(), "scanning");
- self::load_one(&path_for_task, format).map(|game| (path_for_task, fp, game))
+ let mut reads = stream::iter(headers)
+ .map(|(path, format, fingerprint)| {
+ tokio::task::spawn_blocking(move || {
+ let game = self::load_header(&path, format);
+ (path, format, fingerprint, game)
+ })
})
- .await;
+ .buffer_unordered(4);
- let (path, fp, game) = match join {
- Ok(Ok(triple)) => triple,
- Ok(Err(err)) => {
+ while let Some(result) = reads.next().await {
+ let (path, format, fingerprint, game) = match result {
+ Ok((path, format, fingerprint, Ok(game))) => (path, format, fingerprint, game),
+ Ok((path, _, _, Err(err))) => {
tracing::warn!(path = %path.display(), %err, "skip file");
continue;
}
Err(err) => {
- tracing::warn!(?err, path = %path.display(), "scanner task panicked");
+ tracing::warn!(?err, "header reader panicked");
continue;
}
};
- cache.entries.insert(
- path,
- CacheEntry {
- fingerprint: fp,
- game: game.clone(),
- },
- );
+ let entry = CacheEntry {
+ fingerprint,
+ game: game.clone(),
+ banner_scanned: false,
+ };
+ cache.entries.insert(path.clone(), entry);
+ banners.push((path, format, fingerprint));
+
if tx.unbounded_send(ScanProgress::Loaded(Box::new(game))).is_err() {
return;
}
}
+ if !self::checkpoint(&cache, &tx).await {
+ return;
+ }
+
+ let mut last_checkpoint = Instant::now();
+ for (path, format, fingerprint) in banners {
+ if tx.is_closed() {
+ return;
+ }
+
+ let path_for_task = path.clone();
+ match tokio::task::spawn_blocking(move || self::load_one(&path_for_task, format)).await {
+ Ok(Ok(game)) => {
+ let entry = CacheEntry {
+ fingerprint,
+ game: game.clone(),
+ banner_scanned: true,
+ };
+ cache.entries.insert(path, entry);
+
+ if tx.unbounded_send(ScanProgress::Loaded(Box::new(game))).is_err() {
+ return;
+ }
+ }
+ Ok(Err(err)) => tracing::warn!(path = %path.display(), %err, "banner read failed; retaining header"),
+ Err(err) => tracing::warn!(path = %path.display(), ?err, "banner reader panicked; retaining header"),
+ }
+
+ if last_checkpoint.elapsed() >= CHECKPOINT_INTERVAL {
+ if !self::checkpoint(&cache, &tx).await {
+ return;
+ }
+ last_checkpoint = Instant::now();
+ }
+ }
+
+ self::save_cache(&cache).await;
let _ = tx.unbounded_send(ScanProgress::Finished(Box::new(cache)));
}
+async fn checkpoint(cache: &LibraryCache, tx: &mpsc::UnboundedSender<ScanProgress>) -> bool {
+ self::save_cache(cache).await;
+ tx.unbounded_send(ScanProgress::Checkpoint(Box::new(cache.clone())))
+ .is_ok()
+}
+
+async fn save_cache(cache: &LibraryCache) {
+ let snapshot = cache.clone();
+ match tokio::task::spawn_blocking(move || crate::cache::save(&crate::cache::cache_path(), &snapshot)).await {
+ Ok(Ok(())) => {}
+ Ok(Err(err)) => tracing::warn!(%err, "failed to persist library cache"),
+ Err(err) => tracing::warn!(%err, "library cache writer panicked"),
+ }
+}
+
fn enumerate_many(roots: &[PathBuf]) -> Result<Vec<(PathBuf, Format, FileFingerprint)>, String> {
use std::collections::HashSet;
@@ -136,13 +194,14 @@ fn enumerate_many(roots: &[PathBuf]) -> Result<Vec<(PathBuf, Format, FileFingerp
Ok(out)
}
+pub fn load_header(path: &Path, format: Format) -> Result<Game, String> {
+ let header = crate::library_disc::read_header(path).map_err(|e| e.to_string())?;
+ Ok(Game::from_metadata(path, &header, None, format))
+}
+
pub fn load_one(path: &Path, format: Format) -> Result<Game, String> {
- let data = std::fs::read(path).map_err(|e| e.to_string())?;
- let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
- let dvd = image::load_dvd(data);
- Game::from_dvd(path, dvd.as_ref(), format)
- }));
- result.map_err(|_| "image::load_dvd panicked".to_owned())
+ let (header, banner) = crate::library_disc::read_metadata(path).map_err(|e| e.to_string())?;
+ Ok(Game::from_metadata(path, &header, banner, format))
}
pub fn load_dol(path: &Path, platform: Platform) -> Result<Game, String> {
diff --git a/crates/app/src/library_disc.rs b/crates/app/src/library_disc.rs
new file mode 100644
index 0000000..8acd432
--- /dev/null
+++ b/crates/app/src/library_disc.rs
@@ -0,0 +1,179 @@
+use std::fs::File;
+use std::io::{self, BufReader, Cursor, Read, Seek, SeekFrom};
+use std::path::Path;
+use std::sync::{Arc, Mutex};
+
+use image::banner::Banner;
+use image::dvd::{DVD_HEADER_SIZE, Header};
+use image::rvz;
+use indexed_deflate::{AccessPointSpan, DeflateIndexBuilder};
+use zerocopy::FromBytes;
+
+pub fn read_metadata(path: &Path) -> anyhow::Result<(Header, Option<Banner>)> {
+ self::read_stream(self::open(path)?)
+}
+
+pub fn read_header(path: &Path) -> anyhow::Result<Header> {
+ self::header_from_stream(self::open(path)?)
+}
+
+fn open(path: &Path) -> io::Result<ScanStream> {
+ let file = File::open(path)?;
+ let len = file.metadata()?.len();
+ Ok(ScanStream::new(BufReader::new(file), len))
+}
+
+fn header_from_stream(stream: ScanStream) -> anyhow::Result<Header> {
+ let mut stream = self::unwrap_zip(stream)?;
+ let mut bytes = [0; DVD_HEADER_SIZE];
+ stream.read_exact(&mut bytes)?;
+
+ if bytes.starts_with(&rvz::RVZ_MAGIC) {
+ bytes.copy_within(
+ rvz::DISC_HEADER_OFFSET..rvz::DISC_HEADER_OFFSET + rvz::DISC_HEADER_SIZE,
+ 0,
+ );
+ bytes[rvz::DISC_HEADER_SIZE..].fill(0);
+ }
+
+ let header = Header::read_from_bytes(&bytes).unwrap();
+ anyhow::ensure!(header.is_gc() || header.is_wii(), "invalid disc header");
+ Ok(header)
+}
+
+fn unwrap_zip(mut stream: ScanStream) -> anyhow::Result<ScanStream> {
+ let mut magic = [0; 4];
+ stream.read_exact(&mut magic)?;
+ stream.rewind()?;
+
+ if &magic == b"PK\x03\x04" {
+ return self::open_zip(stream);
+ }
+ Ok(stream)
+}
+
+fn read_stream(stream: ScanStream) -> anyhow::Result<(Header, Option<Banner>)> {
+ let stream = self::unwrap_zip(stream)?;
+ let disc = nod::Disc::new_stream(Box::new(stream))?;
+ let mut partition = disc.open_partition_kind(nod::PartitionKind::Data)?;
+
+ let mut bytes = [0; DVD_HEADER_SIZE];
+ partition.read_exact(&mut bytes)?;
+ if disc.header().is_wii() {
+ image::dvd::unshift_wii_header_offsets(&mut bytes);
+ }
+ let header = Header::read_from_bytes(&bytes).unwrap();
+
+ let banner = image::banner::extract(
+ &header,
+ |offset, buf| {
+ partition.seek(SeekFrom::Start(offset as u64))?;
+ partition.read_exact(buf)
+ },
+ crate::banner::decode,
+ )?;
+ Ok((header, banner))
+}
+
+fn open_zip(stream: ScanStream) -> anyhow::Result<ScanStream> {
+ let file_len = stream.len;
+ let mut archive = zip::ZipArchive::new(stream)?;
+ let index = archive
+ .file_names()
+ .position(image::is_disc_entry)
+ .ok_or_else(|| anyhow::anyhow!("no disc image found in ZIP"))?;
+
+ let entry = archive.by_index_raw(index)?;
+ anyhow::ensure!(!entry.encrypted(), "encrypted ZIP disc images are unsupported");
+ let start = entry
+ .data_start()
+ .ok_or_else(|| anyhow::anyhow!("missing ZIP data offset"))?;
+ let compressed = entry.compressed_size();
+ let len = entry.size();
+ let method = entry.compression();
+ anyhow::ensure!(
+ start <= file_len && compressed <= file_len - start,
+ "truncated ZIP entry"
+ );
+ drop(entry);
+
+ let range = nod::WindowedStream::new(BufReader::new(archive.into_inner()), start, compressed)?;
+ match method {
+ zip::CompressionMethod::Stored => {
+ anyhow::ensure!(compressed == len, "invalid stored ZIP entry size");
+ Ok(ScanStream::new(range, len))
+ }
+ zip::CompressionMethod::Deflated => {
+ let span = AccessPointSpan::new(compressed.div_ceil(64).max(1024 * 1024));
+ let reader = DeflateIndexBuilder::new(range, Cursor::new(Vec::new()), span)?;
+ Ok(ScanStream::new(reader, len))
+ }
+ _ => anyhow::bail!("unsupported ZIP compression method: {method}"),
+ }
+}
+
+trait ReadSeek: Read + Seek + Send {}
+impl<T: Read + Seek + Send> ReadSeek for T {}
+
+#[derive(Clone)]
+struct ScanStream {
+ reader: Arc<Mutex<SharedReader>>,
+ position: u64,
+ len: u64,
+}
+
+struct SharedReader {
+ reader: Box<dyn ReadSeek>,
+ position: Option<u64>,
+}
+
+impl ScanStream {
+ fn new(reader: impl Read + Seek + Send + 'static, len: u64) -> Self {
+ Self {
+ reader: Arc::new(Mutex::new(SharedReader {
+ reader: Box::new(reader),
+ position: None,
+ })),
+ position: 0,
+ len,
+ }
+ }
+}
+
+impl Read for ScanStream {
+ fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
+ let len = self.len.saturating_sub(self.position).min(buf.len() as u64) as usize;
+ if len == 0 {
+ return Ok(0);
+ }
+
+ let mut reader = self
+ .reader
+ .lock()
+ .map_err(|_| io::Error::other("disc reader poisoned"))?;
+ let in_place = reader.position == Some(self.position);
+ reader.position = None;
+ if !in_place {
+ reader.reader.seek(SeekFrom::Start(self.position))?;
+ }
+
+ let read = reader.reader.read(&mut buf[..len])?;
+ self.position += read as u64;
+ reader.position = Some(self.position);
+ Ok(read)
+ }
+}
+
+impl Seek for ScanStream {
+ fn seek(&mut self, from: SeekFrom) -> io::Result<u64> {
+ let position = match from {
+ SeekFrom::Start(offset) => Some(offset),
+ SeekFrom::Current(offset) => self.position.checked_add_signed(offset),
+ SeekFrom::End(offset) => self.len.checked_add_signed(offset),
+ }
+ .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "invalid disc seek"))?;
+
+ self.position = position;
+ Ok(position)
+ }
+}
diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs
index eea925b..54e8546 100644
--- a/crates/app/src/main.rs
+++ b/crates/app/src/main.rs
@@ -1,9 +1,11 @@
mod app;
+mod banner;
mod cache;
mod config;
mod game;
mod keybinds;
mod library;
+mod library_disc;
mod player;
mod theme;
mod update;
diff --git a/crates/image/Cargo.toml b/crates/image/Cargo.toml
index 5f7a7d6..14e98ae 100644
--- a/crates/image/Cargo.toml
+++ b/crates/image/Cargo.toml
@@ -12,7 +12,7 @@ banner = []
[dependencies]
idb-rs = { git = "https://github.com/ioncodes/idb-rs.git", optional = true }
object = { version = "0.36.7", default-features = false, features = ["elf", "read"], optional = true }
-zerocopy = { version = "0.8.48", features = ["derive"] }
+zerocopy = { version = "0.8.57", features = ["derive"] }
zstd = { version = "0.13.3", optional = true }
-zip = { version = "8.5.1", default-features = false, features = ["deflate"] }
+zip = { version = "8.6.0", default-features = false, features = ["deflate"] }
tracing = "0.1.44"
diff --git a/crates/image/src/banner.rs b/crates/image/src/banner.rs
index ad5017f..cc985e9 100644
--- a/crates/image/src/banner.rs
+++ b/crates/image/src/banner.rs
@@ -1,10 +1,10 @@
-use crate::Dvd;
-use crate::dvd::FstNode;
+use crate::dvd::Header;
pub const GCN_BANNER_WIDTH: u32 = 96;
pub const GCN_BANNER_HEIGHT: u32 = 32;
const GCN_PIXELS_OFFSET: usize = 0x20;
+const GCN_PIXELS_END: usize = GCN_PIXELS_OFFSET + (GCN_BANNER_WIDTH * GCN_BANNER_HEIGHT * 2) as usize;
const WII_IMET_MAGIC_OFFSET: usize = 0x40;
const WII_U8_OFFSET: usize = 0x600;
const U8_MAGIC: [u8; 4] = [0x55, 0xAA, 0x38, 0x2D];
@@ -17,43 +17,66 @@ pub struct Banner {
pub rgba: Vec<u8>,
}
-pub fn extract(dvd: &dyn Dvd) -> Option<Banner> {
- let header = dvd.header();
+pub struct Texture<'a> {
+ pub width: u32,
+ pub height: u32,
+ pub format: u32,
+ pub pixels: &'a [u8],
+ pub palette: Option<Palette<'a>>,
+}
+
+pub struct Palette<'a> {
+ pub format: u32,
+ pub entries: &'a [u8],
+}
+
+pub type TextureDecoder = fn(Texture<'_>) -> Option<Vec<u8>>;
+
+pub fn extract(
+ header: &Header,
+ mut read: impl FnMut(usize, &mut [u8]) -> std::io::Result<()>,
+ decode: TextureDecoder,
+) -> std::io::Result<Option<Banner>> {
let fst_offset = header.offset_filesystem.get() as usize;
let fst_size = header.filesystem_size.get() as usize;
if fst_size == 0 || fst_offset == 0 {
- return None;
+ return Ok(None);
}
let mut fst_buf = vec![0u8; fst_size];
- dvd.read_disc_into(fst_offset, &mut fst_buf);
+ read(fst_offset, &mut fst_buf)?;
+
let shift = if header.is_wii() { 2 } else { 0 };
- let root = FstNode::parse(&fst_buf, shift);
- let (file_offset, file_size) = self::find_file(&root, "opening.bnr")?;
+ let Some((file_offset, mut file_size)) = self::find_file(&fst_buf, "opening.bnr", shift) else {
+ return Ok(None);
+ };
+ if header.is_gc() {
+ file_size = file_size.min(GCN_PIXELS_END);
+ }
- let mut buf = vec![0u8; file_size as usize];
- dvd.read_disc_into(file_offset as usize, &mut buf);
+ let mut buf = vec![0u8; file_size];
+ read(file_offset, &mut buf)?;
if buf.len() >= 4 && (&buf[0..4] == b"BNR1" || &buf[0..4] == b"BNR2") {
- return self::decode_gcn(&buf);
+ return Ok(self::decode_gcn(&buf, decode));
}
if header.is_wii() {
- return self::decode_wii(&buf);
+ return Ok(self::decode_wii(&buf, decode));
}
- None
+ Ok(None)
}
-fn decode_gcn(buf: &[u8]) -> Option<Banner> {
- let w = GCN_BANNER_WIDTH as usize;
- let h = GCN_BANNER_HEIGHT as usize;
- let need = GCN_PIXELS_OFFSET + w * h * 2;
- if buf.len() < need {
- return None;
- }
+fn decode_gcn(buf: &[u8], decode: TextureDecoder) -> Option<Banner> {
+ let rgba = decode(Texture {
+ width: GCN_BANNER_WIDTH,
+ height: GCN_BANNER_HEIGHT,
+ format: 5,
+ pixels: buf.get(GCN_PIXELS_OFFSET..GCN_PIXELS_END)?,
+ palette: None,
+ })?;
- let rgba = self::decode_rgb5a3_tiled(&buf[GCN_PIXELS_OFFSET..], w, h)?;
Some(Banner {
width: GCN_BANNER_WIDTH,
height: GCN_BANNER_HEIGHT,
@@ -61,16 +84,15 @@ fn decode_gcn(buf: &[u8]) -> Option<Banner> {
})
}
-fn decode_wii(buf: &[u8]) -> Option<Banner> {
+fn decode_wii(buf: &[u8], decode: TextureDecoder) -> Option<Banner> {
if buf.len() < WII_U8_OFFSET + 32 || &buf[WII_IMET_MAGIC_OFFSET..WII_IMET_MAGIC_OFFSET + 4] != b"IMET" {
tracing::warn!("wii banner: outer layout / IMET magic missing");
return None;
}
let banner_bin = self::read_u8_file(&buf[WII_U8_OFFSET..], "banner.bin")?;
- let inner = self::strip_imd5_and_lz77(&banner_bin)?;
- let tpl = self::find_largest_tpl(&inner)?;
- self::decode_first_tpl_texture(&tpl)
+ let inner = self::strip_imd5_and_lz77(banner_bin)?;
+ self::decode_largest_tpl(&inner, decode)
}
fn strip_imd5_and_lz77(banner_bin: &[u8]) -> Option<Vec<u8>> {
@@ -99,14 +121,27 @@ fn strip_imd5_and_lz77(banner_bin: &[u8]) -> Option<Vec<u8>> {
inner
}
-fn find_file(node: &FstNode, name: &str) -> Option<(u32, u32)> {
- match node {
- FstNode::File { name: n, offset, size } => n.eq_ignore_ascii_case(name).then_some((*offset, *size)),
- FstNode::Directory { children, .. } => children.iter().find_map(|c| self::find_file(c, name)),
+fn find_file(fst: &[u8], name: &str, shift: u32) -> Option<(usize, usize)> {
+ let count = self::u32_be(fst, 8)? as usize;
+ let strings = fst.get(count.checked_mul(12)?..)?;
+
+ for index in 1..count {
+ let base = index * 12;
+ if fst[base] != 0 {
+ continue;
+ }
+
+ let name_off = self::u24_be(fst, base + 1)? as usize;
+ if self::read_cstr_at(strings, name_off)?.eq_ignore_ascii_case(name) {
+ let offset = (self::u32_be(fst, base + 4)? as u64) << shift;
+ return Some((usize::try_from(offset).ok()?, self::u32_be(fst, base + 8)? as usize));
+ }
}
+
+ None
}
-fn read_u8_file(archive: &[u8], name: &str) -> Option<Vec<u8>> {
+fn read_u8_file<'a>(archive: &'a [u8], name: &str) -> Option<&'a [u8]> {
let (nodes_base, node_count, strings) = self::parse_u8_header(archive)?;
for i in 1..node_count {
@@ -123,19 +158,15 @@ fn read_u8_file(archive: &[u8], name: &str) -> Option<Vec<u8>> {
continue;
}
- if file_offset + file_size > archive.len() {
- return None;
- }
-
- return Some(archive[file_offset..file_offset + file_size].to_vec());
+ return archive.get(file_offset..file_offset.checked_add(file_size)?);
}
None
}
-fn find_largest_tpl(archive: &[u8]) -> Option<Vec<u8>> {
+fn decode_largest_tpl(archive: &[u8], decode: TextureDecoder) -> Option<Banner> {
let (nodes_base, node_count, strings) = self::parse_u8_header(archive)?;
- let mut best: Option<(usize, usize)> = None;
+ let mut best: Option<Banner> = None;
for i in 1..node_count {
let base = nodes_base + i * 12;
@@ -144,25 +175,41 @@ fn find_largest_tpl(archive: &[u8]) -> Option<Vec<u8>> {
}
let name_off = self::u24_be(archive, base + 1)? as usize;
- let file_offset = self::u32_be(archive, base + 4)? as usize;
- let file_size = self::u32_be(archive, base + 8)? as usize;
- let entry_name = self::read_cstr_at(strings, name_off)?;
-
- if !entry_name.to_ascii_lowercase().ends_with(".tpl") {
+ let name = self::read_cstr_at(strings, name_off)?;
+ if !name.to_ascii_lowercase().ends_with(".tpl") {
continue;
}
- if best.map_or(true, |(_, sz)| file_size > sz) {
- best = Some((file_offset, file_size));
+ let offset = self::u32_be(archive, base + 4)? as usize;
+ let size = self::u32_be(archive, base + 8)? as usize;
+ let Some(tpl) = offset.checked_add(size).and_then(|end| archive.get(offset..end)) else {
+ continue;
+ };
+
+ let Some(count) = self::u32_be(tpl, 4) else { continue };
+ if count as usize > tpl.len() / 8 {
+ continue;
}
- }
- let (off, sz) = best?;
- if off + sz > archive.len() {
- return None;
+ for index in 0..count as usize {
+ let Some(texture) = self::parse_tpl_texture(tpl, index) else {
+ continue;
+ };
+ if best
+ .as_ref()
+ .is_some_and(|b| b.width * b.height >= texture.width * texture.height)
+ {
+ continue;
+ }
+
+ let (width, height) = (texture.width, texture.height);
+ if let Some(rgba) = decode(texture) {
+ best = Some(Banner { width, height, rgba });
+ }
+ }
}
- Some(archive[off..off + sz].to_vec())
+ best
}
fn parse_u8_header(archive: &[u8]) -> Option<(usize, usize, &[u8])> {
@@ -173,13 +220,13 @@ fn parse_u8_header(archive: &[u8]) -> Option<(usize, usize, &[u8])> {
let root_node_offset = self::u32_be(archive, 0x04)? as usize;
let header_size = self::u32_be(archive, 0x08)? as usize;
let nodes_base = root_node_offset;
- let node_count = self::u32_be(archive, nodes_base + 8)? as usize;
+ let node_count = self::u32_be(archive, nodes_base.checked_add(8)?)? as usize;
if node_count == 0 {
return None;
}
- let nodes_end = nodes_base + node_count * 12;
- let strings_end = root_node_offset + header_size;
+ let nodes_end = nodes_base.checked_add(node_count.checked_mul(12)?)?;
+ let strings_end = root_node_offset.checked_add(header_size)?;
if strings_end > archive.len() || nodes_end > strings_end {
return None;
}
@@ -188,7 +235,7 @@ fn parse_u8_header(archive: &[u8]) -> Option<(usize, usize, &[u8])> {
Some((nodes_base, node_count, strings))
}
-fn decode_first_tpl_texture(tpl: &[u8]) -> Option<Banner> {
+fn parse_tpl_texture(tpl: &[u8], index: usize) -> Option<Texture<'_>> {
if tpl.len() < 12 {
return None;
}
@@ -200,14 +247,14 @@ fn decode_first_tpl_texture(tpl: &[u8]) -> Option<Banner> {
}
let ntex = self::u32_be(tpl, 4)?;
- if ntex == 0 {
+ if index >= ntex as usize {
return None;
}
- let table_off = self::u32_be(tpl, 8)? as usize;
+ let table_off = (self::u32_be(tpl, 8)? as usize).checked_add(index.checked_mul(8)?)?;
let img_hdr_off = self::u32_be(tpl, table_off)? as usize;
- let palette_hdr_off = self::u32_be(tpl, table_off + 4)? as usize;
- if img_hdr_off + 0x24 > tpl.len() {
+ let palette_hdr_off = self::u32_be(tpl, table_off.checked_add(4)?)? as usize;
+ if img_hdr_off.checked_add(0x24)? > tpl.len() {
return None;
}
@@ -220,104 +267,37 @@ fn decode_first_tpl_texture(tpl: &[u8]) -> Option<Banner> {
return None;
}
- let pixels = &tpl[data_off..];
- let rgba = match format {
- 4 => self::decode_rgb565_tiled(pixels, width, height)?,
- 5 => self::decode_rgb5a3_tiled(pixels, width, height)?,
- 6 => self::decode_rgba8_tiled(pixels, width, height)?,
- 9 => {
- let palette = self::decode_palette(tpl, palette_hdr_off)?;
- self::decode_c8_tiled(pixels, width, height, &palette)?
- }
- other => {
- tracing::warn!(format = other, width, height, "wii banner: unsupported TPL format");
- return None;
- }
+ let palette = if matches!(format, 8 | 9 | 10) {
+ Some(self::parse_palette(tpl, palette_hdr_off)?)
+ } else {
+ None
};
- Some(Banner {
+ Some(Texture {
width: width as u32,
height: height as u32,
- rgba,
+ format,
+ pixels: &tpl[data_off..],
+ palette,
})
}
-fn decode_palette(tpl: &[u8], palette_hdr_off: usize) -> Option<Vec<(u8, u8, u8, u8)>> {
- if palette_hdr_off == 0 || palette_hdr_off + 0x0C > tpl.len() {
- tracing::warn!(palette_hdr_off, "wii banner: paletted texture without palette header");
- return None;
- }
-
- let entry_count = u16::from_be_bytes(tpl[palette_hdr_off..palette_hdr_off + 2].try_into().ok()?) as usize;
- let format = self::u32_be(tpl, palette_hdr_off + 4)?;
- let data_off = self::u32_be(tpl, palette_hdr_off + 8)? as usize;
- if data_off + entry_count * 2 > tpl.len() {
+fn parse_palette(tpl: &[u8], offset: usize) -> Option<Palette<'_>> {
+ if offset == 0 {
return None;
}
- let decode: fn(u16) -> (u8, u8, u8, u8) = match format {
- 0 => self::decode_ia8_pixel,
- 1 => self::decode_rgb565_pixel,
- 2 => self::decode_rgb5a3_pixel,
- other => {
- tracing::warn!(format = other, "wii banner: unsupported palette format");
- return None;
- }
- };
-
- let mut palette = vec![(0u8, 0u8, 0u8, 0u8); 256];
- for i in 0..entry_count.min(256) {
- let off = data_off + i * 2;
- let value = u16::from_be_bytes([tpl[off], tpl[off + 1]]);
- palette[i] = decode(value);
- }
-
- Some(palette)
-}
-
-fn decode_c8_tiled(indices: &[u8], width: usize, height: usize, palette: &[(u8, u8, u8, u8)]) -> Option<Vec<u8>> {
- const TILE_W: usize = 8;
- const TILE_H: usize = 4;
-
- let (tiles_x, tiles_y) = self::padded_tiles(width, height, TILE_W, TILE_H);
- let need = tiles_x * tiles_y * TILE_W * TILE_H;
- if indices.len() < need {
+ let count = u16::from_be_bytes(tpl.get(offset..offset.checked_add(2)?)?.try_into().ok()?) as usize;
+ let format = self::u32_be(tpl, offset.checked_add(4)?)?;
+ let start = self::u32_be(tpl, offset.checked_add(8)?)? as usize;
+ if count == 0 {
return None;
}
- let mut rgba = vec![0u8; width * height * 4];
- for ty in 0..tiles_y {
- for tx in 0..tiles_x {
- let tile_base = (ty * tiles_x + tx) * TILE_W * TILE_H;
-
- for py in 0..TILE_H {
- for px in 0..TILE_W {
- let dx = tx * TILE_W + px;
- let dy = ty * TILE_H + py;
- if dx >= width || dy >= height {
- continue;
- }
-
- let idx = indices[tile_base + py * TILE_W + px] as usize;
- let (r, g, b, a) = palette[idx];
- let dst = (dy * width + dx) * 4;
-
- rgba[dst] = r;
- rgba[dst + 1] = g;
- rgba[dst + 2] = b;
- rgba[dst + 3] = a;
- }
- }
- }
- }
-
- Some(rgba)
-}
-
-fn decode_ia8_pixel(value: u16) -> (u8, u8, u8, u8) {
- let intensity = (value >> 8) as u8;
- let alpha = (value & 0xFF) as u8;
- (intensity, intensity, intensity, alpha)
+ Some(Palette {
+ format,
+ entries: tpl.get(start..start.checked_add(count * 2)?)?,
+ })
}
fn lz77_decompress(src: &[u8], expected_size: usize) -> Option<Vec<u8>> {
@@ -372,12 +352,12 @@ fn lz77_decompress(src: &[u8], expected_size: usize) -> Option<Vec<u8>> {
}
fn u32_be(buf: &[u8], off: usize) -> Option<u32> {
- let slice = buf.get(off..off + 4)?;
+ let slice = buf.get(off..off.checked_add(4)?)?;
Some(u32::from_be_bytes(slice.try_into().ok()?))
}
fn u24_be(buf: &[u8], off: usize) -> Option<u32> {
- let slice = buf.get(off..off + 3)?;
+ let slice = buf.get(off..off.checked_add(3)?)?;
Some(u32::from_be_bytes([0, slice[0], slice[1], slice[2]]))
}
@@ -386,132 +366,3 @@ fn read_cstr_at(buf: &[u8], off: usize) -> Option<&str> {
let end = slice.iter().position(|&b| b == 0)?;
std::str::from_utf8(&slice[..end]).ok()
}
-
-fn padded_tiles(width: usize, height: usize, tile_w: usize, tile_h: usize) -> (usize, usize) {
- let pw = (width + tile_w - 1) & !(tile_w - 1);
- let ph = (height + tile_h - 1) & !(tile_h - 1);
- (pw / tile_w, ph / tile_h)
-}
-
-fn decode_rgb5a3_tiled(data: &[u8], width: usize, height: usize) -> Option<Vec<u8>> {
- self::decode_2bpp_tiled(data, width, height, self::decode_rgb5a3_pixel)
-}
-
-fn decode_rgb565_tiled(data: &[u8], width: usize, height: usize) -> Option<Vec<u8>> {
- self::decode_2bpp_tiled(data, width, height, self::decode_rgb565_pixel)
-}
-
-fn decode_2bpp_tiled<F>(data: &[u8], width: usize, height: usize, decode: F) -> Option<Vec<u8>>
-where
- F: Fn(u16) -> (u8, u8, u8, u8),
-{
- const TILE_W: usize = 4;
- const TILE_H: usize = 4;
-
- let (tiles_x, tiles_y) = self::padded_tiles(width, height, TILE_W, TILE_H);
- let need = tiles_x * tiles_y * TILE_W * TILE_H * 2;
- if data.len() < need {
- return None;
- }
-
- let mut rgba = vec![0u8; width * height * 4];
- for ty in 0..tiles_y {
- for tx in 0..tiles_x {
- let tile_base = (ty * tiles_x + tx) * TILE_W * TILE_H * 2;
-
- for py in 0..TILE_H {
- for px in 0..TILE_W {
- let dx = tx * TILE_W + px;
- let dy = ty * TILE_H + py;
- if dx >= width || dy >= height {
- continue;
- }
-
- let src = tile_base + (py * TILE_W + px) * 2;
- let pixel = u16::from_be_bytes([data[src], data[src + 1]]);
- let (r, g, b, a) = decode(pixel);
- let dst = (dy * width + dx) * 4;
-
- rgba[dst] = r;
- rgba[dst + 1] = g;
- rgba[dst + 2] = b;
- rgba[dst + 3] = a;
- }
- }
- }
- }
-
- Some(rgba)
-}
-
-fn decode_rgb5a3_pixel(value: u16) -> (u8, u8, u8, u8) {
- if value & 0x8000 != 0 {
- let r5 = ((value >> 10) & 0x1F) as u8;
- let g5 = ((value >> 5) & 0x1F) as u8;
- let b5 = (value & 0x1F) as u8;
- (
- (r5 << 3) | (r5 >> 2),
- (g5 << 3) | (g5 >> 2),
- (b5 << 3) | (b5 >> 2),
- 0xFF,
- )
- } else {
- let a3 = ((value >> 12) & 0x7) as u8;
- let r4 = ((value >> 8) & 0xF) as u8;
- let g4 = ((value >> 4) & 0xF) as u8;
- let b4 = (value & 0xF) as u8;
- let a = (a3 << 5) | (a3 << 2) | (a3 >> 1);
- ((r4 << 4) | r4, (g4 << 4) | g4, (b4 << 4) | b4, a)
- }
-}
-
-fn decode_rgb565_pixel(value: u16) -> (u8, u8, u8, u8) {
- let r5 = ((value >> 11) & 0x1F) as u8;
- let g6 = ((value >> 5) & 0x3F) as u8;
- let b5 = (value & 0x1F) as u8;
- let r = (r5 << 3) | (r5 >> 2);
- let g = (g6 << 2) | (g6 >> 4);
- let b = (b5 << 3) | (b5 >> 2);
- (r, g, b, 0xFF)
-}
-
-fn decode_rgba8_tiled(data: &[u8], width: usize, height: usize) -> Option<Vec<u8>> {
- const TILE_W: usize = 4;
- const TILE_H: usize = 4;
-
- let (tiles_x, tiles_y) = self::padded_tiles(width, height, TILE_W, TILE_H);
- let need = tiles_x * tiles_y * 64;
- if data.len() < need {
- return None;
- }
-
- let mut rgba = vec![0u8; width * height * 4];
- for ty in 0..tiles_y {
- for tx in 0..tiles_x {
- let tile_base = (ty * tiles_x + tx) * 64;
- for py in 0..TILE_H {
- for px in 0..TILE_W {
- let pix_idx = py * TILE_W + px;
- let ar_off = tile_base + pix_idx * 2;
- let gb_off = tile_base + 32 + pix_idx * 2;
- let a = data[ar_off];
- let r = data[ar_off + 1];
- let g = data[gb_off];
- let b = data[gb_off + 1];
- let dx = tx * TILE_W + px;
- let dy = ty * TILE_H + py;
-
- if dx < width && dy < height {
- let dst = (dy * width + dx) * 4;
- rgba[dst] = r;
- rgba[dst + 1] = g;
- rgba[dst + 2] = b;
- rgba[dst + 3] = a;
- }
- }
- }
- }
- }
-
- Some(rgba)
-}
diff --git a/crates/image/src/dvd.rs b/crates/image/src/dvd.rs
index c82958e..34a498d 100644
--- a/crates/image/src/dvd.rs
+++ b/crates/image/src/dvd.rs
@@ -77,6 +77,13 @@ impl Header {
}
}
+pub fn unshift_wii_header_offsets(bytes: &mut [u8; DVD_HEADER_SIZE]) {
+ for off in [0x420, 0x424, 0x428, 0x42C, 0x430, 0x434] {
+ let v = u32::from_be_bytes(bytes[off..off + 4].try_into().unwrap());
+ bytes[off..off + 4].copy_from_slice(&v.wrapping_shl(2).to_be_bytes());
+ }
+}
+
#[repr(C, packed)]
#[derive(FromBytes, IntoBytes, Immutable, KnownLayout, Debug)]
pub struct HeaderInfo {
diff --git a/crates/image/src/lib.rs b/crates/image/src/lib.rs
index 1795f93..b44c884 100644
--- a/crates/image/src/lib.rs
+++ b/crates/image/src/lib.rs
@@ -116,16 +116,18 @@ pub fn load_dvd(data: Vec<u8>) -> Box<dyn Dvd> {
}
}
+pub fn is_disc_entry(name: &str) -> bool {
+ let name = name.to_ascii_lowercase();
+ name.ends_with(".iso") || name.ends_with(".rvz")
+}
+
fn extract_from_zip(data: Vec<u8>) -> Vec<u8> {
use std::io::Read;
let cursor = std::io::Cursor::new(data);
let mut archive = zip::ZipArchive::new(cursor).expect("failed to open ZIP archive");
let index = (0..archive.len())
- .find(|&i| {
- let name = archive.by_index(i).unwrap().name().to_ascii_lowercase();
- name.ends_with(".iso") || name.ends_with(".rvz")
- })
+ .find(|&i| self::is_disc_entry(archive.by_index(i).unwrap().name()))
.expect("no disc image found in ZIP");
let mut entry = archive.by_index(index).unwrap();
diff --git a/crates/image/src/rvz.rs b/crates/image/src/rvz.rs
index 63b5354..c52bd4f 100644
--- a/crates/image/src/rvz.rs
+++ b/crates/image/src/rvz.rs
@@ -1,7 +1,7 @@
use crate::dvd::{Apploader, DVD_APPLOADER_OFFSET, DVD_APPLOADER_SIZE, DVD_HEADER_OFFSET, DVD_HEADER_SIZE, Header};
use zerocopy::FromBytes;
-const RVZ_MAGIC: [u8; 4] = [b'R', b'V', b'Z', 0x01];
+pub const RVZ_MAGIC: [u8; 4] = [b'R', b'V', b'Z', 0x01];
const H1_SIZE: usize = 0x48;
const H1_ISO_FILE_SIZE: usize = 0x24;
@@ -18,6 +18,9 @@ const H2_RAW_DATA_OFFSET: usize = 0xB8;
const H2_RAW_DATA_SIZE: usize = 0xC0;
const H2_NUM_GROUPS: usize = 0xC4;
const H2_GROUPS_OFFSET: usize = 0xC8;
+
+pub const DISC_HEADER_OFFSET: usize = H1_SIZE + H2_DISC_HEADER;
+pub const DISC_HEADER_SIZE: usize = 0x80;
const H2_GROUPS_SIZE: usize = 0xD0;
const RAW_DATA_ENTRY_SIZE: usize = 0x18;
@@ -103,8 +106,8 @@ impl Rvz {
};
let chunk_size = self::be32(&data, h2 + H2_CHUNK_SIZE);
- let mut disc_header = [0u8; 0x80];
- disc_header.copy_from_slice(&data[h2 + H2_DISC_HEADER..h2 + H2_DISC_HEADER + 0x80]);
+ let mut disc_header = [0u8; DISC_HEADER_SIZE];
+ disc_header.copy_from_slice(&data[h2 + H2_DISC_HEADER..h2 + H2_DISC_HEADER + DISC_HEADER_SIZE]);
let num_raw_data = self::be32(&data, h2 + H2_NUM_RAW_DATA);
let raw_data_off = self::be64(&data, h2 + H2_RAW_DATA_OFFSET);
@@ -200,7 +203,7 @@ impl Rvz {
DVD_HEADER_OFFSET as u64,
&mut header_bytes,
);
- self::unshift_wii_header_offsets(&mut header_bytes);
+ crate::dvd::unshift_wii_header_offsets(&mut header_bytes);
let header = Header::read_from_bytes(&header_bytes).expect("invalid DVD header");
let mut apploader_bytes = [0u8; DVD_APPLOADER_SIZE];
@@ -631,13 +634,6 @@ fn decompress_partition_chunk(
}
}
-fn unshift_wii_header_offsets(bytes: &mut [u8; DVD_HEADER_SIZE]) {
- for off in [0x420, 0x424, 0x428, 0x42C, 0x430, 0x434] {
- let v = u32::from_be_bytes(bytes[off..off + 4].try_into().unwrap());
- bytes[off..off + 4].copy_from_slice(&v.wrapping_shl(2).to_be_bytes());
- }
-}
-
const LFG_K: usize = 521;
const LFG_J: usize = 32;
const LFG_STATE_BYTES: usize = LFG_K * 4;