Skip to content

Commit b50c24e

Browse files
authored
fix(gui): read webp render sizes for the side and main views (#2463)
The image-size reader accepted only a PNG IHDR, while the catalog also ships renders as WebP. A WebP side render was dropped, so the variant lost its side view and the side buttons their hotspots; a WebP main view fell back to the metadata origin, which is the base model's size, and scaled its hotspots wrong. read_image_dimensions reads the size from the first 30 bytes of either format: PNG from IHDR, WebP from the VP8X canvas or the VP8 / VP8L bitstream header. No decoder runs. Fixes #2460
1 parent 8bf29cb commit b50c24e

3 files changed

Lines changed: 252 additions & 31 deletions

File tree

‎crates/openlogi-desktop/src/services/assets.rs‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ use walkdir::WalkDir;
4343

4444
use self::images::{
4545
buttons_image_for, find_variant_in_manifest, is_drawable_image, load_manifest, metadata_for,
46-
read_png_dimensions, side_image_for, variant_image_for,
46+
read_image_dimensions, side_image_for, variant_image_for,
4747
};
4848
pub(crate) use self::paths::user_cache_root;
4949
use self::paths::{bundle_assets_root, load_index};
@@ -185,7 +185,7 @@ fn resolve_side_view(
185185
.into_iter()
186186
.chain(["side.png".to_string()])
187187
.filter_map(|n| safe_component_path(dir, &n, "asset file").ok())
188-
.find_map(|p| read_png_dimensions(&p).ok().map(|dims| (p, dims)))?;
188+
.find_map(|p| read_image_dimensions(&p).ok().map(|dims| (p, dims)))?;
189189
Some(SideView {
190190
image_path,
191191
png_width,
@@ -431,13 +431,13 @@ impl AssetResolver {
431431
};
432432
let side_view = resolve_side_view(&dir, entry, manifest.as_ref(), ext, &metadata);
433433
let image_path = main_view(image_path, side_view.as_ref(), hero_image_path.as_ref());
434-
let (png_width, png_height) = match read_png_dimensions(&image_path) {
434+
let (png_width, png_height) = match read_image_dimensions(&image_path) {
435435
Ok(dims) => dims,
436436
Err(e) => {
437437
warn!(
438438
path = %image_path.display(),
439439
error = %e,
440-
"could not read PNG dimensions — falling back to metadata origin"
440+
"could not read image dimensions — falling back to metadata origin"
441441
);
442442
let origin = metadata.origin();
443443
(
@@ -503,7 +503,7 @@ impl AssetResolver {
503503
if !image_path.is_file() {
504504
continue;
505505
}
506-
let Ok((png_width, png_height)) = read_png_dimensions(&image_path) else {
506+
let Ok((png_width, png_height)) = read_image_dimensions(&image_path) else {
507507
continue;
508508
};
509509
debug!(

‎crates/openlogi-desktop/src/services/assets/images.rs‎

Lines changed: 88 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -5,37 +5,100 @@ use std::path::Path;
55
use openlogi_assets::DepotManifest;
66
use tracing::warn;
77

8-
/// Read width + height from a PNG's `IHDR` chunk.
8+
/// The leading bytes [`read_image_dimensions`] reads: a WebP `VP8X` or
9+
/// `VP8 ` size ends at byte 30, a PNG one at byte 24.
10+
const DIMENSIONS_HEADER_LEN: usize = 30;
11+
12+
/// Read a render's width and height from its file header.
913
///
10-
/// PNG layout: 8-byte signature, then chunks. The first chunk is always
11-
/// `IHDR` per the spec, located at bytes 12–24: 4 bytes length, 4 bytes
12-
/// type tag, then the data. The first 8 data bytes are width + height as
13-
/// big-endian u32s. We only need those 24 leading bytes — much cheaper
14-
/// than decoding the whole image.
15-
pub(super) fn read_png_dimensions(path: &Path) -> std::io::Result<(u32, u32)> {
14+
/// The catalog ships renders as PNG and as WebP, many of them under a bare
15+
/// UUID name, so the leading bytes pick the format, not the extension. Only
16+
/// those bytes are read — much cheaper than decoding the whole image.
17+
pub(super) fn read_image_dimensions(path: &Path) -> std::io::Result<(u32, u32)> {
1618
use std::fs::File;
1719
use std::io::Read;
1820

19-
const PNG_SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
21+
let mut header = Vec::with_capacity(DIMENSIONS_HEADER_LEN);
22+
File::open(path)?
23+
.take(DIMENSIONS_HEADER_LEN as u64)
24+
.read_to_end(&mut header)?;
25+
png_dimensions(&header)
26+
.or_else(|| webp_dimensions(&header))
27+
.ok_or_else(|| {
28+
std::io::Error::new(
29+
std::io::ErrorKind::InvalidData,
30+
"no PNG or WebP image size in the file header",
31+
)
32+
})
33+
}
34+
35+
/// PNG: the 8-byte signature, then the `IHDR` chunk, which is always first.
36+
/// After its 4-byte length and its tag, the data opens with the width and the
37+
/// height as big-endian `u32`s.
38+
fn png_dimensions(header: &[u8]) -> Option<(u32, u32)> {
39+
const SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
2040

21-
let mut file = File::open(path)?;
22-
let mut header = [0u8; 24];
23-
file.read_exact(&mut header)?;
24-
if header[0..8] != PNG_SIGNATURE {
25-
return Err(std::io::Error::new(
26-
std::io::ErrorKind::InvalidData,
27-
"missing PNG signature",
28-
));
29-
}
30-
if &header[12..16] != b"IHDR" {
31-
return Err(std::io::Error::new(
32-
std::io::ErrorKind::InvalidData,
33-
"missing IHDR chunk",
34-
));
41+
let ihdr = header
42+
.strip_prefix(&SIGNATURE)?
43+
.get(4..)?
44+
.strip_prefix(b"IHDR")?;
45+
let (width, rest) = ihdr.split_first_chunk::<4>()?;
46+
let height = rest.first_chunk::<4>()?;
47+
Some((u32::from_be_bytes(*width), u32::from_be_bytes(*height)))
48+
}
49+
50+
/// WebP (RFC 9649): a `RIFF` container of form `WEBP`. Its first chunk, after
51+
/// a 4-byte tag and a 4-byte length, carries the size:
52+
/// - `VP8X` (extended format): after 4 bytes of flags, the canvas width and
53+
/// height minus one, each 24-bit little-endian.
54+
/// - `VP8 ` (lossy): after the 3-byte frame tag and the key-frame start code,
55+
/// the width and height as 14-bit little-endian values; the top 2 bits of
56+
/// each `u16` are a scale.
57+
/// - `VP8L` (lossless): after the `0x2f` signature, the width and height minus
58+
/// one, packed as the low two 14-bit fields of a little-endian `u32`.
59+
fn webp_dimensions(header: &[u8]) -> Option<(u32, u32)> {
60+
const VP8_START_CODE: [u8; 3] = [0x9d, 0x01, 0x2a];
61+
const VP8L_SIGNATURE: [u8; 1] = [0x2f];
62+
63+
let form = header
64+
.strip_prefix(b"RIFF")?
65+
.get(4..)?
66+
.strip_prefix(b"WEBP")?;
67+
let (tag, chunk) = form.split_first_chunk::<4>()?;
68+
let data = chunk.get(4..)?;
69+
match tag {
70+
b"VP8X" => {
71+
let (width, rest) = data.get(4..)?.split_first_chunk::<3>()?;
72+
let height = rest.first_chunk::<3>()?;
73+
Some((u24_le(*width) + 1, u24_le(*height) + 1))
74+
}
75+
b"VP8 " => {
76+
let frame = data.get(3..)?.strip_prefix(&VP8_START_CODE)?;
77+
let (width, rest) = frame.split_first_chunk::<2>()?;
78+
let height = rest.first_chunk::<2>()?;
79+
Some((u14_le(*width), u14_le(*height)))
80+
}
81+
b"VP8L" => {
82+
let bits = data.strip_prefix(&VP8L_SIGNATURE)?.first_chunk::<4>()?;
83+
let bits = u32::from_le_bytes(*bits);
84+
Some((
85+
(bits & FOURTEEN_BITS) + 1,
86+
((bits >> 14) & FOURTEEN_BITS) + 1,
87+
))
88+
}
89+
_ => None,
3590
}
36-
let width = u32::from_be_bytes([header[16], header[17], header[18], header[19]]);
37-
let height = u32::from_be_bytes([header[20], header[21], header[22], header[23]]);
38-
Ok((width, height))
91+
}
92+
93+
/// The width and height fields of the WebP bitstreams are 14 bits wide.
94+
const FOURTEEN_BITS: u32 = 0x3fff;
95+
96+
fn u24_le([b0, b1, b2]: [u8; 3]) -> u32 {
97+
u32::from_le_bytes([b0, b1, b2, 0])
98+
}
99+
100+
fn u14_le(bytes: [u8; 2]) -> u32 {
101+
u32::from(u16::from_le_bytes(bytes)) & FOURTEEN_BITS
39102
}
40103

41104
/// Whether the file at `path` starts like an image format, so the GUI can

‎crates/openlogi-desktop/src/services/assets/tests.rs‎

Lines changed: 159 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ fn registry_files(names: &[&str]) -> Vec<openlogi_assets::FileEntry> {
119119
}
120120

121121
/// A 24-byte PNG: signature + an `IHDR` chunk header carrying only the
122-
/// width/height — all `read_png_dimensions` actually reads.
122+
/// width/height — all `read_image_dimensions` reads of a PNG.
123123
fn png_header(width: u32, height: u32) -> Vec<u8> {
124124
let mut bytes = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
125125
bytes.extend_from_slice(&13u32.to_be_bytes());
@@ -1028,6 +1028,86 @@ fn renders_are_recognised_by_their_bytes() {
10281028
assert!(!images::is_drawable_image(&root.path().join("missing.png")));
10291029
}
10301030

1031+
/// The head of a WebP file: the `RIFF` header, then the first chunk's `tag`
1032+
/// and the start of its `data`. The reader skips both lengths, so they stay
1033+
/// zero.
1034+
fn webp_header(tag: [u8; 4], data: &[u8]) -> Vec<u8> {
1035+
let mut bytes = b"RIFF\0\0\0\0WEBP".to_vec();
1036+
bytes.extend_from_slice(&tag);
1037+
bytes.extend_from_slice(&[0; 4]);
1038+
bytes.extend_from_slice(data);
1039+
bytes
1040+
}
1041+
1042+
/// An extended-format WebP head, the shape of the catalog's WebP renders: the
1043+
/// alpha flag and reserved bits, then the canvas width and height minus one,
1044+
/// each 24-bit little-endian.
1045+
fn webp_vp8x_header(width: u32, height: u32) -> Vec<u8> {
1046+
let mut data = vec![0x10, 0, 0, 0];
1047+
data.extend_from_slice(&(width - 1).to_le_bytes()[..3]);
1048+
data.extend_from_slice(&(height - 1).to_le_bytes()[..3]);
1049+
webp_header(*b"VP8X", &data)
1050+
}
1051+
1052+
/// #2460: the size behind each render's hotspots, read from the header of
1053+
/// either format the catalog ships.
1054+
#[test]
1055+
fn render_sizes_are_read_from_png_and_webp_headers() {
1056+
let root = tempfile::tempdir().expect("create temp dir");
1057+
let size_of = |bytes: &[u8]| {
1058+
let path = root.path().join("1b909bb1-911c-42b7-bf07-b60be1655de5");
1059+
std::fs::write(&path, bytes).expect("write render");
1060+
images::read_image_dimensions(&path).ok()
1061+
};
1062+
// Lossy: a key-frame tag and the start code, then 640 with the scale bits
1063+
// set, and 480.
1064+
let lossy = [0x30, 0x01, 0x00, 0x9d, 0x01, 0x2a, 0x80, 0x42, 0xe0, 0x01];
1065+
// Lossless: the signature, then 300 and 200 minus one with the alpha bit.
1066+
let mut lossless = vec![0x2f];
1067+
lossless.extend_from_slice(&((300 - 1) | ((200 - 1) << 14) | (1_u32 << 28)).to_le_bytes());
1068+
1069+
assert_eq!(size_of(&png_header(1391, 2700)), Some((1391, 2700)));
1070+
assert_eq!(
1071+
size_of(&webp_vp8x_header(1157, 2800)),
1072+
Some((1157, 2800)),
1073+
"the G502 X PLUS ext2 side render"
1074+
);
1075+
assert_eq!(size_of(&webp_header(*b"VP8 ", &lossy)), Some((640, 480)));
1076+
assert_eq!(size_of(&webp_header(*b"VP8L", &lossless)), Some((300, 200)));
1077+
}
1078+
1079+
#[test]
1080+
fn a_render_without_a_readable_size_has_none() {
1081+
let root = tempfile::tempdir().expect("create temp dir");
1082+
let size_of = |bytes: &[u8]| {
1083+
let path = root.path().join("render");
1084+
std::fs::write(&path, bytes).expect("write render");
1085+
images::read_image_dimensions(&path).ok()
1086+
};
1087+
let no_start_code = [0x30, 0x01, 0x00, 0, 0, 0, 0x80, 0x02, 0xe0, 0x01];
1088+
1089+
assert_eq!(
1090+
size_of(b"RIFF\x10\0\0\0WEBPVP8 "),
1091+
None,
1092+
"a WebP head cut short"
1093+
);
1094+
assert_eq!(size_of(&webp_vp8x_header(1157, 2800)[..28]), None);
1095+
assert_eq!(size_of(&png_header(1391, 2700)[..20]), None);
1096+
assert_eq!(size_of(&webp_header(*b"VP8 ", &no_start_code)), None);
1097+
assert_eq!(
1098+
size_of(&webp_header(*b"VP8L", &[0; 5])),
1099+
None,
1100+
"no lossless signature"
1101+
);
1102+
assert_eq!(size_of(&webp_header(*b"ANIM", &[0; 10])), None);
1103+
assert_eq!(size_of(&ghub_encrypted_blob()), None);
1104+
assert_eq!(size_of(b""), None);
1105+
assert_eq!(
1106+
images::read_image_dimensions(&root.path().join("missing")).ok(),
1107+
None
1108+
);
1109+
}
1110+
10311111
/// The `g502_wireless` depot as the catalog serves it: the black base model
10321112
/// in PNG, the purple `ext2` variant as `variant_render` with metadata
10331113
/// calibrated for it, everything keyed on the depot name.
@@ -1141,3 +1221,81 @@ fn a_drawable_colour_variant_keeps_its_renders_and_metadata() {
11411221
);
11421222
assert_eq!(first_front_marker_x(&asset), Some(535.0));
11431223
}
1224+
1225+
const G502X_PLUS_EXT2_FRONT: &str = "3253a30b-28e6-4704-85ea-a14a2e5b5df6";
1226+
const G502X_PLUS_EXT2_SIDE: &str = "1b909bb1-911c-42b7-bf07-b60be1655de5";
1227+
1228+
/// A depot whose colour variant ships its renders as WebP and no `side.png`,
1229+
/// sized like the G502 X PLUS `ext2` (#2460). Its metadata origins are smaller
1230+
/// than the renders, as in the catalog. The catalog keys the variant on the
1231+
/// depot name under `images/device/`; this one keys it on the registry model
1232+
/// id with flat names, so only the size check decides the side view.
1233+
fn write_webp_variant_depot(root: &Path) -> PathBuf {
1234+
let dir = root.join("g502x_plus");
1235+
std::fs::create_dir_all(&dir).expect("create depot dir");
1236+
std::fs::write(
1237+
dir.join("manifest.json"),
1238+
format!(
1239+
r#"{{"devices":[
1240+
{{"modelId":"c095_ext2","resources":[
1241+
{{"key":"device_image","src":"{G502X_PLUS_EXT2_FRONT}"}},
1242+
{{"key":"device_side","src":"{G502X_PLUS_EXT2_SIDE}"}}]}}
1243+
]}}"#,
1244+
),
1245+
)
1246+
.expect("write manifest");
1247+
std::fs::write(
1248+
dir.join("metadata.json"),
1249+
r#"{"images":[
1250+
{"key":"device_image","origin":{"width":1391,"height":2700},
1251+
"assignments":[{"slotId":"g502x_plus_g1_m1",
1252+
"marker":{"x":538,"y":614}}]},
1253+
{"key":"device_side","origin":{"width":936,"height":2700},
1254+
"assignments":[{"slotId":"g502x_plus_g4_m1",
1255+
"marker":{"x":580,"y":1800}}]}
1256+
]}"#,
1257+
)
1258+
.expect("write metadata");
1259+
std::fs::write(
1260+
dir.join(G502X_PLUS_EXT2_FRONT),
1261+
webp_vp8x_header(1662, 2800),
1262+
)
1263+
.expect("write front render");
1264+
std::fs::write(dir.join(G502X_PLUS_EXT2_SIDE), webp_vp8x_header(1157, 2800))
1265+
.expect("write side render");
1266+
dir
1267+
}
1268+
1269+
/// #2460: a WebP side render got no side view, and a WebP main view took the
1270+
/// metadata origin for its size, so its hotspots were scaled wrong.
1271+
#[test]
1272+
fn a_webp_colour_variant_gets_both_views_at_their_own_size() {
1273+
let root = tempfile::tempdir().expect("create temp dir");
1274+
let dir = write_webp_variant_depot(root.path());
1275+
let index = index_of(
1276+
"g502x_plus",
1277+
DeviceEntry {
1278+
model_id: "c095".into(),
1279+
model_ids: vec!["c095".into(), "4099".into()],
1280+
display_name: "G502 X PLUS".into(),
1281+
kind: "MOUSE".into(),
1282+
asset_path: "v1/devices/g502x_plus/".into(),
1283+
files: Vec::new(),
1284+
},
1285+
);
1286+
let resolver = resolver_over(&[root.path()], Some(index));
1287+
let model = DeviceModelInfo {
1288+
model_ids: [0x4099, 0xc095, 0x0000],
1289+
extended_model_id: 2,
1290+
..bare_model()
1291+
};
1292+
1293+
let asset = resolver
1294+
.resolve(&model, None)
1295+
.expect("the G502 X PLUS ext2 resolves");
1296+
let side = asset.side_view.as_ref().expect("the WebP side view");
1297+
assert_eq!(side.image_path, dir.join(G502X_PLUS_EXT2_SIDE));
1298+
assert_eq!((side.png_width, side.png_height), (1157, 2800));
1299+
assert_eq!(asset.image_path, dir.join(G502X_PLUS_EXT2_FRONT));
1300+
assert_eq!((asset.png_width, asset.png_height), (1662, 2800));
1301+
}

0 commit comments

Comments
 (0)