From ebae7004cf956589e301a6d3de5a8e4a7d0d8704 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Wed, 18 Nov 2026 20:36:00 -0300 Subject: [PATCH 01/17] feat(data): read GRIB files without GDAL (#2428, part 1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A native reader for GRIB editions 1 and 2 (`raster::grib`): simple packing on regular latitude/longitude grids, any scanning order, bitmaps and constant fields, laid out north up and, round the whole globe, from -180°. Each field on the first field's grid is a band named from its message (wgrib's inventory fields in GRIB1). Other packings and grids, fields on another grid, fields past the memory limit and a cut message are left out with a notice; the file is read message by message, never whole. CPTEC's BAM files give -90° and 90° (the grid's edges) as their first and last latitudes but scan north to south: rows then follow the scanning mode, centred between the two, with a notice. Add Data, uploads, the open dialog, the Catalog's folders and the web upload picker know the .grb, .grib, .grb2 and .grib2 extensions. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- apps/rustgis-web/src/web.rs | 4 + crates/data/src/raster/grib.rs | 781 +++++++++++++++++++++++++++ crates/data/src/raster/grib_tests.rs | 452 ++++++++++++++++ crates/data/src/raster/mod.rs | 6 +- crates/ui-egui/src/lib.rs | 5 + crates/ui-egui/src/panes.rs | 4 + docs/user-guide/data-formats.md | 1 + docs/user-guide/data.md | 1 + 9 files changed, 1254 insertions(+), 2 deletions(-) create mode 100644 crates/data/src/raster/grib.rs create mode 100644 crates/data/src/raster/grib_tests.rs diff --git a/README.md b/README.md index 3a9fe7619f..6b46cbc9e9 100644 --- a/README.md +++ b/README.md @@ -103,7 +103,7 @@ Every screenshot is RustGIS itself, rendered offscreen by `cargo run -p rustgis- |---|---| | **Data** | GeoJSON, CSV/TSV with x/y columns in other coordinate systems or WKT geometry, Excel and OpenDocument spreadsheets, GeoRSS, LandXML, encoded polylines, Shapefile (zipped too, in the browser as well), GeoPackage, GeoParquet, FlatGeobuf, KML/KMZ (with styles), GPX, GML, MapInfo MIF/MID, OpenStreetMap PBF, TopoJSON, CityJSON, CityGML 1.0–3.0, AutoCAD DXF, LiDAR point clouds (LAS, LAZ, COPC) and geotagged photos (large GeoPackage, GeoParquet and FlatGeobuf files, and Shapefiles on the desktop, are read in place), files by their web address, every vector format GDAL reads when it is installed (desktop), Esri File Geodatabases without GDAL (desktop), PostGIS, MySQL, MariaDB and SQL Server tables read live (desktop), and SQL queries and DuckDB databases through DuckDB Spatial when DuckDB is installed (desktop); PMTiles archives (by web address, or a file on the desktop) and MBTiles files; GeoJSON, CSV, GeoPackage (also as a table added to an existing file), GeoParquet, Shapefile, FlatGeobuf, KML/KMZ, GPX and WKT out (GeoPackage and FlatGeobuf not from the web app); standalone tables; reusable connections; Reload Data for linked files (desktop); geocoding (Find Place, address tables); a Data Sources pane (favourites, recent, saved services, a library) and an SQL pane (desktop); supported QGIS and GeoLibre projects and layer styles; layer and map files, styles, templates and packages | | **Open data** | STAC search (Planetary Computer assets), NASA Earthdata imagery and granule search (GeoTIFFs added on the desktop), Hugging Face, Overture Maps, Source Cooperative, OpenStreetMap by area, geoBoundaries, CKAN, Socrata and ArcGIS Hub portals; S3 buckets with signed connections and a bucket browser; a Data Cubes pane with a catalog of cubes for the time slider (added on the desktop) | -| **Rasters** | GeoTIFF and cloud-optimised GeoTIFF (any pixel type, tiled or striped, compressed), ASCII grids, Zarr 2 and 3 stores (a variable at a time step, by web address, or folder on the desktop), and JPEG 2000, NetCDF, HDF, ERDAS Imagine and the other rasters GDAL reads when it is installed (desktop); reprojection by EPSG code; Stretch, RGB, Classify, Unique Values, Colormap and Shaded Relief; DRA, band combinations, brightness/contrast/gamma; raster functions, indices, change detection, classification, georeferencing; cloud-optimised GeoTIFF export (desktop); data cubes, point time-series charts (desktop), temporal summaries and trends (Sen's slope, Mann–Kendall); a spectral profile comparing a multiband raster's bands at points | +| **Rasters** | GeoTIFF and cloud-optimised GeoTIFF (any pixel type, tiled or striped, compressed), ASCII grids, GRIB 1 and 2 (simple packing on latitude/longitude grids), Zarr 2 and 3 stores (a variable at a time step, by web address, or folder on the desktop), and JPEG 2000, NetCDF, HDF, ERDAS Imagine and the other rasters GDAL reads when it is installed (desktop); reprojection by EPSG code; Stretch, RGB, Classify, Unique Values, Colormap and Shaded Relief; DRA, band combinations, brightness/contrast/gamma; raster functions, indices, change detection, classification, georeferencing; cloud-optimised GeoTIFF export (desktop); data cubes, point time-series charts (desktop), temporal summaries and trends (Sen's slope, Mann–Kendall); a spectral profile comparing a multiband raster's bands at points | | **Maps** | Multiple maps and layouts per project, renamed and duplicated from the Browser pane; a GPU renderer (beta) with smooth zoom and pan; tilt, rotation, terrain and a 3D globe; maps of the Moon, Mars and other celestial bodies; Web Mercator or another projection (Equal Earth, Robinson, Winkel Tripel, polar and regional presets, or a [supported](docs/user-guide/maps.md#projections) projected EPSG or ESRI code); a search box for layers, places and coordinates; UTM and MGRS readouts; an on-map right-click menu (copy the coordinate, quick buffer, viewshed and line of sight); identify pop-ups with links and pictures; bookmarks, extent history, coordinate navigation; five offline basemaps, with borders in 32 worldviews (31 downloaded when chosen) | | **Web services** | WMS, WMTS, WFS, WCS, OGC API Features and Tiles, and ArcGIS REST (FeatureServer, MapServer, ImageServer, VectorTileServer) from their capabilities; CSW catalogue search; sign-in to ArcGIS Online and Enterprise, basic-auth and API-key logins; WMS and WMTS time on the time slider, legends and GetFeatureInfo | | **Web tiles** | XYZ/TMS/WMS raster tiles, Mapbox Vector Tiles and MapLibre styles (sprites, patterns, expressions), cached and fetched in the background | diff --git a/apps/rustgis-web/src/web.rs b/apps/rustgis-web/src/web.rs index e8c00d8565..250e89731e 100644 --- a/apps/rustgis-web/src/web.rs +++ b/apps/rustgis-web/src/web.rs @@ -57,6 +57,10 @@ const DATA_EXTS: &[&str] = &[ "tif", "tiff", "asc", + "grb", + "grib", + "grb2", + "grib2", ]; const CANVAS_ID: &str = "rustgis_canvas"; const LOADING_ID: &str = "rustgis_loading"; diff --git a/crates/data/src/raster/grib.rs b/crates/data/src/raster/grib.rs new file mode 100644 index 0000000000..12542bd9b2 --- /dev/null +++ b/crates/data/src/raster/grib.rs @@ -0,0 +1,781 @@ +//! GRIB files (`.grb`, `.grib`, `.grb2`, `.grib2`): weather and climate model output, read +//! without GDAL. Each field is a band. +//! +//! Read: editions 1 and 2, simple packing (GRIB1's grid point data with simple packing, GRIB2's +//! data representation template 5.0), on a regular latitude/longitude grid (GRIB1 data +//! representation type 0, GRIB2 grid definition template 3.0), in any scanning order, with or +//! without a bitmap. Following WMO's Manual on Codes (WMO-No. 306), Volume I.2, FM 92 GRIB. +//! +//! Not read yet, and said: complex, JPEG 2000, PNG and the other packings; other grids (Gaussian, +//! rotated, projected, quasi-regular). A message the reader can't read is left out with a notice +//! naming why; a file with nothing it can read is an error naming why. +//! +//! The fields on the grid of the first one read are the raster's bands, in file order; fields on +//! another grid are left out with a notice. Values are `(R + X × 2^E) / 10^D`, in the units the +//! file stores (kelvin stays kelvin). Points a bitmap masks are NaN. Rows are laid out north up, +//! and a grid round the whole globe runs from −180° (as GDAL lays it out). + +use super::{Crs, GeoTransform, Raster, max_samples}; +use crate::{DataError, Result}; +use std::io::{Read, Seek, SeekFrom}; + +/// File extensions read as GRIB. +pub const EXTENSIONS: &[&str] = &["grb", "grib", "grb2", "grib2"]; + +/// Whether a file name is a GRIB file's. +pub fn is_grib_name(name: &str) -> bool { + let ext = std::path::Path::new(name).extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); + EXTENSIONS.contains(&ext.as_str()) +} + +/// Most bytes looked through for the start of the next message ("GRIB"): files may put a +/// bulletin header or padding between messages, never this much. +const MAX_GAP: u64 = 64 * 1024; + +/// The most bits a packed value may have: GRIB allows more, no producer writes them. +const MAX_BITS: u32 = 32; + +/// The smallest a message can be: GRIB1's indicator, its shortest sections and "7777". +const MIN_MESSAGE: u64 = 8 + 28 + 11 + 4; + +fn bad(m: impl std::fmt::Display) -> DataError { + DataError::Format(format!("GRIB: {m}")) +} + +/// Reads a GRIB file's bytes (an upload, a download, a byte range of a larger file). +pub fn read_bytes(bytes: &[u8], name: &str) -> Result { + read(std::io::Cursor::new(bytes), name) +} + +/// Reads a GRIB file: its fields on the first readable one's grid, as bands. +pub fn read(mut source: R, name: &str) -> Result { + let file_len = source.seek(SeekFrom::End(0))?; + source.seek(SeekFrom::Start(0))?; + let limit = max_samples(); + let mut fields: Vec = Vec::new(); + let mut skipped = Skipped::default(); + let mut at = 0u64; + let mut messages = 0usize; + let mut held = 0usize; + while let Some(start) = find_message(&mut source, at, file_len)? { + crate::progress::check()?; + let (len, edition) = message_header(&mut source, start)?; + if len < MIN_MESSAGE || start.saturating_add(len) > file_len { + // A message cut short (a byte range that ends early, a truncated download): what was + // read before it stands, and the cut is said. + skipped.cut += 1; + break; + } + messages += 1; + at = start + len; + // Past the memory limit: the rest is only counted. + if held >= limit { + skipped.over_limit += count_fields(&mut source, start, len, edition)?; + continue; + } + let mut bytes = Vec::new(); + bytes.try_reserve_exact(len as usize).map_err(|_| bad("not enough memory for a message"))?; + source.seek(SeekFrom::Start(start))?; + source.by_ref().take(len).read_to_end(&mut bytes)?; + let decoded = match edition { + 1 => vec![grib1(&bytes, limit.saturating_sub(held))], + 2 => grib2(&bytes, limit.saturating_sub(held)), + e => vec![Err(Skip::Other(format!("edition {e}")))], + }; + for d in decoded { + match d { + Ok(f) => { + let first = fields.first().map(|f| f.grid); + if first.is_some_and(|g| !g.same(&f.grid)) { + skipped.other_grid += 1; + } else if held + f.values.len() > limit { + skipped.over_limit += 1; + } else { + held += f.values.len(); + fields.push(f); + } + } + Err(Skip::TooLarge) => skipped.over_limit += 1, + Err(Skip::Other(why)) => skipped.add(why), + } + } + } + if messages == 0 { + return Err(bad(if skipped.cut > 0 { "the first message is cut short" } else { "no GRIB message in the file" })); + } + let Some(first) = fields.first() else { + return Err(bad(format!("nothing in it can be read here: {}", skipped.notes(limit).join("; ")))); + }; + let grid = first.grid; + let mut r = to_raster(fields, name)?; + r.lost.extend(grid.notes()); + r.lost.extend(skipped.notes(limit)); + Ok(r) +} + +/// The offset of the next "GRIB" at or after `at`, within [`MAX_GAP`] bytes; `None` at the end. +fn find_message(source: &mut R, at: u64, file_len: u64) -> Result> { + if at >= file_len { + return Ok(None); + } + source.seek(SeekFrom::Start(at))?; + let n = (file_len - at).min(MAX_GAP + 4); + let mut window = Vec::new(); + source.by_ref().take(n).read_to_end(&mut window)?; + Ok(window.windows(4).position(|w| w == b"GRIB").map(|p| at + p as u64)) +} + +/// A message's length and edition, from its indicator section. +fn message_header(source: &mut R, start: u64) -> Result<(u64, u8)> { + source.seek(SeekFrom::Start(start))?; + let mut head = [0u8; 16]; + let mut got = 0; + while got < head.len() { + match source.read(head.get_mut(got..).unwrap_or_default())? { + 0 => break, + n => got += n, + } + } + if got < 8 { + return Ok((0, 0)); + } + let edition = head[7]; + let len = match edition { + 1 => u64::from(be(&head, 4, 3)), + 2 if got == 16 => head[8..16].iter().fold(0u64, |v, &b| (v << 8) | u64::from(b)), + _ => 0, + }; + Ok((len, edition)) +} + +/// How many fields a message holds: one in GRIB1, one a data section (7) in GRIB2, counted from +/// the sections' headers alone. +fn count_fields(source: &mut R, start: u64, len: u64, edition: u8) -> Result { + if edition != 2 { + return Ok(1); + } + let (mut at, end, mut n) = (start + 16, start + len, 0usize); + while at + 5 <= end { + source.seek(SeekFrom::Start(at))?; + let mut head = [0u8; 5]; + source.read_exact(&mut head)?; + if head.starts_with(b"7777") { + break; + } + let size = u64::from(be(&head, 0, 4)); + if size < 5 { + break; + } + n += usize::from(head[4] == 7); + at += size; + } + Ok(n.max(1)) +} + +/// Why a field isn't read: past the memory limit, or another reason said once with a count. +enum Skip { + TooLarge, + Other(String), +} + +/// What was left out of a file, for its notices. +#[derive(Default)] +struct Skipped { + /// Each reason, with how many fields it left out, in the order first met. + reasons: Vec<(String, usize)>, + other_grid: usize, + over_limit: usize, + cut: usize, +} + +impl Skipped { + fn add(&mut self, why: String) { + match self.reasons.iter_mut().find(|(r, _)| *r == why) { + Some((_, n)) => *n += 1, + None => self.reasons.push((why, 1)), + } + } + + fn notes(&self, limit: usize) -> Vec { + let mut out: Vec = self.reasons.iter().map(|(r, n)| format!("{} left out: {r}, not read yet", count(*n))).collect(); + if self.other_grid > 0 { + out.push(format!("{} left out: on another grid than the first field's", count(self.other_grid))); + } + if self.over_limit > 0 { + out.push(format!( + "{} left out: the bands read hold the most this computer keeps in memory ({limit} values); open a smaller part of the file", + count(self.over_limit) + )); + } + if self.cut > 0 { + out.push("the file ends inside a message, which is left out".to_string()); + } + out + } +} + +fn count(n: usize) -> String { + if n == 1 { "1 field".to_string() } else { format!("{n} fields") } +} + +/// A regular latitude/longitude grid, as the file gives it: degrees of the first and last points' +/// centres, the increments, and the scanning mode (WMO flag table 3.4). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Grid { + ni: usize, + nj: usize, + lat1: f64, + lon1: f64, + lat2: f64, + lon2: f64, + dx: f64, + dy: f64, + scan: u8, + /// The earth's shape when it isn't WGS 84's (or near enough): its description. + earth: Option<&'static str>, +} + +const SCAN_I_NEGATIVE: u8 = 0x80; +const SCAN_J_POSITIVE: u8 = 0x40; +const SCAN_J_CONSECUTIVE: u8 = 0x20; +const SCAN_ALTERNATE: u8 = 0x10; + +impl Grid { + fn same(&self, o: &Grid) -> bool { + let close = |a: f64, b: f64| (a - b).abs() <= 1e-6; + self.ni == o.ni + && self.nj == o.nj + && close(self.lat1, o.lat1) + && close(self.lon1, o.lon1) + && close(self.dx, o.dx) + && close(self.dy, o.dy) + && self.scan == o.scan + } + + fn goes_north(&self) -> bool { + self.scan & SCAN_J_POSITIVE != 0 + } + + /// Whether the first and last latitudes run against the scanning mode (CPTEC's BAM files + /// give −90° first and +90° last, the grid's edges, and scan north to south): rows then follow + /// the scanning mode, centred between the two latitudes. + fn latitudes_disagree(&self) -> bool { + self.nj > 1 && self.lat1 != self.lat2 && (self.lat2 > self.lat1) != self.goes_north() + } + + /// The centre latitude of the northernmost row. + fn north(&self) -> f64 { + if self.latitudes_disagree() { + (self.lat1 + self.lat2) / 2.0 + (self.nj.saturating_sub(1)) as f64 * self.dy / 2.0 + } else if self.goes_north() { + self.lat1 + (self.nj.saturating_sub(1)) as f64 * self.dy + } else { + self.lat1 + } + } + + /// The centre longitude of the westernmost column, in −180..180 (a grid given from 0 to 360° + /// east of 180° is moved west of the antimeridian, as GDAL moves one). + fn west(&self) -> f64 { + let w = if self.scan & SCAN_I_NEGATIVE != 0 { self.lon1 - (self.ni.saturating_sub(1)) as f64 * self.dx } else { self.lon1 }; + let w = w.rem_euclid(360.0); + if w >= 180.0 { w - 360.0 } else { w } + } + + /// Whether the columns go round the whole globe. + fn whole_turn(&self) -> bool { + (self.ni as f64 * self.dx - 360.0).abs() < self.dx * 0.5 + } + + /// The column and row (north up) of the `k`th value in scanning order. + fn place(&self, k: usize) -> (usize, usize) { + let (i, j) = if self.scan & SCAN_J_CONSECUTIVE != 0 { (k / self.nj, k % self.nj) } else { (k % self.ni, k / self.ni) }; + let alternate = self.scan & SCAN_ALTERNATE != 0; + let (i, j) = if alternate && self.scan & SCAN_J_CONSECUTIVE == 0 && j % 2 == 1 { + (self.ni - 1 - i, j) + } else if alternate && self.scan & SCAN_J_CONSECUTIVE != 0 && i % 2 == 1 { + (i, self.nj - 1 - j) + } else { + (i, j) + }; + let col = if self.scan & SCAN_I_NEGATIVE != 0 { self.ni - 1 - i } else { i }; + let row = if self.goes_north() { self.nj - 1 - j } else { j }; + (col, row) + } + + fn notes(&self) -> Vec { + let mut out = Vec::new(); + if self.latitudes_disagree() { + let north = self.north(); + out.push(format!( + "the grid gives its first row at {}° and its last at {}° but scans {}: its {} rows of {}° are laid out as the scanning mode says, centred between the two, from {}° to {}°", + self.lat1, + self.lat2, + if self.goes_north() { "south to north" } else { "north to south" }, + self.nj, + self.dy, + round6(north), + round6(north - (self.nj.saturating_sub(1)) as f64 * self.dy), + )); + } + if let Some(earth) = self.earth { + out.push(format!("its earth is {earth}; latitudes and longitudes are read as WGS 84's")); + } + out + } +} + +/// `v` to a millionth, for a notice (89.91, not 89.91000000000001). +fn round6(v: f64) -> f64 { + (v * 1e6).round() / 1e6 +} + +/// One field: its band name, grid and values in scanning order (NaN where a bitmap masks). +struct Field { + name: String, + grid: Grid, + values: Vec, + /// Values `f32` changed (only packings of more than 24 bits can lose any). + rounded: u64, +} + +/// The raster of fields on one grid: north up, a whole turn of longitude from −180°. +fn to_raster(fields: Vec, name: &str) -> Result { + let Some(grid) = fields.first().map(|f| f.grid) else { return Err(bad("no field")) }; + let (w, h) = (grid.ni, grid.nj); + let west = grid.west(); + // A whole turn starting east of −180°: the column at 180° moves to the first, so the columns + // run from −180°. + let roll = if grid.whole_turn() && west > -180.0 + grid.dx * 0.5 { + let at_180 = ((180.0 - west) / grid.dx).round() as usize % w.max(1); + (w - at_180) % w.max(1) + } else { + 0 + }; + let origin_x = if roll > 0 { west - (roll as f64) * grid.dx } else { west } - grid.dx / 2.0; + let origin_y = grid.north() + grid.dy / 2.0; + let mut names = Vec::with_capacity(fields.len()); + let mut rounded = Vec::with_capacity(fields.len()); + let mut bands = Vec::with_capacity(fields.len()); + for f in fields { + let mut band = super::filled(w, h, f32::NAN)?; + for (k, v) in f.values.iter().enumerate() { + let (col, row) = grid.place(k); + let col = (col + roll) % w.max(1); + if let Some(cell) = band.get_mut(row * w + col) { + *cell = *v; + } + } + names.push(f.name); + rounded.push(f.rounded); + bands.push(band); + } + let size = |n: usize| u32::try_from(n).map_err(|_| bad("the grid is too large")); + let transform = GeoTransform { origin_x, origin_y, pixel_width: grid.dx, pixel_height: -grid.dy }; + let mut r = Raster::new(name, size(w)?, size(h)?, bands, transform, Crs::LonLat, None, Default::default(), "Float32")?; + for (b, n) in r.bands.iter_mut().zip(names) { + b.name = n; + } + if rounded.iter().any(|n| *n > 0) { + r.rounded = rounded; + } + Ok(r) +} + +/// Octets `o..o + n` (0-based offset `o`) of `b`, unsigned, big-endian; 0 past the end. +fn be(b: &[u8], o: usize, n: usize) -> u32 { + b.get(o..o + n).map_or(0, |s| s.iter().fold(0u32, |v, &x| (v << 8) | u32::from(x))) +} + +/// Octets `o..o + n` of `b`, a sign bit and magnitude (GRIB's signed integers). +fn signed(b: &[u8], o: usize, n: usize) -> i64 { + let v = i64::from(be(b, o, n)); + let sign = 1i64 << (8 * n - 1); + if v & sign != 0 { -(v & (sign - 1)) } else { v } +} + +/// An IBM System/360 single-precision number (GRIB1's reference value). +fn ibm(v: u32) -> f64 { + let sign = if v & 0x8000_0000 != 0 { -1.0 } else { 1.0 }; + let exponent = ((v >> 24) & 0x7f) as i32 - 64; + let mantissa = f64::from(v & 0x00ff_ffff) / f64::from(1u32 << 24); + sign * mantissa * 16f64.powi(exponent) +} + +/// `count` values of `bits` bits each from `data`, big-endian, unpacked as `(R + X × 2^E) / 10^D`; +/// with fewer bits there than that, an error. +fn unpack(data: &[u8], count: usize, bits: u32, r: f64, e: i64, d: i64) -> std::result::Result<(Vec, u64), Skip> { + if bits > MAX_BITS { + return Err(Skip::Other(format!("values of {bits} bits"))); + } + let need = (count as u64).saturating_mul(u64::from(bits)).div_ceil(8); + if (data.len() as u64) < need { + return Err(Skip::Other("a data section shorter than its values".to_string())); + } + let scale = 2f64.powi(e.clamp(-1000, 1000) as i32); + let ten = 10f64.powi(d.clamp(-1000, 1000) as i32); + let mut out = Vec::new(); + out.try_reserve_exact(count).map_err(|_| Skip::TooLarge)?; + let mut rounded = 0u64; + let mut bit = 0u64; + for _ in 0..count { + // The 8 octets from the value's first: at most 7 bits before it, and its 32 at most. + let byte = (bit / 8) as usize; + let word = (0..8).fold(0u64, |w, i| (w << 8) | u64::from(data.get(byte + i).copied().unwrap_or(0))); + let x = (word << (bit % 8)) >> (64 - bits); + bit += u64::from(bits); + let v = (r + x as f64 * scale) / ten; + if bits > 24 && f64::from(v as f32) != v { + rounded += 1; + } + out.push(v); + } + Ok((out, rounded)) +} + +/// `count` copies of `v`: a field packed in no bits holds its reference value everywhere. +fn constant(v: f64, count: usize) -> std::result::Result, Skip> { + let mut out = Vec::new(); + out.try_reserve_exact(count).map_err(|_| Skip::TooLarge)?; + out.resize(count, v); + Ok(out) +} + +/// Values in scanning order: those unpacked, spread over the points a bitmap keeps (NaN at the +/// others), or all of them without one. +fn spread(values: Vec, bitmap: Option<&[u8]>, points: usize) -> std::result::Result, Skip> { + let mut out = Vec::new(); + out.try_reserve_exact(points).map_err(|_| Skip::TooLarge)?; + match bitmap { + None => { + if values.len() != points { + return Err(Skip::Other("a field whose values don't fill its grid".to_string())); + } + out.extend(values.into_iter().map(|v| v as f32)); + } + Some(bits) => { + if (bits.len() as u64) * 8 < points as u64 { + return Err(Skip::Other("a bitmap shorter than its grid".to_string())); + } + let mut values = values.into_iter(); + for k in 0..points { + let set = bits.get(k / 8).is_some_and(|b| b & (0x80 >> (k % 8)) != 0); + out.push(if set { values.next().map_or(f32::NAN, |v| v as f32) } else { f32::NAN }); + } + } + } + Ok(out) +} + +/// `n` bitmap bits set among the first `points`. +fn kept(bits: &[u8], points: usize) -> usize { + (0..points).filter(|k| bits.get(k / 8).is_some_and(|b| b & (0x80 >> (k % 8)) != 0)).count() +} + +/// The reference time, `d=YYYYMMDDHH` as wgrib's inventories write it (with the century). +fn date(year: i64, month: u32, day: u32, hour: u32) -> String { + format!("d={year:04}{month:02}{day:02}{hour:02}") +} + +/// A section of `b` at `at`: its bytes, by the 3-octet length GRIB1 sections start with. +fn section1(b: &[u8], at: usize) -> std::result::Result<&[u8], Skip> { + let len = be(b, at, 3) as usize; + if len < 3 { + return Err(Skip::Other("a damaged section".to_string())); + } + b.get(at..at + len).ok_or_else(|| Skip::Other("a section past the end of its message".to_string())) +} + +/// A GRIB1 message (WMO FM 92 GRIB edition 1): its one field. +fn grib1(b: &[u8], room: usize) -> std::result::Result { + let pds = section1(b, 8)?; + if pds.len() < 28 { + return Err(Skip::Other("a damaged product definition section".to_string())); + } + let flags = pds[7]; + if flags & 0x80 == 0 { + return Err(Skip::Other(format!("predefined grids (grid {})", pds[6]))); + } + let d = signed(pds, 26, 2); + let century = i64::from(pds[24]); + let year = (century - 1) * 100 + i64::from(pds[12]); + let name = format!( + "{}:kpds5={}:kpds6={}:kpds7={}:TR={}:P1={}:P2={}:TimeU={}", + date(year, u32::from(pds[13]), u32::from(pds[14]), u32::from(pds[15])), + pds[8], + pds[9], + be(pds, 10, 2), + pds[20], + pds[18], + pds[19], + pds[17], + ); + let gds_at = 8 + pds.len(); + let gds = section1(b, gds_at)?; + let grid = grib1_grid(gds)?; + let points = grid.ni.checked_mul(grid.nj).filter(|n| *n <= room).ok_or(Skip::TooLarge)?; + let mut at = gds_at + gds.len(); + let bitmap = if flags & 0x40 != 0 { + let bms = section1(b, at)?; + if be(bms, 4, 2) != 0 { + return Err(Skip::Other("predefined bitmaps".to_string())); + } + at += bms.len(); + Some(bms.get(6..).unwrap_or_default()) + } else { + None + }; + let bds = section1(b, at)?; + let bds_flags = bds.get(3).copied().unwrap_or(0); + if bds_flags & 0x80 != 0 { + return Err(Skip::Other("spherical harmonics".to_string())); + } + if bds_flags & 0x40 != 0 { + return Err(Skip::Other("GRIB1 second-order (complex) packing".to_string())); + } + let e = signed(bds, 4, 2); + let r = ibm(be(bds, 6, 4)); + let bits = u32::from(bds.get(10).copied().unwrap_or(0)); + let count = bitmap.map_or(points, |m| kept(m, points)); + let data = bds.get(11..).unwrap_or_default(); + let (values, rounded) = + if bits == 0 { (constant(r / 10f64.powi(d.clamp(-1000, 1000) as i32), count)?, 0) } else { unpack(data, count, bits, r, e, d)? }; + Ok(Field { name, grid, values: spread(values, bitmap, points)?, rounded }) +} + +/// A GRIB1 grid description section: a regular latitude/longitude grid only. +fn grib1_grid(g: &[u8]) -> std::result::Result { + if g.len() < 28 { + return Err(Skip::Other("a damaged grid description section".to_string())); + } + let kind = g[5]; + if kind != 0 { + return Err(Skip::Other(format!("GRIB1 grids of data representation type {kind} (not latitude/longitude)"))); + } + let (ni, nj) = (be(g, 6, 2) as usize, be(g, 8, 2) as usize); + // A missing row or column length: a quasi-regular grid. + if ni == 0xffff || nj == 0xffff || ni == 0 || nj == 0 { + return Err(Skip::Other("quasi-regular grids".to_string())); + } + let deg = |o: usize| signed(g, o, 3) as f64 / 1000.0; + let (lat1, lon1, lat2, lon2) = (deg(10), deg(13), deg(17), deg(20)); + let res = g[16]; + let (di, dj) = (be(g, 23, 2), be(g, 25, 2)); + let given = res & 0x80 != 0; + let dx = if given && di != 0xffff { f64::from(di) / 1000.0 } else { span(lon1, lon2, true) / (ni.saturating_sub(1)).max(1) as f64 }; + let dy = if given && dj != 0xffff { f64::from(dj) / 1000.0 } else { span(lat1, lat2, false) / (nj.saturating_sub(1)).max(1) as f64 }; + let earth = + Some(if res & 0x40 != 0 { "the IAU 1965 spheroid (GRIB1's oblate earth)" } else { "a sphere of radius 6,367,470 m (GRIB1's)" }); + checked(Grid { ni, nj, lat1, lon1, lat2, lon2, dx, dy, scan: g[27], earth }) +} + +/// The distance between two longitudes (eastward, wrapping) or latitudes. +fn span(a: f64, b: f64, lon: bool) -> f64 { + if lon { + let d = (b - a).rem_euclid(360.0); + if d == 0.0 { 360.0 } else { d } + } else { + (b - a).abs() + } +} + +/// A grid whose increments and corners are usable, or why it isn't. +fn checked(g: Grid) -> std::result::Result { + let ok = g.dx.is_finite() + && g.dy.is_finite() + && g.dx > 0.0 + && g.dy > 0.0 + && g.lat1.abs() <= 90.0 + && g.lat2.abs() <= 90.0 + && g.ni as f64 * g.dx <= 360.0 + g.dx + && g.nj as f64 * g.dy <= 180.0 + g.dy; + let north = g.north(); + let south = north - (g.nj.saturating_sub(1)) as f64 * g.dy; + if ok && north <= 90.0 + 1e-6 && south >= -90.0 - 1e-6 { + Ok(g) + } else { + Err(Skip::Other("a latitude/longitude grid that isn't on the globe".to_string())) + } +} + +/// A GRIB2 section at `at`: its number and bytes. +fn section2(b: &[u8], at: usize) -> Option<(u8, &[u8])> { + let len = be(b, at, 4) as usize; + let s = b.get(at..at.checked_add(len)?)?; + (len >= 5).then(|| (s[4], s)) +} + +/// A GRIB2 message (WMO FM 92 GRIB edition 2): each of its fields. +fn grib2(b: &[u8], room: usize) -> Vec> { + let mut out = Vec::new(); + let discipline = b.get(6).copied().unwrap_or(255); + let mut at = 16usize; + let mut reference = String::from("d=?"); + let mut grid: Option> = None; + let mut product = String::new(); + let mut packing: Option> = None; + let mut bitmap: Option, String>> = None; + let mut previous_bitmap: Option<&[u8]> = None; + let mut held = 0usize; + while b.get(at..at + 4).is_some_and(|m| m != b"7777") { + let Some((number, s)) = section2(b, at) else { + out.push(Err(Skip::Other("a damaged GRIB2 section".to_string()))); + break; + }; + at += s.len(); + match number { + 1 => { + reference = date( + i64::from(be(s, 12, 2)), + u32::from(s.get(14).copied().unwrap_or(0)), + u32::from(s.get(15).copied().unwrap_or(0)), + u32::from(s.get(16).copied().unwrap_or(0)), + ); + } + 3 => grid = Some(grib2_grid(s)), + 4 => product = grib2_product(s), + 5 => packing = Some(grib2_packing(s)), + 6 => { + bitmap = Some(match s.get(5).copied().unwrap_or(255) { + 255 => Ok(None), + 0 => { + let bits = s.get(6..).unwrap_or_default(); + previous_bitmap = Some(bits); + Ok(Some(bits)) + } + 254 => previous_bitmap.map(Some).ok_or_else(|| "a bitmap that refers to none before it".to_string()), + _ => Err("predefined bitmaps".to_string()), + }); + } + 7 => { + let field = (|| { + let grid = grid.clone().ok_or_else(|| Skip::Other("a field without a grid".to_string()))?.map_err(Skip::Other)?; + let (count, r, e, d, bits) = + packing.clone().ok_or_else(|| Skip::Other("a field without its packing".to_string()))?.map_err(Skip::Other)?; + let mask = bitmap.clone().unwrap_or(Ok(None)).map_err(Skip::Other)?; + let points = grid.ni.checked_mul(grid.nj).filter(|n| held.saturating_add(*n) <= room).ok_or(Skip::TooLarge)?; + if mask.is_some_and(|m| kept(m, points) != count) || (mask.is_none() && count != points) { + return Err(Skip::Other("a field whose values don't fill its grid".to_string())); + } + let (values, rounded) = if bits == 0 { + (constant(r / 10f64.powi(d.clamp(-1000, 1000) as i32), count)?, 0) + } else { + unpack(s.get(5..).unwrap_or_default(), count, bits, r, e, d)? + }; + held += points; + Ok(Field { + name: format!("{reference}:discipline={discipline}:{product}"), + grid, + values: spread(values, mask, points)?, + rounded, + }) + })(); + out.push(field); + } + _ => {} + } + } + if out.is_empty() { + out.push(Err(Skip::Other("a GRIB2 message without a data section".to_string()))); + } + out +} + +/// A GRIB2 grid definition section: template 3.0 (regular latitude/longitude) only. +fn grib2_grid(s: &[u8]) -> std::result::Result { + if s.get(5).copied().unwrap_or(1) != 0 { + return Err("predefined grids".to_string()); + } + if s.get(10).copied().unwrap_or(0) != 0 { + return Err("quasi-regular grids".to_string()); + } + let template = be(s, 12, 2); + if template != 0 { + return Err(format!("GRIB2 grid template 3.{template} (not regular latitude/longitude)")); + } + if s.len() < 72 { + return Err("a damaged grid definition section".to_string()); + } + let earth = match s[14] { + // GRS 80, WGS 84: near enough. + 4 | 5 => None, + 0 => Some("a sphere of radius 6,367,470 m"), + 6 => Some("a sphere of radius 6,371,229 m"), + 8 => Some("a sphere of radius 6,371,200 m"), + 1 => Some("a sphere of a radius the file gives"), + 2 => Some("the IAU 1965 spheroid"), + _ => Some("a spheroid the file gives"), + }; + let (ni, nj) = (be(s, 30, 4) as usize, be(s, 34, 4) as usize); + if ni == 0 || nj == 0 || ni == u32::MAX as usize || nj == u32::MAX as usize { + return Err("quasi-regular grids".to_string()); + } + let (basic, sub) = (be(s, 38, 4), be(s, 42, 4)); + let unit = if basic == 0 || basic == u32::MAX { + 1e-6 + } else if sub == 0 || sub == u32::MAX { + return Err("a grid with no angle subdivisions".to_string()); + } else { + f64::from(basic) / f64::from(sub) + }; + let deg = |o: usize| signed(s, o, 4) as f64 * unit; + let (lat1, lon1, lat2, lon2) = (deg(46), deg(50), deg(55), deg(59)); + let res = s[54]; + let (di, dj) = (be(s, 63, 4), be(s, 67, 4)); + let dx = if res & 0x20 != 0 && di != u32::MAX { + f64::from(di) * unit + } else { + span(lon1, lon2, true) / (ni.saturating_sub(1)).max(1) as f64 + }; + let dy = if res & 0x10 != 0 && dj != u32::MAX { + f64::from(dj) * unit + } else { + span(lat1, lat2, false) / (nj.saturating_sub(1)).max(1) as f64 + }; + checked(Grid { ni, nj, lat1, lon1, lat2, lon2, dx, dy, scan: s[71], earth }).map_err(|e| match e { + Skip::Other(m) => m, + Skip::TooLarge => "a grid too large".to_string(), + }) +} + +/// A GRIB2 product definition section, as part of a band name: the parameter's category and +/// number (its discipline is section 0's), the template, and for templates 4.0 to 4.15 the first +/// fixed surface and the forecast time. +fn grib2_product(s: &[u8]) -> String { + let template = be(s, 7, 2); + let (category, number) = (s.get(9).copied().unwrap_or(255), s.get(10).copied().unwrap_or(255)); + let mut name = format!("category={category}:number={number}:template=4.{template}"); + // Templates 4.0 to 4.15 share these octets; the surface's value is scaled by 10^-(its scale + // factor). + if template <= 15 && s.len() >= 28 { + let value = signed(s, 24, 4) as f64 / 10f64.powi(signed(s, 23, 1) as i32); + name.push_str(&format!(":surface={}:value={}:TimeU={}:forecast={}", s[22], round6(value), s[17], be(s, 18, 4))); + } + name +} + +/// A GRIB2 data representation section: template 5.0 (simple packing) only, as the number of +/// values, R, E, D and the bits a value. +fn grib2_packing(s: &[u8]) -> std::result::Result<(usize, f64, i64, i64, u32), String> { + let template = be(s, 9, 2); + if template != 0 { + let kind = match template { + 2 | 3 => "complex packing", + 4 => "IEEE floating point", + 40 => "JPEG 2000", + 41 => "PNG", + 42 => "CCSDS", + _ => "a packing", + }; + return Err(format!("GRIB2 {kind} (template 5.{template})")); + } + if s.len() < 21 { + return Err("a damaged data representation section".to_string()); + } + let r = f64::from(f32::from_bits(be(s, 11, 4))); + Ok((be(s, 5, 4) as usize, r, signed(s, 15, 2), signed(s, 17, 2), u32::from(s[19]))) +} + +#[cfg(test)] +#[path = "grib_tests.rs"] +mod tests; diff --git a/crates/data/src/raster/grib_tests.rs b/crates/data/src/raster/grib_tests.rs new file mode 100644 index 0000000000..33a4feff27 --- /dev/null +++ b/crates/data/src/raster/grib_tests.rs @@ -0,0 +1,452 @@ +use super::*; + +/// `values` packed in `bits` bits each, most significant first. +fn pack(values: &[u32], bits: u32) -> Vec { + let mut out = Vec::new(); + let (mut acc, mut n) = (0u64, 0u32); + for &v in values { + acc = (acc << bits) | u64::from(v); + n += bits; + while n >= 8 { + out.push((acc >> (n - 8)) as u8); + n -= 8; + } + } + if n > 0 { + out.push((acc << (8 - n)) as u8); + } + out +} + +/// A sign bit and magnitude in `n` octets. +fn sm(v: i64, n: usize) -> Vec { + let m = v.unsigned_abs() | if v < 0 { 1 << (8 * n - 1) } else { 0 }; + (0..n).rev().map(|i| (m >> (8 * i)) as u8).collect() +} + +fn u(v: u64, n: usize) -> Vec { + (0..n).rev().map(|i| (v >> (8 * i)) as u8).collect() +} + +/// The bits of a bitmap keeping the points `keep` says. +fn bitmap(keep: &[bool]) -> Vec { + pack(&keep.iter().map(|&k| u32::from(k)).collect::>(), 1) +} + +struct G1 { + ni: usize, + nj: usize, + /// Millidegrees. + lat1: i64, + lon1: i64, + lat2: i64, + lon2: i64, + di: u64, + dj: u64, + scan: u8, + /// IBM reference value, E, D, bits. + r: u32, + e: i64, + d: i64, + bits: u32, + /// Packed values, and the bitmap when some points are masked. + x: Vec, + keep: Option>, + /// BDS flag bits (0x40: second-order packing). + bds_flags: u8, + param: u8, +} + +impl G1 { + fn new(ni: usize, nj: usize, x: Vec) -> G1 { + // 1° cells from 60° N, 10° E, north to south. + G1 { + ni, + nj, + lat1: 60_000, + lon1: 10_000, + lat2: 60_000 - (nj as i64 - 1) * 1000, + lon2: 10_000 + (ni as i64 - 1) * 1000, + di: 1000, + dj: 1000, + scan: 0, + r: 0, + e: 0, + d: 0, + bits: 16, + x, + keep: None, + bds_flags: 0, + param: 11, + } + } + + fn bytes(&self) -> Vec { + let mut pds = u(28, 3); + pds.extend([2, 7, 96, 255, 0x80 | if self.keep.is_some() { 0x40 } else { 0 }, self.param, 105]); + pds.extend(u(2, 2)); + pds.extend([26, 11, 18, 6, 0, 1, 0, 0, 0]); + pds.extend(u(0, 2)); + pds.extend([0, 21, 0]); + pds.extend(sm(self.d, 2)); + let mut gds = u(32, 3); + gds.extend([0, 255, 0]); + gds.extend(u(self.ni as u64, 2)); + gds.extend(u(self.nj as u64, 2)); + gds.extend(sm(self.lat1, 3)); + gds.extend(sm(self.lon1, 3)); + gds.push(0x80); + gds.extend(sm(self.lat2, 3)); + gds.extend(sm(self.lon2, 3)); + gds.extend(u(self.di, 2)); + gds.extend(u(self.dj, 2)); + gds.push(self.scan); + gds.extend([0, 0, 0, 0]); + let mut body = pds; + body.extend(gds); + if let Some(keep) = &self.keep { + let bits = bitmap(keep); + let mut bms = u(6 + bits.len() as u64, 3); + bms.extend([0, 0, 0]); + bms.extend(bits); + body.extend(bms); + } + let data = pack(&self.x, self.bits); + let mut bds = u(11 + data.len() as u64, 3); + bds.push(self.bds_flags); + bds.extend(sm(self.e, 2)); + bds.extend(u(u64::from(self.r), 4)); + bds.push(self.bits as u8); + bds.extend(data); + body.extend(bds); + let mut out = b"GRIB".to_vec(); + out.extend(u(8 + body.len() as u64 + 4, 3)); + out.push(1); + out.extend(body); + out.extend(b"7777"); + out + } +} + +/// A GRIB2 field: its grid, product and data sections. +struct F2 { + ni: usize, + nj: usize, + /// Micro-degrees. + lat1: i64, + lon1: i64, + lat2: i64, + lon2: i64, + di: u64, + dj: u64, + scan: u8, + template5: u16, + r: f32, + e: i64, + d: i64, + bits: u32, + x: Vec, + keep: Option>, + category: u8, + number: u8, + /// The first fixed surface's scale factor and scaled value. + surface_scale: u8, + surface_value: u64, +} + +impl F2 { + fn new(ni: usize, nj: usize, x: Vec) -> F2 { + // 0.5° cells from 10° S, 300° E, south to north. + F2 { + ni, + nj, + lat1: -10_000_000, + lon1: 300_000_000, + lat2: -10_000_000 + (nj as i64 - 1) * 500_000, + lon2: 300_000_000 + (ni as i64 - 1) * 500_000, + di: 500_000, + dj: 500_000, + scan: 0x40, + template5: 0, + r: 0.0, + e: 0, + d: 0, + bits: 12, + x, + keep: None, + category: 0, + number: 0, + surface_scale: 0, + surface_value: 2, + } + } + + fn sections(&self) -> Vec { + let mut s3 = u(72, 4); + s3.extend([3, 0]); + s3.extend(u((self.ni * self.nj) as u64, 4)); + s3.extend([0, 0]); + s3.extend(u(0, 2)); + s3.push(6); + s3.extend([0; 15]); + s3.extend(u(self.ni as u64, 4)); + s3.extend(u(self.nj as u64, 4)); + s3.extend(u(0, 4)); + s3.extend(u(u64::from(u32::MAX), 4)); + s3.extend(sm(self.lat1, 4)); + s3.extend(sm(self.lon1, 4)); + s3.push(0x30); + s3.extend(sm(self.lat2, 4)); + s3.extend(sm(self.lon2, 4)); + s3.extend(u(self.di, 4)); + s3.extend(u(self.dj, 4)); + s3.push(self.scan); + assert_eq!(s3.len(), 72); + let mut s4 = u(34, 4); + s4.push(4); + s4.extend(u(0, 2)); + s4.extend(u(0, 2)); + s4.extend([self.category, self.number, 2, 0, 96]); + s4.extend(u(0, 2)); + s4.extend([0, 1]); + s4.extend(u(6, 4)); + s4.extend([103, self.surface_scale]); + s4.extend(u(self.surface_value, 4)); + s4.extend([255, 0]); + s4.extend(u(0, 4)); + assert_eq!(s4.len(), 34); + let count = self.keep.as_ref().map_or(self.x.len(), |k| k.iter().filter(|b| **b).count()); + let mut s5 = u(21, 4); + s5.push(5); + s5.extend(u(count as u64, 4)); + s5.extend(u(u64::from(self.template5), 2)); + s5.extend(u(u64::from(self.r.to_bits()), 4)); + s5.extend(sm(self.e, 2)); + s5.extend(sm(self.d, 2)); + s5.extend([self.bits as u8, 0]); + let mut s6 = match &self.keep { + None => { + let mut s6 = u(6, 4); + s6.extend([6, 255]); + s6 + } + Some(keep) => { + let bits = bitmap(keep); + let mut s6 = u(6 + bits.len() as u64, 4); + s6.extend([6, 0]); + s6.extend(bits); + s6 + } + }; + let data = pack(&self.x, self.bits); + let mut s7 = u(5 + data.len() as u64, 4); + s7.push(7); + s7.extend(data); + let mut out = s3; + out.append(&mut s4); + out.append(&mut s5); + out.append(&mut s6); + out.append(&mut s7); + out + } +} + +/// A GRIB2 message of `fields` (meteorological products, discipline 0). +fn grib2_message(fields: &[F2]) -> Vec { + let mut s1 = u(21, 4); + s1.extend([1, 0, 7, 0, 0, 2, 1, 1]); + s1.extend(u(2026, 2)); + s1.extend([11, 18, 0, 0, 0, 0, 1]); + let mut body = s1; + for f in fields { + body.extend(f.sections()); + } + let mut out = b"GRIB".to_vec(); + out.extend([0, 0, 0, 2]); + out.extend(u(16 + body.len() as u64 + 4, 8)); + out.extend(body); + out.extend(b"7777"); + out +} + +fn approx(a: f32, b: f64) -> bool { + (f64::from(a) - b).abs() < 1e-4 +} + +#[test] +fn ibm_reference_values() { + assert_eq!(ibm(0), 0.0); + assert_eq!(ibm(0x4264_0000), 100.0); + assert_eq!(ibm(0xc110_0000), -1.0); + // BAM's land-sea mask (an actual record): R = -4.5555553... + assert!((ibm(0xc148_e38e) + 4.555_555_3).abs() < 1e-6); +} + +#[test] +fn grib1_simple_packing_north_to_south() { + let mut g = G1::new(3, 2, vec![0, 1, 2, 30, 40, 50]); + g.r = 0x4264_0000; // 100 + g.d = 1; + let r = read_bytes(&g.bytes(), "t").unwrap(); + assert_eq!((r.width, r.height, r.bands.len()), (3, 2, 1)); + let v = &r.bands[0].data; + for (got, want) in v.iter().zip([10.0, 10.1, 10.2, 13.0, 14.0, 15.0]) { + assert!(approx(*got, want), "{v:?}"); + } + let t = r.transform; + assert_eq!((t.origin_x, t.origin_y, t.pixel_width, t.pixel_height), (9.5, 60.5, 1.0, -1.0)); + assert_eq!(r.bands[0].name, "d=2026111806:kpds5=11:kpds6=105:kpds7=2:TR=0:P1=0:P2=0:TimeU=1"); + // GRIB1's earth is a sphere: said once. + assert_eq!(r.lost, vec!["its earth is a sphere of radius 6,367,470 m (GRIB1's); latitudes and longitudes are read as WGS 84's"]); + assert!(r.rounded.is_empty()); +} + +#[test] +fn grib1_bitmap_masks_points() { + let mut g = G1::new(2, 2, vec![5, 7]); + g.keep = Some(vec![true, false, false, true]); + let r = read_bytes(&g.bytes(), "t").unwrap(); + let v = &r.bands[0].data; + assert_eq!(v[0], 5.0); + assert!(v[1].is_nan() && v[2].is_nan()); + assert_eq!(v[3], 7.0); +} + +#[test] +fn grib1_constant_field() { + let mut g = G1::new(2, 1, vec![]); + g.bits = 0; + g.r = 0x4264_0000; + let r = read_bytes(&g.bytes(), "t").unwrap(); + assert_eq!(r.bands[0].data, vec![100.0, 100.0]); +} + +#[test] +fn bam_latitudes_against_the_scanning_mode() { + // CPTEC's BAM: the first point at the south pole's row, scanning north to south, round the + // globe from 0°. Rows follow the scanning mode; columns run from −180°. + // (GRIB1 increments are two octets of millidegrees: 60° cells.) + let mut g = G1::new(6, 2, (1..=12).collect()); + (g.lat1, g.lat2, g.lon1, g.lon2, g.di, g.dj) = (-30_000, 30_000, 0, 300_000, 60_000, 60_000); + let r = read_bytes(&g.bytes(), "t").unwrap(); + // The first row is the northern one; the 180° column comes first. + assert_eq!(r.bands[0].data, vec![4.0, 5.0, 6.0, 1.0, 2.0, 3.0, 10.0, 11.0, 12.0, 7.0, 8.0, 9.0]); + let t = r.transform; + assert_eq!((t.origin_x, t.origin_y), (-210.0, 60.0)); + assert!( + r.lost.contains(&"the grid gives its first row at -30° and its last at 30° but scans north to south: its 2 rows of 60° are laid out as the scanning mode says, centred between the two, from 30° to -30°".to_string()), + "{:?}", + r.lost + ); + // BAM's own header: −90° and 90°, the grid's edges, for 1000 rows of 0.18° whose centres + // its GrADS descriptor puts at ±89.91°. + let mut g = G1::new(2, 1000, vec![0; 2000]); + (g.lat1, g.lat2, g.lon1, g.lon2, g.di, g.dj, g.bits) = (-90_000, 90_000, 0, 180, 180, 180, 1); + let r = read_bytes(&g.bytes(), "t").unwrap(); + assert!((r.transform.origin_y - 90.0).abs() < 1e-9, "{:?}", r.transform); + assert!(r.lost[0].ends_with("from 89.91° to -89.91°"), "{:?}", r.lost); +} + +#[test] +fn grib1_second_order_packing_is_refused_by_name() { + let mut g = G1::new(2, 1, vec![1, 2]); + g.bds_flags = 0x40; + let e = read_bytes(&g.bytes(), "t").unwrap_err().to_string(); + assert!(e.contains("nothing in it can be read here: 1 field left out: GRIB1 second-order (complex) packing, not read yet"), "{e}"); +} + +#[test] +fn grib2_fields_south_to_north_with_a_bitmap() { + let a = F2::new(2, 2, vec![1, 2, 3, 4]); + let mut b = F2::new(2, 2, vec![9, 8]); + (b.r, b.e, b.d, b.category, b.number) = (273.15, 1, 1, 0, 0); + b.keep = Some(vec![false, true, true, false]); + let r = read_bytes(&grib2_message(&[a, b]), "t").unwrap(); + assert_eq!(r.bands.len(), 2); + // Rows flipped north up: the second row scanned is the first. + assert_eq!(r.bands[0].data, vec![3.0, 4.0, 1.0, 2.0]); + let v = &r.bands[1].data; + assert!(v[1].is_nan() && v[2].is_nan()); + // (R + X × 2^E) / 10^D: the point scanned second (east, south) gets 9, the third (west, + // north) 8. + assert!(approx(v[3], (273.15f32 as f64 + 9.0 * 2.0) / 10.0) && approx(v[0], (273.15f32 as f64 + 8.0 * 2.0) / 10.0), "{v:?}"); + // From 300° E: moved west of the antimeridian, half a cell west and north of the corners. + let t = r.transform; + assert_eq!((t.origin_x, t.origin_y, t.pixel_width, t.pixel_height), (-60.25, -9.25, 0.5, -0.5)); + assert_eq!(r.bands[0].name, "d=2026111800:discipline=0:category=0:number=0:template=4.0:surface=103:value=2:TimeU=1:forecast=6"); + assert!(r.lost.iter().any(|l| l.contains("6,371,229")), "{:?}", r.lost); +} + +#[test] +fn grib2_other_packings_are_left_out_and_said() { + let a = F2::new(2, 1, vec![1, 2]); + let mut b = F2::new(2, 1, vec![1, 2]); + b.template5 = 3; + let r = read_bytes(&grib2_message(&[a, b]), "t").unwrap(); + assert_eq!(r.bands.len(), 1); + assert!(r.lost.contains(&"1 field left out: GRIB2 complex packing (template 5.3), not read yet".to_string()), "{:?}", r.lost); + // A file with nothing readable is an error naming why. + let mut c = F2::new(2, 1, vec![1, 2]); + c.template5 = 40; + // The surface's value is scaled: 25 at scale factor 1 is 2.5. + let mut d = F2::new(2, 1, vec![1, 2]); + (d.surface_scale, d.surface_value) = (1, 25); + let r = read_bytes(&grib2_message(&[d]), "t").unwrap(); + assert!(r.bands[0].name.contains(":surface=103:value=2.5:"), "{}", r.bands[0].name); + let e = read_bytes(&grib2_message(&[c]), "t").unwrap_err().to_string(); + assert!(e.contains("JPEG 2000 (template 5.40)"), "{e}"); +} + +#[test] +fn fields_on_another_grid_are_left_out_and_said() { + let mut file = G1::new(2, 2, vec![1, 2, 3, 4]).bytes(); + // Padding between messages, as bulletins have. + file.extend([0u8; 10]); + file.extend(G1::new(3, 2, vec![1, 2, 3, 4, 5, 6]).bytes()); + file.extend(G1::new(2, 2, vec![5, 6, 7, 8]).bytes()); + let r = read_bytes(&file, "t").unwrap(); + assert_eq!(r.bands.len(), 2); + assert_eq!(r.bands[1].data, vec![5.0, 6.0, 7.0, 8.0]); + assert!(r.lost.contains(&"1 field left out: on another grid than the first field's".to_string()), "{:?}", r.lost); +} + +#[test] +fn a_cut_message_is_said_or_refused() { + let one = G1::new(2, 2, vec![1, 2, 3, 4]).bytes(); + let mut file = one.clone(); + file.extend(&one[..one.len() - 5]); + let r = read_bytes(&file, "t").unwrap(); + assert_eq!(r.bands.len(), 1); + assert!(r.lost.contains(&"the file ends inside a message, which is left out".to_string()), "{:?}", r.lost); + let e = read_bytes(&one[..one.len() - 1], "t").unwrap_err().to_string(); + assert!(e.contains("cut short"), "{e}"); + let e = read_bytes(b"not a grib file at all", "t").unwrap_err().to_string(); + assert!(e.contains("no GRIB message"), "{e}"); +} + +#[test] +fn hostile_bytes_never_panic() { + let mut file = G1::new(3, 2, vec![0, 1, 2, 3, 4, 5]).bytes(); + file.extend(grib2_message(&[F2::new(2, 2, vec![1, 2, 3, 4])])); + // Every prefix, and every octet flipped in turn. + for n in 0..file.len() { + let _ = read_bytes(&file[..n], "t"); + } + for i in 0..file.len() { + for x in [0x00, 0xff, 0x80, 0x7f] { + let mut bad = file.clone(); + bad[i] = x; + let _ = read_bytes(&bad, "t"); + } + } +} + +#[test] +fn grib_names_are_rasters() { + for n in ["a.grb", "A.GRIB", "b.grb2", "c.grib2"] { + assert!(is_grib_name(n) && crate::raster::is_raster_name(n), "{n}"); + } + assert!(!is_grib_name("a.grd")); + let r = crate::raster::read_bytes("run.grb2", &grib2_message(&[F2::new(2, 1, vec![1, 2])])).unwrap(); + assert_eq!(r.name, "run"); +} diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index 9424473bbf..8547ee5a0d 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -14,6 +14,7 @@ mod decoded; #[cfg(not(target_arch = "wasm32"))] pub mod gdal; pub mod geotiff; +pub mod grib; mod image_grid; mod lerc; mod lzw; @@ -94,7 +95,7 @@ pub fn max_samples() -> usize { /// Largest ASCII grid file read (1 GiB). pub const MAX_ASCII_BYTES: u64 = 1 << 30; /// File extensions read as rasters. -pub const READ_EXTENSIONS: &[&str] = &["tif", "tiff", "asc", "png", "jpg", "jpeg"]; +pub const READ_EXTENSIONS: &[&str] = &["tif", "tiff", "asc", "png", "jpg", "jpeg", "grb", "grib", "grb2", "grib2"]; /// Whether a file name is a raster this module reads: a PDF's page too (refused with /// [`PDF_ELSEWHERE`] where [`PDF_PAGES`] is false). @@ -1234,6 +1235,8 @@ fn read_path_placing(path: &Path, world: bool) -> Result { let text = crate::provenance::read_to_string(path)?; read_ascii(path, &text, &name, sidecar_nodata)? } + // Read message by message, never whole. + "grb" | "grib" | "grb2" | "grib2" => grib::read(std::io::BufReader::new(crate::provenance::open(path)?), &name)?, #[cfg(not(target_arch = "wasm32"))] _ if gdal::is_gdal_raster_name(&path.to_string_lossy()) => { // Converted once to a GeoTIFF in the cache; the layer still names this file. @@ -1687,6 +1690,7 @@ pub fn read_bytes(file_name: &str, bytes: &[u8]) -> Result { let text = std::str::from_utf8(bytes).map_err(|_| DataError::Format("not a text file".into()))?; ascii::read(text, &name, None) } + "grb" | "grib" | "grb2" | "grib2" => grib::read_bytes(bytes, &name), other => Err(DataError::Unsupported(format!(".{other}"))), } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 1340849086..076154f7b8 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -4250,6 +4250,11 @@ impl RustGisApp { "tif", "tiff", "asc", + // GRIB weather and climate model output. + "grb", + "grib", + "grb2", + "grib2", ][..], // Rasters GDAL reads (every one it is asked to read). #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index e3e183091d..898d9dbecc 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -2784,6 +2784,10 @@ fn folder_browser(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { "tif", "tiff", "asc", + "grb", + "grib", + "grb2", + "grib2", // A File Geodatabase's folder, listed as data above. "gdb", // Databases holding several layers, which ask which to add (#934). diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 57acb0bc54..278048a171 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -646,6 +646,7 @@ databases](data.md#sql-queries-and-duckdb-databases). | Scans with no coordinates | an untagged `.tif` or `.png`, or a PDF page without coordinates; any `.tif`, `.png`, `.jpg`/`.jpeg` or `.pdf` with `"as": "scan"` | Add Data, or upload (`layer.addData`, `layer.addDataBytes`) | Grey or RGB(A), 8- or 16-bit pixels. An untagged TIFF or PNG opens as a scan by default; a JPEG needs `"as": "scan"` (otherwise it is a photo). `"as": "scan"` also discards a GeoTIFF's coordinates. A world file beside a TIFF, PNG or JPEG (`.tfw`, `.jgw`, `.pgw`, the four-letter `.tifw`, `.jpgw`, `.pngw`, or `.wld`), with a `.prj` beside it for the coordinate system, places it instead (a JPEG too, which is then not a photo): a turned or skewed one is resampled north up; without a `.prj`, with one RustGIS can't use, or with a world file that can't be read or places the picture nowhere it can be drawn (UTM meters with a longitude/latitude `.prj`), it stays a scan and a notice says why. `"as": "scan"` passes the world file over. World files are read for files added by their path (an upload doesn't bring the files beside it). A project reopens a picture as it was added: one that opened as a scan stays one (add it again once its `.prj` is there), and one a world file placed still opens if its `.prj` or world file is gone, at a stand-in place, with a notice saying it has no coordinates now. A world file is compared with a GeoTIFF's own tags only when both are north up (a turned GeoTIFF is resampled as it is read). A GeoTIFF keeps its own tags, and a notice says when a world file places it differently. The scan initially covers the current view and is marked not georeferenced (`georeferenced: false`) until **Georeference** places it. Export and tools needing ground coordinates refuse it until then. PNG/JPEG decoding is bounded and may reduce the image; large TIFFs can be read at reduced resolution. | | ASCII grid | `.asc` (with an optional `.prj` on desktop) | Add Data, or upload | A single numeric band with square `CELLSIZE` or separate `DX` and `DY` pixel sizes. Desktop files use the neighbouring `.prj`; uploaded and downloaded grids have no sidecar and must have coordinates that fit WGS 84 longitude/latitude. A grid with no `.prj` is read as WGS 84, and a notice says so. | | Zarr | a store's folder (`.zarr`, desktop) or web address (desktop and browser), format 2 (consolidated) or 3 | Home › Add › Add Data › Zarr… (`layer.addZarr`), Add Data on a local folder, or a `?zarr=` link | A variable's latitude/longitude (or y/x) map at the steps picked of its other dimensions (time, level), read chunk by chunk in pure Rust (blosc, zlib, gzip, zstd, LZ4; sharded arrays too). See [Zarr stores](data.md#zarr-stores). | +| GRIB | `.grb`, `.grib`, `.grb2`, `.grib2` | Add Data, or upload | Weather and climate model output, editions 1 and 2, read in pure Rust: each field on the grid of the first one read is a band, named from its message (`d=2026111800:kpds5=61:…` in GRIB1, as wgrib's inventories write it; discipline, category, number and surface in GRIB2). Simple packing on regular latitude/longitude grids, with bitmaps (masked points have no value), in any scanning order, laid out north up and, round the whole globe, from −180°. Values are in the file's units (kelvin stays kelvin). Other packings (complex, JPEG 2000, PNG) and grids are left out with a notice naming them; fields on another grid are left out with a count. A sphere's or another earth's latitudes and longitudes are read as WGS 84's, and a notice says so. | | Rasters GDAL reads | `.img`, `.hgt`, `.dem`, `.dt0`–`.dt2`, `.nc`, `.nc4`, `.hdf`, `.hdf5`, `.h5`, `.he5`, `.bil`, `.bsq`, `.bip`, `.envi`, `.grd`, `.rst`, `.sdat`, `.kea`, `.ers`, `.ntf`, `.nitf`, `.ecw`, `.sid`, `.gsb`, `.bt`, `.rsw` | Add Data (desktop, with [GDAL](https://gdal.org): `gdal_translate`, `gdalinfo` and `gdalwarp`; the installed build must include the driver) | Converted once to a cached cloud-optimised GeoTIFF. NetCDF/HDF variables are subdatasets: the first is added, the others named in a notice; `"layer"` picks one. Without a declared coordinate system, longitude/latitude-like coordinates use WGS 84 (0–360° longitudes are moved to −180–180°) and a notice says so, every time the file is read, not only when it is added; otherwise give `"crs"`. JPEG 2000 is listed separately above. | For GDAL subdatasets, the notice counts the other variables, names at most the first 20, and diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 22f5fa7a6b..28acf17b8e 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -26,6 +26,7 @@ Formats](data-formats.md). | DuckDB databases (`.duckdb`, `.ddb`) and SQL queries | Yes (desktop, when DuckDB is installed) | No | | GeoTIFF and cloud-optimised GeoTIFF (`.tif`, `.tiff`) | Yes | Yes | | ASCII grid (`.asc`, with an optional `.prj`) | Yes | No | +| GRIB editions 1 and 2, simple packing on latitude/longitude grids (`.grb`, `.grib`, `.grb2`, `.grib2`) | Yes | No | | Unreferenced TIFF and PNG scans; JPEG with `"as": "scan"` | Yes | GeoTIFF after georeferencing | | PDF pages: GeoPDFs placed by their coordinates, other pages as scans | Yes (desktop, command line and Python) | GeoTIFF after georeferencing | | Through GDAL: JPEG 2000, ERDAS Imagine, SRTM HGT, DTED, NetCDF, HDF, ENVI, SAGA… | Yes (desktop, when GDAL is installed) | No | From 0fc49eeff3a3c02b6cad67804eff0b849c968a85 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Wed, 18 Nov 2026 21:05:04 -0300 Subject: [PATCH 02/17] fix(data): GRIB review round 1 (#2428) - Count every value f32 changes in Raster::rounded, not only those of packings over 24 bits. - A message of another edition is said and passed over; reading goes on to the next message instead of stopping as if the file were cut. - Look for the next message in 4 KiB chunks to the end of the file, so a long gap no longer ends the read; non-GRIB bytes passed over are counted. - Progress counts the file's KiB. - Name a GRIB2 ensemble member apart (template 4.1 and 4.11). - layer.addDataBytes's description and the Assistant's add-data skill list GRIB. Co-Authored-By: Claude Opus 5.5 --- crates/assistant/skills/add-data/SKILL.md | 4 +- crates/data/src/raster/grib.rs | 123 +++++++++++++++------- crates/data/src/raster/grib_tests.rs | 60 ++++++++++- crates/engine/src/cmd/raster.rs | 2 +- 4 files changed, 147 insertions(+), 42 deletions(-) diff --git a/crates/assistant/skills/add-data/SKILL.md b/crates/assistant/skills/add-data/SKILL.md index 1747497a83..d966a4be81 100644 --- a/crates/assistant/skills/add-data/SKILL.md +++ b/crates/assistant/skills/add-data/SKILL.md @@ -1,6 +1,6 @@ --- name: add-data -description: Add data to the map — files (GeoJSON, CSV with coordinates, Shapefile, GeoPackage, GeoParquet, FlatGeobuf, KML, GPX, GeoTIFF, LiDAR), web addresses, DuckDB SQL queries, STAC catalogs and Overture Maps — with the right coordinate system. Use for "open", "load", "add", "import", "show this file/URL". +description: Add data to the map — files (GeoJSON, CSV with coordinates, Shapefile, GeoPackage, GeoParquet, FlatGeobuf, KML, GPX, GeoTIFF, GRIB, LiDAR), web addresses, DuckDB SQL queries, STAC catalogs and Overture Maps — with the right coordinate system. Use for "open", "load", "add", "import", "show this file/URL". --- # Adding data @@ -14,7 +14,7 @@ and its limits are listed in `user-guide/data-formats.md`. coordinates aren't longitude/latitude, give their `"crs"` (`"EPSG:2271"`). Without it, projected coordinates land in the wrong place. Use `"delimiter"` when it isn't a comma. - **A web address:** `layer.addUrl` `{"url": U}` for GeoJSON, CSV, GeoParquet, FlatGeobuf, - GeoPackage, zipped Shapefiles, KML/KMZ, GPX, GeoTIFF or a PMTiles archive. This uses the + GeoPackage, zipped Shapefiles, KML/KMZ, GPX, GeoTIFF, GRIB or a PMTiles archive. This uses the network, so the user is asked first. - **SQL:** `layer.addSql` `{"sql": "SELECT … FROM read_parquet('…')"}` runs one DuckDB query (DuckDB Spatial's `ST_` functions; PostgreSQL through `"database"`). It needs DuckDB installed on diff --git a/crates/data/src/raster/grib.rs b/crates/data/src/raster/grib.rs index 12542bd9b2..c3d4082005 100644 --- a/crates/data/src/raster/grib.rs +++ b/crates/data/src/raster/grib.rs @@ -12,7 +12,8 @@ //! //! The fields on the grid of the first one read are the raster's bands, in file order; fields on //! another grid are left out with a notice. Values are `(R + X × 2^E) / 10^D`, in the units the -//! file stores (kelvin stays kelvin). Points a bitmap masks are NaN. Rows are laid out north up, +//! file stores (kelvin stays kelvin), unpacked in `f64`; those `f32` changes are counted in +//! [`Raster::rounded`]. Points a bitmap masks are NaN. Rows are laid out north up, //! and a grid round the whole globe runs from −180° (as GDAL lays it out). use super::{Crs, GeoTransform, Raster, max_samples}; @@ -28,9 +29,9 @@ pub fn is_grib_name(name: &str) -> bool { EXTENSIONS.contains(&ext.as_str()) } -/// Most bytes looked through for the start of the next message ("GRIB"): files may put a -/// bulletin header or padding between messages, never this much. -const MAX_GAP: u64 = 64 * 1024; +/// The bytes read at a time while looking for the next message ("GRIB"): files may put a +/// bulletin header or padding between messages. +const CHUNK: usize = 4 * 1024; /// The most bits a packed value may have: GRIB allows more, no producer writes them. const MAX_BITS: u32 = 32; @@ -57,31 +58,55 @@ pub fn read(mut source: R, name: &str) -> Result { let mut at = 0u64; let mut messages = 0usize; let mut held = 0usize; - while let Some(start) = find_message(&mut source, at, file_len)? { - crate::progress::check()?; + let mut chunk = vec![0u8; CHUNK]; + // Progress in KiB of the file; one message is decoded without a check (at most + // `max_samples` values). + crate::progress::begin(usize::try_from(file_len / 1024).unwrap_or(usize::MAX)); + loop { + let (found, junk) = find_message(&mut source, at, file_len, &mut chunk)?; + skipped.junk += junk; + let Some(start) = found else { break }; + crate::progress::step(usize::try_from(start.saturating_sub(at) / 1024).unwrap_or(0))?; let (len, edition) = message_header(&mut source, start)?; - if len < MIN_MESSAGE || start.saturating_add(len) > file_len { + match (edition, len) { + // Not a message GRIB 1 or 2 describes: its four letters are passed, and the search + // goes on. + (Some(e), _) if e != 1 && e != 2 => { + skipped.add(format!("GRIB edition {e}")); + at = start + 4; + continue; + } + (Some(_), len) if len < MIN_MESSAGE => { + skipped.add("a damaged message".to_string()); + at = start + 4; + continue; + } // A message cut short (a byte range that ends early, a truncated download): what was // read before it stands, and the cut is said. - skipped.cut += 1; - break; + (None, _) => { + skipped.cut += 1; + break; + } + (Some(_), len) if start.saturating_add(len) > file_len => { + skipped.cut += 1; + break; + } + _ => {} } messages += 1; at = start + len; + crate::progress::step(usize::try_from(len / 1024).unwrap_or(0))?; // Past the memory limit: the rest is only counted. if held >= limit { - skipped.over_limit += count_fields(&mut source, start, len, edition)?; + skipped.over_limit += count_fields(&mut source, start, len, edition == Some(2))?; continue; } let mut bytes = Vec::new(); bytes.try_reserve_exact(len as usize).map_err(|_| bad("not enough memory for a message"))?; source.seek(SeekFrom::Start(start))?; source.by_ref().take(len).read_to_end(&mut bytes)?; - let decoded = match edition { - 1 => vec![grib1(&bytes, limit.saturating_sub(held))], - 2 => grib2(&bytes, limit.saturating_sub(held)), - e => vec![Err(Skip::Other(format!("edition {e}")))], - }; + let decoded = + if edition == Some(1) { vec![grib1(&bytes, limit.saturating_sub(held))] } else { grib2(&bytes, limit.saturating_sub(held)) }; for d in decoded { match d { Ok(f) => { @@ -100,7 +125,7 @@ pub fn read(mut source: R, name: &str) -> Result { } } } - if messages == 0 { + if messages == 0 && skipped.reasons.is_empty() { return Err(bad(if skipped.cut > 0 { "the first message is cut short" } else { "no GRIB message in the file" })); } let Some(first) = fields.first() else { @@ -113,20 +138,31 @@ pub fn read(mut source: R, name: &str) -> Result { Ok(r) } -/// The offset of the next "GRIB" at or after `at`, within [`MAX_GAP`] bytes; `None` at the end. -fn find_message(source: &mut R, at: u64, file_len: u64) -> Result> { - if at >= file_len { - return Ok(None); +/// The offset of the next "GRIB" at or after `at` (`None` at the end of the file), and how many +/// of the bytes passed on the way aren't zeros (padding): a bulletin header, other data. +fn find_message(source: &mut R, at: u64, file_len: u64, chunk: &mut [u8]) -> Result<(Option, u64)> { + let mut from = at; + let mut junk = 0u64; + while from < file_len { + source.seek(SeekFrom::Start(from))?; + let n = usize::try_from(file_len - from).unwrap_or(usize::MAX).min(chunk.len()); + let window = chunk.get_mut(..n).unwrap_or_default(); + source.read_exact(window)?; + if let Some(p) = window.windows(4).position(|w| w == b"GRIB") { + junk += window.iter().take(p).filter(|b| **b != 0).count() as u64; + return Ok((Some(from + p as u64), junk)); + } + // The last three bytes may start a "GRIB" that the next chunk ends. + let keep = if from + n as u64 >= file_len { 0 } else { 3.min(n) }; + junk += window.iter().take(n - keep).filter(|b| **b != 0).count() as u64; + from += (n - keep).max(1) as u64; } - source.seek(SeekFrom::Start(at))?; - let n = (file_len - at).min(MAX_GAP + 4); - let mut window = Vec::new(); - source.by_ref().take(n).read_to_end(&mut window)?; - Ok(window.windows(4).position(|w| w == b"GRIB").map(|p| at + p as u64)) + Ok((None, junk)) } -/// A message's length and edition, from its indicator section. -fn message_header(source: &mut R, start: u64) -> Result<(u64, u8)> { +/// A message's length and edition, from its indicator section: no edition when the file ends +/// inside the section, a length of 0 for an edition other than 1 and 2. +fn message_header(source: &mut R, start: u64) -> Result<(u64, Option)> { source.seek(SeekFrom::Start(start))?; let mut head = [0u8; 16]; let mut got = 0; @@ -137,21 +173,22 @@ fn message_header(source: &mut R, start: u64) -> Result<(u64, u8 } } if got < 8 { - return Ok((0, 0)); + return Ok((0, None)); } let edition = head[7]; let len = match edition { 1 => u64::from(be(&head, 4, 3)), 2 if got == 16 => head[8..16].iter().fold(0u64, |v, &b| (v << 8) | u64::from(b)), + 2 => return Ok((0, None)), _ => 0, }; - Ok((len, edition)) + Ok((len, Some(edition))) } /// How many fields a message holds: one in GRIB1, one a data section (7) in GRIB2, counted from /// the sections' headers alone. -fn count_fields(source: &mut R, start: u64, len: u64, edition: u8) -> Result { - if edition != 2 { +fn count_fields(source: &mut R, start: u64, len: u64, grib2: bool) -> Result { + if !grib2 { return Ok(1); } let (mut at, end, mut n) = (start + 16, start + len, 0usize); @@ -186,6 +223,8 @@ struct Skipped { other_grid: usize, over_limit: usize, cut: usize, + /// Bytes outside every message that aren't zeros. + junk: u64, } impl Skipped { @@ -210,6 +249,9 @@ impl Skipped { if self.cut > 0 { out.push("the file ends inside a message, which is left out".to_string()); } + if self.junk > 0 { + out.push(format!("{} bytes outside its messages aren't GRIB, and are passed over", self.junk)); + } out } } @@ -335,7 +377,7 @@ struct Field { name: String, grid: Grid, values: Vec, - /// Values `f32` changed (only packings of more than 24 bits can lose any). + /// Values `f32` changed: decimals (`D` > 0) and sums with more digits than it holds. rounded: u64, } @@ -425,7 +467,7 @@ fn unpack(data: &[u8], count: usize, bits: u32, r: f64, e: i64, d: i64) -> std:: let x = (word << (bit % 8)) >> (64 - bits); bit += u64::from(bits); let v = (r + x as f64 * scale) / ten; - if bits > 24 && f64::from(v as f32) != v { + if f64::from(v as f32) != v { rounded += 1; } out.push(v); @@ -433,12 +475,13 @@ fn unpack(data: &[u8], count: usize, bits: u32, r: f64, e: i64, d: i64) -> std:: Ok((out, rounded)) } -/// `count` copies of `v`: a field packed in no bits holds its reference value everywhere. -fn constant(v: f64, count: usize) -> std::result::Result, Skip> { +/// `count` copies of `v`, and how many of them `f32` changes: a field packed in no bits holds its +/// reference value everywhere. +fn constant(v: f64, count: usize) -> std::result::Result<(Vec, u64), Skip> { let mut out = Vec::new(); out.try_reserve_exact(count).map_err(|_| Skip::TooLarge)?; out.resize(count, v); - Ok(out) + Ok((out, if f64::from(v as f32) != v { count as u64 } else { 0 })) } /// Values in scanning order: those unpacked, spread over the points a bitmap keeps (NaN at the @@ -539,7 +582,7 @@ fn grib1(b: &[u8], room: usize) -> std::result::Result { let count = bitmap.map_or(points, |m| kept(m, points)); let data = bds.get(11..).unwrap_or_default(); let (values, rounded) = - if bits == 0 { (constant(r / 10f64.powi(d.clamp(-1000, 1000) as i32), count)?, 0) } else { unpack(data, count, bits, r, e, d)? }; + if bits == 0 { constant(r / 10f64.powi(d.clamp(-1000, 1000) as i32), count)? } else { unpack(data, count, bits, r, e, d)? }; Ok(Field { name, grid, values: spread(values, bitmap, points)?, rounded }) } @@ -658,7 +701,7 @@ fn grib2(b: &[u8], room: usize) -> Vec> { return Err(Skip::Other("a field whose values don't fill its grid".to_string())); } let (values, rounded) = if bits == 0 { - (constant(r / 10f64.powi(d.clamp(-1000, 1000) as i32), count)?, 0) + constant(r / 10f64.powi(d.clamp(-1000, 1000) as i32), count)? } else { unpack(s.get(5..).unwrap_or_default(), count, bits, r, e, d)? }; @@ -751,6 +794,10 @@ fn grib2_product(s: &[u8]) -> String { let value = signed(s, 24, 4) as f64 / 10f64.powi(signed(s, 23, 1) as i32); name.push_str(&format!(":surface={}:value={}:TimeU={}:forecast={}", s[22], round6(value), s[17], be(s, 18, 4))); } + // An ensemble's member (templates 4.1 and 4.11): its type and perturbation number. + if matches!(template, 1 | 11) && s.len() >= 37 { + name.push_str(&format!(":ensemble={}:member={}", s[34], s[35])); + } name } diff --git a/crates/data/src/raster/grib_tests.rs b/crates/data/src/raster/grib_tests.rs index 33a4feff27..d076e5a787 100644 --- a/crates/data/src/raster/grib_tests.rs +++ b/crates/data/src/raster/grib_tests.rs @@ -298,7 +298,8 @@ fn grib1_simple_packing_north_to_south() { assert_eq!(r.bands[0].name, "d=2026111806:kpds5=11:kpds6=105:kpds7=2:TR=0:P1=0:P2=0:TimeU=1"); // GRIB1's earth is a sphere: said once. assert_eq!(r.lost, vec!["its earth is a sphere of radius 6,367,470 m (GRIB1's); latitudes and longitudes are read as WGS 84's"]); - assert!(r.rounded.is_empty()); + // 10.1 and 10.2 change in `f32`; 10, 13, 14 and 15 don't. + assert_eq!(r.rounded, vec![2]); } #[test] @@ -450,3 +451,60 @@ fn grib_names_are_rasters() { let r = crate::raster::read_bytes("run.grb2", &grib2_message(&[F2::new(2, 1, vec![1, 2])])).unwrap(); assert_eq!(r.name, "run"); } + +#[test] +fn another_edition_is_said_and_the_next_message_read() { + let mut other = G1::new(2, 1, vec![1, 2]).bytes(); + other[7] = 3; + let mut file = other; + file.extend(G1::new(2, 1, vec![3, 4]).bytes()); + let r = read_bytes(&file, "t").unwrap(); + assert_eq!(r.bands.len(), 1); + assert_eq!(r.bands[0].data, vec![3.0, 4.0]); + assert!(r.lost.contains(&"1 field left out: GRIB edition 3, not read yet".to_string()), "{:?}", r.lost); + assert!(!r.lost.iter().any(|l| l.contains("ends inside")), "{:?}", r.lost); +} + +#[test] +fn a_long_gap_between_messages_is_passed_and_said() { + let mut file = G1::new(2, 1, vec![1, 2]).bytes(); + // About 70 KiB of something else, with "GRI" split over a chunk's end on the way. + file.extend(std::iter::repeat_n(b'x', 70 * 1024)); + file.extend(b"GRI"); + file.extend(G1::new(2, 1, vec![3, 4]).bytes()); + let r = read_bytes(&file, "t").unwrap(); + assert_eq!(r.bands.len(), 2); + assert_eq!(r.bands[1].data, vec![3.0, 4.0]); + assert!(r.lost.contains(&format!("{} bytes outside its messages aren't GRIB, and are passed over", 70 * 1024 + 3)), "{:?}", r.lost); + // A "GRIB" split over two chunks is found. + for pad in 4090..4100 { + let mut file = vec![0u8; pad]; + file.extend(G1::new(2, 1, vec![1, 2]).bytes()); + assert_eq!(read_bytes(&file, "t").unwrap().bands.len(), 1, "{pad}"); + } +} + +#[test] +fn ensemble_members_are_named_apart() { + let mut s = F2::new(2, 1, vec![1, 2]).sections(); + // Section 4 is at 72 (after section 3): template 4.1, with its ensemble octets. + let at = 72; + s[at + 8] = 1; + let mut s4_tail = vec![3u8, 7, 20]; + // Grow section 4 from 34 to 37 octets. + s.splice(at + 34..at + 34, s4_tail.drain(..)); + s[at + 3] = 37; + let mut s1 = u(21, 4); + s1.extend([1, 0, 7, 0, 0, 2, 1, 1]); + s1.extend(u(2026, 2)); + s1.extend([11, 18, 0, 0, 0, 0, 1]); + let mut body = s1; + body.extend(s); + let mut msg = b"GRIB".to_vec(); + msg.extend([0, 0, 0, 2]); + msg.extend(u(16 + body.len() as u64 + 4, 8)); + msg.extend(body); + msg.extend(b"7777"); + let r = read_bytes(&msg, "t").unwrap(); + assert!(r.bands[0].name.ends_with(":template=4.1:surface=103:value=2:TimeU=1:forecast=6:ensemble=3:member=7"), "{}", r.bands[0].name); +} diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index 5dcdec2525..764de3b93c 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -34,7 +34,7 @@ pub(crate) fn need_raster(s: &Session) -> Option<&'static str> { pub fn commands() -> Vec { vec![ C::new("layer.addDataBytes", "Add Data (from file contents)", "Home › Add", add_bytes::).roles(&[]).effects(crate::policy::Effects::NONE) - .params(r#"{"fileName": "name.tif|.tiff|.asc|.geojson|.csv|.zip|.kml|.kmz|.gpx|.parquet|.fgb|.gpkg|.mbtiles|.jp2|.j2k|.dxf|.pdf (JPEG 2000: desktop, through GDAL; PDF: desktop, command line and Python)", "data": base64, "zoom"?: bool, "layer"?: "one layer of a zip, KML or GPX by name, or a PDF's page number (the first when left out or blank)", "name"?: text, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData)}"#), + .params(r#"{"fileName": "name.tif|.tiff|.asc|.grb|.grib|.grb2|.grib2 (GRIB)|.geojson|.csv|.zip|.kml|.kmz|.gpx|.parquet|.fgb|.gpkg|.mbtiles|.jp2|.j2k|.dxf|.pdf (JPEG 2000: desktop, through GDAL; PDF: desktop, command line and Python)", "data": base64, "zoom"?: bool, "layer"?: "one layer of a zip, KML or GPX by name, or a PDF's page number (the first when left out or blank)", "name"?: text, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData)}"#), C::new("raster.symbology", "Symbology", "Style › Rendering", symbology).when(need_raster).roles(&[]).effects(crate::policy::Effects::NONE).params( r#"{"layer"?, "type": "stretch"|"rgb"|"classify"|"unique"|"colormap"|"shadedRelief", "band"?: 1.., "ramp"?, "invert"?: bool, "classes"?: 1..32, "method"?, "azimuth"?, "altitude"?, "zFactor"?, "shadow"?: 0..1 (shadedRelief: how dark the shadows the terrain casts are; left out, kept; 0 casts none), "sky"?: 0..1 (shadedRelief: how much the share of the sky each cell sees dims its ambient light; left out, kept; 0 leaves it whole), "fill"?: 0..1 (shadedRelief: a fill light from the side opposite the sun that lightens the slopes turned toward it; left out, kept; 0 has none), "ambient"?: 0..1|null (shadedRelief: the share of the colour a slope turned fully from the sun keeps; left out, kept; null, the default: 0.25, or 0.5 balanced), "balanced"?: bool (shadedRelief: flat ground keeps the ramp's colour and slopes facing the sun brighten, up to 1.3; left out, kept; false, the default, lights as before), "rock"?: {"from"?: 0..90, "to"?: 0..90, "color"?: #RRGGBB} | false (shadedRelief: steep slopes tinted toward a rock colour before the light, from the ground's own slope in degrees, without the Z factor: the ramp below from, the colour above to, blended between; left out, kept; an object's missing keys keep the current rock's, or 25, 40 and #B2ACA4; false or null removes it), "grey"?: bool (shadedRelief without its colour ramp)}"#, ), From 50955f0ae5c3556054c2521189ba1008b7549083 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Wed, 18 Nov 2026 21:22:33 -0300 Subject: [PATCH 03/17] fix(data): GRIB review round 2 (#2428) - The search for the next message looks at Cancel and counts progress for each window it reads. - A message larger than the values left room for can take is counted as past the memory limit without being read. - The body of a message left out (another edition, damaged) is no longer counted as bytes outside the messages. - Messages left out whole get their own notice ("1 message left out: not GRIB 1 or 2 (edition 3)"); "not read yet" stays for packings and grids. - The Python embed list takes GRIB files. Co-Authored-By: Claude Opus 5.5 --- apps/rustgis-python/python/rustgis/_embed.py | 1 + crates/data/src/raster/grib.rs | 59 ++++++++++++++------ crates/data/src/raster/grib_tests.rs | 12 +++- 3 files changed, 53 insertions(+), 19 deletions(-) diff --git a/apps/rustgis-python/python/rustgis/_embed.py b/apps/rustgis-python/python/rustgis/_embed.py index d2c04867de..a0090bc30c 100644 --- a/apps/rustgis-python/python/rustgis/_embed.py +++ b/apps/rustgis-python/python/rustgis/_embed.py @@ -33,6 +33,7 @@ _EMBEDDABLE = { ".tif", ".tiff", ".asc", ".geojson", ".json", ".csv", ".tsv", ".txt", ".zip", ".kml", ".kmz", ".gpx", ".parquet", ".geoparquet", ".fgb", ".gpkg", ".mbtiles", ".xlsx", ".xls", ".ods", + ".grb", ".grib", ".grb2", ".grib2", } #: The page script that frames the app: an anywidget module, also run by the Qt host page. diff --git a/crates/data/src/raster/grib.rs b/crates/data/src/raster/grib.rs index c3d4082005..21641b368f 100644 --- a/crates/data/src/raster/grib.rs +++ b/crates/data/src/raster/grib.rs @@ -59,26 +59,31 @@ pub fn read(mut source: R, name: &str) -> Result { let mut messages = 0usize; let mut held = 0usize; let mut chunk = vec![0u8; CHUNK]; - // Progress in KiB of the file; one message is decoded without a check (at most - // `max_samples` values). + // Progress in KiB of the file, counted as the search for each message reads it and as each + // message is read; one message is decoded without a check (at most `max_samples` values). crate::progress::begin(usize::try_from(file_len / 1024).unwrap_or(usize::MAX)); + // Whether the bytes before the next "GRIB" are the rest of a message left out (whose length + // isn't known), rather than something outside the messages. + let mut in_skipped = false; loop { let (found, junk) = find_message(&mut source, at, file_len, &mut chunk)?; - skipped.junk += junk; + if !in_skipped { + skipped.junk += junk; + } let Some(start) = found else { break }; - crate::progress::step(usize::try_from(start.saturating_sub(at) / 1024).unwrap_or(0))?; let (len, edition) = message_header(&mut source, start)?; + in_skipped = false; match (edition, len) { // Not a message GRIB 1 or 2 describes: its four letters are passed, and the search // goes on. (Some(e), _) if e != 1 && e != 2 => { - skipped.add(format!("GRIB edition {e}")); - at = start + 4; + skipped.message(format!("not GRIB 1 or 2 (edition {e})")); + (at, in_skipped) = (start + 4, true); continue; } (Some(_), len) if len < MIN_MESSAGE => { - skipped.add("a damaged message".to_string()); - at = start + 4; + skipped.message("damaged".to_string()); + (at, in_skipped) = (start + 4, true); continue; } // A message cut short (a byte range that ends early, a truncated download): what was @@ -96,8 +101,10 @@ pub fn read(mut source: R, name: &str) -> Result { messages += 1; at = start + len; crate::progress::step(usize::try_from(len / 1024).unwrap_or(0))?; - // Past the memory limit: the rest is only counted. - if held >= limit { + // Past the memory limit, or a message larger than the values left room for can take (at + // most 32 bits each, a bitmap and a megabyte of sections): only counted, never read. + let room = limit.saturating_sub(held); + if held >= limit || len > (room as u64).saturating_mul(5).saturating_add(1 << 20) { skipped.over_limit += count_fields(&mut source, start, len, edition == Some(2))?; continue; } @@ -105,8 +112,7 @@ pub fn read(mut source: R, name: &str) -> Result { bytes.try_reserve_exact(len as usize).map_err(|_| bad("not enough memory for a message"))?; source.seek(SeekFrom::Start(start))?; source.by_ref().take(len).read_to_end(&mut bytes)?; - let decoded = - if edition == Some(1) { vec![grib1(&bytes, limit.saturating_sub(held))] } else { grib2(&bytes, limit.saturating_sub(held)) }; + let decoded = if edition == Some(1) { vec![grib1(&bytes, room)] } else { grib2(&bytes, room) }; for d in decoded { match d { Ok(f) => { @@ -125,7 +131,7 @@ pub fn read(mut source: R, name: &str) -> Result { } } } - if messages == 0 && skipped.reasons.is_empty() { + if messages == 0 && skipped.messages.is_empty() { return Err(bad(if skipped.cut > 0 { "the first message is cut short" } else { "no GRIB message in the file" })); } let Some(first) = fields.first() else { @@ -148,12 +154,16 @@ fn find_message(source: &mut R, at: u64, file_len: u64, chunk: & let n = usize::try_from(file_len - from).unwrap_or(usize::MAX).min(chunk.len()); let window = chunk.get_mut(..n).unwrap_or_default(); source.read_exact(window)?; + // Each window looks at Cancel, and counts the bytes it passes (a message's own are counted + // as it is read): a long run of other bytes can be stopped. if let Some(p) = window.windows(4).position(|w| w == b"GRIB") { + crate::progress::step(p / 1024)?; junk += window.iter().take(p).filter(|b| **b != 0).count() as u64; return Ok((Some(from + p as u64), junk)); } // The last three bytes may start a "GRIB" that the next chunk ends. let keep = if from + n as u64 >= file_len { 0 } else { 3.min(n) }; + crate::progress::step((n - keep) / 1024)?; junk += window.iter().take(n - keep).filter(|b| **b != 0).count() as u64; from += (n - keep).max(1) as u64; } @@ -220,6 +230,8 @@ enum Skip { struct Skipped { /// Each reason, with how many fields it left out, in the order first met. reasons: Vec<(String, usize)>, + /// Each reason a whole message was left out (another edition, damaged), with a count. + messages: Vec<(String, usize)>, other_grid: usize, over_limit: usize, cut: usize, @@ -229,14 +241,19 @@ struct Skipped { impl Skipped { fn add(&mut self, why: String) { - match self.reasons.iter_mut().find(|(r, _)| *r == why) { - Some((_, n)) => *n += 1, - None => self.reasons.push((why, 1)), - } + tally(&mut self.reasons, why); + } + + fn message(&mut self, why: String) { + tally(&mut self.messages, why); } fn notes(&self, limit: usize) -> Vec { let mut out: Vec = self.reasons.iter().map(|(r, n)| format!("{} left out: {r}, not read yet", count(*n))).collect(); + out.extend(self.messages.iter().map(|(r, n)| { + let what = if *n == 1 { "1 message".to_string() } else { format!("{n} messages") }; + format!("{what} left out: {r}") + })); if self.other_grid > 0 { out.push(format!("{} left out: on another grid than the first field's", count(self.other_grid))); } @@ -256,6 +273,14 @@ impl Skipped { } } +/// One more of `why` in `list`. +fn tally(list: &mut Vec<(String, usize)>, why: String) { + match list.iter_mut().find(|(r, _)| *r == why) { + Some((_, n)) => *n += 1, + None => list.push((why, 1)), + } +} + fn count(n: usize) -> String { if n == 1 { "1 field".to_string() } else { format!("{n} fields") } } diff --git a/crates/data/src/raster/grib_tests.rs b/crates/data/src/raster/grib_tests.rs index d076e5a787..ea2e6c3297 100644 --- a/crates/data/src/raster/grib_tests.rs +++ b/crates/data/src/raster/grib_tests.rs @@ -461,8 +461,16 @@ fn another_edition_is_said_and_the_next_message_read() { let r = read_bytes(&file, "t").unwrap(); assert_eq!(r.bands.len(), 1); assert_eq!(r.bands[0].data, vec![3.0, 4.0]); - assert!(r.lost.contains(&"1 field left out: GRIB edition 3, not read yet".to_string()), "{:?}", r.lost); - assert!(!r.lost.iter().any(|l| l.contains("ends inside")), "{:?}", r.lost); + // Its body isn't said to be bytes outside the messages. + assert_eq!( + r.lost.iter().filter(|l| !l.starts_with("its earth")).collect::>(), + vec!["1 message left out: not GRIB 1 or 2 (edition 3)"] + ); + // Nothing readable: the error names why. + let mut only = G1::new(2, 1, vec![1, 2]).bytes(); + only[7] = 3; + let e = read_bytes(&only, "t").unwrap_err().to_string(); + assert!(e.contains("1 message left out: not GRIB 1 or 2 (edition 3)"), "{e}"); } #[test] From 7df5c15635c449e5755186b5bde89fc0456d51be Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Wed, 18 Nov 2026 21:39:32 -0300 Subject: [PATCH 04/17] fix(data): GRIB review round 3 (#2428) - A message whose grids hold more points than are left room for is counted as past the memory limit from its headers, before its body is read. - Damaged fields are said as damaged ("1 field left out: damaged (...)"); "not read yet" stays for packings and grids this reader doesn't read. - Progress carries what is left of a KiB, so every byte passed is counted. - layer.addUrl's description lists GRIB. - A test that GRIB2's given increments (code table 3.3, bits 3 and 4) set the cell size. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/raster/grib.rs | 158 ++++++++++++++++++++------- crates/data/src/raster/grib_tests.rs | 25 +++++ crates/engine/src/cmd/layer.rs | 2 +- 3 files changed, 142 insertions(+), 43 deletions(-) diff --git a/crates/data/src/raster/grib.rs b/crates/data/src/raster/grib.rs index 21641b368f..def5fe5492 100644 --- a/crates/data/src/raster/grib.rs +++ b/crates/data/src/raster/grib.rs @@ -59,6 +59,7 @@ pub fn read(mut source: R, name: &str) -> Result { let mut messages = 0usize; let mut held = 0usize; let mut chunk = vec![0u8; CHUNK]; + let mut counted = Counted::default(); // Progress in KiB of the file, counted as the search for each message reads it and as each // message is read; one message is decoded without a check (at most `max_samples` values). crate::progress::begin(usize::try_from(file_len / 1024).unwrap_or(usize::MAX)); @@ -66,7 +67,7 @@ pub fn read(mut source: R, name: &str) -> Result { // isn't known), rather than something outside the messages. let mut in_skipped = false; loop { - let (found, junk) = find_message(&mut source, at, file_len, &mut chunk)?; + let (found, junk) = find_message(&mut source, at, file_len, &mut chunk, &mut counted)?; if !in_skipped { skipped.junk += junk; } @@ -100,11 +101,13 @@ pub fn read(mut source: R, name: &str) -> Result { } messages += 1; at = start + len; - crate::progress::step(usize::try_from(len / 1024).unwrap_or(0))?; - // Past the memory limit, or a message larger than the values left room for can take (at - // most 32 bits each, a bitmap and a megabyte of sections): only counted, never read. + counted.add(len)?; + // Past the memory limit, a message whose grids hold more points than are left room for, + // or one larger than those points can take (at most 32 bits each, a bitmap and a megabyte + // of sections): only counted, never read. let room = limit.saturating_sub(held); - if held >= limit || len > (room as u64).saturating_mul(5).saturating_add(1 << 20) { + let too_long = len > (room as u64).saturating_mul(5).saturating_add(1 << 20); + if held >= limit || too_long || points_in(&mut source, start, len, edition == Some(2))?.is_some_and(|n| n > room) { skipped.over_limit += count_fields(&mut source, start, len, edition == Some(2))?; continue; } @@ -128,6 +131,7 @@ pub fn read(mut source: R, name: &str) -> Result { } Err(Skip::TooLarge) => skipped.over_limit += 1, Err(Skip::Other(why)) => skipped.add(why), + Err(Skip::Damaged(why)) => skipped.damaged(why), } } } @@ -146,7 +150,13 @@ pub fn read(mut source: R, name: &str) -> Result { /// The offset of the next "GRIB" at or after `at` (`None` at the end of the file), and how many /// of the bytes passed on the way aren't zeros (padding): a bulletin header, other data. -fn find_message(source: &mut R, at: u64, file_len: u64, chunk: &mut [u8]) -> Result<(Option, u64)> { +fn find_message( + source: &mut R, + at: u64, + file_len: u64, + chunk: &mut [u8], + counted: &mut Counted, +) -> Result<(Option, u64)> { let mut from = at; let mut junk = 0u64; while from < file_len { @@ -157,13 +167,13 @@ fn find_message(source: &mut R, at: u64, file_len: u64, chunk: & // Each window looks at Cancel, and counts the bytes it passes (a message's own are counted // as it is read): a long run of other bytes can be stopped. if let Some(p) = window.windows(4).position(|w| w == b"GRIB") { - crate::progress::step(p / 1024)?; + counted.add(p as u64)?; junk += window.iter().take(p).filter(|b| **b != 0).count() as u64; return Ok((Some(from + p as u64), junk)); } // The last three bytes may start a "GRIB" that the next chunk ends. let keep = if from + n as u64 >= file_len { 0 } else { 3.min(n) }; - crate::progress::step((n - keep) / 1024)?; + counted.add((n - keep) as u64)?; junk += window.iter().take(n - keep).filter(|b| **b != 0).count() as u64; from += (n - keep).max(1) as u64; } @@ -195,6 +205,61 @@ fn message_header(source: &mut R, start: u64) -> Result<(u64, Op Ok((len, Some(edition))) } +/// The bytes counted for the progress, in KiB, with what is left of a KiB carried over. +#[derive(Default)] +struct Counted(u64); + +impl Counted { + /// Counts `n` more bytes, and looks at Cancel. + fn add(&mut self, n: u64) -> Result<()> { + self.0 = self.0.saturating_add(n); + let kib = self.0 / 1024; + self.0 %= 1024; + crate::progress::step(usize::try_from(kib).unwrap_or(usize::MAX)) + } +} + +/// How many points a message's fields cover, from its headers alone (GRIB1's grid description, +/// GRIB2's number of data points of the grid each data section follows); `None` when they don't +/// say (a predefined grid), which the decoder then refuses or reads. +fn points_in(source: &mut R, start: u64, len: u64, grib2: bool) -> Result> { + let end = start + len; + let mut head = [0u8; 16]; + let read = |source: &mut R, at: u64, out: &mut [u8]| -> Result { + if at + out.len() as u64 > end { + return Ok(false); + } + source.seek(SeekFrom::Start(at))?; + source.read_exact(out)?; + Ok(true) + }; + if !grib2 { + // The product definition's length and flags, then the grid description's sizes. + if !read(source, start + 8, &mut head[..8])? || head[7] & 0x80 == 0 { + return Ok(None); + } + let gds = start + 8 + u64::from(be(&head, 0, 3)); + if !read(source, gds, &mut head[..10])? || head[5] != 0 { + return Ok(None); + } + return Ok(Some((be(&head, 6, 2) as usize).saturating_mul(be(&head, 8, 2) as usize))); + } + let (mut at, mut points, mut total) = (start + 16, 0usize, 0usize); + while read(source, at, &mut head[..10])? && &head[..4] != b"7777" { + let size = u64::from(be(&head, 0, 4)); + if size < 5 { + break; + } + match head[4] { + 3 => points = be(&head, 6, 4) as usize, + 7 => total = total.saturating_add(points), + _ => {} + } + at += size; + } + Ok(Some(total)) +} + /// How many fields a message holds: one in GRIB1, one a data section (7) in GRIB2, counted from /// the sections' headers alone. fn count_fields(source: &mut R, start: u64, len: u64, grib2: bool) -> Result { @@ -219,10 +284,13 @@ fn count_fields(source: &mut R, start: u64, len: u64, grib2: boo Ok(n.max(1)) } -/// Why a field isn't read: past the memory limit, or another reason said once with a count. +/// Why a field isn't read: past the memory limit, something this reader doesn't read yet (a +/// packing, a grid), or damage; each reason is said once with a count. +#[derive(Clone)] enum Skip { TooLarge, Other(String), + Damaged(String), } /// What was left out of a file, for its notices. @@ -232,6 +300,8 @@ struct Skipped { reasons: Vec<(String, usize)>, /// Each reason a whole message was left out (another edition, damaged), with a count. messages: Vec<(String, usize)>, + /// Each kind of damage that left a field out, with a count. + damage: Vec<(String, usize)>, other_grid: usize, over_limit: usize, cut: usize, @@ -248,8 +318,13 @@ impl Skipped { tally(&mut self.messages, why); } + fn damaged(&mut self, why: String) { + tally(&mut self.damage, why); + } + fn notes(&self, limit: usize) -> Vec { let mut out: Vec = self.reasons.iter().map(|(r, n)| format!("{} left out: {r}, not read yet", count(*n))).collect(); + out.extend(self.damage.iter().map(|(r, n)| format!("{} left out: damaged ({r})", count(*n)))); out.extend(self.messages.iter().map(|(r, n)| { let what = if *n == 1 { "1 message".to_string() } else { format!("{n} messages") }; format!("{what} left out: {r}") @@ -477,7 +552,7 @@ fn unpack(data: &[u8], count: usize, bits: u32, r: f64, e: i64, d: i64) -> std:: } let need = (count as u64).saturating_mul(u64::from(bits)).div_ceil(8); if (data.len() as u64) < need { - return Err(Skip::Other("a data section shorter than its values".to_string())); + return Err(Skip::Damaged("a data section shorter than its values".to_string())); } let scale = 2f64.powi(e.clamp(-1000, 1000) as i32); let ten = 10f64.powi(d.clamp(-1000, 1000) as i32); @@ -517,13 +592,13 @@ fn spread(values: Vec, bitmap: Option<&[u8]>, points: usize) -> std::result match bitmap { None => { if values.len() != points { - return Err(Skip::Other("a field whose values don't fill its grid".to_string())); + return Err(Skip::Damaged("a field whose values don't fill its grid".to_string())); } out.extend(values.into_iter().map(|v| v as f32)); } Some(bits) => { if (bits.len() as u64) * 8 < points as u64 { - return Err(Skip::Other("a bitmap shorter than its grid".to_string())); + return Err(Skip::Damaged("a bitmap shorter than its grid".to_string())); } let mut values = values.into_iter(); for k in 0..points { @@ -549,16 +624,16 @@ fn date(year: i64, month: u32, day: u32, hour: u32) -> String { fn section1(b: &[u8], at: usize) -> std::result::Result<&[u8], Skip> { let len = be(b, at, 3) as usize; if len < 3 { - return Err(Skip::Other("a damaged section".to_string())); + return Err(Skip::Damaged("a damaged section".to_string())); } - b.get(at..at + len).ok_or_else(|| Skip::Other("a section past the end of its message".to_string())) + b.get(at..at + len).ok_or_else(|| Skip::Damaged("a section past the end of its message".to_string())) } /// A GRIB1 message (WMO FM 92 GRIB edition 1): its one field. fn grib1(b: &[u8], room: usize) -> std::result::Result { let pds = section1(b, 8)?; if pds.len() < 28 { - return Err(Skip::Other("a damaged product definition section".to_string())); + return Err(Skip::Damaged("a damaged product definition section".to_string())); } let flags = pds[7]; if flags & 0x80 == 0 { @@ -614,7 +689,7 @@ fn grib1(b: &[u8], room: usize) -> std::result::Result { /// A GRIB1 grid description section: a regular latitude/longitude grid only. fn grib1_grid(g: &[u8]) -> std::result::Result { if g.len() < 28 { - return Err(Skip::Other("a damaged grid description section".to_string())); + return Err(Skip::Damaged("a damaged grid description section".to_string())); } let kind = g[5]; if kind != 0 { @@ -662,7 +737,7 @@ fn checked(g: Grid) -> std::result::Result { if ok && north <= 90.0 + 1e-6 && south >= -90.0 - 1e-6 { Ok(g) } else { - Err(Skip::Other("a latitude/longitude grid that isn't on the globe".to_string())) + Err(Skip::Damaged("a latitude/longitude grid that isn't on the globe".to_string())) } } @@ -679,15 +754,15 @@ fn grib2(b: &[u8], room: usize) -> Vec> { let discipline = b.get(6).copied().unwrap_or(255); let mut at = 16usize; let mut reference = String::from("d=?"); - let mut grid: Option> = None; + let mut grid: Option> = None; let mut product = String::new(); - let mut packing: Option> = None; - let mut bitmap: Option, String>> = None; + let mut packing: Option> = None; + let mut bitmap: Option, Skip>> = None; let mut previous_bitmap: Option<&[u8]> = None; let mut held = 0usize; while b.get(at..at + 4).is_some_and(|m| m != b"7777") { let Some((number, s)) = section2(b, at) else { - out.push(Err(Skip::Other("a damaged GRIB2 section".to_string()))); + out.push(Err(Skip::Damaged("a damaged GRIB2 section".to_string()))); break; }; at += s.len(); @@ -711,19 +786,19 @@ fn grib2(b: &[u8], room: usize) -> Vec> { previous_bitmap = Some(bits); Ok(Some(bits)) } - 254 => previous_bitmap.map(Some).ok_or_else(|| "a bitmap that refers to none before it".to_string()), - _ => Err("predefined bitmaps".to_string()), + 254 => previous_bitmap.map(Some).ok_or_else(|| Skip::Damaged("a bitmap that refers to none before it".to_string())), + _ => Err(Skip::Other("predefined bitmaps".to_string())), }); } 7 => { let field = (|| { - let grid = grid.clone().ok_or_else(|| Skip::Other("a field without a grid".to_string()))?.map_err(Skip::Other)?; + let grid = grid.clone().ok_or_else(|| Skip::Damaged("a field without a grid".to_string()))??; let (count, r, e, d, bits) = - packing.clone().ok_or_else(|| Skip::Other("a field without its packing".to_string()))?.map_err(Skip::Other)?; - let mask = bitmap.clone().unwrap_or(Ok(None)).map_err(Skip::Other)?; + packing.clone().ok_or_else(|| Skip::Damaged("a field without its packing".to_string()))??; + let mask = bitmap.clone().unwrap_or(Ok(None))?; let points = grid.ni.checked_mul(grid.nj).filter(|n| held.saturating_add(*n) <= room).ok_or(Skip::TooLarge)?; if mask.is_some_and(|m| kept(m, points) != count) || (mask.is_none() && count != points) { - return Err(Skip::Other("a field whose values don't fill its grid".to_string())); + return Err(Skip::Damaged("a field whose values don't fill its grid".to_string())); } let (values, rounded) = if bits == 0 { constant(r / 10f64.powi(d.clamp(-1000, 1000) as i32), count)? @@ -744,25 +819,25 @@ fn grib2(b: &[u8], room: usize) -> Vec> { } } if out.is_empty() { - out.push(Err(Skip::Other("a GRIB2 message without a data section".to_string()))); + out.push(Err(Skip::Damaged("a GRIB2 message without a data section".to_string()))); } out } /// A GRIB2 grid definition section: template 3.0 (regular latitude/longitude) only. -fn grib2_grid(s: &[u8]) -> std::result::Result { +fn grib2_grid(s: &[u8]) -> std::result::Result { if s.get(5).copied().unwrap_or(1) != 0 { - return Err("predefined grids".to_string()); + return Err(Skip::Other("predefined grids".to_string())); } if s.get(10).copied().unwrap_or(0) != 0 { - return Err("quasi-regular grids".to_string()); + return Err(Skip::Other("quasi-regular grids".to_string())); } let template = be(s, 12, 2); if template != 0 { - return Err(format!("GRIB2 grid template 3.{template} (not regular latitude/longitude)")); + return Err(Skip::Other(format!("GRIB2 grid template 3.{template} (not regular latitude/longitude)"))); } if s.len() < 72 { - return Err("a damaged grid definition section".to_string()); + return Err(Skip::Damaged("a damaged grid definition section".to_string())); } let earth = match s[14] { // GRS 80, WGS 84: near enough. @@ -776,18 +851,20 @@ fn grib2_grid(s: &[u8]) -> std::result::Result { }; let (ni, nj) = (be(s, 30, 4) as usize, be(s, 34, 4) as usize); if ni == 0 || nj == 0 || ni == u32::MAX as usize || nj == u32::MAX as usize { - return Err("quasi-regular grids".to_string()); + return Err(Skip::Other("quasi-regular grids".to_string())); } let (basic, sub) = (be(s, 38, 4), be(s, 42, 4)); let unit = if basic == 0 || basic == u32::MAX { 1e-6 } else if sub == 0 || sub == u32::MAX { - return Err("a grid with no angle subdivisions".to_string()); + return Err(Skip::Damaged("a grid with no angle subdivisions".to_string())); } else { f64::from(basic) / f64::from(sub) }; let deg = |o: usize| signed(s, o, 4) as f64 * unit; let (lat1, lon1, lat2, lon2) = (deg(46), deg(50), deg(55), deg(59)); + // Code table 3.3: bit 3 (0x20) says the i direction's increments are given, bit 4 (0x10) + // the j direction's. let res = s[54]; let (di, dj) = (be(s, 63, 4), be(s, 67, 4)); let dx = if res & 0x20 != 0 && di != u32::MAX { @@ -800,10 +877,7 @@ fn grib2_grid(s: &[u8]) -> std::result::Result { } else { span(lat1, lat2, false) / (nj.saturating_sub(1)).max(1) as f64 }; - checked(Grid { ni, nj, lat1, lon1, lat2, lon2, dx, dy, scan: s[71], earth }).map_err(|e| match e { - Skip::Other(m) => m, - Skip::TooLarge => "a grid too large".to_string(), - }) + checked(Grid { ni, nj, lat1, lon1, lat2, lon2, dx, dy, scan: s[71], earth }) } /// A GRIB2 product definition section, as part of a band name: the parameter's category and @@ -828,7 +902,7 @@ fn grib2_product(s: &[u8]) -> String { /// A GRIB2 data representation section: template 5.0 (simple packing) only, as the number of /// values, R, E, D and the bits a value. -fn grib2_packing(s: &[u8]) -> std::result::Result<(usize, f64, i64, i64, u32), String> { +fn grib2_packing(s: &[u8]) -> std::result::Result<(usize, f64, i64, i64, u32), Skip> { let template = be(s, 9, 2); if template != 0 { let kind = match template { @@ -839,10 +913,10 @@ fn grib2_packing(s: &[u8]) -> std::result::Result<(usize, f64, i64, i64, u32), S 42 => "CCSDS", _ => "a packing", }; - return Err(format!("GRIB2 {kind} (template 5.{template})")); + return Err(Skip::Other(format!("GRIB2 {kind} (template 5.{template})"))); } if s.len() < 21 { - return Err("a damaged data representation section".to_string()); + return Err(Skip::Damaged("a damaged data representation section".to_string())); } let r = f64::from(f32::from_bits(be(s, 11, 4))); Ok((be(s, 5, 4) as usize, r, signed(s, 15, 2), signed(s, 17, 2), u32::from(s[19]))) diff --git a/crates/data/src/raster/grib_tests.rs b/crates/data/src/raster/grib_tests.rs index ea2e6c3297..8d87bfdc71 100644 --- a/crates/data/src/raster/grib_tests.rs +++ b/crates/data/src/raster/grib_tests.rs @@ -516,3 +516,28 @@ fn ensemble_members_are_named_apart() { let r = read_bytes(&msg, "t").unwrap(); assert!(r.bands[0].name.ends_with(":template=4.1:surface=103:value=2:TimeU=1:forecast=6:ensemble=3:member=7"), "{}", r.bands[0].name); } + +#[test] +fn a_damaged_field_is_said_as_damaged() { + let a = F2::new(2, 1, vec![1, 2]); + let mut msg = grib2_message(&[F2::new(2, 1, vec![1, 2]), F2::new(2, 1, vec![3, 4])]); + // The second field's data section claims more values than it holds: its 12-bit values need + // 3 octets; cut its length by giving section 5 a larger count. + let first = a.sections().len(); + let s5 = 16 + 21 + first + 72 + 34; + msg[s5 + 5..s5 + 9].copy_from_slice(&u(2000, 4)); + let r = read_bytes(&msg, "t").unwrap(); + assert_eq!(r.bands.len(), 1); + assert!(r.lost.contains(&"1 field left out: damaged (a field whose values don't fill its grid)".to_string()), "{:?}", r.lost); + assert!(!r.lost.iter().any(|l| l.contains("not read yet")), "{:?}", r.lost); +} + +#[test] +fn grib2_increments_given_are_used() { + // Code table 3.3: 0x20 and 0x10 say the increments are given; the last point then doesn't + // decide the cell size. + let mut f = F2::new(3, 2, vec![1, 2, 3, 4, 5, 6]); + (f.lon2, f.lat2) = (f.lon1 + 5_000_000, f.lat1 + 3_000_000); + let r = read_bytes(&grib2_message(&[f]), "t").unwrap(); + assert_eq!((r.transform.pixel_width, r.transform.pixel_height), (0.5, -0.5)); +} diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 90eb2987f5..6befc37cd7 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -51,7 +51,7 @@ pub fn commands() -> Vec { .params(r#"{"layer"?: name|id, "crs": "EPSG:… or WKT; reinterpret native coordinates, without rewriting the source file"}"#), C::new("layer.loadAll", "Load All Features", "Layers", load_all).roles(&[]).effects(crate::policy::Effects::NONE).when(need_streamed).params(r#"{"layer"?: name|id}"#), C::new("layer.addUrl", "Add Data From URL", "Home › Add › Add Data", add_url).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( - r#"{"url": "https://…/data.geojson|.csv|.parquet|.fgb|.gpkg|.zip|.shp (its .dbf fetched beside it, and its .shx, .prj and .cpg when there)|.kml|.kmz|.gpx|.tif|.jp2 (JPEG 2000: desktop, through GDAL) (the format from the address, else the contents) | a .pmtiles archive", "name"?: text, "layer"?: "one layer of a zip, KML or GPX", "zoom"?: "bool: true frames everything added; false keeps the view, even on an empty map; omitted, the first content on an empty map is framed (a GeoParquet, FlatGeobuf or cloud-optimised GeoTIFF read in place likewise; a PMTiles or MBTiles archive ignores zoom and is framed on its bounds unless it covers the whole world)", "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "whole"?: "bool: download a cloud-optimised GeoTIFF whole (as a raster layer) instead of reading it in place (an address without a file name is read in place when its first bytes are a cloud-optimised GeoTIFF)", "cog"?: "bool: the address is a cloud-optimised GeoTIFF whatever its name says (the app's probe found it so)", "bbox"?: "[west, south, east, north] in degrees | "view": a cloud-optimised GeoTIFF's window as a raster layer (desktop and command line), read by range at full resolution, in the file's coordinate system, with its colour table and class names; at most 64 million values (all bands)", "cellSize"?: "with bbox: the coarsest overview whose cells are at most this size is read (the file's units; metres for longitude/latitude, a degree taken as 111.32 km)", "cube"?: "bool: a data cube's file: a tile layer that follows the time slider (stac.addCube adds them), kept one when the project opens again", "start"?, "end"?, "unit"?, "interval"?, "dates"?: "a GeoTIFF address with date placeholders ({date:YYYY}, {YYYY}{MM}{DD}), one file per date: the dates it spans and steps through (as time.set), turning the time slider on", "connection"?: "the id of the saved web-service connection it comes from (as service.add)", "service"?: "bool: a web service's features (an ArcGIS query, OGC API Features items): read in pages as service.add reads them, known by the address as its layers are, and an ArcGIS layer drawn as its description says", "bounds"?: "with service: [west, south, east, north], the layer's longitude/latitude bounds its axes are checked against", "from"?: "the web document address that named url (internal: enforces public-address reach)", "fromDocument"?: bool, "anonymous"?: bool (internal: a plugin-origin download must never adopt a saved login), "request"?: "number (internal: the download a plugin command left to the app, #1202)"}"#, + r#"{"url": "https://…/data.geojson|.csv|.parquet|.fgb|.gpkg|.zip|.shp (its .dbf fetched beside it, and its .shx, .prj and .cpg when there)|.kml|.kmz|.gpx|.tif|.grb|.grib|.grb2|.grib2 (GRIB)|.jp2 (JPEG 2000: desktop, through GDAL) (the format from the address, else the contents) | a .pmtiles archive", "name"?: text, "layer"?: "one layer of a zip, KML or GPX", "zoom"?: "bool: true frames everything added; false keeps the view, even on an empty map; omitted, the first content on an empty map is framed (a GeoParquet, FlatGeobuf or cloud-optimised GeoTIFF read in place likewise; a PMTiles or MBTiles archive ignores zoom and is framed on its bounds unless it covers the whole world)", "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "whole"?: "bool: download a cloud-optimised GeoTIFF whole (as a raster layer) instead of reading it in place (an address without a file name is read in place when its first bytes are a cloud-optimised GeoTIFF)", "cog"?: "bool: the address is a cloud-optimised GeoTIFF whatever its name says (the app's probe found it so)", "bbox"?: "[west, south, east, north] in degrees | "view": a cloud-optimised GeoTIFF's window as a raster layer (desktop and command line), read by range at full resolution, in the file's coordinate system, with its colour table and class names; at most 64 million values (all bands)", "cellSize"?: "with bbox: the coarsest overview whose cells are at most this size is read (the file's units; metres for longitude/latitude, a degree taken as 111.32 km)", "cube"?: "bool: a data cube's file: a tile layer that follows the time slider (stac.addCube adds them), kept one when the project opens again", "start"?, "end"?, "unit"?, "interval"?, "dates"?: "a GeoTIFF address with date placeholders ({date:YYYY}, {YYYY}{MM}{DD}), one file per date: the dates it spans and steps through (as time.set), turning the time slider on", "connection"?: "the id of the saved web-service connection it comes from (as service.add)", "service"?: "bool: a web service's features (an ArcGIS query, OGC API Features items): read in pages as service.add reads them, known by the address as its layers are, and an ArcGIS layer drawn as its description says", "bounds"?: "with service: [west, south, east, north], the layer's longitude/latitude bounds its axes are checked against", "from"?: "the web document address that named url (internal: enforces public-address reach)", "fromDocument"?: bool, "anonymous"?: bool (internal: a plugin-origin download must never adopt a saved login), "request"?: "number (internal: the download a plugin command left to the app, #1202)"}"#, ), C::new("layer.addDownload", "Add Downloaded Data", "Home › Add", add_download).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Reserved).with(crate::policy::Effect::Files)) .params(r#"{"id": a download the app finished (Home › Add › Add Data › From URL), "url": its address, "name"?: text, "layer"?: text, "zoom"?: bool, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "service"?: bool (a service's features: their axes (when they came as GeoJSON) and paging are checked, and the address is kept as the layer's source), "bounds"?: [west, south, east, north] (with service: the layer's longitude/latitude bounds from its capabilities, which its axes are checked against; without bounds they are left as they come; ignored without service), "coverage"?: bool (a WCS coverage: a GeoTIFF, else the service's error, and its request kept as the layer's source), "drawingInfo"?: object (internal, with service: an ArcGIS layer's drawingInfo from its description, which the layer is drawn with), "geolibreProject"?: bool (internal: downloaded project JSON), "geolibreLayer"?: {"token", "record"} (internal: reserved imported layer and its saved style), "geolibreZarr"?: bool (internal: an imported Zarr slice as GeoTIFF), "connection"?: "as layer.addUrl", "anonymous"?: bool (internal: preserves a plugin-origin download's anonymous reads), "request"?: number (internal: the download a plugin command left to the app, #1202), "window"?: {"bbox", "cellSize"?, "cog"?} (internal: what a cloud-optimised GeoTIFF's window the app read off the frame asked for, for a task to read it again, #1330)}"#), From 3b888a688e238a4ccf6242ddf5c26abdbdacf25e Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Wed, 18 Nov 2026 22:04:12 -0300 Subject: [PATCH 05/17] fix(data): GRIB review round 4 (#2428) - The header count of a GRIB2 message's points includes a last constant field (a 5-octet data section just before "7777"). - Values are unpacked straight into f32, so a field never holds an f64 copy of its values as well. - Placing the bands looks at Cancel before each band. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/raster/grib.rs | 54 +++++++++++++++------------- crates/data/src/raster/grib_tests.rs | 12 +++++++ 2 files changed, 41 insertions(+), 25 deletions(-) diff --git a/crates/data/src/raster/grib.rs b/crates/data/src/raster/grib.rs index def5fe5492..1483e4935d 100644 --- a/crates/data/src/raster/grib.rs +++ b/crates/data/src/raster/grib.rs @@ -245,13 +245,16 @@ fn points_in(source: &mut R, start: u64, len: u64, grib2: bool) return Ok(Some((be(&head, 6, 2) as usize).saturating_mul(be(&head, 8, 2) as usize))); } let (mut at, mut points, mut total) = (start + 16, 0usize, 0usize); - while read(source, at, &mut head[..10])? && &head[..4] != b"7777" { + // Each section's 5-octet header (a constant field's data section is no longer, just before + // "7777"), and the grid's number of data points (octets 7 to 10) when it is section 3. + while read(source, at, &mut head[..5])? && &head[..4] != b"7777" { let size = u64::from(be(&head, 0, 4)); if size < 5 { break; } + let mut count = [0u8; 4]; match head[4] { - 3 => points = be(&head, 6, 4) as usize, + 3 if read(source, at + 6, &mut count)? => points = be(&count, 0, 4) as usize, 7 => total = total.saturating_add(points), _ => {} } @@ -481,7 +484,9 @@ struct Field { rounded: u64, } -/// The raster of fields on one grid: north up, a whole turn of longitude from −180°. +/// The raster of fields on one grid: north up, a whole turn of longitude from −180°. Cancel is +/// looked at before each band is placed; one band's placement (at most `max_samples` values, one +/// pass) runs without a check. fn to_raster(fields: Vec, name: &str) -> Result { let Some(grid) = fields.first().map(|f| f.grid) else { return Err(bad("no field")) }; let (w, h) = (grid.ni, grid.nj); @@ -500,6 +505,7 @@ fn to_raster(fields: Vec, name: &str) -> Result { let mut rounded = Vec::with_capacity(fields.len()); let mut bands = Vec::with_capacity(fields.len()); for f in fields { + crate::progress::check()?; let mut band = super::filled(w, h, f32::NAN)?; for (k, v) in f.values.iter().enumerate() { let (col, row) = grid.place(k); @@ -546,7 +552,7 @@ fn ibm(v: u32) -> f64 { /// `count` values of `bits` bits each from `data`, big-endian, unpacked as `(R + X × 2^E) / 10^D`; /// with fewer bits there than that, an error. -fn unpack(data: &[u8], count: usize, bits: u32, r: f64, e: i64, d: i64) -> std::result::Result<(Vec, u64), Skip> { +fn unpack(data: &[u8], count: usize, bits: u32, r: f64, e: i64, d: i64) -> std::result::Result<(Vec, u64), Skip> { if bits > MAX_BITS { return Err(Skip::Other(format!("values of {bits} bits"))); } @@ -570,42 +576,40 @@ fn unpack(data: &[u8], count: usize, bits: u32, r: f64, e: i64, d: i64) -> std:: if f64::from(v as f32) != v { rounded += 1; } - out.push(v); + // Unpacked in `f64` and held as `f32`, never both for the whole field. + out.push(v as f32); } Ok((out, rounded)) } /// `count` copies of `v`, and how many of them `f32` changes: a field packed in no bits holds its /// reference value everywhere. -fn constant(v: f64, count: usize) -> std::result::Result<(Vec, u64), Skip> { +fn constant(v: f64, count: usize) -> std::result::Result<(Vec, u64), Skip> { let mut out = Vec::new(); out.try_reserve_exact(count).map_err(|_| Skip::TooLarge)?; - out.resize(count, v); + out.resize(count, v as f32); Ok((out, if f64::from(v as f32) != v { count as u64 } else { 0 })) } /// Values in scanning order: those unpacked, spread over the points a bitmap keeps (NaN at the /// others), or all of them without one. -fn spread(values: Vec, bitmap: Option<&[u8]>, points: usize) -> std::result::Result, Skip> { +fn spread(values: Vec, bitmap: Option<&[u8]>, points: usize) -> std::result::Result, Skip> { + let Some(bits) = bitmap else { + // Without a bitmap, the values are the field as they are. + if values.len() != points { + return Err(Skip::Damaged("a field whose values don't fill its grid".to_string())); + } + return Ok(values); + }; + if (bits.len() as u64) * 8 < points as u64 { + return Err(Skip::Damaged("a bitmap shorter than its grid".to_string())); + } let mut out = Vec::new(); out.try_reserve_exact(points).map_err(|_| Skip::TooLarge)?; - match bitmap { - None => { - if values.len() != points { - return Err(Skip::Damaged("a field whose values don't fill its grid".to_string())); - } - out.extend(values.into_iter().map(|v| v as f32)); - } - Some(bits) => { - if (bits.len() as u64) * 8 < points as u64 { - return Err(Skip::Damaged("a bitmap shorter than its grid".to_string())); - } - let mut values = values.into_iter(); - for k in 0..points { - let set = bits.get(k / 8).is_some_and(|b| b & (0x80 >> (k % 8)) != 0); - out.push(if set { values.next().map_or(f32::NAN, |v| v as f32) } else { f32::NAN }); - } - } + let mut values = values.into_iter(); + for k in 0..points { + let set = bits.get(k / 8).is_some_and(|b| b & (0x80 >> (k % 8)) != 0); + out.push(if set { values.next().unwrap_or(f32::NAN) } else { f32::NAN }); } Ok(out) } diff --git a/crates/data/src/raster/grib_tests.rs b/crates/data/src/raster/grib_tests.rs index 8d87bfdc71..a5e83aa90d 100644 --- a/crates/data/src/raster/grib_tests.rs +++ b/crates/data/src/raster/grib_tests.rs @@ -541,3 +541,15 @@ fn grib2_increments_given_are_used() { let r = read_bytes(&grib2_message(&[f]), "t").unwrap(); assert_eq!((r.transform.pixel_width, r.transform.pixel_height), (0.5, -0.5)); } + +#[test] +fn points_in_counts_a_last_constant_field() { + // A constant field's data section is 5 octets, just before "7777". + let mut c = F2::new(3, 2, vec![]); + c.bits = 0; + let msg = grib2_message(&[F2::new(2, 1, vec![1, 2]), c]); + let n = points_in(&mut std::io::Cursor::new(&msg), 0, msg.len() as u64, true).unwrap(); + assert_eq!(n, Some(2 + 6)); + let one = G1::new(4, 3, vec![0; 12]).bytes(); + assert_eq!(points_in(&mut std::io::Cursor::new(&one), 0, one.len() as u64, false).unwrap(), Some(12)); +} From 3543ef5dd5dafe8a776ed2d2c4d1ff7c23c93214 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Wed, 18 Nov 2026 22:29:06 -0300 Subject: [PATCH 06/17] fix(data): GRIB review round 5 (#2428) - A message whose length doesn't end on "7777" is said as damaged, and the search goes on from inside it, so a message the length would hide is still read. - Decimal and binary scale factors f64 can't take are damage, not fields of zeros or infinities. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/raster/grib.rs | 35 ++++++++++++++++++++++++---- crates/data/src/raster/grib_tests.rs | 33 ++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 4 deletions(-) diff --git a/crates/data/src/raster/grib.rs b/crates/data/src/raster/grib.rs index 1483e4935d..4e700879ab 100644 --- a/crates/data/src/raster/grib.rs +++ b/crates/data/src/raster/grib.rs @@ -97,6 +97,13 @@ pub fn read(mut source: R, name: &str) -> Result { skipped.cut += 1; break; } + // A length that doesn't end on "7777" says the message wrongly: the search goes on + // from inside it, so a message it would hide is still found. + (Some(_), len) if !ends_message(&mut source, start + len)? => { + skipped.message("damaged".to_string()); + (at, in_skipped) = (start + 4, true); + continue; + } _ => {} } messages += 1; @@ -205,6 +212,14 @@ fn message_header(source: &mut R, start: u64) -> Result<(u64, Op Ok((len, Some(edition))) } +/// Whether the four octets before `end` are "7777", the end of a message. +fn ends_message(source: &mut R, end: u64) -> Result { + let mut tail = [0u8; 4]; + source.seek(SeekFrom::Start(end.saturating_sub(4)))?; + source.read_exact(&mut tail)?; + Ok(&tail == b"7777") +} + /// The bytes counted for the progress, in KiB, with what is left of a KiB carried over. #[derive(Default)] struct Counted(u64); @@ -561,7 +576,13 @@ fn unpack(data: &[u8], count: usize, bits: u32, r: f64, e: i64, d: i64) -> std:: return Err(Skip::Damaged("a data section shorter than its values".to_string())); } let scale = 2f64.powi(e.clamp(-1000, 1000) as i32); - let ten = 10f64.powi(d.clamp(-1000, 1000) as i32); + let ten = decimal(d)?; + // The largest value the field can hold must be a number: past `f64`, every value would be + // infinite. + let top = (r.abs() + ((1u64 << bits) - 1) as f64 * scale) / ten; + if !top.is_finite() { + return Err(Skip::Damaged("a binary scale factor its values can't take".to_string())); + } let mut out = Vec::new(); out.try_reserve_exact(count).map_err(|_| Skip::TooLarge)?; let mut rounded = 0u64; @@ -582,6 +603,13 @@ fn unpack(data: &[u8], count: usize, bits: u32, r: f64, e: i64, d: i64) -> std:: Ok((out, rounded)) } +/// 10^`d`, the decimal scale factor's divisor; damage when `f64` can't hold it (every value +/// would be 0 or infinite). +fn decimal(d: i64) -> std::result::Result { + let ten = 10f64.powi(d.clamp(-1000, 1000) as i32); + if ten.is_finite() && ten > 0.0 { Ok(ten) } else { Err(Skip::Damaged("a decimal scale factor its values can't take".to_string())) } +} + /// `count` copies of `v`, and how many of them `f32` changes: a field packed in no bits holds its /// reference value everywhere. fn constant(v: f64, count: usize) -> std::result::Result<(Vec, u64), Skip> { @@ -685,8 +713,7 @@ fn grib1(b: &[u8], room: usize) -> std::result::Result { let bits = u32::from(bds.get(10).copied().unwrap_or(0)); let count = bitmap.map_or(points, |m| kept(m, points)); let data = bds.get(11..).unwrap_or_default(); - let (values, rounded) = - if bits == 0 { constant(r / 10f64.powi(d.clamp(-1000, 1000) as i32), count)? } else { unpack(data, count, bits, r, e, d)? }; + let (values, rounded) = if bits == 0 { constant(r / decimal(d)?, count)? } else { unpack(data, count, bits, r, e, d)? }; Ok(Field { name, grid, values: spread(values, bitmap, points)?, rounded }) } @@ -805,7 +832,7 @@ fn grib2(b: &[u8], room: usize) -> Vec> { return Err(Skip::Damaged("a field whose values don't fill its grid".to_string())); } let (values, rounded) = if bits == 0 { - constant(r / 10f64.powi(d.clamp(-1000, 1000) as i32), count)? + constant(r / decimal(d)?, count)? } else { unpack(s.get(5..).unwrap_or_default(), count, bits, r, e, d)? }; diff --git a/crates/data/src/raster/grib_tests.rs b/crates/data/src/raster/grib_tests.rs index a5e83aa90d..e06f74c9ae 100644 --- a/crates/data/src/raster/grib_tests.rs +++ b/crates/data/src/raster/grib_tests.rs @@ -542,6 +542,39 @@ fn grib2_increments_given_are_used() { assert_eq!((r.transform.pixel_width, r.transform.pixel_height), (0.5, -0.5)); } +#[test] +fn a_length_past_its_message_hides_nothing() { + let mut first = G1::new(2, 1, vec![1, 2]).bytes(); + let second = G1::new(2, 1, vec![3, 4]).bytes(); + // The first says it is 8 octets longer: its end falls inside the second. + let len = first.len() as u64 + 8; + first[4..7].copy_from_slice(&u(len, 3)); + let mut file = first; + file.extend(&second); + let r = read_bytes(&file, "t").unwrap(); + assert_eq!(r.bands.len(), 1); + assert_eq!(r.bands[0].data, vec![3.0, 4.0]); + assert!(r.lost.contains(&"1 message left out: damaged".to_string()), "{:?}", r.lost); +} + +#[test] +fn scale_factors_past_f64_are_damage() { + for (d, bits) in [(400, 16), (-400, 16), (400, 0)] { + let mut g = G1::new(2, 1, vec![1, 2]); + (g.d, g.bits) = (d, bits); + if bits == 0 { + g.x.clear(); + } + let e = read_bytes(&g.bytes(), "t").unwrap_err().to_string(); + assert!(e.contains("damaged (a decimal scale factor its values can't take)"), "{d}: {e}"); + } + let mut g = G1::new(2, 1, vec![1, 2]); + (g.e, g.bits) = (1000, 32); + g.x = vec![u32::MAX, 1]; + let e = read_bytes(&g.bytes(), "t").unwrap_err().to_string(); + assert!(e.contains("damaged (a binary scale factor its values can't take)"), "{e}"); +} + #[test] fn points_in_counts_a_last_constant_field() { // A constant field's data section is 5 octets, just before "7777". From c45e694a34acd1051e27f4f7f44c67ffb3f852f1 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Wed, 18 Nov 2026 22:56:08 -0300 Subject: [PATCH 07/17] fix(data): GRIB review round 6 (#2428) - A GRIB1 quasi-regular grid is said as such, not as past the memory limit. - A clean GRIB2 file gives no notice (test). - to_raster's doc names the statistics pass without a Cancel check. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/raster/grib.rs | 10 ++++++++-- crates/data/src/raster/grib_tests.rs | 21 +++++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/data/src/raster/grib.rs b/crates/data/src/raster/grib.rs index 4e700879ab..e4f8a75e17 100644 --- a/crates/data/src/raster/grib.rs +++ b/crates/data/src/raster/grib.rs @@ -257,7 +257,12 @@ fn points_in(source: &mut R, start: u64, len: u64, grib2: bool) if !read(source, gds, &mut head[..10])? || head[5] != 0 { return Ok(None); } - return Ok(Some((be(&head, 6, 2) as usize).saturating_mul(be(&head, 8, 2) as usize))); + let (ni, nj) = (be(&head, 6, 2) as usize, be(&head, 8, 2) as usize); + // A quasi-regular grid's missing length: the decoder says why it isn't read. + if ni == 0xffff || nj == 0xffff { + return Ok(None); + } + return Ok(Some(ni.saturating_mul(nj))); } let (mut at, mut points, mut total) = (start + 16, 0usize, 0usize); // Each section's 5-octet header (a constant field's data section is no longer, just before @@ -501,7 +506,8 @@ struct Field { /// The raster of fields on one grid: north up, a whole turn of longitude from −180°. Cancel is /// looked at before each band is placed; one band's placement (at most `max_samples` values, one -/// pass) runs without a check. +/// pass) runs without a check, and so does the statistics pass `Raster::new` makes over the +/// bands. fn to_raster(fields: Vec, name: &str) -> Result { let Some(grid) = fields.first().map(|f| f.grid) else { return Err(bad("no field")) }; let (w, h) = (grid.ni, grid.nj); diff --git a/crates/data/src/raster/grib_tests.rs b/crates/data/src/raster/grib_tests.rs index e06f74c9ae..63ed92d5ed 100644 --- a/crates/data/src/raster/grib_tests.rs +++ b/crates/data/src/raster/grib_tests.rs @@ -575,6 +575,27 @@ fn scale_factors_past_f64_are_damage() { assert!(e.contains("damaged (a binary scale factor its values can't take)"), "{e}"); } +#[test] +fn clean_input_says_nothing() { + // A GRIB2 field on WGS 84 (shape 5), whole numbers in 12 bits, no bitmap: no notice. + let msg = grib2_message(&[F2::new(2, 2, vec![1, 2, 3, 4])]); + let mut msg = msg; + // Section 3 starts after section 0 (16) and section 1 (21); its shape of the earth is octet 15. + msg[16 + 21 + 14] = 5; + let r = read_bytes(&msg, "t").unwrap(); + assert!(r.lost.is_empty(), "{:?}", r.lost); + assert!(r.rounded.is_empty()); +} + +#[test] +fn a_grib1_quasi_regular_grid_is_said_as_such() { + let mut g = G1::new(2, 1, vec![1, 2]).bytes(); + // Ni (GDS octets 7 and 8, after the 8-octet indicator and the 28-octet product section). + g[8 + 28 + 6..8 + 28 + 8].copy_from_slice(&[0xff, 0xff]); + let e = read_bytes(&g, "t").unwrap_err().to_string(); + assert!(e.contains("quasi-regular grids"), "{e}"); +} + #[test] fn points_in_counts_a_last_constant_field() { // A constant field's data section is 5 octets, just before "7777". From 275450e957ec87aef9fb331643caa0d2ac6b4653 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 19 Nov 2026 18:51:25 -0300 Subject: [PATCH 08/17] fix(data): GRIB review round 7 (#2428) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A message whose length runs past the end of the file no longer stops the read: the search goes on from inside it, so a message after it is still read (and this one said as damaged); with none, the file ends inside it, as before. - A grid whose last column repeats the first, 360° on (0° to 360° inclusive), is a whole turn: the repeated column is left out with a notice, and the globe is laid out from -180°. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/raster/grib.rs | 43 ++++++++++++++++++++++++---- crates/data/src/raster/grib_tests.rs | 33 +++++++++++++++++++++ docs/user-guide/data-formats.md | 2 +- 3 files changed, 72 insertions(+), 6 deletions(-) diff --git a/crates/data/src/raster/grib.rs b/crates/data/src/raster/grib.rs index e4f8a75e17..458e0c07d2 100644 --- a/crates/data/src/raster/grib.rs +++ b/crates/data/src/raster/grib.rs @@ -66,12 +66,24 @@ pub fn read(mut source: R, name: &str) -> Result { // Whether the bytes before the next "GRIB" are the rest of a message left out (whose length // isn't known), rather than something outside the messages. let mut in_skipped = false; + // Whether the last message found said it runs past the end of the file: cut short, unless + // another message follows it (its length is then damaged). + let mut overrun = false; loop { let (found, junk) = find_message(&mut source, at, file_len, &mut chunk, &mut counted)?; if !in_skipped { skipped.junk += junk; } - let Some(start) = found else { break }; + let Some(start) = found else { + if overrun { + skipped.cut += 1; + } + break; + }; + if overrun { + skipped.message("damaged".to_string()); + overrun = false; + } let (len, edition) = message_header(&mut source, start)?; in_skipped = false; match (edition, len) { @@ -93,9 +105,12 @@ pub fn read(mut source: R, name: &str) -> Result { skipped.cut += 1; break; } + // A length past the end of the file: the search goes on from inside the message, so a + // message after it is still found (and this one said as damaged); without one, the + // file ends inside it. (Some(_), len) if start.saturating_add(len) > file_len => { - skipped.cut += 1; - break; + (at, in_skipped, overrun) = (start + 4, true, true); + continue; } // A length that doesn't end on "7777" says the message wrongly: the search goes on // from inside it, so a message it would hide is still found. @@ -449,7 +464,18 @@ impl Grid { /// Whether the columns go round the whole globe. fn whole_turn(&self) -> bool { - (self.ni as f64 * self.dx - 360.0).abs() < self.dx * 0.5 + (self.columns() as f64 * self.dx - 360.0).abs() < self.dx * 0.5 + } + + /// Whether the last column is the first again, 360° on (a grid given from 0° to 360° + /// inclusive): it is left out, and the grid is a whole turn. + fn repeats_first_column(&self) -> bool { + self.ni > 1 && ((self.ni - 1) as f64 * self.dx - 360.0).abs() < self.dx * 0.5 + } + + /// The columns laid out: all of them, less a last one that repeats the first. + fn columns(&self) -> usize { + if self.repeats_first_column() { self.ni - 1 } else { self.ni } } /// The column and row (north up) of the `k`th value in scanning order. @@ -483,6 +509,9 @@ impl Grid { round6(north - (self.nj.saturating_sub(1)) as f64 * self.dy), )); } + if self.repeats_first_column() { + out.push(format!("its last column repeats the first, 360° on, and is left out: {} columns are read", self.ni - 1)); + } if let Some(earth) = self.earth { out.push(format!("its earth is {earth}; latitudes and longitudes are read as WGS 84's")); } @@ -510,7 +539,7 @@ struct Field { /// bands. fn to_raster(fields: Vec, name: &str) -> Result { let Some(grid) = fields.first().map(|f| f.grid) else { return Err(bad("no field")) }; - let (w, h) = (grid.ni, grid.nj); + let (w, h) = (grid.columns(), grid.nj); let west = grid.west(); // A whole turn starting east of −180°: the column at 180° moves to the first, so the columns // run from −180°. @@ -530,6 +559,10 @@ fn to_raster(fields: Vec, name: &str) -> Result { let mut band = super::filled(w, h, f32::NAN)?; for (k, v) in f.values.iter().enumerate() { let (col, row) = grid.place(k); + // A repeated first column, 360° on, is the last (west to east); it isn't laid out. + if col >= w { + continue; + } let col = (col + roll) % w.max(1); if let Some(cell) = band.get_mut(row * w + col) { *cell = *v; diff --git a/crates/data/src/raster/grib_tests.rs b/crates/data/src/raster/grib_tests.rs index 63ed92d5ed..80440630eb 100644 --- a/crates/data/src/raster/grib_tests.rs +++ b/crates/data/src/raster/grib_tests.rs @@ -596,6 +596,39 @@ fn a_grib1_quasi_regular_grid_is_said_as_such() { assert!(e.contains("quasi-regular grids"), "{e}"); } +#[test] +fn a_length_past_the_file_hides_nothing() { + let mut first = G1::new(2, 1, vec![1, 2]).bytes(); + let second = G1::new(2, 1, vec![3, 4]).bytes(); + // The first says it runs far past the end of the file. + first[4..7].copy_from_slice(&u(0x00ff_ffff, 3)); + let mut file = first; + file.extend(&second); + let r = read_bytes(&file, "t").unwrap(); + assert_eq!(r.bands.len(), 1); + assert_eq!(r.bands[0].data, vec![3.0, 4.0]); + assert!(r.lost.contains(&"1 message left out: damaged".to_string()), "{:?}", r.lost); + assert!(!r.lost.iter().any(|l| l.contains("ends inside")), "{:?}", r.lost); +} + +#[test] +fn a_repeated_first_column_is_left_out_and_the_globe_laid_out_from_180() { + // 7 columns of 60° from 0° to 360°: the last is the first again. No increments given in + // the file would give the same 60° (360° / 6 intervals). + let mut g = G1::new(7, 1, vec![1, 2, 3, 4, 5, 6, 1]); + (g.lat1, g.lat2, g.lon1, g.lon2, g.di, g.dj) = (0, 0, 0, 0, 60_000, 60_000); + let r = read_bytes(&g.bytes(), "t").unwrap(); + assert_eq!(r.width, 6); + // From −180°: the 180° column first. + assert_eq!(r.bands[0].data, vec![4.0, 5.0, 6.0, 1.0, 2.0, 3.0]); + assert_eq!(r.transform.origin_x, -210.0); + assert!( + r.lost.contains(&"its last column repeats the first, 360° on, and is left out: 6 columns are read".to_string()), + "{:?}", + r.lost + ); +} + #[test] fn points_in_counts_a_last_constant_field() { // A constant field's data section is 5 octets, just before "7777". diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 278048a171..2a27b3b3e1 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -646,7 +646,7 @@ databases](data.md#sql-queries-and-duckdb-databases). | Scans with no coordinates | an untagged `.tif` or `.png`, or a PDF page without coordinates; any `.tif`, `.png`, `.jpg`/`.jpeg` or `.pdf` with `"as": "scan"` | Add Data, or upload (`layer.addData`, `layer.addDataBytes`) | Grey or RGB(A), 8- or 16-bit pixels. An untagged TIFF or PNG opens as a scan by default; a JPEG needs `"as": "scan"` (otherwise it is a photo). `"as": "scan"` also discards a GeoTIFF's coordinates. A world file beside a TIFF, PNG or JPEG (`.tfw`, `.jgw`, `.pgw`, the four-letter `.tifw`, `.jpgw`, `.pngw`, or `.wld`), with a `.prj` beside it for the coordinate system, places it instead (a JPEG too, which is then not a photo): a turned or skewed one is resampled north up; without a `.prj`, with one RustGIS can't use, or with a world file that can't be read or places the picture nowhere it can be drawn (UTM meters with a longitude/latitude `.prj`), it stays a scan and a notice says why. `"as": "scan"` passes the world file over. World files are read for files added by their path (an upload doesn't bring the files beside it). A project reopens a picture as it was added: one that opened as a scan stays one (add it again once its `.prj` is there), and one a world file placed still opens if its `.prj` or world file is gone, at a stand-in place, with a notice saying it has no coordinates now. A world file is compared with a GeoTIFF's own tags only when both are north up (a turned GeoTIFF is resampled as it is read). A GeoTIFF keeps its own tags, and a notice says when a world file places it differently. The scan initially covers the current view and is marked not georeferenced (`georeferenced: false`) until **Georeference** places it. Export and tools needing ground coordinates refuse it until then. PNG/JPEG decoding is bounded and may reduce the image; large TIFFs can be read at reduced resolution. | | ASCII grid | `.asc` (with an optional `.prj` on desktop) | Add Data, or upload | A single numeric band with square `CELLSIZE` or separate `DX` and `DY` pixel sizes. Desktop files use the neighbouring `.prj`; uploaded and downloaded grids have no sidecar and must have coordinates that fit WGS 84 longitude/latitude. A grid with no `.prj` is read as WGS 84, and a notice says so. | | Zarr | a store's folder (`.zarr`, desktop) or web address (desktop and browser), format 2 (consolidated) or 3 | Home › Add › Add Data › Zarr… (`layer.addZarr`), Add Data on a local folder, or a `?zarr=` link | A variable's latitude/longitude (or y/x) map at the steps picked of its other dimensions (time, level), read chunk by chunk in pure Rust (blosc, zlib, gzip, zstd, LZ4; sharded arrays too). See [Zarr stores](data.md#zarr-stores). | -| GRIB | `.grb`, `.grib`, `.grb2`, `.grib2` | Add Data, or upload | Weather and climate model output, editions 1 and 2, read in pure Rust: each field on the grid of the first one read is a band, named from its message (`d=2026111800:kpds5=61:…` in GRIB1, as wgrib's inventories write it; discipline, category, number and surface in GRIB2). Simple packing on regular latitude/longitude grids, with bitmaps (masked points have no value), in any scanning order, laid out north up and, round the whole globe, from −180°. Values are in the file's units (kelvin stays kelvin). Other packings (complex, JPEG 2000, PNG) and grids are left out with a notice naming them; fields on another grid are left out with a count. A sphere's or another earth's latitudes and longitudes are read as WGS 84's, and a notice says so. | +| GRIB | `.grb`, `.grib`, `.grb2`, `.grib2` | Add Data, or upload | Weather and climate model output, editions 1 and 2, read in pure Rust: each field on the grid of the first one read is a band, named from its message (`d=2026111800:kpds5=61:…` in GRIB1, as wgrib's inventories write it; discipline, category, number and surface in GRIB2). Simple packing on regular latitude/longitude grids, with bitmaps (masked points have no value), in any scanning order, laid out north up and, round the whole globe, from −180° (a last column that repeats the first, 360° on, is left out with a notice). Values are in the file's units (kelvin stays kelvin). Other packings (complex, JPEG 2000, PNG) and grids are left out with a notice naming them; fields on another grid are left out with a count. A sphere's or another earth's latitudes and longitudes are read as WGS 84's, and a notice says so. | | Rasters GDAL reads | `.img`, `.hgt`, `.dem`, `.dt0`–`.dt2`, `.nc`, `.nc4`, `.hdf`, `.hdf5`, `.h5`, `.he5`, `.bil`, `.bsq`, `.bip`, `.envi`, `.grd`, `.rst`, `.sdat`, `.kea`, `.ers`, `.ntf`, `.nitf`, `.ecw`, `.sid`, `.gsb`, `.bt`, `.rsw` | Add Data (desktop, with [GDAL](https://gdal.org): `gdal_translate`, `gdalinfo` and `gdalwarp`; the installed build must include the driver) | Converted once to a cached cloud-optimised GeoTIFF. NetCDF/HDF variables are subdatasets: the first is added, the others named in a notice; `"layer"` picks one. Without a declared coordinate system, longitude/latitude-like coordinates use WGS 84 (0–360° longitudes are moved to −180–180°) and a notice says so, every time the file is read, not only when it is added; otherwise give `"crs"`. JPEG 2000 is listed separately above. | For GDAL subdatasets, the notice counts the other variables, names at most the first 20, and From 34d07c677a7763dd4640cbca9acf7ef40c908dac Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 19 Nov 2026 19:27:55 -0300 Subject: [PATCH 09/17] fix(data): GRIB review round 8 (#2428) - A GRIB1 message on a grid this reader refuses (predefined, a type other than latitude/longitude, quasi-regular) is left out from its headers, with the decoder's words, before its body is read. - GRIB2 section walks stop at 1024 sections: a message of more is said as damaged and left out unread. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/raster/grib.rs | 84 ++++++++++++++++++++++------ crates/data/src/raster/grib_tests.rs | 55 ++++++++++++++++-- 2 files changed, 118 insertions(+), 21 deletions(-) diff --git a/crates/data/src/raster/grib.rs b/crates/data/src/raster/grib.rs index 458e0c07d2..4a5d98976b 100644 --- a/crates/data/src/raster/grib.rs +++ b/crates/data/src/raster/grib.rs @@ -39,6 +39,10 @@ const MAX_BITS: u32 = 32; /// The smallest a message can be: GRIB1's indicator, its shortest sections and "7777". const MIN_MESSAGE: u64 = 8 + 28 + 11 + 4; +/// The most sections a GRIB2 message is walked through: a real one has about eight a field, and +/// a message of more (sections of five octets, from a damaged or hostile file) is left out. +const MAX_SECTIONS: usize = 1024; + fn bad(m: impl std::fmt::Display) -> DataError { DataError::Format(format!("GRIB: {m}")) } @@ -127,9 +131,23 @@ pub fn read(mut source: R, name: &str) -> Result { // Past the memory limit, a message whose grids hold more points than are left room for, // or one larger than those points can take (at most 32 bits each, a bitmap and a megabyte // of sections): only counted, never read. + // What the headers say, before the body is read: a grid this reader refuses, or too many + // sections, leaves the message out unread. + let header = header(&mut source, start, len, edition == Some(2))?; + match header { + Header::Refused(why) => { + skipped.add(why); + continue; + } + Header::TooManySections => { + skipped.message(format!("damaged (more than {MAX_SECTIONS} sections)")); + continue; + } + Header::Points(_) | Header::Unknown => {} + } let room = limit.saturating_sub(held); let too_long = len > (room as u64).saturating_mul(5).saturating_add(1 << 20); - if held >= limit || too_long || points_in(&mut source, start, len, edition == Some(2))?.is_some_and(|n| n > room) { + if held >= limit || too_long || matches!(header, Header::Points(n) if n > room) { skipped.over_limit += count_fields(&mut source, start, len, edition == Some(2))?; continue; } @@ -249,10 +267,22 @@ impl Counted { } } -/// How many points a message's fields cover, from its headers alone (GRIB1's grid description, -/// GRIB2's number of data points of the grid each data section follows); `None` when they don't -/// say (a predefined grid), which the decoder then refuses or reads. -fn points_in(source: &mut R, start: u64, len: u64, grib2: bool) -> Result> { +/// What a message's headers say before its body is read. +#[derive(Debug, PartialEq)] +enum Header { + /// How many points its fields cover (GRIB1's grid description, GRIB2's number of data points + /// of the grid each data section follows). + Points(usize), + /// Headers the decoder will find damaged: it says why. + Unknown, + /// A GRIB1 grid this reader doesn't read, with the reason the decoder gives. + Refused(String), + /// A GRIB2 message of more than [`MAX_SECTIONS`] sections. + TooManySections, +} + +/// A message's [`Header`], from its headers alone. +fn header(source: &mut R, start: u64, len: u64, grib2: bool) -> Result
{ let end = start + len; let mut head = [0u8; 16]; let read = |source: &mut R, at: u64, out: &mut [u8]| -> Result { @@ -264,22 +294,29 @@ fn points_in(source: &mut R, start: u64, len: u64, grib2: bool) Ok(true) }; if !grib2 { - // The product definition's length and flags, then the grid description's sizes. - if !read(source, start + 8, &mut head[..8])? || head[7] & 0x80 == 0 { - return Ok(None); + // The product definition's length, grid number and flags, then the grid description's + // type and sizes: the same refusals as `grib1` and `grib1_grid`, in the same words. + if !read(source, start + 8, &mut head[..8])? { + return Ok(Header::Unknown); + } + if head[7] & 0x80 == 0 { + return Ok(Header::Refused(format!("predefined grids (grid {})", head[6]))); } let gds = start + 8 + u64::from(be(&head, 0, 3)); - if !read(source, gds, &mut head[..10])? || head[5] != 0 { - return Ok(None); + if !read(source, gds, &mut head[..10])? { + return Ok(Header::Unknown); + } + let kind = head[5]; + if kind != 0 { + return Ok(Header::Refused(format!("GRIB1 grids of data representation type {kind} (not latitude/longitude)"))); } let (ni, nj) = (be(&head, 6, 2) as usize, be(&head, 8, 2) as usize); - // A quasi-regular grid's missing length: the decoder says why it isn't read. - if ni == 0xffff || nj == 0xffff { - return Ok(None); + if ni == 0xffff || nj == 0xffff || ni == 0 || nj == 0 { + return Ok(Header::Refused("quasi-regular grids".to_string())); } - return Ok(Some(ni.saturating_mul(nj))); + return Ok(Header::Points(ni.saturating_mul(nj))); } - let (mut at, mut points, mut total) = (start + 16, 0usize, 0usize); + let (mut at, mut points, mut total, mut sections) = (start + 16, 0usize, 0usize, 0usize); // Each section's 5-octet header (a constant field's data section is no longer, just before // "7777"), and the grid's number of data points (octets 7 to 10) when it is section 3. while read(source, at, &mut head[..5])? && &head[..4] != b"7777" { @@ -287,6 +324,10 @@ fn points_in(source: &mut R, start: u64, len: u64, grib2: bool) if size < 5 { break; } + sections += 1; + if sections > MAX_SECTIONS { + return Ok(Header::TooManySections); + } let mut count = [0u8; 4]; match head[4] { 3 if read(source, at + 6, &mut count)? => points = be(&count, 0, 4) as usize, @@ -295,7 +336,7 @@ fn points_in(source: &mut R, start: u64, len: u64, grib2: bool) } at += size; } - Ok(Some(total)) + Ok(Header::Points(total)) } /// How many fields a message holds: one in GRIB1, one a data section (7) in GRIB2, counted from @@ -305,7 +346,10 @@ fn count_fields(source: &mut R, start: u64, len: u64, grib2: boo return Ok(1); } let (mut at, end, mut n) = (start + 16, start + len, 0usize); - while at + 5 <= end { + for _ in 0..MAX_SECTIONS { + if at + 5 > end { + break; + } source.seek(SeekFrom::Start(at))?; let mut head = [0u8; 5]; source.read_exact(&mut head)?; @@ -830,7 +874,13 @@ fn grib2(b: &[u8], room: usize) -> Vec> { let mut bitmap: Option, Skip>> = None; let mut previous_bitmap: Option<&[u8]> = None; let mut held = 0usize; + let mut sections = 0usize; while b.get(at..at + 4).is_some_and(|m| m != b"7777") { + sections += 1; + if sections > MAX_SECTIONS { + out.push(Err(Skip::Damaged(format!("a message of more than {MAX_SECTIONS} sections")))); + break; + } let Some((number, s)) = section2(b, at) else { out.push(Err(Skip::Damaged("a damaged GRIB2 section".to_string()))); break; diff --git a/crates/data/src/raster/grib_tests.rs b/crates/data/src/raster/grib_tests.rs index 80440630eb..b0fadd1c9c 100644 --- a/crates/data/src/raster/grib_tests.rs +++ b/crates/data/src/raster/grib_tests.rs @@ -630,13 +630,60 @@ fn a_repeated_first_column_is_left_out_and_the_globe_laid_out_from_180() { } #[test] -fn points_in_counts_a_last_constant_field() { +fn header_counts_a_last_constant_field() { // A constant field's data section is 5 octets, just before "7777". let mut c = F2::new(3, 2, vec![]); c.bits = 0; let msg = grib2_message(&[F2::new(2, 1, vec![1, 2]), c]); - let n = points_in(&mut std::io::Cursor::new(&msg), 0, msg.len() as u64, true).unwrap(); - assert_eq!(n, Some(2 + 6)); + let n = header(&mut std::io::Cursor::new(&msg), 0, msg.len() as u64, true).unwrap(); + assert_eq!(n, Header::Points(2 + 6)); let one = G1::new(4, 3, vec![0; 12]).bytes(); - assert_eq!(points_in(&mut std::io::Cursor::new(&one), 0, one.len() as u64, false).unwrap(), Some(12)); + assert_eq!(header(&mut std::io::Cursor::new(&one), 0, one.len() as u64, false).unwrap(), Header::Points(12)); +} + +#[test] +fn grib1_grids_refused_from_the_headers() { + let at = |g: &[u8]| header(&mut std::io::Cursor::new(g), 0, g.len() as u64, false).unwrap(); + // A Gaussian grid (data representation type 4), in the decoder's words. + let mut g = G1::new(2, 1, vec![1, 2]).bytes(); + g[8 + 28 + 5] = 4; + assert_eq!(at(&g), Header::Refused("GRIB1 grids of data representation type 4 (not latitude/longitude)".to_string())); + let e = read_bytes(&g, "t").unwrap_err().to_string(); + assert!(e.contains("1 field left out: GRIB1 grids of data representation type 4 (not latitude/longitude), not read yet"), "{e}"); + // No grid description: a predefined grid, by its number (octet 7 of the product section). + let mut g = G1::new(2, 1, vec![1, 2]).bytes(); + g[8 + 7] &= 0x7f; + g[8 + 6] = 3; + assert_eq!(at(&g), Header::Refused("predefined grids (grid 3)".to_string())); + // A row length missing: quasi-regular. + let mut g = G1::new(2, 1, vec![1, 2]).bytes(); + g[8 + 28 + 8..8 + 28 + 10].copy_from_slice(&[0xff, 0xff]); + assert_eq!(at(&g), Header::Refused("quasi-regular grids".to_string())); +} + +#[test] +fn a_message_of_too_many_sections_is_left_out() { + // 1100 empty local-use sections (section 2, five octets each) before a field. + let mut s1 = u(21, 4); + s1.extend([1, 0, 7, 0, 0, 2, 1, 1]); + s1.extend(u(2026, 2)); + s1.extend([11, 18, 0, 0, 0, 0, 1]); + let mut body = s1; + for _ in 0..1100 { + body.extend([0, 0, 0, 5, 2]); + } + body.extend(F2::new(2, 1, vec![1, 2]).sections()); + let mut msg = b"GRIB".to_vec(); + msg.extend([0, 0, 0, 2]); + msg.extend(u(16 + body.len() as u64 + 4, 8)); + msg.extend(body); + msg.extend(b"7777"); + assert_eq!(header(&mut std::io::Cursor::new(&msg), 0, msg.len() as u64, true).unwrap(), Header::TooManySections); + let mut file = msg; + file.extend(grib2_message(&[F2::new(2, 1, vec![3, 4])])); + let r = read_bytes(&file, "t").unwrap(); + assert_eq!(r.bands.len(), 1); + assert!(r.lost.contains(&"1 message left out: damaged (more than 1024 sections)".to_string()), "{:?}", r.lost); + // The decoder refuses one too, should it get one. + assert!(matches!(grib2(&file, usize::MAX).first(), Some(Err(Skip::Damaged(m))) if m.contains("more than 1024 sections"))); } From a837e0ae6addb0026f968785a71b18b72e67e98a Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Fri, 20 Nov 2026 12:22:37 -0300 Subject: [PATCH 10/17] fix(data): GRIB review round 9 (#2428) - A field's values are written straight into its band's vector, masked points included, so they are never held apart from it: 4 bytes a point, plus the message's bytes while it is decoded. - The memory-limit notice names a way out that exists: split the file with a GRIB tool (wgrib2 or CDO) and add its parts. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/raster/grib.rs | 113 +++++++++++++++++---------------- 1 file changed, 58 insertions(+), 55 deletions(-) diff --git a/crates/data/src/raster/grib.rs b/crates/data/src/raster/grib.rs index 4a5d98976b..4089598607 100644 --- a/crates/data/src/raster/grib.rs +++ b/crates/data/src/raster/grib.rs @@ -416,7 +416,7 @@ impl Skipped { } if self.over_limit > 0 { out.push(format!( - "{} left out: the bands read hold the most this computer keeps in memory ({limit} values); open a smaller part of the file", + "{} left out: the bands read hold the most this computer keeps in memory ({limit} values); split the file with a GRIB tool (wgrib2 or CDO) and add its parts", count(self.over_limit) )); } @@ -648,9 +648,50 @@ fn ibm(v: u32) -> f64 { sign * mantissa * 16f64.powi(exponent) } -/// `count` values of `bits` bits each from `data`, big-endian, unpacked as `(R + X × 2^E) / 10^D`; -/// with fewer bits there than that, an error. -fn unpack(data: &[u8], count: usize, bits: u32, r: f64, e: i64, d: i64) -> std::result::Result<(Vec, u64), Skip> { +/// The `points` values of a field in scanning order, written straight into one vector: the +/// `count` values `next` gives, over the points a bitmap keeps (NaN at the others), or all of +/// them without one; and how many of them `f32` changed (`next`'s second value). The values are +/// never held apart from the field, so it costs 4 bytes a point. +fn field_values( + points: usize, + mask: Option<&[u8]>, + count: usize, + mut next: impl FnMut() -> (f32, bool), +) -> std::result::Result<(Vec, u64), Skip> { + match mask { + None if count != points => return Err(Skip::Damaged("a field whose values don't fill its grid".to_string())), + Some(bits) if (bits.len() as u64) * 8 < points as u64 => { + return Err(Skip::Damaged("a bitmap shorter than its grid".to_string())); + } + _ => {} + } + let mut out = Vec::new(); + out.try_reserve_exact(points).map_err(|_| Skip::TooLarge)?; + let (mut rounded, mut left) = (0u64, count); + for k in 0..points { + let kept = mask.is_none_or(|bits| bits.get(k / 8).is_some_and(|b| b & (0x80 >> (k % 8)) != 0)); + if kept && left > 0 { + left -= 1; + let (v, changed) = next(); + rounded += u64::from(changed); + out.push(v); + } else { + out.push(f32::NAN); + } + } + Ok((out, rounded)) +} + +/// A field's `count` values of `bits` bits each from `data`, big-endian, unpacked as +/// `(R + X × 2^E) / 10^D` in `f64` and held as `f32`, over the `points` of its grid +/// ([`field_values`]); with fewer bits there than that, an error. +fn unpack( + data: &[u8], + (count, bits): (usize, u32), + (r, e, d): (f64, i64, i64), + mask: Option<&[u8]>, + points: usize, +) -> std::result::Result<(Vec, u64), Skip> { if bits > MAX_BITS { return Err(Skip::Other(format!("values of {bits} bits"))); } @@ -666,24 +707,16 @@ fn unpack(data: &[u8], count: usize, bits: u32, r: f64, e: i64, d: i64) -> std:: if !top.is_finite() { return Err(Skip::Damaged("a binary scale factor its values can't take".to_string())); } - let mut out = Vec::new(); - out.try_reserve_exact(count).map_err(|_| Skip::TooLarge)?; - let mut rounded = 0u64; let mut bit = 0u64; - for _ in 0..count { + field_values(points, mask, count, || { // The 8 octets from the value's first: at most 7 bits before it, and its 32 at most. let byte = (bit / 8) as usize; let word = (0..8).fold(0u64, |w, i| (w << 8) | u64::from(data.get(byte + i).copied().unwrap_or(0))); let x = (word << (bit % 8)) >> (64 - bits); bit += u64::from(bits); let v = (r + x as f64 * scale) / ten; - if f64::from(v as f32) != v { - rounded += 1; - } - // Unpacked in `f64` and held as `f32`, never both for the whole field. - out.push(v as f32); - } - Ok((out, rounded)) + (v as f32, f64::from(v as f32) != v) + }) } /// 10^`d`, the decimal scale factor's divisor; damage when `f64` can't hold it (every value @@ -693,36 +726,10 @@ fn decimal(d: i64) -> std::result::Result { if ten.is_finite() && ten > 0.0 { Ok(ten) } else { Err(Skip::Damaged("a decimal scale factor its values can't take".to_string())) } } -/// `count` copies of `v`, and how many of them `f32` changes: a field packed in no bits holds its -/// reference value everywhere. -fn constant(v: f64, count: usize) -> std::result::Result<(Vec, u64), Skip> { - let mut out = Vec::new(); - out.try_reserve_exact(count).map_err(|_| Skip::TooLarge)?; - out.resize(count, v as f32); - Ok((out, if f64::from(v as f32) != v { count as u64 } else { 0 })) -} - -/// Values in scanning order: those unpacked, spread over the points a bitmap keeps (NaN at the -/// others), or all of them without one. -fn spread(values: Vec, bitmap: Option<&[u8]>, points: usize) -> std::result::Result, Skip> { - let Some(bits) = bitmap else { - // Without a bitmap, the values are the field as they are. - if values.len() != points { - return Err(Skip::Damaged("a field whose values don't fill its grid".to_string())); - } - return Ok(values); - }; - if (bits.len() as u64) * 8 < points as u64 { - return Err(Skip::Damaged("a bitmap shorter than its grid".to_string())); - } - let mut out = Vec::new(); - out.try_reserve_exact(points).map_err(|_| Skip::TooLarge)?; - let mut values = values.into_iter(); - for k in 0..points { - let set = bits.get(k / 8).is_some_and(|b| b & (0x80 >> (k % 8)) != 0); - out.push(if set { values.next().unwrap_or(f32::NAN) } else { f32::NAN }); - } - Ok(out) +/// A field packed in no bits: its reference value `v` at every point a bitmap keeps +/// ([`field_values`]). +fn constant(v: f64, count: usize, mask: Option<&[u8]>, points: usize) -> std::result::Result<(Vec, u64), Skip> { + field_values(points, mask, count, || (v as f32, f64::from(v as f32) != v)) } /// `n` bitmap bits set among the first `points`. @@ -796,8 +803,9 @@ fn grib1(b: &[u8], room: usize) -> std::result::Result { let bits = u32::from(bds.get(10).copied().unwrap_or(0)); let count = bitmap.map_or(points, |m| kept(m, points)); let data = bds.get(11..).unwrap_or_default(); - let (values, rounded) = if bits == 0 { constant(r / decimal(d)?, count)? } else { unpack(data, count, bits, r, e, d)? }; - Ok(Field { name, grid, values: spread(values, bitmap, points)?, rounded }) + let (values, rounded) = + if bits == 0 { constant(r / decimal(d)?, count, bitmap, points)? } else { unpack(data, (count, bits), (r, e, d), bitmap, points)? }; + Ok(Field { name, grid, values, rounded }) } /// A GRIB1 grid description section: a regular latitude/longitude grid only. @@ -921,17 +929,12 @@ fn grib2(b: &[u8], room: usize) -> Vec> { return Err(Skip::Damaged("a field whose values don't fill its grid".to_string())); } let (values, rounded) = if bits == 0 { - constant(r / decimal(d)?, count)? + constant(r / decimal(d)?, count, mask, points)? } else { - unpack(s.get(5..).unwrap_or_default(), count, bits, r, e, d)? + unpack(s.get(5..).unwrap_or_default(), (count, bits), (r, e, d), mask, points)? }; held += points; - Ok(Field { - name: format!("{reference}:discipline={discipline}:{product}"), - grid, - values: spread(values, mask, points)?, - rounded, - }) + Ok(Field { name: format!("{reference}:discipline={discipline}:{product}"), grid, values, rounded }) })(); out.push(field); } From f9dae537e6b1d5e1c93baabb37f0c9502248e3f6 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Fri, 20 Nov 2026 14:26:54 -0300 Subject: [PATCH 11/17] fix(data): GRIB values past f32's range have no value, and are said (#2428) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A value past the range of 32-bit floats (about ±3.4 × 10^38) became an infinity held in the band and was counted as rounded. It now has no value (NaN), is left out of the rounded count, and the raster says how many values were past the range. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/raster/grib.rs | 52 ++++++++++++++++++---------- crates/data/src/raster/grib_tests.rs | 19 ++++++++++ 2 files changed, 52 insertions(+), 19 deletions(-) diff --git a/crates/data/src/raster/grib.rs b/crates/data/src/raster/grib.rs index 4089598607..0b139cf399 100644 --- a/crates/data/src/raster/grib.rs +++ b/crates/data/src/raster/grib.rs @@ -575,6 +575,8 @@ struct Field { values: Vec, /// Values `f32` changed: decimals (`D` > 0) and sums with more digits than it holds. rounded: u64, + /// Values past `f32`'s range, which have no value. + past: u64, } /// The raster of fields on one grid: north up, a whole turn of longitude from −180°. Cancel is @@ -597,6 +599,7 @@ fn to_raster(fields: Vec, name: &str) -> Result { let origin_y = grid.north() + grid.dy / 2.0; let mut names = Vec::with_capacity(fields.len()); let mut rounded = Vec::with_capacity(fields.len()); + let mut past = 0u64; let mut bands = Vec::with_capacity(fields.len()); for f in fields { crate::progress::check()?; @@ -614,6 +617,7 @@ fn to_raster(fields: Vec, name: &str) -> Result { } names.push(f.name); rounded.push(f.rounded); + past += f.past; bands.push(band); } let size = |n: usize| u32::try_from(n).map_err(|_| bad("the grid is too large")); @@ -625,6 +629,10 @@ fn to_raster(fields: Vec, name: &str) -> Result { if rounded.iter().any(|n| *n > 0) { r.rounded = rounded; } + if past > 0 { + let (what, has) = if past == 1 { ("1 value".to_string(), "has") } else { (format!("{past} values"), "have") }; + r.lost.push(format!("{what} past the range of 32-bit floats (±3.4 × 10^38) {has} no value")); + } Ok(r) } @@ -649,15 +657,16 @@ fn ibm(v: u32) -> f64 { } /// The `points` values of a field in scanning order, written straight into one vector: the -/// `count` values `next` gives, over the points a bitmap keeps (NaN at the others), or all of -/// them without one; and how many of them `f32` changed (`next`'s second value). The values are -/// never held apart from the field, so it costs 4 bytes a point. +/// `count` values `next` gives (in `f64`), held as `f32`, over the points a bitmap keeps (NaN at +/// the others), or all of them without one. Also how many of them `f32` rounded, and how many +/// are past its range (about ±3.4 × 10^38): those have no value (NaN) rather than an infinity. +/// The values are never held apart from the field, so it costs 4 bytes a point. fn field_values( points: usize, mask: Option<&[u8]>, count: usize, - mut next: impl FnMut() -> (f32, bool), -) -> std::result::Result<(Vec, u64), Skip> { + mut next: impl FnMut() -> f64, +) -> std::result::Result<(Vec, u64, u64), Skip> { match mask { None if count != points => return Err(Skip::Damaged("a field whose values don't fill its grid".to_string())), Some(bits) if (bits.len() as u64) * 8 < points as u64 => { @@ -667,19 +676,25 @@ fn field_values( } let mut out = Vec::new(); out.try_reserve_exact(points).map_err(|_| Skip::TooLarge)?; - let (mut rounded, mut left) = (0u64, count); + let (mut rounded, mut past, mut left) = (0u64, 0u64, count); for k in 0..points { let kept = mask.is_none_or(|bits| bits.get(k / 8).is_some_and(|b| b & (0x80 >> (k % 8)) != 0)); if kept && left > 0 { left -= 1; - let (v, changed) = next(); - rounded += u64::from(changed); - out.push(v); + let wide = next(); + let v = wide as f32; + if v.is_infinite() && wide.is_finite() { + past += 1; + out.push(f32::NAN); + } else { + rounded += u64::from(f64::from(v) != wide); + out.push(v); + } } else { out.push(f32::NAN); } } - Ok((out, rounded)) + Ok((out, rounded, past)) } /// A field's `count` values of `bits` bits each from `data`, big-endian, unpacked as @@ -691,7 +706,7 @@ fn unpack( (r, e, d): (f64, i64, i64), mask: Option<&[u8]>, points: usize, -) -> std::result::Result<(Vec, u64), Skip> { +) -> std::result::Result<(Vec, u64, u64), Skip> { if bits > MAX_BITS { return Err(Skip::Other(format!("values of {bits} bits"))); } @@ -714,8 +729,7 @@ fn unpack( let word = (0..8).fold(0u64, |w, i| (w << 8) | u64::from(data.get(byte + i).copied().unwrap_or(0))); let x = (word << (bit % 8)) >> (64 - bits); bit += u64::from(bits); - let v = (r + x as f64 * scale) / ten; - (v as f32, f64::from(v as f32) != v) + (r + x as f64 * scale) / ten }) } @@ -728,8 +742,8 @@ fn decimal(d: i64) -> std::result::Result { /// A field packed in no bits: its reference value `v` at every point a bitmap keeps /// ([`field_values`]). -fn constant(v: f64, count: usize, mask: Option<&[u8]>, points: usize) -> std::result::Result<(Vec, u64), Skip> { - field_values(points, mask, count, || (v as f32, f64::from(v as f32) != v)) +fn constant(v: f64, count: usize, mask: Option<&[u8]>, points: usize) -> std::result::Result<(Vec, u64, u64), Skip> { + field_values(points, mask, count, || v) } /// `n` bitmap bits set among the first `points`. @@ -803,9 +817,9 @@ fn grib1(b: &[u8], room: usize) -> std::result::Result { let bits = u32::from(bds.get(10).copied().unwrap_or(0)); let count = bitmap.map_or(points, |m| kept(m, points)); let data = bds.get(11..).unwrap_or_default(); - let (values, rounded) = + let (values, rounded, past) = if bits == 0 { constant(r / decimal(d)?, count, bitmap, points)? } else { unpack(data, (count, bits), (r, e, d), bitmap, points)? }; - Ok(Field { name, grid, values, rounded }) + Ok(Field { name, grid, values, rounded, past }) } /// A GRIB1 grid description section: a regular latitude/longitude grid only. @@ -928,13 +942,13 @@ fn grib2(b: &[u8], room: usize) -> Vec> { if mask.is_some_and(|m| kept(m, points) != count) || (mask.is_none() && count != points) { return Err(Skip::Damaged("a field whose values don't fill its grid".to_string())); } - let (values, rounded) = if bits == 0 { + let (values, rounded, past) = if bits == 0 { constant(r / decimal(d)?, count, mask, points)? } else { unpack(s.get(5..).unwrap_or_default(), (count, bits), (r, e, d), mask, points)? }; held += points; - Ok(Field { name: format!("{reference}:discipline={discipline}:{product}"), grid, values, rounded }) + Ok(Field { name: format!("{reference}:discipline={discipline}:{product}"), grid, values, rounded, past }) })(); out.push(field); } diff --git a/crates/data/src/raster/grib_tests.rs b/crates/data/src/raster/grib_tests.rs index b0fadd1c9c..5e5cc8a0e4 100644 --- a/crates/data/src/raster/grib_tests.rs +++ b/crates/data/src/raster/grib_tests.rs @@ -687,3 +687,22 @@ fn a_message_of_too_many_sections_is_left_out() { // The decoder refuses one too, should it get one. assert!(matches!(grib2(&file, usize::MAX).first(), Some(Err(Skip::Damaged(m))) if m.contains("more than 1024 sections"))); } + +#[test] +fn values_past_f32_are_said_not_rounded() { + // E = 130: 1 × 2^130 is past f32's range; 0 isn't. + let mut g = G1::new(2, 1, vec![0, 1]); + g.e = 130; + let r = read_bytes(&g.bytes(), "t").unwrap(); + let v = &r.bands[0].data; + assert_eq!(v[0], 0.0); + assert!(v[1].is_nan(), "{v:?}"); + assert!(r.rounded.is_empty(), "{:?}", r.rounded); + assert!(r.lost.contains(&"1 value past the range of 32-bit floats (±3.4 × 10^38) has no value".to_string()), "{:?}", r.lost); + // A constant field whose reference value is past it (IBM 16^60). + let mut c = G1::new(2, 1, vec![]); + (c.bits, c.r) = (0, 0x7c10_0000); + let r = read_bytes(&c.bytes(), "t").unwrap(); + assert!(r.bands[0].data.iter().all(|v| v.is_nan())); + assert!(r.lost.contains(&"2 values past the range of 32-bit floats (±3.4 × 10^38) have no value".to_string()), "{:?}", r.lost); +} From eafaca613161ad405a03ba919367ff7151a60a4f Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Fri, 20 Nov 2026 18:33:43 -0300 Subject: [PATCH 12/17] fix(data): GRIB review round 10 (#2428) CodeRabbit's first full review, and the four claude-review threads: - Values: E is no longer clamped (2^E / 10^D made in steps past f64's exponents); each value is judged as it is made, with a sum past f64 that the division brings back made the other way round; a value not finite in f32 (a constant R / 10^D past f64 included) has no value and is said; a reference value that isn't a number is damage. - GRIB2: each field takes its own sections 4 to 6; one missing is damaged, never read with the field before's. A bitmap section without its indicator is damage, as are GRIB1 bitmap and data sections shorter than their fixed octets. - A message whose sections end on "7777" before its length does is damaged, and the search goes on inside it, so the message it hides is read. The preflight admits a message when its smallest field fits. - Grids are compared where their points fall (BAM's latitudes laid out, any scanning order), and each band is placed by its own grid; a whole turn and a repeated column need 360 degrees within GRIB1's rounding; a span without increments is measured in the scanning direction; staggered rows (flag table 3.4 bits 5 to 8) are refused by name. - A second fixed surface is in the band name; a sidecar's no-data isn't counted as rounded (Uncounted's rule); reasons past 16 of a kind are counted together. - GRIB is known by its first bytes (io::sniff_extension), and a GRIB download is read off the frame on the desktop, as a PDF's page is. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/io.rs | 4 +- crates/data/src/raster/grib.rs | 331 +++++++++++++++++++-------- crates/data/src/raster/grib_tests.rs | 265 ++++++++++++++++++++- crates/data/src/raster/mod.rs | 11 +- crates/engine/src/cmd/raster.rs | 19 +- crates/engine/src/tests.rs | 16 ++ crates/ui-egui/src/lib.rs | 16 +- 7 files changed, 540 insertions(+), 122 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index caf0f8b1a2..884dc2e1ad 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -232,7 +232,7 @@ pub fn read_layers(file_name: &str, bytes: &[u8]) -> Result> { /// The extension of a file from its first bytes, for a download whose address doesn't say: /// GeoParquet, FlatGeobuf, GeoTIFF, a zip, a GeoPackage, an ArcGIS feature service's protocol -/// buffer answer (`pbf`), KML, GPX, GeoJSON, delimited text, JPEG 2000 or a PDF (`None` for +/// buffer answer (`pbf`), KML, GPX, GeoJSON, delimited text, JPEG 2000, a PDF or GRIB (`None` for /// anything else, such as a web page). pub fn sniff_extension(bytes: &[u8]) -> Option<&'static str> { if let Some(ext) = crate::raster::jpeg2000_extension(bytes) { @@ -258,6 +258,8 @@ pub fn sniff_extension(bytes: &[u8]) -> Option<&'static str> { [b'P', b'K', 3, 4, ..] => "zip", _ if bytes.starts_with(b"SQLite format 3\0") => "gpkg", _ if bytes.starts_with(b"%PDF-") => "pdf", + // A GRIB message of edition 1 or 2 (a byte range of a model's file starts with one). + [b'G', b'R', b'I', b'B', _, _, _, 1 | 2, ..] => "grb", // LiDAR: LAZ marks its point format's top bits. _ if crate::lidar::looks_like_las(bytes) => { if bytes.get(104).is_some_and(|f| f & 0xC0 != 0) { diff --git a/crates/data/src/raster/grib.rs b/crates/data/src/raster/grib.rs index 0b139cf399..f4f4c9b060 100644 --- a/crates/data/src/raster/grib.rs +++ b/crates/data/src/raster/grib.rs @@ -16,7 +16,7 @@ //! [`Raster::rounded`]. Points a bitmap masks are NaN. Rows are laid out north up, //! and a grid round the whole globe runs from −180° (as GDAL lays it out). -use super::{Crs, GeoTransform, Raster, max_samples}; +use super::{Crs, Exact, GeoTransform, Raster, Uncounted, max_samples}; use crate::{DataError, Result}; use std::io::{Read, Seek, SeekFrom}; @@ -53,7 +53,14 @@ pub fn read_bytes(bytes: &[u8], name: &str) -> Result { } /// Reads a GRIB file: its fields on the first readable one's grid, as bands. -pub fn read(mut source: R, name: &str) -> Result { +pub fn read(source: R, name: &str) -> Result { + read_with_nodata(source, name, None) +} + +/// [`read`], with the no-data value of a sidecar (`.aux.xml`) beside the file, whose values aren't +/// counted as rounded ([`Uncounted`]'s rule): GRIB has no no-data value of its own (a bitmap masks). +pub fn read_with_nodata(mut source: R, name: &str, sidecar_nodata: Option) -> Result { + let uncounted = Uncounted::new(None, sidecar_nodata); let file_len = source.seek(SeekFrom::End(0))?; source.seek(SeekFrom::Start(0))?; let limit = max_samples(); @@ -125,15 +132,22 @@ pub fn read(mut source: R, name: &str) -> Result { } _ => {} } + // What the headers say, before the body is read: sections that end on a "7777" before the + // message's length does say that length wrongly (it may hide the next message), so the + // search goes on from inside it, as for a length that doesn't end on "7777". + let header = header(&mut source, start, len, edition == Some(2))?; + if header == Header::WrongLength { + skipped.message("damaged".to_string()); + (at, in_skipped) = (start + 4, true); + continue; + } messages += 1; at = start + len; counted.add(len)?; - // Past the memory limit, a message whose grids hold more points than are left room for, - // or one larger than those points can take (at most 32 bits each, a bitmap and a megabyte - // of sections): only counted, never read. - // What the headers say, before the body is read: a grid this reader refuses, or too many - // sections, leaves the message out unread. - let header = header(&mut source, start, len, edition == Some(2))?; + // Past the memory limit, a message none of whose fields fits in the room left, or one + // larger than those points can take (at most 32 bits each, a bitmap and a megabyte of + // sections): only counted, never read. A grid this reader refuses, or too many sections, + // leaves the message out unread. match header { Header::Refused(why) => { skipped.add(why); @@ -143,7 +157,7 @@ pub fn read(mut source: R, name: &str) -> Result { skipped.message(format!("damaged (more than {MAX_SECTIONS} sections)")); continue; } - Header::Points(_) | Header::Unknown => {} + Header::Points(_) | Header::Unknown | Header::WrongLength => {} } let room = limit.saturating_sub(held); let too_long = len > (room as u64).saturating_mul(5).saturating_add(1 << 20); @@ -155,7 +169,7 @@ pub fn read(mut source: R, name: &str) -> Result { bytes.try_reserve_exact(len as usize).map_err(|_| bad("not enough memory for a message"))?; source.seek(SeekFrom::Start(start))?; source.by_ref().take(len).read_to_end(&mut bytes)?; - let decoded = if edition == Some(1) { vec![grib1(&bytes, room)] } else { grib2(&bytes, room) }; + let decoded = if edition == Some(1) { vec![grib1(&bytes, room, uncounted)] } else { grib2(&bytes, room, uncounted) }; for d in decoded { match d { Ok(f) => { @@ -178,12 +192,21 @@ pub fn read(mut source: R, name: &str) -> Result { if messages == 0 && skipped.messages.is_empty() { return Err(bad(if skipped.cut > 0 { "the first message is cut short" } else { "no GRIB message in the file" })); } - let Some(first) = fields.first() else { + if fields.is_empty() { return Err(bad(format!("nothing in it can be read here: {}", skipped.notes(limit).join("; ")))); - }; - let grid = first.grid; + } + // Each grid's notices, once: grids at the same places may still say different things (one + // laid out from BAM's latitudes, one not). + let mut notes: Vec = Vec::new(); + for f in &fields { + for n in f.grid.notes() { + if !notes.contains(&n) { + notes.push(n); + } + } + } let mut r = to_raster(fields, name)?; - r.lost.extend(grid.notes()); + r.lost.extend(notes); r.lost.extend(skipped.notes(limit)); Ok(r) } @@ -270,9 +293,13 @@ impl Counted { /// What a message's headers say before its body is read. #[derive(Debug, PartialEq)] enum Header { - /// How many points its fields cover (GRIB1's grid description, GRIB2's number of data points - /// of the grid each data section follows). + /// How many points the smallest of its fields covers (GRIB1's grid description, GRIB2's + /// number of data points of the grid each data section follows): when not even that one fits + /// in the room left, the message is left out unread; each of the others is admitted or not as + /// it is decoded. Points(usize), + /// Sections that end on a "7777" before the message's length does: the length is damaged. + WrongLength, /// Headers the decoder will find damaged: it says why. Unknown, /// A GRIB1 grid this reader doesn't read, with the reason the decoder gives. @@ -299,7 +326,28 @@ fn header(source: &mut R, start: u64, len: u64, grib2: bool) -> if !read(source, start + 8, &mut head[..8])? { return Ok(Header::Unknown); } - if head[7] & 0x80 == 0 { + // The sections the flags say are there (product definition, grid description, bitmap, + // binary data), by their lengths: ending on a "7777" before the message's end, the + // message's length is wrong. + let flags = head[7]; + let mut at = start + 8 + u64::from(be(&head, 0, 3)); + let mut chained = true; + for there in [flags & 0x80 != 0, flags & 0x40 != 0, true] { + if !there { + continue; + } + let mut size = [0u8; 3]; + if !read(source, at, &mut size)? || be(&size, 0, 3) < 3 { + chained = false; + break; + } + at += u64::from(be(&size, 0, 3)); + } + let mut tail = [0u8; 4]; + if chained && at + 4 < end && read(source, at, &mut tail)? && &tail == b"7777" { + return Ok(Header::WrongLength); + } + if flags & 0x80 == 0 { return Ok(Header::Refused(format!("predefined grids (grid {})", head[6]))); } let gds = start + 8 + u64::from(be(&head, 0, 3)); @@ -316,10 +364,14 @@ fn header(source: &mut R, start: u64, len: u64, grib2: bool) -> } return Ok(Header::Points(ni.saturating_mul(nj))); } - let (mut at, mut points, mut total, mut sections) = (start + 16, 0usize, 0usize, 0usize); + let (mut at, mut points, mut fewest, mut sections) = (start + 16, 0usize, None::, 0usize); // Each section's 5-octet header (a constant field's data section is no longer, just before - // "7777"), and the grid's number of data points (octets 7 to 10) when it is section 3. - while read(source, at, &mut head[..5])? && &head[..4] != b"7777" { + // "7777"), and the grid's number of data points (octets 7 to 10) when it is section 3. The + // last "7777" can't be read with a fifth octet: one that can comes before the message's end. + while read(source, at, &mut head[..5])? { + if &head[..4] == b"7777" { + return Ok(Header::WrongLength); + } let size = u64::from(be(&head, 0, 4)); if size < 5 { break; @@ -331,12 +383,12 @@ fn header(source: &mut R, start: u64, len: u64, grib2: bool) -> let mut count = [0u8; 4]; match head[4] { 3 if read(source, at + 6, &mut count)? => points = be(&count, 0, 4) as usize, - 7 => total = total.saturating_add(points), + 7 => fewest = Some(fewest.map_or(points, |n| n.min(points))), _ => {} } at += size; } - Ok(Header::Points(total)) + Ok(Header::Points(fewest.unwrap_or(0))) } /// How many fields a message holds: one in GRIB1, one a data section (7) in GRIB2, counted from @@ -430,11 +482,23 @@ impl Skipped { } } +/// The most reasons of one kind said apart: past them (a file of messages of a thousand grid +/// templates), the rest are counted under [`OTHER_REASONS`], so the list and the time spent on it +/// stay small. +const MAX_REASONS: usize = 16; + +const OTHER_REASONS: &str = "other kinds than those above"; + /// One more of `why` in `list`. fn tally(list: &mut Vec<(String, usize)>, why: String) { - match list.iter_mut().find(|(r, _)| *r == why) { - Some((_, n)) => *n += 1, - None => list.push((why, 1)), + if let Some((_, n)) = list.iter_mut().find(|(r, _)| *r == why) { + *n += 1; + } else if list.len() < MAX_REASONS { + list.push((why, 1)); + } else if let Some((_, n)) = list.iter_mut().find(|(r, _)| r == OTHER_REASONS) { + *n += 1; + } else { + list.push((OTHER_REASONS.to_string(), 1)); } } @@ -465,15 +529,17 @@ const SCAN_J_CONSECUTIVE: u8 = 0x20; const SCAN_ALTERNATE: u8 = 0x10; impl Grid { + /// Whether two grids put their points at the same places, whatever order they scan them in + /// (each band is placed by its own grid): the same sizes, increments and north-west centre, + /// after BAM's latitudes are laid out ([`Grid::north`]). fn same(&self, o: &Grid) -> bool { let close = |a: f64, b: f64| (a - b).abs() <= 1e-6; self.ni == o.ni && self.nj == o.nj - && close(self.lat1, o.lat1) - && close(self.lon1, o.lon1) + && close(self.north(), o.north()) + && close(self.west(), o.west()) && close(self.dx, o.dx) && close(self.dy, o.dy) - && self.scan == o.scan } fn goes_north(&self) -> bool { @@ -508,13 +574,13 @@ impl Grid { /// Whether the columns go round the whole globe. fn whole_turn(&self) -> bool { - (self.columns() as f64 * self.dx - 360.0).abs() < self.dx * 0.5 + (self.columns() as f64 * self.dx - 360.0).abs() <= turn_tolerance(self.columns()) } /// Whether the last column is the first again, 360° on (a grid given from 0° to 360° /// inclusive): it is left out, and the grid is a whole turn. fn repeats_first_column(&self) -> bool { - self.ni > 1 && ((self.ni - 1) as f64 * self.dx - 360.0).abs() < self.dx * 0.5 + self.ni > 1 && ((self.ni - 1) as f64 * self.dx - 360.0).abs() <= turn_tolerance(self.ni - 1) } /// The columns laid out: all of them, less a last one that repeats the first. @@ -563,6 +629,13 @@ impl Grid { } } +/// How far `n` steps of a grid's increment may come from 360° and still be a whole turn: half a +/// millidegree a step, as GRIB1 rounds increments to millidegrees (GRIB2's are finer). A grid whose +/// increment doesn't divide 360° (seven columns of 50°) isn't one. +fn turn_tolerance(n: usize) -> f64 { + n as f64 * 0.0005 + 1e-9 +} + /// `v` to a millionth, for a notice (89.91, not 89.91000000000001). fn round6(v: f64) -> f64 { (v * 1e6).round() / 1e6 @@ -604,8 +677,9 @@ fn to_raster(fields: Vec, name: &str) -> Result { for f in fields { crate::progress::check()?; let mut band = super::filled(w, h, f32::NAN)?; + // Each band by its own grid: the same places as the first's, maybe in another order. for (k, v) in f.values.iter().enumerate() { - let (col, row) = grid.place(k); + let (col, row) = f.grid.place(k); // A repeated first column, 360° on, is the last (west to east); it isn't laid out. if col >= w { continue; @@ -659,12 +733,14 @@ fn ibm(v: u32) -> f64 { /// The `points` values of a field in scanning order, written straight into one vector: the /// `count` values `next` gives (in `f64`), held as `f32`, over the points a bitmap keeps (NaN at /// the others), or all of them without one. Also how many of them `f32` rounded, and how many -/// are past its range (about ±3.4 × 10^38): those have no value (NaN) rather than an infinity. -/// The values are never held apart from the field, so it costs 4 bytes a point. +/// are past its range (about ±3.4 × 10^38, `f64`'s too): those have no value (NaN) rather than +/// an infinity. A sidecar's no-data value isn't counted either way ([`Uncounted`]'s rule). The +/// values are never held apart from the field, so it costs 4 bytes a point. fn field_values( points: usize, mask: Option<&[u8]>, count: usize, + uncounted: Uncounted, mut next: impl FnMut() -> f64, ) -> std::result::Result<(Vec, u64, u64), Skip> { match mask { @@ -683,12 +759,22 @@ fn field_values( left -= 1; let wide = next(); let v = wide as f32; - if v.is_infinite() && wide.is_finite() { - past += 1; - out.push(f32::NAN); - } else { - rounded += u64::from(f64::from(v) != wide); - out.push(v); + match uncounted.decides(v, || Some(Exact::Float(wide))) { + // The no-data value itself (masked when the sidecar is applied). + Some(true) => out.push(if v.is_finite() { v } else { f32::NAN }), + _ if !v.is_finite() => { + past += 1; + out.push(f32::NAN); + } + // A value that became the no-data value. + Some(false) => { + rounded += 1; + out.push(v); + } + None => { + rounded += u64::from(f64::from(v) != wide); + out.push(v); + } } } else { out.push(f32::NAN); @@ -706,6 +792,7 @@ fn unpack( (r, e, d): (f64, i64, i64), mask: Option<&[u8]>, points: usize, + uncounted: Uncounted, ) -> std::result::Result<(Vec, u64, u64), Skip> { if bits > MAX_BITS { return Err(Skip::Other(format!("values of {bits} bits"))); @@ -714,25 +801,42 @@ fn unpack( if (data.len() as u64) < need { return Err(Skip::Damaged("a data section shorter than its values".to_string())); } - let scale = 2f64.powi(e.clamp(-1000, 1000) as i32); let ten = decimal(d)?; - // The largest value the field can hold must be a number: past `f64`, every value would be - // infinite. - let top = (r.abs() + ((1u64 << bits) - 1) as f64 * scale) / ten; - if !top.is_finite() { - return Err(Skip::Damaged("a binary scale factor its values can't take".to_string())); - } + reference(r)?; + // 2^E, where `f64` holds it; past that (no producer writes such an E, but it is kept), and + // where `R + X × 2^E` is past `f64` but the division brings it back, the value is made as + // `R / 10^D + X × (2^E / 10^D)`. A value past `f64` either way is past `f32`'s range. + let scale = (-1000..=1000).contains(&e).then(|| 2f64.powi(e as i32)); + let (base, step) = (r / ten, times_two_to(1.0 / ten, e)); let mut bit = 0u64; - field_values(points, mask, count, || { + field_values(points, mask, count, uncounted, || { // The 8 octets from the value's first: at most 7 bits before it, and its 32 at most. let byte = (bit / 8) as usize; let word = (0..8).fold(0u64, |w, i| (w << 8) | u64::from(data.get(byte + i).copied().unwrap_or(0))); - let x = (word << (bit % 8)) >> (64 - bits); + let x = ((word << (bit % 8)) >> (64 - bits)) as f64; bit += u64::from(bits); - (r + x as f64 * scale) / ten + let wide = scale.map_or(f64::INFINITY, |s| (r + x * s) / ten); + if wide.is_finite() { + wide + } else if x == 0.0 { + base + } else { + base + x * step + } }) } +/// `v` × 2^`e`, by at most 2^±1000 at a time, so an `e` past `f64`'s exponents still gives a +/// value `v` brings back into its range. +fn times_two_to(mut v: f64, mut e: i64) -> f64 { + while e != 0 && v != 0.0 && v.is_finite() { + let s = e.clamp(-1000, 1000); + v *= 2f64.powi(s as i32); + e -= s; + } + v +} + /// 10^`d`, the decimal scale factor's divisor; damage when `f64` can't hold it (every value /// would be 0 or infinite). fn decimal(d: i64) -> std::result::Result { @@ -740,10 +844,25 @@ fn decimal(d: i64) -> std::result::Result { if ten.is_finite() && ten > 0.0 { Ok(ten) } else { Err(Skip::Damaged("a decimal scale factor its values can't take".to_string())) } } -/// A field packed in no bits: its reference value `v` at every point a bitmap keeps -/// ([`field_values`]). -fn constant(v: f64, count: usize, mask: Option<&[u8]>, points: usize) -> std::result::Result<(Vec, u64, u64), Skip> { - field_values(points, mask, count, || v) +/// A reference value that is a number: GRIB2's IEEE bits may give an infinity or NaN, which no +/// value can be made from. +fn reference(r: f64) -> std::result::Result<(), Skip> { + if r.is_finite() { Ok(()) } else { Err(Skip::Damaged("a reference value that isn't a number".to_string())) } +} + +/// A field packed in no bits: its reference value `R / 10^D` at every point a bitmap keeps +/// ([`field_values`]); past `f32`'s range, the points have no value and are said. +fn constant( + (r, d): (f64, i64), + count: usize, + mask: Option<&[u8]>, + points: usize, + uncounted: Uncounted, +) -> std::result::Result<(Vec, u64, u64), Skip> { + let ten = decimal(d)?; + reference(r)?; + let v = r / ten; + field_values(points, mask, count, uncounted, || v) } /// `n` bitmap bits set among the first `points`. @@ -766,7 +885,7 @@ fn section1(b: &[u8], at: usize) -> std::result::Result<&[u8], Skip> { } /// A GRIB1 message (WMO FM 92 GRIB edition 1): its one field. -fn grib1(b: &[u8], room: usize) -> std::result::Result { +fn grib1(b: &[u8], room: usize, uncounted: Uncounted) -> std::result::Result { let pds = section1(b, 8)?; if pds.len() < 28 { return Err(Skip::Damaged("a damaged product definition section".to_string())); @@ -796,6 +915,10 @@ fn grib1(b: &[u8], room: usize) -> std::result::Result { let mut at = gds_at + gds.len(); let bitmap = if flags & 0x40 != 0 { let bms = section1(b, at)?; + // Its length, unused bits and table reference come before the bits. + if bms.len() < 6 { + return Err(Skip::Damaged("a damaged bitmap section".to_string())); + } if be(bms, 4, 2) != 0 { return Err(Skip::Other("predefined bitmaps".to_string())); } @@ -805,7 +928,11 @@ fn grib1(b: &[u8], room: usize) -> std::result::Result { None }; let bds = section1(b, at)?; - let bds_flags = bds.get(3).copied().unwrap_or(0); + // Its flags, E, R and the bits a value come before the values (none, for a constant field). + if bds.len() < 11 { + return Err(Skip::Damaged("a damaged binary data section".to_string())); + } + let bds_flags = bds[3]; if bds_flags & 0x80 != 0 { return Err(Skip::Other("spherical harmonics".to_string())); } @@ -814,11 +941,14 @@ fn grib1(b: &[u8], room: usize) -> std::result::Result { } let e = signed(bds, 4, 2); let r = ibm(be(bds, 6, 4)); - let bits = u32::from(bds.get(10).copied().unwrap_or(0)); + let bits = u32::from(bds[10]); let count = bitmap.map_or(points, |m| kept(m, points)); let data = bds.get(11..).unwrap_or_default(); - let (values, rounded, past) = - if bits == 0 { constant(r / decimal(d)?, count, bitmap, points)? } else { unpack(data, (count, bits), (r, e, d), bitmap, points)? }; + let (values, rounded, past) = if bits == 0 { + constant((r, d), count, bitmap, points, uncounted)? + } else { + unpack(data, (count, bits), (r, e, d), bitmap, points, uncounted)? + }; Ok(Field { name, grid, values, rounded, past }) } @@ -839,27 +969,30 @@ fn grib1_grid(g: &[u8]) -> std::result::Result { let deg = |o: usize| signed(g, o, 3) as f64 / 1000.0; let (lat1, lon1, lat2, lon2) = (deg(10), deg(13), deg(17), deg(20)); let res = g[16]; + let scan = g[27]; let (di, dj) = (be(g, 23, 2), be(g, 25, 2)); let given = res & 0x80 != 0; - let dx = if given && di != 0xffff { f64::from(di) / 1000.0 } else { span(lon1, lon2, true) / (ni.saturating_sub(1)).max(1) as f64 }; - let dy = if given && dj != 0xffff { f64::from(dj) / 1000.0 } else { span(lat1, lat2, false) / (nj.saturating_sub(1)).max(1) as f64 }; + let dx = if given && di != 0xffff { f64::from(di) / 1000.0 } else { lon_span(lon1, lon2, scan) / (ni.saturating_sub(1)).max(1) as f64 }; + let dy = if given && dj != 0xffff { f64::from(dj) / 1000.0 } else { (lat2 - lat1).abs() / (nj.saturating_sub(1)).max(1) as f64 }; let earth = Some(if res & 0x40 != 0 { "the IAU 1965 spheroid (GRIB1's oblate earth)" } else { "a sphere of radius 6,367,470 m (GRIB1's)" }); - checked(Grid { ni, nj, lat1, lon1, lat2, lon2, dx, dy, scan: g[27], earth }) + checked(Grid { ni, nj, lat1, lon1, lat2, lon2, dx, dy, scan, earth }) } -/// The distance between two longitudes (eastward, wrapping) or latitudes. -fn span(a: f64, b: f64, lon: bool) -> f64 { - if lon { - let d = (b - a).rem_euclid(360.0); - if d == 0.0 { 360.0 } else { d } - } else { - (b - a).abs() - } +/// The distance from the first longitude to the last in the direction the grid scans its columns +/// (east, or west when the scanning mode says), wrapping round the globe. +fn lon_span(first: f64, last: f64, scan: u8) -> f64 { + let d = (if scan & SCAN_I_NEGATIVE != 0 { first - last } else { last - first }).rem_euclid(360.0); + if d == 0.0 { 360.0 } else { d } } /// A grid whose increments and corners are usable, or why it isn't. fn checked(g: Grid) -> std::result::Result { + // Flag table 3.4's bits 5 to 8: rows offset by half a cell, or one point short; GRIB1 leaves + // them 0. Placing such a grid's points on one grid of cells would move them. + if g.scan & 0x0f != 0 { + return Err(Skip::Other("grids whose rows are offset or shortened (scanning mode bits 5 to 8)".to_string())); + } let ok = g.dx.is_finite() && g.dy.is_finite() && g.dx > 0.0 @@ -884,14 +1017,17 @@ fn section2(b: &[u8], at: usize) -> Option<(u8, &[u8])> { (len >= 5).then(|| (s[4], s)) } -/// A GRIB2 message (WMO FM 92 GRIB edition 2): each of its fields. -fn grib2(b: &[u8], room: usize) -> Vec> { +/// A GRIB2 message (WMO FM 92 GRIB edition 2): each of its fields. A grid (section 3) may serve +/// the fields after it, but each field has its own sections 4 to 7 (WMO's regulation 92.1.3): a +/// field without its own product, packing or bitmap section is damaged, never read with the one +/// before it. +fn grib2(b: &[u8], room: usize, uncounted: Uncounted) -> Vec> { let mut out = Vec::new(); let discipline = b.get(6).copied().unwrap_or(255); let mut at = 16usize; let mut reference = String::from("d=?"); let mut grid: Option> = None; - let mut product = String::new(); + let mut product: Option = None; let mut packing: Option> = None; let mut bitmap: Option, Skip>> = None; let mut previous_bitmap: Option<&[u8]> = None; @@ -918,34 +1054,39 @@ fn grib2(b: &[u8], room: usize) -> Vec> { ); } 3 => grid = Some(grib2_grid(s)), - 4 => product = grib2_product(s), + 4 => product = Some(grib2_product(s)), 5 => packing = Some(grib2_packing(s)), 6 => { - bitmap = Some(match s.get(5).copied().unwrap_or(255) { - 255 => Ok(None), - 0 => { + bitmap = Some(match s.get(5).copied() { + None => Err(Skip::Damaged("a damaged bitmap section".to_string())), + Some(255) => Ok(None), + Some(0) => { let bits = s.get(6..).unwrap_or_default(); previous_bitmap = Some(bits); Ok(Some(bits)) } - 254 => previous_bitmap.map(Some).ok_or_else(|| Skip::Damaged("a bitmap that refers to none before it".to_string())), - _ => Err(Skip::Other("predefined bitmaps".to_string())), + Some(254) => { + previous_bitmap.map(Some).ok_or_else(|| Skip::Damaged("a bitmap that refers to none before it".to_string())) + } + Some(_) => Err(Skip::Other("predefined bitmaps".to_string())), }); } 7 => { + // This field's sections 4 to 6, taken: the next field gives its own. + let (product, packing, bitmap) = (product.take(), packing.take(), bitmap.take()); let field = (|| { let grid = grid.clone().ok_or_else(|| Skip::Damaged("a field without a grid".to_string()))??; - let (count, r, e, d, bits) = - packing.clone().ok_or_else(|| Skip::Damaged("a field without its packing".to_string()))??; - let mask = bitmap.clone().unwrap_or(Ok(None))?; + let product = product.ok_or_else(|| Skip::Damaged("a field without its product definition".to_string()))?; + let (count, r, e, d, bits) = packing.ok_or_else(|| Skip::Damaged("a field without its packing".to_string()))??; + let mask = bitmap.ok_or_else(|| Skip::Damaged("a field without its bitmap section".to_string()))??; let points = grid.ni.checked_mul(grid.nj).filter(|n| held.saturating_add(*n) <= room).ok_or(Skip::TooLarge)?; if mask.is_some_and(|m| kept(m, points) != count) || (mask.is_none() && count != points) { return Err(Skip::Damaged("a field whose values don't fill its grid".to_string())); } let (values, rounded, past) = if bits == 0 { - constant(r / decimal(d)?, count, mask, points)? + constant((r, d), count, mask, points, uncounted)? } else { - unpack(s.get(5..).unwrap_or_default(), (count, bits), (r, e, d), mask, points)? + unpack(s.get(5..).unwrap_or_default(), (count, bits), (r, e, d), mask, points, uncounted)? }; held += points; Ok(Field { name: format!("{reference}:discipline={discipline}:{product}"), grid, values, rounded, past }) @@ -1003,32 +1144,34 @@ fn grib2_grid(s: &[u8]) -> std::result::Result { // Code table 3.3: bit 3 (0x20) says the i direction's increments are given, bit 4 (0x10) // the j direction's. let res = s[54]; + let scan = s[71]; let (di, dj) = (be(s, 63, 4), be(s, 67, 4)); let dx = if res & 0x20 != 0 && di != u32::MAX { f64::from(di) * unit } else { - span(lon1, lon2, true) / (ni.saturating_sub(1)).max(1) as f64 + lon_span(lon1, lon2, scan) / (ni.saturating_sub(1)).max(1) as f64 }; - let dy = if res & 0x10 != 0 && dj != u32::MAX { - f64::from(dj) * unit - } else { - span(lat1, lat2, false) / (nj.saturating_sub(1)).max(1) as f64 - }; - checked(Grid { ni, nj, lat1, lon1, lat2, lon2, dx, dy, scan: s[71], earth }) + let dy = + if res & 0x10 != 0 && dj != u32::MAX { f64::from(dj) * unit } else { (lat2 - lat1).abs() / (nj.saturating_sub(1)).max(1) as f64 }; + checked(Grid { ni, nj, lat1, lon1, lat2, lon2, dx, dy, scan, earth }) } /// A GRIB2 product definition section, as part of a band name: the parameter's category and /// number (its discipline is section 0's), the template, and for templates 4.0 to 4.15 the first -/// fixed surface and the forecast time. +/// fixed surface, the forecast time and, for a layer between two surfaces, the second. fn grib2_product(s: &[u8]) -> String { let template = be(s, 7, 2); let (category, number) = (s.get(9).copied().unwrap_or(255), s.get(10).copied().unwrap_or(255)); let mut name = format!("category={category}:number={number}:template=4.{template}"); - // Templates 4.0 to 4.15 share these octets; the surface's value is scaled by 10^-(its scale + // Templates 4.0 to 4.15 share these octets; a surface's value is scaled by 10^-(its scale // factor). + let value = |o: usize| round6(signed(s, o + 1, 4) as f64 / 10f64.powi(signed(s, o, 1) as i32)); if template <= 15 && s.len() >= 28 { - let value = signed(s, 24, 4) as f64 / 10f64.powi(signed(s, 23, 1) as i32); - name.push_str(&format!(":surface={}:value={}:TimeU={}:forecast={}", s[22], round6(value), s[17], be(s, 18, 4))); + name.push_str(&format!(":surface={}:value={}:TimeU={}:forecast={}", s[22], value(23), s[17], be(s, 18, 4))); + // The second fixed surface (255: none). + if let Some(&second) = s.get(28).filter(|t| **t != 255 && s.len() >= 34) { + name.push_str(&format!(":surface2={second}:value2={}", value(29))); + } } // An ensemble's member (templates 4.1 and 4.11): its type and perturbation number. if matches!(template, 1 | 11) && s.len() >= 37 { diff --git a/crates/data/src/raster/grib_tests.rs b/crates/data/src/raster/grib_tests.rs index 5e5cc8a0e4..db2c12cc37 100644 --- a/crates/data/src/raster/grib_tests.rs +++ b/crates/data/src/raster/grib_tests.rs @@ -104,16 +104,24 @@ impl G1 { gds.extend([0, 0, 0, 0]); let mut body = pds; body.extend(gds); + // Sections of an even number of octets (GRIB1's rule), padded, with their unused bits said. if let Some(keep) = &self.keep { - let bits = bitmap(keep); + let mut bits = bitmap(keep); + if (6 + bits.len()) % 2 == 1 { + bits.push(0); + } let mut bms = u(6 + bits.len() as u64, 3); - bms.extend([0, 0, 0]); + bms.extend([(bits.len() * 8 - keep.len()) as u8, 0, 0]); bms.extend(bits); body.extend(bms); } - let data = pack(&self.x, self.bits); + let mut data = pack(&self.x, self.bits); + if (11 + data.len()) % 2 == 1 { + data.push(0); + } + let unused = data.len() * 8 - self.x.len() * self.bits as usize; let mut bds = u(11 + data.len() as u64, 3); - bds.push(self.bds_flags); + bds.push(self.bds_flags | (unused as u8 & 0x0f)); bds.extend(sm(self.e, 2)); bds.extend(u(u64::from(self.r), 4)); bds.push(self.bits as u8); @@ -215,7 +223,9 @@ impl F2 { s4.extend([255, 0]); s4.extend(u(0, 4)); assert_eq!(s4.len(), 34); - let count = self.keep.as_ref().map_or(self.x.len(), |k| k.iter().filter(|b| **b).count()); + // A constant field (0 bits) has no packed values, but still one a point. + let all = if self.bits == 0 { self.ni * self.nj } else { self.x.len() }; + let count = self.keep.as_ref().map_or(all, |k| k.iter().filter(|b| **b).count()); let mut s5 = u(21, 4); s5.push(5); s5.extend(u(count as u64, 4)); @@ -568,11 +578,34 @@ fn scale_factors_past_f64_are_damage() { let e = read_bytes(&g.bytes(), "t").unwrap_err().to_string(); assert!(e.contains("damaged (a decimal scale factor its values can't take)"), "{d}: {e}"); } + // Values past f64 with E = 1000: past f32's range, said (not the whole field refused). let mut g = G1::new(2, 1, vec![1, 2]); (g.e, g.bits) = (1000, 32); g.x = vec![u32::MAX, 1]; - let e = read_bytes(&g.bytes(), "t").unwrap_err().to_string(); - assert!(e.contains("damaged (a binary scale factor its values can't take)"), "{e}"); + let r = read_bytes(&g.bytes(), "t").unwrap(); + assert!(r.bands[0].data.iter().all(|v| v.is_nan())); + assert!(r.lost.contains(&"2 values past the range of 32-bit floats (±3.4 × 10^38) have no value".to_string()), "{:?}", r.lost); +} + +#[test] +fn the_values_present_are_made_whatever_their_scale_factors() { + // E = 1000 and D = 280 in 32 bits: the largest value the bits could hold is past f64, but + // 1 × 2^1000 / 10^280 and 2 × 2^1000 / 10^280 aren't. + let mut g = G1::new(2, 1, vec![1, 2]); + (g.e, g.d, g.bits) = (1000, 280, 32); + let r = read_bytes(&g.bytes(), "t").unwrap(); + let one = 2f64.powi(1000) / 1e280; + for (v, want) in r.bands[0].data.iter().zip([one, 2.0 * one]) { + assert!((f64::from(*v) / want - 1.0).abs() < 1e-6, "{v} {want}"); + } + assert!(!r.lost.iter().any(|l| l.contains("past the range")), "{:?}", r.lost); + // E = -1100 (past f64's exponents) and D = -300: 2^-1100 × 10^300, about 7.4 × 10^-32, kept. + let mut g = G1::new(2, 1, vec![1, 0]); + (g.e, g.d) = (-1100, -300); + let r = read_bytes(&g.bytes(), "t").unwrap(); + let want = 1e300 * 2f64.powi(-1000) * 2f64.powi(-100); + assert!((f64::from(r.bands[0].data[0]) / want - 1.0).abs() < 1e-6, "{:?}", r.bands[0].data); + assert_eq!(r.bands[0].data[1], 0.0); } #[test] @@ -636,7 +669,8 @@ fn header_counts_a_last_constant_field() { c.bits = 0; let msg = grib2_message(&[F2::new(2, 1, vec![1, 2]), c]); let n = header(&mut std::io::Cursor::new(&msg), 0, msg.len() as u64, true).unwrap(); - assert_eq!(n, Header::Points(2 + 6)); + // The smallest field: a message is left out unread only when not even it fits. + assert_eq!(n, Header::Points(2)); let one = G1::new(4, 3, vec![0; 12]).bytes(); assert_eq!(header(&mut std::io::Cursor::new(&one), 0, one.len() as u64, false).unwrap(), Header::Points(12)); } @@ -685,7 +719,8 @@ fn a_message_of_too_many_sections_is_left_out() { assert_eq!(r.bands.len(), 1); assert!(r.lost.contains(&"1 message left out: damaged (more than 1024 sections)".to_string()), "{:?}", r.lost); // The decoder refuses one too, should it get one. - assert!(matches!(grib2(&file, usize::MAX).first(), Some(Err(Skip::Damaged(m))) if m.contains("more than 1024 sections"))); + let first = grib2(&file, usize::MAX, Uncounted::default()); + assert!(matches!(first.first(), Some(Err(Skip::Damaged(m))) if m.contains("more than 1024 sections"))); } #[test] @@ -706,3 +741,215 @@ fn values_past_f32_are_said_not_rounded() { assert!(r.bands[0].data.iter().all(|v| v.is_nan())); assert!(r.lost.contains(&"2 values past the range of 32-bit floats (±3.4 × 10^38) have no value".to_string()), "{:?}", r.lost); } + +#[test] +fn a_constant_past_f64_is_said_and_a_reference_that_isnt_a_number_is_damage() { + // R about 10^10 (IBM 0x4925_40be) and D = −300: R / 10^D is past f64, so past f32. + let mut c = G1::new(2, 1, vec![]); + (c.bits, c.r, c.d) = (0, 0x4925_40be, -300); + let r = read_bytes(&c.bytes(), "t").unwrap(); + assert!(r.bands[0].data.iter().all(|v| v.is_nan()), "{:?}", r.bands[0].data); + assert!(r.lost.contains(&"2 values past the range of 32-bit floats (±3.4 × 10^38) have no value".to_string()), "{:?}", r.lost); + assert!(r.rounded.is_empty()); + // A GRIB2 constant field whose IEEE reference value is NaN. + let mut f = F2::new(2, 1, vec![]); + (f.bits, f.r) = (0, f32::NAN); + let e = read_bytes(&grib2_message(&[f]), "t").unwrap_err().to_string(); + assert!(e.contains("damaged (a reference value that isn't a number)"), "{e}"); + // A constant GRIB2 field that is a number reads as one. + let mut f = F2::new(2, 1, vec![]); + (f.bits, f.r) = (0, 7.0); + assert_eq!(read_bytes(&grib2_message(&[f]), "t").unwrap().bands[0].data, vec![7.0, 7.0]); +} + +/// A field's sections with its section `number` (4, 5 or 6) cut out. +fn without_section(field: &F2, number: u8) -> Vec { + let s = field.sections(); + let mut at = 0; + while at + 5 <= s.len() { + let len = u32::from_be_bytes([s[at], s[at + 1], s[at + 2], s[at + 3]]) as usize; + if s[at + 4] == number { + let mut out = s[..at].to_vec(); + out.extend(&s[at + len..]); + return out; + } + at += len; + } + panic!("no section {number}"); +} + +#[test] +fn a_grib2_field_without_its_own_sections_is_damaged() { + for (number, why) in [(4, "its product definition"), (5, "its packing"), (6, "its bitmap section")] { + let first = F2::new(2, 1, vec![1, 2]); + let mut second = F2::new(2, 1, vec![3, 4]); + second.number = 1; + let mut s1 = u(21, 4); + s1.extend([1, 0, 7, 0, 0, 2, 1, 1]); + s1.extend(u(2026, 2)); + s1.extend([11, 18, 0, 0, 0, 0, 1]); + let mut body = s1; + body.extend(first.sections()); + body.extend(without_section(&second, number)); + let mut msg = b"GRIB".to_vec(); + msg.extend([0, 0, 0, 2]); + msg.extend(u(16 + body.len() as u64 + 4, 8)); + msg.extend(body); + msg.extend(b"7777"); + let r = read_bytes(&msg, "t").unwrap(); + assert_eq!(r.bands.len(), 1, "{number}"); + assert_eq!(r.bands[0].data, vec![1.0, 2.0]); + assert!(r.lost.contains(&format!("1 field left out: damaged (a field without {why})")), "{number}: {:?}", r.lost); + } +} + +#[test] +fn a_length_that_hides_the_next_message_is_damage() { + // GRIB1: the first message's length runs to the end of the second, whose "7777" it ends on. + let mut first = G1::new(2, 1, vec![1, 2]).bytes(); + let second = G1::new(2, 1, vec![3, 4]).bytes(); + let len = (first.len() + second.len()) as u64; + first[4..7].copy_from_slice(&u(len, 3)); + let mut file = first; + file.extend(&second); + assert_eq!(header(&mut std::io::Cursor::new(&file), 0, len, false).unwrap(), Header::WrongLength); + let r = read_bytes(&file, "t").unwrap(); + assert_eq!(r.bands.len(), 1); + assert_eq!(r.bands[0].data, vec![3.0, 4.0]); + assert!(r.lost.contains(&"1 message left out: damaged".to_string()), "{:?}", r.lost); + // GRIB2 alike. + let mut first = grib2_message(&[F2::new(2, 1, vec![1, 2])]); + let second = grib2_message(&[F2::new(2, 1, vec![3, 4])]); + let len = (first.len() + second.len()) as u64; + first[8..16].copy_from_slice(&u(len, 8)); + let mut file = first; + file.extend(&second); + let r = read_bytes(&file, "t").unwrap(); + assert_eq!(r.bands.len(), 1); + assert_eq!(r.bands[0].data, vec![3.0, 4.0]); + assert!(r.lost.contains(&"1 message left out: damaged".to_string()), "{:?}", r.lost); +} + +#[test] +fn grids_are_compared_where_their_points_are() { + // BAM's latitudes: two southward grids of two 60° rows from −30°, given last at 30° and at + // 50°, are laid out from 30° and from 40°: not the same grid. + let grid = |lat2: i64| { + let mut g = G1::new(2, 2, vec![1, 2, 3, 4]); + (g.lat1, g.lat2, g.dj) = (-30_000, lat2, 60_000); + g + }; + let mut file = grid(30_000).bytes(); + file.extend(grid(50_000).bytes()); + let r = read_bytes(&file, "t").unwrap(); + assert_eq!(r.bands.len(), 1); + assert!(r.lost.contains(&"1 field left out: on another grid than the first field's".to_string()), "{:?}", r.lost); + // The same points scanned from the other end (south to north) are the same grid: a second + // band, placed by its own scanning mode. + let mut south_up = G1::new(2, 2, vec![3, 4, 1, 2]); + (south_up.lat1, south_up.lat2, south_up.scan) = (59_000, 60_000, 0x40); + let mut file = G1::new(2, 2, vec![1, 2, 3, 4]).bytes(); + file.extend(south_up.bytes()); + let r = read_bytes(&file, "t").unwrap(); + assert_eq!(r.bands.len(), 2, "{:?}", r.lost); + assert_eq!(r.bands[0].data, vec![1.0, 2.0, 3.0, 4.0]); + assert_eq!(r.bands[1].data, vec![1.0, 2.0, 3.0, 4.0]); +} + +#[test] +fn only_a_whole_turn_is_rolled_and_only_a_repeated_column_dropped() { + // Seven columns of 50° from 0° cover 350°: not a whole turn, so not moved. + let mut g = G1::new(7, 1, vec![1, 2, 3, 4, 5, 6, 7]); + (g.lat1, g.lat2, g.lon1, g.lon2, g.di) = (0, 0, 0, 300_000, 50_000); + let r = read_bytes(&g.bytes(), "t").unwrap(); + assert_eq!(r.bands[0].data, vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]); + assert_eq!(r.transform.origin_x, -25.0); + // Eight columns of 50° from 0° to 350°: the last isn't the first again. + let mut g = G1::new(8, 1, vec![1, 2, 3, 4, 5, 6, 7, 8]); + (g.lat1, g.lat2, g.lon1, g.lon2, g.di) = (0, 0, 0, 350_000, 50_000); + let r = read_bytes(&g.bytes(), "t").unwrap(); + assert_eq!(r.width, 8); + assert!(!r.lost.iter().any(|l| l.contains("repeats the first")), "{:?}", r.lost); +} + +#[test] +fn increments_left_out_follow_the_scanning_direction() { + // Three columns scanned west from 12° E to 10° E, without increments: 1° cells, not 179°. + let mut g = G1::new(3, 2, vec![1, 2, 3, 4, 5, 6]); + (g.lon1, g.lon2, g.scan) = (12_000, 10_000, 0x80); + let mut b = g.bytes(); + // The resolution flags (GDS octet 17): no increments given. + b[8 + 28 + 16] = 0; + let r = read_bytes(&b, "t").unwrap(); + assert_eq!(r.transform.pixel_width, 1.0); + assert_eq!(r.transform.origin_x, 9.5); + assert_eq!(r.transform.pixel_height, -1.0); + assert_eq!(r.bands[0].data, vec![3.0, 2.0, 1.0, 6.0, 5.0, 4.0]); +} + +#[test] +fn staggered_rows_are_refused_by_name() { + let mut f = F2::new(2, 2, vec![1, 2, 3, 4]); + f.scan = 0x44; + let e = read_bytes(&grib2_message(&[f]), "t").unwrap_err().to_string(); + assert!(e.contains("grids whose rows are offset or shortened"), "{e}"); +} + +#[test] +fn short_grib1_sections_are_damage() { + // A binary data section of 4 octets: no reference value or bits a value. + let mut c = G1::new(2, 1, vec![]); + c.bits = 0; + let full = c.bytes(); + let bds = 8 + 28 + 32; + let mut b = full[..bds].to_vec(); + b.extend([0, 0, 4, 0]); + b.extend(b"7777"); + let len = b.len() as u64; + b[4..7].copy_from_slice(&u(len, 3)); + let e = read_bytes(&b, "t").unwrap_err().to_string(); + assert!(e.contains("damaged (a damaged binary data section)"), "{e}"); +} + +#[test] +fn a_layer_between_two_surfaces_is_named_by_both() { + let mut msg = grib2_message(&[F2::new(2, 1, vec![1, 2])]); + // Section 4 starts after sections 0, 1 and 3; its second surface's type is octet 29, its + // value octets 31 to 34. + let s4 = 16 + 21 + 72; + msg[s4 + 28] = 105; + msg[s4 + 33] = 5; + let r = read_bytes(&msg, "t").unwrap(); + let name = &r.bands[0].name; + assert!(name.contains(":surface=103:value=2:") && name.ends_with(":surface2=105:value2=5"), "{name}"); +} + +#[test] +fn a_sidecars_nodata_isnt_counted_as_rounded() { + // D = 1: 0.1 and 0.2, which f32 both rounds; a sidecar's no-data of 0.1 leaves one counted. + let mut g = G1::new(2, 1, vec![1, 2]); + g.d = 1; + let bytes = g.bytes(); + let plain = read_bytes(&bytes, "t").unwrap(); + assert_eq!(plain.rounded, vec![2]); + let masked = read_with_nodata(std::io::Cursor::new(&bytes), "t", Some(0.1)).unwrap(); + assert_eq!(masked.rounded, vec![1]); +} + +#[test] +fn reasons_past_the_most_said_apart_are_counted_together() { + let mut list = Vec::new(); + for k in 0..20 { + tally(&mut list, format!("GRIB2 grid template 3.{k}")); + } + tally(&mut list, "GRIB2 grid template 3.0".to_string()); + assert_eq!(list.len(), MAX_REASONS + 1); + assert_eq!(list[0], ("GRIB2 grid template 3.0".to_string(), 2)); + assert_eq!(list[MAX_REASONS], (OTHER_REASONS.to_string(), 4)); +} + +#[test] +fn grib_is_known_by_its_first_bytes() { + assert_eq!(crate::io::sniff_extension(&grib2_message(&[F2::new(2, 1, vec![1, 2])])), Some("grb")); + assert_eq!(crate::io::sniff_extension(&G1::new(2, 1, vec![1, 2]).bytes()), Some("grb")); +} diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index 8547ee5a0d..f74a66b893 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -1236,7 +1236,9 @@ fn read_path_placing(path: &Path, world: bool) -> Result { read_ascii(path, &text, &name, sidecar_nodata)? } // Read message by message, never whole. - "grb" | "grib" | "grb2" | "grib2" => grib::read(std::io::BufReader::new(crate::provenance::open(path)?), &name)?, + "grb" | "grib" | "grb2" | "grib2" => { + grib::read_with_nodata(std::io::BufReader::new(crate::provenance::open(path)?), &name, sidecar_nodata)? + } #[cfg(not(target_arch = "wasm32"))] _ if gdal::is_gdal_raster_name(&path.to_string_lossy()) => { // Converted once to a GeoTIFF in the cache; the layer still names this file. @@ -1248,12 +1250,13 @@ fn read_path_placing(path: &Path, world: bool) -> Result { // left out of the rounded count: it left out the sidecar's no-data for all bands. When the two // differ (a record for a band the raster lacks, or one only some bands give), the file is read // again with the one applied (none, when the bands it has give none), so the rounded count - // leaves out just its pixels. Only an ASCII grid, or a GeoTIFF of a type `f32` can round, is read again. + // leaves out just its pixels. Only an ASCII grid, a GRIB file, or a GeoTIFF of a type `f32` can + // round, is read again. let applied = pam.as_ref().map(|p| p.nodata_within(r.bands.len())); if let Some(nd) = applied && nd != sidecar_nodata && r.nodata.is_none() - && (ext == "asc" + && (matches!(ext.as_str(), "asc" | "grb" | "grib" | "grb2" | "grib2") || (matches!(ext.as_str(), "tif" | "tiff") && matches!(r.data_type.as_str(), "UInt32" | "Int32" | "UInt64" | "Int64" | "Float64"))) { @@ -1261,6 +1264,8 @@ fn read_path_placing(path: &Path, world: bool) -> Result { drop(r); r = if ext == "asc" { read_ascii(path, &crate::provenance::read_to_string(path)?, &name, nd)? + } else if grib::EXTENSIONS.contains(&ext.as_str()) { + grib::read_with_nodata(std::io::BufReader::new(crate::provenance::open(path)?), &name, nd)? } else { #[cfg(not(target_arch = "wasm32"))] let again = geotiff::read_file_with_nodata(path, &name, nd)?; diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index 764de3b93c..ddf580034b 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -598,26 +598,29 @@ pub(crate) fn pdf_page(path: &str, p: &Value) -> Result, String> } } -/// Whether a whole file downloaded from `url` is a PDF page to draw off the frame before it is -/// added (`layer.addDownload` with `p`): its file name, page and whether it is placed by its -/// coordinates (not `"as": "scan"`). `None` for anything else, or a page that can't be read here, -/// which `layer.addDownload` reads (or refuses) as it adds it. +/// Whether a whole file downloaded from `url` is read off the frame before it is added +/// (`layer.addDownload` with `p`): a PDF's page to draw, or a GRIB file (whose fields can be +/// many). Its file name, page and whether it is placed by its coordinates (not `"as": "scan"`). +/// `None` for anything else, or a page that can't be read here, which `layer.addDownload` reads +/// (or refuses) as it adds it. #[cfg(not(target_arch = "wasm32"))] pub fn download_page(url: &str, p: &Value, bytes: &[u8]) -> Option<(String, Option, bool)> { let plain = ["service", "coverage", "geolibreProject", "geolibreLayer"] .iter() .all(|k| p.get(k).is_none_or(|v| v.is_null() || v.as_bool() == Some(false))); - if !raster::PDF_PAGES || !plain { + if !plain { return None; } - let name = super::layer::url_file_name(url, bytes).ok().filter(|n| raster::is_pdf_name(n))?; + let name = super::layer::url_file_name(url, bytes) + .ok() + .filter(|n| (raster::PDF_PAGES && raster::is_pdf_name(n)) || raster::grib::is_grib_name(n))?; let page = pdf_page(&name, p).ok()?; let scan = wants_scan(p, &name).ok()?; Some((name, page, !scan)) } -/// Draws a downloaded PDF's page off the frame ([`download_page`]), for -/// [`crate::Session::download_landed_page`]. +/// Draws a downloaded PDF's page, or reads a downloaded GRIB file, off the frame +/// ([`download_page`]), for [`crate::Session::download_landed_page`]. #[cfg(not(target_arch = "wasm32"))] pub fn read_download_page(name: &str, bytes: &[u8], page: Option<&str>, place: bool) -> Result { raster::read_bytes_page(name, bytes, page, place).map_err(|e| format!("{name}: {e}")) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a3f156f62c..66b05091fb 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -45308,6 +45308,22 @@ fn a_pdf_says_which_frames_it_doesnt_georeference() { assert!(said.contains("(Main on pages 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 and 3 more: it is tilted)"), "{said}"); } +/// A downloaded GRIB file is read off the frame, as a PDF's page is drawn: by its name, or by its +/// first bytes when the address has none; never as a scan. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_grib_download_is_read_off_the_frame() { + use crate::cmd::raster::download_page; + let asked = json!({"url": "x"}); + let message = b"GRIB4"; + let found = download_page("https://example.org/bam/PREC.grb", &asked, message); + assert_eq!(found, Some(("PREC.grb".to_string(), None, true))); + let (sniffed, ..) = download_page("https://example.org/record?id=7", &asked, message).unwrap(); + assert!(rustgis_data::raster::grib::is_grib_name(&sniffed), "{sniffed}"); + assert!(download_page("https://example.org/PREC.grb", &json!({"as": "scan"}), message).is_none()); + assert!(download_page("https://example.org/a.tif", &asked, message).is_none()); +} + /// Each page of a map series is georeferenced with its own view, not the first page's (#1191). #[test] fn a_map_series_pdf_georeferences_each_page_with_its_view() { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 076154f7b8..6d8081b05a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -5676,7 +5676,8 @@ impl RustGisApp { match r { Ok(bytes) => { let landed = serviceui::Landed { id, url, params: p, origin }; - // A PDF's page is drawn on a thread first, so a large one doesn't hold the window. + // A PDF's page is drawn, and a GRIB file read, on a thread first, so a large one + // doesn't hold the window. #[cfg(not(target_arch = "wasm32"))] if let Some(page) = rustgis_engine::cmd::raster::download_page(&landed.url, &landed.params, &bytes) { self.draw_page(landed, bytes, page); @@ -5687,7 +5688,7 @@ impl RustGisApp { Err(e) => self.landed_failed(id, &url, &p, e), } } - // PDF pages drawn on threads, added with their downloads' bytes. + // PDF pages drawn (and GRIB files read) on threads, added with their downloads' bytes. #[cfg(not(target_arch = "wasm32"))] { let mut drawn = Vec::new(); @@ -5716,7 +5717,7 @@ impl RustGisApp { std::mem::take(&mut self.ui.page_queue).into_iter().partition(|(l, ..)| self.session.download_under_way(l.id)); self.ui.page_queue = waiting; for (landed, ..) in gone { - let why = tl!("given up before its page was drawn: its project was closed, or more than 64 downloads started after it"); + let why = tl!("given up before it was read: its project was closed, or more than 64 downloads started after it"); self.landed_failed(landed.id, &landed.url, &landed.params, why.to_string()); } // Those waiting take the places freed, oldest first. @@ -5921,7 +5922,8 @@ impl RustGisApp { Ok(Value::Null) } - /// Draws a downloaded PDF's page on a thread ([`rustgis_engine::cmd::raster::read_download_page`]), + /// Draws a downloaded PDF's page, or reads a downloaded GRIB file, on a thread + /// ([`rustgis_engine::cmd::raster::read_download_page`]), /// to be added with its bytes once drawn ([`UiState::page_reads`]). `page`: its file name, page /// and whether it is placed ([`download_page`]). Drawn one at a time with the windows' reads; /// past [`MAX_WINDOW_READS`] under way, or where the OS gives no thread, it waits in @@ -5946,14 +5948,14 @@ impl RustGisApp { // Kept here too, so a thread the OS refuses doesn't take the download with it. let bytes = std::sync::Arc::new(bytes); let mine = bytes.clone(); - let spawned = std::thread::Builder::new().name("pdf-page".into()).spawn(move || { + let spawned = std::thread::Builder::new().name("download-read".into()).spawn(move || { let read = match window_turn(&leaving) { // On a thread no command's catch reaches: a bug must not leave it running forever. Some(_turn) => std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { rustgis_engine::cmd::raster::read_download_page(&name, &bytes, page.as_deref(), place) })) - .unwrap_or_else(|_| Err(tl!("Drawing the PDF's page failed unexpectedly").to_string())), - None => Err(tl!("given up before its page was drawn: it was cancelled, or its project was closed").to_string()), + .unwrap_or_else(|_| Err(tl!("Reading the download failed unexpectedly").to_string())), + None => Err(tl!("given up before it was read: it was cancelled, or its project was closed").to_string()), }; let bytes = std::sync::Arc::try_unwrap(bytes).unwrap_or_else(|shared| (*shared).clone()); *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(read.map(|r| (bytes, r))); From f91e717b122c303cadaa6d934b4a568876e02e98 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Fri, 20 Nov 2026 23:00:22 -0300 Subject: [PATCH 13/17] fix(data): GRIB review round 12 (#2428) - A GRIB2 message that ends on a field's sections 4 to 6, without section 7, says that field as damaged. - A field on another grid than the one kept is told apart before it is decoded, so it takes none of the room a later field may need. - Grid notices are capped at 16, the rest counted in one entry. - A grid one point across without its increment is refused by name rather than given 360 degrees. - Fixed-surface scaled values are read unsigned; all ones is "missing". - Band names carry a statistic's process and period, a probability's limits, a percentile and a derived forecast's kind; a name still taken gets the band number. - "1 byte" for a single byte outside the messages. - ui-egui: a download's read installs a cancel probe on its thread, so Cancel stops a GRIB read under way and frees its turn. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/raster/grib.rs | 153 ++++++++++++++++++++++----- crates/data/src/raster/grib_tests.rs | 150 +++++++++++++++++++++++++- crates/ui-egui/src/lib.rs | 52 +++++++-- crates/ui-egui/src/syncmark.rs | 5 +- 4 files changed, 318 insertions(+), 42 deletions(-) diff --git a/crates/data/src/raster/grib.rs b/crates/data/src/raster/grib.rs index f4f4c9b060..9989593d5e 100644 --- a/crates/data/src/raster/grib.rs +++ b/crates/data/src/raster/grib.rs @@ -169,7 +169,8 @@ pub fn read_with_nodata(mut source: R, name: &str, sidecar_nodat bytes.try_reserve_exact(len as usize).map_err(|_| bad("not enough memory for a message"))?; source.seek(SeekFrom::Start(start))?; source.by_ref().take(len).read_to_end(&mut bytes)?; - let decoded = if edition == Some(1) { vec![grib1(&bytes, room, uncounted)] } else { grib2(&bytes, room, uncounted) }; + let first = fields.first().map(|f| f.grid); + let decoded = if edition == Some(1) { vec![grib1(&bytes, room, first, uncounted)] } else { grib2(&bytes, room, first, uncounted) }; for d in decoded { match d { Ok(f) => { @@ -184,6 +185,7 @@ pub fn read_with_nodata(mut source: R, name: &str, sidecar_nodat } } Err(Skip::TooLarge) => skipped.over_limit += 1, + Err(Skip::OtherGrid) => skipped.other_grid += 1, Err(Skip::Other(why)) => skipped.add(why), Err(Skip::Damaged(why)) => skipped.damaged(why), } @@ -196,14 +198,35 @@ pub fn read_with_nodata(mut source: R, name: &str, sidecar_nodat return Err(bad(format!("nothing in it can be read here: {}", skipped.notes(limit).join("; ")))); } // Each grid's notices, once: grids at the same places may still say different things (one - // laid out from BAM's latitudes, one not). + // laid out from BAM's latitudes, one not). Past [`MAX_REASONS`] of them, the fields with more + // are counted, so the list and the time spent on it stay small; a field on the grid of the one + // before says what it said. let mut notes: Vec = Vec::new(); + let mut unlisted = 0usize; + let mut last: Option<(Grid, bool)> = None; for f in &fields { - for n in f.grid.notes() { - if !notes.contains(&n) { - notes.push(n); + let more = match last { + Some((g, more)) if g == f.grid => more, + _ => { + let mut more = false; + for n in f.grid.notes() { + if notes.contains(&n) { + continue; + } + if notes.len() < MAX_REASONS { + notes.push(n); + } else { + more = true; + } + } + more } - } + }; + last = Some((f.grid, more)); + unlisted += usize::from(more); + } + if unlisted > 0 { + notes.push(format!("more notices about the grids of {} aren't listed", count(unlisted))); } let mut r = to_raster(fields, name)?; r.lost.extend(notes); @@ -423,6 +446,9 @@ fn count_fields(source: &mut R, start: u64, len: u64, grib2: boo #[derive(Clone)] enum Skip { TooLarge, + /// On another grid than the first field kept: told before it is decoded, so it takes none of + /// the room a later field on that grid may need. + OtherGrid, Other(String), Damaged(String), } @@ -475,7 +501,9 @@ impl Skipped { if self.cut > 0 { out.push("the file ends inside a message, which is left out".to_string()); } - if self.junk > 0 { + if self.junk == 1 { + out.push("1 byte outside its messages isn't GRIB, and is passed over".to_string()); + } else if self.junk > 1 { out.push(format!("{} bytes outside its messages aren't GRIB, and are passed over", self.junk)); } out @@ -670,7 +698,10 @@ fn to_raster(fields: Vec, name: &str) -> Result { }; let origin_x = if roll > 0 { west - (roll as f64) * grid.dx } else { west } - grid.dx / 2.0; let origin_y = grid.north() + grid.dy / 2.0; - let mut names = Vec::with_capacity(fields.len()); + let mut names: Vec = Vec::with_capacity(fields.len()); + // Each name's first band: a field named as one before it (the same message twice, a GRIB1 + // ensemble's members, octets a name doesn't read) is named by its band number too. + let mut taken = std::collections::HashSet::with_capacity(fields.len()); let mut rounded = Vec::with_capacity(fields.len()); let mut past = 0u64; let mut bands = Vec::with_capacity(fields.len()); @@ -689,7 +720,9 @@ fn to_raster(fields: Vec, name: &str) -> Result { *cell = *v; } } - names.push(f.name); + let name = if taken.contains(&f.name) { format!("{}:band={}", f.name, names.len() + 1) } else { f.name }; + taken.insert(name.clone()); + names.push(name); rounded.push(f.rounded); past += f.past; bands.push(band); @@ -885,7 +918,7 @@ fn section1(b: &[u8], at: usize) -> std::result::Result<&[u8], Skip> { } /// A GRIB1 message (WMO FM 92 GRIB edition 1): its one field. -fn grib1(b: &[u8], room: usize, uncounted: Uncounted) -> std::result::Result { +fn grib1(b: &[u8], room: usize, first: Option, uncounted: Uncounted) -> std::result::Result { let pds = section1(b, 8)?; if pds.len() < 28 { return Err(Skip::Damaged("a damaged product definition section".to_string())); @@ -911,6 +944,9 @@ fn grib1(b: &[u8], room: usize, uncounted: Uncounted) -> std::result::Result std::result::Result { let scan = g[27]; let (di, dj) = (be(g, 23, 2), be(g, 25, 2)); let given = res & 0x80 != 0; - let dx = if given && di != 0xffff { f64::from(di) / 1000.0 } else { lon_span(lon1, lon2, scan) / (ni.saturating_sub(1)).max(1) as f64 }; - let dy = if given && dj != 0xffff { f64::from(dj) / 1000.0 } else { (lat2 - lat1).abs() / (nj.saturating_sub(1)).max(1) as f64 }; + let dx = if given && di != 0xffff { f64::from(di) / 1000.0 } else { spacing(lon_span(lon1, lon2, scan), ni) }; + let dy = if given && dj != 0xffff { f64::from(dj) / 1000.0 } else { spacing((lat2 - lat1).abs(), nj) }; let earth = Some(if res & 0x40 != 0 { "the IAU 1965 spheroid (GRIB1's oblate earth)" } else { "a sphere of radius 6,367,470 m (GRIB1's)" }); checked(Grid { ni, nj, lat1, lon1, lat2, lon2, dx, dy, scan, earth }) } /// The distance from the first longitude to the last in the direction the grid scans its columns -/// (east, or west when the scanning mode says), wrapping round the globe. +/// (east, or west when the scanning mode says), wrapping round the globe. The same longitude first +/// and last is a whole turn: a regular grid of more than one column that ends where it starts has +/// its last column on its first, 360° on ([`Grid::repeats_first_column`], said and left out). fn lon_span(first: f64, last: f64, scan: u8) -> f64 { let d = (if scan & SCAN_I_NEGATIVE != 0 { first - last } else { last - first }).rem_euclid(360.0); if d == 0.0 { 360.0 } else { d } } +/// An increment the file leaves out: the span from the first point to the last over the steps +/// between them. A grid one point across has no steps, and the file doesn't say how wide its +/// point is: NaN, which [`checked`] refuses by name. +fn spacing(span: f64, points: usize) -> f64 { + if points > 1 { span / (points - 1) as f64 } else { f64::NAN } +} + /// A grid whose increments and corners are usable, or why it isn't. fn checked(g: Grid) -> std::result::Result { // Flag table 3.4's bits 5 to 8: rows offset by half a cell, or one point short; GRIB1 leaves @@ -993,6 +1038,9 @@ fn checked(g: Grid) -> std::result::Result { if g.scan & 0x0f != 0 { return Err(Skip::Other("grids whose rows are offset or shortened (scanning mode bits 5 to 8)".to_string())); } + if g.dx.is_nan() || g.dy.is_nan() { + return Err(Skip::Other("grids one point across that don't give their spacing".to_string())); + } let ok = g.dx.is_finite() && g.dy.is_finite() && g.dx > 0.0 @@ -1020,8 +1068,9 @@ fn section2(b: &[u8], at: usize) -> Option<(u8, &[u8])> { /// A GRIB2 message (WMO FM 92 GRIB edition 2): each of its fields. A grid (section 3) may serve /// the fields after it, but each field has its own sections 4 to 7 (WMO's regulation 92.1.3): a /// field without its own product, packing or bitmap section is damaged, never read with the one -/// before it. -fn grib2(b: &[u8], room: usize, uncounted: Uncounted) -> Vec> { +/// before it, and so are sections 4 to 6 the message ends on without a section 7. `first`: the +/// grid of the fields kept, if any; a field on another is left out before it is decoded. +fn grib2(b: &[u8], room: usize, mut first: Option, uncounted: Uncounted) -> Vec> { let mut out = Vec::new(); let discipline = b.get(6).copied().unwrap_or(255); let mut at = 16usize; @@ -1033,14 +1082,18 @@ fn grib2(b: &[u8], room: usize, uncounted: Uncounted) -> Vec = None; let mut held = 0usize; let mut sections = 0usize; + // Whether the sections stop at damage (said already) rather than at the message's end. + let mut broken = false; while b.get(at..at + 4).is_some_and(|m| m != b"7777") { sections += 1; if sections > MAX_SECTIONS { out.push(Err(Skip::Damaged(format!("a message of more than {MAX_SECTIONS} sections")))); + broken = true; break; } let Some((number, s)) = section2(b, at) else { out.push(Err(Skip::Damaged("a damaged GRIB2 section".to_string()))); + broken = true; break; }; at += s.len(); @@ -1079,6 +1132,9 @@ fn grib2(b: &[u8], room: usize, uncounted: Uncounted) -> Vec Vec Vec {} } } + // A field's sections the message ends on, without its data section. + if !broken && (product.is_some() || packing.is_some() || bitmap.is_some()) { + out.push(Err(Skip::Damaged("a field without its data section".to_string()))); + } if out.is_empty() { out.push(Err(Skip::Damaged("a GRIB2 message without a data section".to_string()))); } @@ -1146,40 +1207,76 @@ fn grib2_grid(s: &[u8]) -> std::result::Result { let res = s[54]; let scan = s[71]; let (di, dj) = (be(s, 63, 4), be(s, 67, 4)); - let dx = if res & 0x20 != 0 && di != u32::MAX { - f64::from(di) * unit - } else { - lon_span(lon1, lon2, scan) / (ni.saturating_sub(1)).max(1) as f64 - }; - let dy = - if res & 0x10 != 0 && dj != u32::MAX { f64::from(dj) * unit } else { (lat2 - lat1).abs() / (nj.saturating_sub(1)).max(1) as f64 }; + let dx = if res & 0x20 != 0 && di != u32::MAX { f64::from(di) * unit } else { spacing(lon_span(lon1, lon2, scan), ni) }; + let dy = if res & 0x10 != 0 && dj != u32::MAX { f64::from(dj) * unit } else { spacing((lat2 - lat1).abs(), nj) }; checked(Grid { ni, nj, lat1, lon1, lat2, lon2, dx, dy, scan, earth }) } /// A GRIB2 product definition section, as part of a band name: the parameter's category and /// number (its discipline is section 0's), the template, and for templates 4.0 to 4.15 the first -/// fixed surface, the forecast time and, for a layer between two surfaces, the second. +/// fixed surface, the forecast time and, for a layer between two surfaces, the second. What tells +/// the fields of one template apart follows: an ensemble's member, a derived forecast's kind, a +/// probability's limits, a percentile, and a statistic's process and period. fn grib2_product(s: &[u8]) -> String { let template = be(s, 7, 2); let (category, number) = (s.get(9).copied().unwrap_or(255), s.get(10).copied().unwrap_or(255)); let mut name = format!("category={category}:number={number}:template=4.{template}"); - // Templates 4.0 to 4.15 share these octets; a surface's value is scaled by 10^-(its scale - // factor). - let value = |o: usize| round6(signed(s, o + 1, 4) as f64 / 10f64.powi(signed(s, o, 1) as i32)); + // Templates 4.0 to 4.15 share these octets; a surface's scaled value is unsigned. if template <= 15 && s.len() >= 28 { - name.push_str(&format!(":surface={}:value={}:TimeU={}:forecast={}", s[22], value(23), s[17], be(s, 18, 4))); + name.push_str(&format!(":surface={}:value={}:TimeU={}:forecast={}", s[22], scaled(s, 23, false), s[17], be(s, 18, 4))); // The second fixed surface (255: none). if let Some(&second) = s.get(28).filter(|t| **t != 255 && s.len() >= 34) { - name.push_str(&format!(":surface2={second}:value2={}", value(29))); + name.push_str(&format!(":surface2={second}:value2={}", scaled(s, 29, false))); } } // An ensemble's member (templates 4.1 and 4.11): its type and perturbation number. if matches!(template, 1 | 11) && s.len() >= 37 { name.push_str(&format!(":ensemble={}:member={}", s[34], s[35])); } + // A derived forecast (4.2, 4.12): its kind (code table 4.7). + if matches!(template, 2 | 12) && s.len() >= 35 { + name.push_str(&format!(":derived={}", s[34])); + } + // A probability (4.5, 4.9): its type (code table 4.9) and limits, whose scaled values are + // signed. + if matches!(template, 5 | 9) && s.len() >= 47 { + name.push_str(&format!(":probability={}:lower={}:upper={}", s[36], scaled(s, 37, true), scaled(s, 42, true))); + } + // A percentile (4.6, 4.10). + if matches!(template, 6 | 10) && s.len() >= 35 { + name.push_str(&format!(":percentile={}", s[34])); + } + // A statistic over a period (4.8 to 4.12): its first time range's process (code table 4.10), + // time unit and length, after the period's end, how many ranges and the values missing. The + // period starts at the forecast time, so two accumulations from one forecast time over + // different periods are named apart. + let period = match template { + 8 => Some(34), + 9 => Some(47), + 10 => Some(35), + 11 => Some(37), + 12 => Some(36), + _ => None, + }; + if let Some(at) = period.filter(|at| s.len() >= at + 19) { + name.push_str(&format!(":statistic={}:rangeU={}:range={}", s[at + 12], s[at + 14], be(s, at + 15, 4))); + } name } +/// The value at octets `o + 1..o + 5` scaled by 10^-(the signed scale factor at octet `o`), as +/// part of a band name: `missing` when either is all ones (GRIB2's missing value). `value_signed`: +/// whether the scaled value is signed (a probability's limits) or not (a fixed surface's, as +/// ecCodes reads them). +fn scaled(s: &[u8], o: usize, value_signed: bool) -> String { + let raw = be(s, o + 1, 4); + if s.get(o) == Some(&0xff) || raw == u32::MAX { + return "missing".to_string(); + } + let v = if value_signed { signed(s, o + 1, 4) as f64 } else { f64::from(raw) }; + round6(v / 10f64.powi(signed(s, o, 1) as i32)).to_string() +} + /// A GRIB2 data representation section: template 5.0 (simple packing) only, as the number of /// values, R, E, D and the bits a value. fn grib2_packing(s: &[u8]) -> std::result::Result<(usize, f64, i64, i64, u32), Skip> { diff --git a/crates/data/src/raster/grib_tests.rs b/crates/data/src/raster/grib_tests.rs index db2c12cc37..1217a3898f 100644 --- a/crates/data/src/raster/grib_tests.rs +++ b/crates/data/src/raster/grib_tests.rs @@ -263,14 +263,17 @@ impl F2 { /// A GRIB2 message of `fields` (meteorological products, discipline 0). fn grib2_message(fields: &[F2]) -> Vec { + message_of(&fields.iter().flat_map(F2::sections).collect::>()) +} + +/// A GRIB2 message of these sections, after its section 1 (meteorological products, discipline 0). +fn message_of(sections: &[u8]) -> Vec { let mut s1 = u(21, 4); s1.extend([1, 0, 7, 0, 0, 2, 1, 1]); s1.extend(u(2026, 2)); s1.extend([11, 18, 0, 0, 0, 0, 1]); let mut body = s1; - for f in fields { - body.extend(f.sections()); - } + body.extend(sections); let mut out = b"GRIB".to_vec(); out.extend([0, 0, 0, 2]); out.extend(u(16 + body.len() as u64 + 4, 8)); @@ -719,7 +722,7 @@ fn a_message_of_too_many_sections_is_left_out() { assert_eq!(r.bands.len(), 1); assert!(r.lost.contains(&"1 message left out: damaged (more than 1024 sections)".to_string()), "{:?}", r.lost); // The decoder refuses one too, should it get one. - let first = grib2(&file, usize::MAX, Uncounted::default()); + let first = grib2(&file, usize::MAX, None, Uncounted::default()); assert!(matches!(first.first(), Some(Err(Skip::Damaged(m))) if m.contains("more than 1024 sections"))); } @@ -953,3 +956,142 @@ fn grib_is_known_by_its_first_bytes() { assert_eq!(crate::io::sniff_extension(&grib2_message(&[F2::new(2, 1, vec![1, 2])])), Some("grb")); assert_eq!(crate::io::sniff_extension(&G1::new(2, 1, vec![1, 2]).bytes()), Some("grb")); } + +#[test] +fn a_field_the_message_ends_without_its_data_is_damaged() { + let first = F2::new(2, 1, vec![1, 2]); + let mut second = F2::new(2, 1, vec![3, 4]); + second.number = 1; + let mut body = first.sections(); + body.extend(without_section(&second, 7)); + let r = read_bytes(&message_of(&body), "t").unwrap(); + assert_eq!(r.bands.len(), 1); + assert_eq!(r.bands[0].data, vec![1.0, 2.0]); + assert!(r.lost.contains(&"1 field left out: damaged (a field without its data section)".to_string()), "{:?}", r.lost); +} + +#[test] +fn one_byte_outside_the_messages_is_said_as_one() { + let mut file = G1::new(2, 1, vec![1, 2]).bytes(); + file.push(9); + file.extend(G1::new(2, 1, vec![3, 4]).bytes()); + let r = read_bytes(&file, "t").unwrap(); + assert!(r.lost.contains(&"1 byte outside its messages isn't GRIB, and is passed over".to_string()), "{:?}", r.lost); +} + +#[test] +fn grid_notices_past_the_most_said_are_counted() { + // BAM's latitudes, each pair centred on 0°: the same rows, given by other values each time. + let mut file = Vec::new(); + for k in 0..20 { + let mut g = G1::new(2, 2, vec![1, 2, 3, 4]); + (g.lat1, g.lat2, g.dj) = (-30_000 - k, 30_000 + k, 60_000); + file.extend(g.bytes()); + } + // The last grid again: it says what the one before said. + let mut g = G1::new(2, 2, vec![1, 2, 3, 4]); + (g.lat1, g.lat2, g.dj) = (-30_019, 30_019, 60_000); + file.extend(g.bytes()); + let r = read_bytes(&file, "t").unwrap(); + assert_eq!(r.bands.len(), 21); + // GRIB1's earth is said once too: 15 of the latitudes' notices, then the 6 fields with more. + assert!(r.lost.iter().any(|l| l.starts_with("its earth is")), "{:?}", r.lost); + assert_eq!(r.lost.iter().filter(|l| l.contains("gives its first row")).count(), MAX_REASONS - 1); + assert!(r.lost.contains(&"more notices about the grids of 6 fields aren't listed".to_string()), "{:?}", r.lost); +} + +#[test] +fn a_grid_one_point_across_without_its_spacing_is_refused_by_name() { + // The resolution flags (GDS octet 17): no increments given. + let mut b = G1::new(1, 2, vec![1, 2]).bytes(); + b[8 + 28 + 16] = 0; + let e = read_bytes(&b, "t").unwrap_err().to_string(); + assert!(e.contains("grids one point across that don't give their spacing"), "{e}"); + // Three columns from 0° back to 0°: the only regular grid that ends where it starts goes + // round once, its last column on its first, which is said and left out. + let mut g = G1::new(3, 2, vec![1, 2, 3, 4, 5, 6]); + (g.lon1, g.lon2) = (0, 0); + let mut b = g.bytes(); + b[8 + 28 + 16] = 0; + let r = read_bytes(&b, "t").unwrap(); + assert_eq!((r.width, r.transform.pixel_width), (2, 180.0)); + assert!(r.lost.iter().any(|l| l.contains("its last column repeats the first")), "{:?}", r.lost); +} + +#[test] +fn surface_values_are_unsigned_or_missing() { + let mut f = F2::new(2, 1, vec![1, 2]); + (f.surface_scale, f.surface_value) = (9, 3_000_000_000); + let name = read_bytes(&grib2_message(&[f]), "t").unwrap().bands[0].name.clone(); + assert!(name.contains(":surface=103:value=3:"), "{name}"); + let mut f = F2::new(2, 1, vec![1, 2]); + (f.surface_scale, f.surface_value) = (255, u64::from(u32::MAX)); + let name = read_bytes(&grib2_message(&[f]), "t").unwrap().bands[0].name.clone(); + assert!(name.contains(":surface=103:value=missing:"), "{name}"); +} + +/// A field's sections with its product definition made template 4.`template`, `tail` its octets +/// from 35 on. +fn with_template(field: &F2, template: u8, tail: &[u8]) -> Vec { + let mut s = field.sections(); + // Section 4 is at 72 (after section 3), 34 octets long. + let at = 72; + s[at + 8] = template; + s.splice(at + 34..at + 34, tail.iter().copied()); + s[at + 3] = (34 + tail.len()) as u8; + s +} + +#[test] +fn statistics_probabilities_and_percentiles_are_named_apart() { + // Template 4.8: accumulations (process 1) over 6 and 12 hours from the same forecast time. + let period = |hours: u64| { + let mut tail = u(2026, 2); + tail.extend([11, 18, 12, 0, 0, 1]); + tail.extend(u(0, 4)); + tail.extend([1, 2, 1]); + tail.extend(u(hours, 4)); + tail.extend([255]); + tail.extend(u(0, 4)); + with_template(&F2::new(2, 1, vec![1, 2]), 8, &tail) + }; + let mut body = period(6); + body.extend(period(12)); + let r = read_bytes(&message_of(&body), "t").unwrap(); + assert!(r.bands[0].name.ends_with(":forecast=6:statistic=1:rangeU=1:range=6"), "{}", r.bands[0].name); + assert!(r.bands[1].name.ends_with(":forecast=6:statistic=1:rangeU=1:range=12"), "{}", r.bands[1].name); + // Template 4.5: above a lower limit of −5 (type 3), the upper one missing. + let mut tail = vec![1, 1, 3, 0]; + tail.extend(sm(-5, 4)); + tail.push(255); + tail.extend(u(u64::from(u32::MAX), 4)); + let r = read_bytes(&message_of(&with_template(&F2::new(2, 1, vec![1, 2]), 5, &tail)), "t").unwrap(); + assert!(r.bands[0].name.ends_with(":probability=3:lower=-5:upper=missing"), "{}", r.bands[0].name); + // Template 4.6: the 90th percentile. + let r = read_bytes(&message_of(&with_template(&F2::new(2, 1, vec![1, 2]), 6, &[90])), "t").unwrap(); + assert!(r.bands[0].name.ends_with(":percentile=90"), "{}", r.bands[0].name); +} + +#[test] +fn fields_named_alike_are_named_by_their_band_too() { + let mut file = G1::new(2, 1, vec![1, 2]).bytes(); + file.extend(G1::new(2, 1, vec![3, 4]).bytes()); + let r = read_bytes(&file, "t").unwrap(); + assert!(!r.bands[0].name.contains(":band="), "{}", r.bands[0].name); + assert_eq!(r.bands[1].name, format!("{}:band=2", r.bands[0].name)); +} + +#[test] +fn a_field_on_another_grid_takes_none_of_the_room() { + let a = || F2::new(2, 1, vec![1, 2]); + // Two points 10° east of A's. + let mut b = F2::new(2, 1, vec![3, 4]); + (b.lon1, b.lon2) = (310_000_000, 310_500_000); + let kept = grib2(&grib2_message(&[a()]), usize::MAX, None, Uncounted::default()); + let grid = kept.first().and_then(|f| f.as_ref().ok()).map(|f| f.grid); + assert!(grid.is_some()); + // Room for two points: B is told apart before it is decoded, so A still fits. + let got = grib2(&grib2_message(&[b, a()]), 2, grid, Uncounted::default()); + assert!(matches!(got.first(), Some(Err(Skip::OtherGrid)))); + assert!(matches!(got.get(1), Some(Ok(f)) if f.values == vec![1.0, 2.0])); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6d8081b05a..9589a2e02b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -285,6 +285,25 @@ fn window_turn(left: &std::sync::atomic::AtomicBool) -> Option, + place: bool, + left: &std::sync::Arc, +) -> Result { + let _probe = rustgis_engine::data::progress::install(Some(std::sync::Arc::new(syncmark::Stop(left.clone())))); + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rustgis_engine::cmd::raster::read_download_page(name, bytes, page, place))) + .unwrap_or_else(|_| Err(tl!("Reading the download failed unexpectedly").to_string())) +} + /// A shell's overrides of the Settings › Start-up preferences for one launch. #[derive(Clone, Debug, Default)] pub struct Start { @@ -5792,8 +5811,9 @@ impl RustGisApp { left.store(true, std::sync::atomic::Ordering::Relaxed); Some((url, p)) }); - // A PDF page waiting for its turn gives it up; one being drawn is left to finish, its - // page dropped (drawing a page is one step that can't be stopped). + // A PDF page or GRIB file waiting for its turn gives it up; a GRIB file being read stops + // within a moment ([`read_download`]), and a page being drawn is left to finish, its page + // dropped (drawing a page is one step that can't be stopped). #[cfg(not(target_arch = "wasm32"))] let cancelled = cancelled.or_else(|| { let i = self.ui.page_reads.iter().position(|(l, ..)| l.id == id)?; @@ -5930,8 +5950,9 @@ impl RustGisApp { /// [`UiState::page_queue`] and is tried again each frame: held, listed under way and /// cancellable, until a thread can be had (never drawn on the frame, and the download isn't /// lost). Whether it started now. Cancel takes it - /// off the list and gives up its turn; a drawing under way (one step the renderer can't stop) - /// finishes, its page dropped. + /// off the list and gives up its turn; a GRIB file's read under way stops within a moment + /// ([`read_download`]), and a drawing under way (one step the renderer can't stop) finishes, + /// its page dropped. /// /// [`download_page`]: rustgis_engine::cmd::raster::download_page #[cfg(not(target_arch = "wasm32"))] @@ -5951,10 +5972,7 @@ impl RustGisApp { let spawned = std::thread::Builder::new().name("download-read".into()).spawn(move || { let read = match window_turn(&leaving) { // On a thread no command's catch reaches: a bug must not leave it running forever. - Some(_turn) => std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - rustgis_engine::cmd::raster::read_download_page(&name, &bytes, page.as_deref(), place) - })) - .unwrap_or_else(|_| Err(tl!("Reading the download failed unexpectedly").to_string())), + Some(_turn) => read_download(&name, &bytes, page.as_deref(), place, &leaving), None => Err(tl!("given up before it was read: it was cancelled, or its project was closed").to_string()), }; let bytes = std::sync::Arc::try_unwrap(bytes).unwrap_or_else(|shared| (*shared).clone()); @@ -7651,6 +7669,24 @@ mod record_tests { assert!(app.session.map().layer_by_name("Cancelled download").is_none()); } + /// A GRIB download's read looks at its Cancel as it goes: once cancelled, it stops and says so + /// rather than reading on to its end with the turn held. + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn a_cancelled_grib_read_stops() { + use std::sync::atomic::{AtomicBool, Ordering}; + // A GRIB2 message whose length runs past these bytes: read through, it is cut short. + let mut bytes = b"GRIB\0\0\0\x02".to_vec(); + bytes.extend(1000u64.to_be_bytes()); + bytes.resize(64, 0); + let left = std::sync::Arc::new(AtomicBool::new(false)); + let read = crate::read_download("t.grb", &bytes, None, true, &left).unwrap_err(); + assert!(!read.contains("cancel"), "{read}"); + left.store(true, Ordering::Relaxed); + let cancelled = crate::read_download("t.grb", &bytes, None, true, &left).unwrap_err(); + assert!(cancelled.to_lowercase().contains("cancel"), "{cancelled}"); + } + /// A PDF download's page waiting for its turn to be drawn is cancelled like a download: taken /// off the list at once, said cancelled, and not added when its turn comes (#2336). #[test] diff --git a/crates/ui-egui/src/syncmark.rs b/crates/ui-egui/src/syncmark.rs index cfcda3778b..6bfb58bb58 100644 --- a/crates/ui-egui/src/syncmark.rs +++ b/crates/ui-egui/src/syncmark.rs @@ -48,8 +48,9 @@ impl Drop for Job { } } -/// The hash thread's Cancel, as `rows_digest` looks at it. -struct Stop(Arc); +/// A thread's Cancel, as the readers' progress checks look at it: the hash thread's +/// (`rows_digest`), a download's read ([`crate::read_download`]). +pub(crate) struct Stop(pub(crate) Arc); impl rustgis_engine::data::progress::Probe for Stop { fn cancelled(&self) -> bool { From 447e85de6682b1e723fec065c8c45971f24c428d Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sat, 21 Nov 2026 03:57:33 -0300 Subject: [PATCH 14/17] fix(data): GRIB review round 13 (#2428) - GRIB2: a field's sections 4 to 6 given again before its section 7 say the field before as damaged and are never read with the next field's (no lost field, no wrong bitmap). - A section chain that breaks (too short, or past the message's end) makes the message's length WrongLength in GRIB1 and GRIB2, so a message it would hide is still found and read. - Fields of a message too large to read whole are counted apart, with their own reason, not as past the memory limit; read_limited lets a test give a small limit. - The engine test's GRIB fixture is written with escapes, not raw control bytes. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/raster/grib.rs | 61 ++++++++++++++---- crates/data/src/raster/grib_tests.rs | 92 ++++++++++++++++++++++++++++ crates/engine/src/tests.rs | 3 +- 3 files changed, 143 insertions(+), 13 deletions(-) diff --git a/crates/data/src/raster/grib.rs b/crates/data/src/raster/grib.rs index 9989593d5e..d33b8d2503 100644 --- a/crates/data/src/raster/grib.rs +++ b/crates/data/src/raster/grib.rs @@ -59,11 +59,15 @@ pub fn read(source: R, name: &str) -> Result { /// [`read`], with the no-data value of a sidecar (`.aux.xml`) beside the file, whose values aren't /// counted as rounded ([`Uncounted`]'s rule): GRIB has no no-data value of its own (a bitmap masks). -pub fn read_with_nodata(mut source: R, name: &str, sidecar_nodata: Option) -> Result { +pub fn read_with_nodata(source: R, name: &str, sidecar_nodata: Option) -> Result { + read_limited(source, name, sidecar_nodata, max_samples()) +} + +/// [`read_with_nodata`], holding at most `limit` values. +fn read_limited(mut source: R, name: &str, sidecar_nodata: Option, limit: usize) -> Result { let uncounted = Uncounted::new(None, sidecar_nodata); let file_len = source.seek(SeekFrom::End(0))?; source.seek(SeekFrom::Start(0))?; - let limit = max_samples(); let mut fields: Vec = Vec::new(); let mut skipped = Skipped::default(); let mut at = 0u64; @@ -146,8 +150,9 @@ pub fn read_with_nodata(mut source: R, name: &str, sidecar_nodat counted.add(len)?; // Past the memory limit, a message none of whose fields fits in the room left, or one // larger than those points can take (at most 32 bits each, a bitmap and a megabyte of - // sections): only counted, never read. A grid this reader refuses, or too many sections, - // leaves the message out unread. + // sections): only counted, never read. A message is read whole, so that size bounds the bytes + // held: its fields are left out even where one of them would fit, and are said apart. + // A grid this reader refuses, or too many sections, leaves the message out unread. match header { Header::Refused(why) => { skipped.add(why); @@ -161,10 +166,14 @@ pub fn read_with_nodata(mut source: R, name: &str, sidecar_nodat } let room = limit.saturating_sub(held); let too_long = len > (room as u64).saturating_mul(5).saturating_add(1 << 20); - if held >= limit || too_long || matches!(header, Header::Points(n) if n > room) { + if held >= limit || matches!(header, Header::Points(n) if n > room) { skipped.over_limit += count_fields(&mut source, start, len, edition == Some(2))?; continue; } + if too_long { + skipped.too_long += count_fields(&mut source, start, len, edition == Some(2))?; + continue; + } let mut bytes = Vec::new(); bytes.try_reserve_exact(len as usize).map_err(|_| bad("not enough memory for a message"))?; source.seek(SeekFrom::Start(start))?; @@ -319,9 +328,10 @@ enum Header { /// How many points the smallest of its fields covers (GRIB1's grid description, GRIB2's /// number of data points of the grid each data section follows): when not even that one fits /// in the room left, the message is left out unread; each of the others is admitted or not as - /// it is decoded. + /// it is decoded, unless the message's bytes are more than the room left lets be read whole. Points(usize), - /// Sections that end on a "7777" before the message's length does: the length is damaged. + /// Sections that end on a "7777" before the message's length does, or don't chain to its + /// end: the length is damaged. WrongLength, /// Headers the decoder will find damaged: it says why. Unknown, @@ -350,8 +360,9 @@ fn header(source: &mut R, start: u64, len: u64, grib2: bool) -> return Ok(Header::Unknown); } // The sections the flags say are there (product definition, grid description, bitmap, - // binary data), by their lengths: ending on a "7777" before the message's end, the - // message's length is wrong. + // binary data), by their lengths: ending on a "7777" before the message's end, or broken + // (a section shorter than its length octets, or past the message's end), the message's + // length can't be trusted (it may hide the next message). let flags = head[7]; let mut at = start + 8 + u64::from(be(&head, 0, 3)); let mut chained = true; @@ -367,7 +378,7 @@ fn header(source: &mut R, start: u64, len: u64, grib2: bool) -> at += u64::from(be(&size, 0, 3)); } let mut tail = [0u8; 4]; - if chained && at + 4 < end && read(source, at, &mut tail)? && &tail == b"7777" { + if !chained || (at + 4 < end && read(source, at, &mut tail)? && &tail == b"7777") { return Ok(Header::WrongLength); } if flags & 0x80 == 0 { @@ -391,13 +402,15 @@ fn header(source: &mut R, start: u64, len: u64, grib2: bool) -> // Each section's 5-octet header (a constant field's data section is no longer, just before // "7777"), and the grid's number of data points (octets 7 to 10) when it is section 3. The // last "7777" can't be read with a fifth octet: one that can comes before the message's end. + // Sections that don't end on the last "7777" (one shorter than its header, or past the + // message's end) break the message's length as one: it may hide the next message. while read(source, at, &mut head[..5])? { if &head[..4] == b"7777" { return Ok(Header::WrongLength); } let size = u64::from(be(&head, 0, 4)); if size < 5 { - break; + return Ok(Header::WrongLength); } sections += 1; if sections > MAX_SECTIONS { @@ -411,6 +424,9 @@ fn header(source: &mut R, start: u64, len: u64, grib2: bool) -> } at += size; } + if at != end - 4 { + return Ok(Header::WrongLength); + } Ok(Header::Points(fewest.unwrap_or(0))) } @@ -464,6 +480,8 @@ struct Skipped { damage: Vec<(String, usize)>, other_grid: usize, over_limit: usize, + /// Fields of messages larger than the room left lets be read whole. + too_long: usize, cut: usize, /// Bytes outside every message that aren't zeros. junk: u64, @@ -498,6 +516,12 @@ impl Skipped { count(self.over_limit) )); } + if self.too_long > 0 { + out.push(format!( + "{} left out: their message is larger than the memory left lets be read whole, even where one of its fields would fit; split the file with a GRIB tool (wgrib2 or CDO) and add its parts", + count(self.too_long) + )); + } if self.cut > 0 { out.push("the file ends inside a message, which is left out".to_string()); } @@ -1068,7 +1092,8 @@ fn section2(b: &[u8], at: usize) -> Option<(u8, &[u8])> { /// A GRIB2 message (WMO FM 92 GRIB edition 2): each of its fields. A grid (section 3) may serve /// the fields after it, but each field has its own sections 4 to 7 (WMO's regulation 92.1.3): a /// field without its own product, packing or bitmap section is damaged, never read with the one -/// before it, and so are sections 4 to 6 the message ends on without a section 7. `first`: the +/// before it, and so are sections 4 to 6 without a section 7 after them, whether the message ends +/// on them or another field's sections follow (never read with that field's). `first`: the /// grid of the fields kept, if any; a field on another is left out before it is decoded. fn grib2(b: &[u8], room: usize, mut first: Option, uncounted: Uncounted) -> Vec> { let mut out = Vec::new(); @@ -1097,6 +1122,18 @@ fn grib2(b: &[u8], room: usize, mut first: Option, uncounted: Uncounted) - break; }; at += s.len(); + // A field's product, packing or bitmap given again before its data section: the field + // before ends without one, and gives nothing to the field after it. + let again = match number { + 4 => product.is_some() || packing.is_some() || bitmap.is_some(), + 5 => packing.is_some() || bitmap.is_some(), + 6 => bitmap.is_some(), + _ => false, + }; + if again { + out.push(Err(Skip::Damaged("a field without its data section".to_string()))); + (product, packing, bitmap) = (None, None, None); + } match number { 1 => { reference = date( diff --git a/crates/data/src/raster/grib_tests.rs b/crates/data/src/raster/grib_tests.rs index 1217a3898f..43effe9450 100644 --- a/crates/data/src/raster/grib_tests.rs +++ b/crates/data/src/raster/grib_tests.rs @@ -1095,3 +1095,95 @@ fn a_field_on_another_grid_takes_none_of_the_room() { assert!(matches!(got.first(), Some(Err(Skip::OtherGrid)))); assert!(matches!(got.get(1), Some(Ok(f)) if f.values == vec![1.0, 2.0])); } + +#[test] +fn a_field_whose_sections_come_again_before_its_data_is_damaged() { + // Field A's sections 3 to 6, no section 7, then field B whole: A is said, B read. + let a = || { + let mut a = F2::new(2, 1, vec![1]); + a.keep = Some(vec![true, false]); + a + }; + let b = F2::new(2, 1, vec![3, 4]); + let mut body = without_section(&a(), 7); + body.extend(b.sections()); + let r = read_bytes(&message_of(&body), "t").unwrap(); + assert_eq!(r.bands.len(), 1); + assert_eq!(r.bands[0].data, vec![3.0, 4.0]); + assert!(r.lost.contains(&"1 field left out: damaged (a field without its data section)".to_string()), "{:?}", r.lost); + // Then field B without its bitmap section: never read with A's bitmap. + let mut body = without_section(&a(), 7); + body.extend(without_section(&b, 6)); + let got = grib2(&message_of(&body), usize::MAX, None, Uncounted::default()); + assert_eq!(got.len(), 2); + assert!(matches!(&got[0], Err(Skip::Damaged(why)) if why == "a field without its data section")); + assert!(matches!(&got[1], Err(Skip::Damaged(why)) if why == "a field without its bitmap section")); +} + +/// The offset in a GRIB2 message of its section `number`. +fn section_at(message: &[u8], number: u8) -> usize { + let mut at = 16; + while message[at..at + 4] != *b"7777" { + if message[at + 4] == number { + return at; + } + at += u32::from_be_bytes([message[at], message[at + 1], message[at + 2], message[at + 3]]) as usize; + } + panic!("no section {number}"); +} + +#[test] +fn sections_that_break_before_a_length_that_hides_the_next_message_are_damage() { + // GRIB1: the first message's binary data section 2 octets long, its length running to the + // end of the second message. + let mut first = G1::new(2, 1, vec![1, 2]).bytes(); + let second = G1::new(2, 1, vec![3, 4]).bytes(); + let len = (first.len() + second.len()) as u64; + first[4..7].copy_from_slice(&u(len, 3)); + let gds = 8 + be(&first, 8, 3) as usize; + let bds = gds + be(&first, gds, 3) as usize; + first[bds..bds + 3].copy_from_slice(&u(2, 3)); + let mut file = first; + file.extend(&second); + assert_eq!(header(&mut std::io::Cursor::new(&file), 0, len, false).unwrap(), Header::WrongLength); + let r = read_bytes(&file, "t").unwrap(); + assert_eq!(r.bands.len(), 1); + assert_eq!(r.bands[0].data, vec![3.0, 4.0]); + assert!(r.lost.contains(&"1 message left out: damaged".to_string()), "{:?}", r.lost); + // GRIB2: a data section shorter than its header, then one running past the first message's + // "7777" into the second. + for grow in [None, Some(2)] { + let mut first = grib2_message(&[F2::new(2, 1, vec![1, 2])]); + let second = grib2_message(&[F2::new(2, 1, vec![3, 4])]); + let len = (first.len() + second.len()) as u64; + first[8..16].copy_from_slice(&u(len, 8)); + let at = section_at(&first, 7); + let size = grow.map_or(2, |n| be(&first, at, 4) + n); + first[at..at + 4].copy_from_slice(&u(u64::from(size), 4)); + let mut file = first; + file.extend(&second); + assert_eq!(header(&mut std::io::Cursor::new(&file), 0, len, true).unwrap(), Header::WrongLength, "{grow:?}"); + let r = read_bytes(&file, "t").unwrap(); + assert_eq!(r.bands.len(), 1); + assert_eq!(r.bands[0].data, vec![3.0, 4.0]); + assert!(r.lost.contains(&"1 message left out: damaged".to_string()), "{:?}", r.lost); + } +} + +#[test] +fn fields_of_a_message_too_large_to_read_whole_are_said_so() { + // Room for 4 values: a message of a 2-point field with a megabyte of local use (section 2) is + // larger than that room lets be read; the next message is read. + let mut local = u(5 + (1 << 20), 4); + local.push(2); + local.resize(5 + (1 << 20), 0); + local.extend(F2::new(2, 1, vec![1, 2]).sections()); + let mut file = message_of(&local); + file.extend(grib2_message(&[F2::new(2, 1, vec![3, 4])])); + let r = read_limited(std::io::Cursor::new(&file), "t", None, 4).unwrap(); + assert_eq!(r.bands.len(), 1); + assert_eq!(r.bands[0].data, vec![3.0, 4.0]); + let said = "1 field left out: their message is larger than the memory left lets be read whole, even where one of its fields would fit; split the file with a GRIB tool (wgrib2 or CDO) and add its parts"; + assert!(r.lost.contains(&said.to_string()), "{:?}", r.lost); + assert!(!r.lost.iter().any(|l| l.contains("the bands read hold the most")), "{:?}", r.lost); +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 66b05091fb..f609606aa3 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -45315,7 +45315,8 @@ fn a_pdf_says_which_frames_it_doesnt_georeference() { fn a_grib_download_is_read_off_the_frame() { use crate::cmd::raster::download_page; let asked = json!({"url": "x"}); - let message = b"GRIB4"; + // A GRIB1 message of 52 octets: "GRIB", its length, its edition. + let message = b"GRIB\0\0\x34\x01"; let found = download_page("https://example.org/bam/PREC.grb", &asked, message); assert_eq!(found, Some(("PREC.grb".to_string(), None, true))); let (sniffed, ..) = download_page("https://example.org/record?id=7", &asked, message).unwrap(); From c6cf33c6717d7754eca4e0dc133007c60156c894 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sat, 21 Nov 2026 09:44:46 -0300 Subject: [PATCH 15/17] fix(data): GRIB review round 14 (#2428) - A decimal scale factor past f64 no longer refuses the field: past it, R / 10^D and 2^E / 10^D are made by scaled_by, in steps taken toward 1, so a value past f64 only when it truly is. A value too small for f64 is kept as its smallest, counted as rounded, never an exact 0. times_two_to gives way to it. - The download read's Cancel docs say what the reader does: it stops once the message or band under way is done. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/raster/grib.rs | 58 +++++++++++++++++----------- crates/data/src/raster/grib_tests.rs | 38 +++++++++++++----- crates/ui-egui/src/lib.rs | 16 ++++---- 3 files changed, 72 insertions(+), 40 deletions(-) diff --git a/crates/data/src/raster/grib.rs b/crates/data/src/raster/grib.rs index d33b8d2503..f50a15bba0 100644 --- a/crates/data/src/raster/grib.rs +++ b/crates/data/src/raster/grib.rs @@ -858,13 +858,13 @@ fn unpack( if (data.len() as u64) < need { return Err(Skip::Damaged("a data section shorter than its values".to_string())); } - let ten = decimal(d)?; reference(r)?; - // 2^E, where `f64` holds it; past that (no producer writes such an E, but it is kept), and - // where `R + X × 2^E` is past `f64` but the division brings it back, the value is made as - // `R / 10^D + X × (2^E / 10^D)`. A value past `f64` either way is past `f32`'s range. - let scale = (-1000..=1000).contains(&e).then(|| 2f64.powi(e as i32)); - let (base, step) = (r / ten, times_two_to(1.0 / ten, e)); + // 2^E and 10^D, where `f64` holds them; past that (no producer writes such an E or D, but + // they are kept), and where `R + X × 2^E` is past `f64` but the division brings it back, the + // value is made as `R / 10^D + X × (2^E / 10^D)`, each by [`scaled_by`]. A value past `f64` + // either way is past `f32`'s range. + let scale = decimal(d).filter(|_| (-1000..=1000).contains(&e)).map(|ten| (2f64.powi(e as i32), ten)); + let (base, step) = (scaled_by(r, 0, d), scaled_by(1.0, e, d)); let mut bit = 0u64; field_values(points, mask, count, uncounted, || { // The 8 octets from the value's first: at most 7 bits before it, and its 32 at most. @@ -872,7 +872,7 @@ fn unpack( let word = (0..8).fold(0u64, |w, i| (w << 8) | u64::from(data.get(byte + i).copied().unwrap_or(0))); let x = ((word << (bit % 8)) >> (64 - bits)) as f64; bit += u64::from(bits); - let wide = scale.map_or(f64::INFINITY, |s| (r + x * s) / ten); + let wide = scale.map_or(f64::INFINITY, |(s, ten)| (r + x * s) / ten); if wide.is_finite() { wide } else if x == 0.0 { @@ -883,22 +883,35 @@ fn unpack( }) } -/// `v` × 2^`e`, by at most 2^±1000 at a time, so an `e` past `f64`'s exponents still gives a -/// value `v` brings back into its range. -fn times_two_to(mut v: f64, mut e: i64) -> f64 { - while e != 0 && v != 0.0 && v.is_finite() { - let s = e.clamp(-1000, 1000); - v *= 2f64.powi(s as i32); - e -= s; - } - v +/// 10^`d`, the decimal scale factor's divisor, where `f64` holds it at full precision. +fn decimal(d: i64) -> Option { + let ten = 10f64.powi(d.clamp(-1000, 1000) as i32); + ten.is_normal().then_some(ten) } -/// 10^`d`, the decimal scale factor's divisor; damage when `f64` can't hold it (every value -/// would be 0 or infinite). -fn decimal(d: i64) -> std::result::Result { - let ten = 10f64.powi(d.clamp(-1000, 1000) as i32); - if ten.is_finite() && ten > 0.0 { Ok(ten) } else { Err(Skip::Damaged("a decimal scale factor its values can't take".to_string())) } +/// `v` × 2^`e` / 10^`d`, by steps of at most 2^±500 and 10^±150, each taken toward 1 while one +/// that way is left: the result is past `f64` only when the value is. A value too small for +/// `f64` that isn't 0 is kept as its smallest, so it is counted as rounded to 0 in `f32`, never +/// read as an exact 0. +fn scaled_by(mut v: f64, mut e: i64, mut d: i64) -> f64 { + let sign = v.signum(); + let zero = v == 0.0; + while (e != 0 || d != 0) && v != 0.0 && v.is_finite() { + // Toward 1: down by 2^-n (e < 0) or 10^-n (d > 0) from above 1, up from below. + let down = v.abs() > 1.0; + let two = if down { e < 0 } else { e > 0 }; + let ten = if down { d > 0 } else { d < 0 }; + if two || (!ten && e != 0) { + let s = e.clamp(-500, 500); + v *= 2f64.powi(s as i32); + e -= s; + } else { + let s = d.clamp(-150, 150); + v /= 10f64.powi(s as i32); + d -= s; + } + } + if v == 0.0 && !zero { sign * f64::from_bits(1) } else { v } } /// A reference value that is a number: GRIB2's IEEE bits may give an infinity or NaN, which no @@ -916,9 +929,8 @@ fn constant( points: usize, uncounted: Uncounted, ) -> std::result::Result<(Vec, u64, u64), Skip> { - let ten = decimal(d)?; reference(r)?; - let v = r / ten; + let v = decimal(d).map_or_else(|| scaled_by(r, 0, d), |ten| r / ten); field_values(points, mask, count, uncounted, || v) } diff --git a/crates/data/src/raster/grib_tests.rs b/crates/data/src/raster/grib_tests.rs index 43effe9450..91a36d7826 100644 --- a/crates/data/src/raster/grib_tests.rs +++ b/crates/data/src/raster/grib_tests.rs @@ -571,16 +571,34 @@ fn a_length_past_its_message_hides_nothing() { } #[test] -fn scale_factors_past_f64_are_damage() { - for (d, bits) in [(400, 16), (-400, 16), (400, 0)] { - let mut g = G1::new(2, 1, vec![1, 2]); - (g.d, g.bits) = (d, bits); - if bits == 0 { - g.x.clear(); - } - let e = read_bytes(&g.bytes(), "t").unwrap_err().to_string(); - assert!(e.contains("damaged (a decimal scale factor its values can't take)"), "{d}: {e}"); - } +fn scale_factors_past_f64_give_the_values_they_make() { + // D = 400: 1 / 10^400 and 2 / 10^400 are 0 in f32, counted as rounded, never an exact 0. + let mut g = G1::new(2, 1, vec![1, 2]); + (g.d, g.bits) = (400, 16); + let r = read_bytes(&g.bytes(), "t").unwrap(); + assert_eq!(r.bands[0].data, vec![0.0, 0.0]); + assert_eq!(r.rounded.first(), Some(&2)); + // D = −400: 10^400 and 2 × 10^400, past f32's range, said. + let mut g = G1::new(2, 1, vec![1, 2]); + (g.d, g.bits) = (-400, 16); + let r = read_bytes(&g.bytes(), "t").unwrap(); + assert!(r.bands[0].data.iter().all(|v| v.is_nan())); + assert!(r.lost.contains(&"2 values past the range of 32-bit floats (±3.4 × 10^38) have no value".to_string()), "{:?}", r.lost); + // A constant field of 0 with D = 400: exactly 0, nothing said. + let mut g = G1::new(2, 1, vec![]); + (g.d, g.bits) = (400, 0); + let r = read_bytes(&g.bytes(), "t").unwrap(); + assert_eq!(r.bands[0].data, vec![0.0, 0.0]); + assert!(r.rounded.iter().all(|n| *n == 0), "{:?}", r.rounded); + assert!(!r.lost.iter().any(|l| l.contains("past the range") || l.contains("decimal")), "{:?}", r.lost); + // E = 1030 and D = 310, each past f64 alone: 2^1030 / 10^310, about 1.15, read. + let mut g = G1::new(2, 1, vec![1, 0]); + (g.e, g.d, g.bits) = (1030, 310, 16); + let r = read_bytes(&g.bytes(), "t").unwrap(); + let want = (2f64.powi(1000) / 1e300) * (2f64.powi(30) / 1e10); + assert!((f64::from(r.bands[0].data[0]) / want - 1.0).abs() < 1e-6, "{:?} {want}", r.bands[0].data); + assert_eq!(r.bands[0].data[1], 0.0); + assert!(!r.lost.iter().any(|l| l.contains("past the range")), "{:?}", r.lost); // Values past f64 with E = 1000: past f32's range, said (not the whole field refused). let mut g = G1::new(2, 1, vec![1, 2]); (g.e, g.bits) = (1000, 32); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9589a2e02b..5152af5d1b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -286,8 +286,10 @@ fn window_turn(left: &std::sync::atomic::AtomicBool) -> Option Date: Sat, 21 Nov 2026 19:16:15 -0300 Subject: [PATCH 16/17] fix(data,ui-egui): GRIB review round 15 (#2428) - A repeated first column, 360 degrees on, is not laid out, so its points are no longer counted as rounded or past f32's range. - A whole turn's tolerance is never half a step or more: a fine global grid a step short of 360 degrees (1440 x 0.25) keeps every column. - Past f64's decimal scale, R + X x 2^E is scaled as one sum where f64 holds it, so a sum of 0 stays 0 instead of inf - inf. - A download read keeps its turn until the frame takes its result, as a window read does, so at most one read raster waits to be added. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/raster/grib.rs | 61 ++++++++++++++++------------ crates/data/src/raster/grib_tests.rs | 46 +++++++++++++++++++++ crates/ui-egui/src/lib.rs | 11 ++++- 3 files changed, 89 insertions(+), 29 deletions(-) diff --git a/crates/data/src/raster/grib.rs b/crates/data/src/raster/grib.rs index f50a15bba0..9061b6838e 100644 --- a/crates/data/src/raster/grib.rs +++ b/crates/data/src/raster/grib.rs @@ -626,13 +626,13 @@ impl Grid { /// Whether the columns go round the whole globe. fn whole_turn(&self) -> bool { - (self.columns() as f64 * self.dx - 360.0).abs() <= turn_tolerance(self.columns()) + (self.columns() as f64 * self.dx - 360.0).abs() <= turn_tolerance(self.columns(), self.dx) } /// Whether the last column is the first again, 360° on (a grid given from 0° to 360° /// inclusive): it is left out, and the grid is a whole turn. fn repeats_first_column(&self) -> bool { - self.ni > 1 && ((self.ni - 1) as f64 * self.dx - 360.0).abs() <= turn_tolerance(self.ni - 1) + self.ni > 1 && ((self.ni - 1) as f64 * self.dx - 360.0).abs() <= turn_tolerance(self.ni - 1, self.dx) } /// The columns laid out: all of them, less a last one that repeats the first. @@ -683,9 +683,10 @@ impl Grid { /// How far `n` steps of a grid's increment may come from 360° and still be a whole turn: half a /// millidegree a step, as GRIB1 rounds increments to millidegrees (GRIB2's are finer). A grid whose -/// increment doesn't divide 360° (seven columns of 50°) isn't one. -fn turn_tolerance(n: usize) -> f64 { - n as f64 * 0.0005 + 1e-9 +/// increment doesn't divide 360° (seven columns of 50°) isn't one. Never half a step or more: a +/// grid a whole step short of 360° (1440 columns of 0.25° from 0° to 359.75°) isn't one either. +fn turn_tolerance(n: usize, dx: f64) -> f64 { + (n as f64 * 0.0005 + 1e-9).min(dx * 0.5) } /// `v` to a millionth, for a notice (89.91, not 89.91000000000001). @@ -791,10 +792,11 @@ fn ibm(v: u32) -> f64 { /// `count` values `next` gives (in `f64`), held as `f32`, over the points a bitmap keeps (NaN at /// the others), or all of them without one. Also how many of them `f32` rounded, and how many /// are past its range (about ±3.4 × 10^38, `f64`'s too): those have no value (NaN) rather than -/// an infinity. A sidecar's no-data value isn't counted either way ([`Uncounted`]'s rule). The -/// values are never held apart from the field, so it costs 4 bytes a point. +/// an infinity. A sidecar's no-data value isn't counted either way ([`Uncounted`]'s rule), and +/// neither is a point of a repeated first column (`grid`'s, which [`to_raster`] doesn't lay out). +/// The values are never held apart from the field, so it costs 4 bytes a point. fn field_values( - points: usize, + (points, grid): (usize, &Grid), mask: Option<&[u8]>, count: usize, uncounted: Uncounted, @@ -810,26 +812,28 @@ fn field_values( let mut out = Vec::new(); out.try_reserve_exact(points).map_err(|_| Skip::TooLarge)?; let (mut rounded, mut past, mut left) = (0u64, 0u64, count); + let (repeats, columns) = (grid.repeats_first_column(), grid.columns()); for k in 0..points { let kept = mask.is_none_or(|bits| bits.get(k / 8).is_some_and(|b| b & (0x80 >> (k % 8)) != 0)); if kept && left > 0 { left -= 1; let wide = next(); let v = wide as f32; + let laid = u64::from(!repeats || grid.place(k).0 < columns); match uncounted.decides(v, || Some(Exact::Float(wide))) { // The no-data value itself (masked when the sidecar is applied). Some(true) => out.push(if v.is_finite() { v } else { f32::NAN }), _ if !v.is_finite() => { - past += 1; + past += laid; out.push(f32::NAN); } // A value that became the no-data value. Some(false) => { - rounded += 1; + rounded += laid; out.push(v); } None => { - rounded += u64::from(f64::from(v) != wide); + rounded += laid * u64::from(f64::from(v) != wide); out.push(v); } } @@ -848,7 +852,7 @@ fn unpack( (count, bits): (usize, u32), (r, e, d): (f64, i64, i64), mask: Option<&[u8]>, - points: usize, + at: (usize, &Grid), uncounted: Uncounted, ) -> std::result::Result<(Vec, u64, u64), Skip> { if bits > MAX_BITS { @@ -859,24 +863,27 @@ fn unpack( return Err(Skip::Damaged("a data section shorter than its values".to_string())); } reference(r)?; - // 2^E and 10^D, where `f64` holds them; past that (no producer writes such an E or D, but - // they are kept), and where `R + X × 2^E` is past `f64` but the division brings it back, the - // value is made as `R / 10^D + X × (2^E / 10^D)`, each by [`scaled_by`]. A value past `f64` - // either way is past `f32`'s range. - let scale = decimal(d).filter(|_| (-1000..=1000).contains(&e)).map(|ten| (2f64.powi(e as i32), ten)); + // 2^E and 10^D, where `f64` holds them. Past that (no producer writes such an E or D, but + // they are kept), `R + X × 2^E` is divided by [`scaled_by`] where `f64` holds it (so a sum of + // 0 stays 0); where it is past `f64` but the division brings it back, the value is made as + // `R / 10^D + X × (2^E / 10^D)`, each by [`scaled_by`]. A value past `f64` either way is past + // `f32`'s range. + let two = (-1000..=1000).contains(&e).then(|| 2f64.powi(e as i32)); + let ten = decimal(d); let (base, step) = (scaled_by(r, 0, d), scaled_by(1.0, e, d)); let mut bit = 0u64; - field_values(points, mask, count, uncounted, || { + field_values(at, mask, count, uncounted, || { // The 8 octets from the value's first: at most 7 bits before it, and its 32 at most. let byte = (bit / 8) as usize; let word = (0..8).fold(0u64, |w, i| (w << 8) | u64::from(data.get(byte + i).copied().unwrap_or(0))); let x = ((word << (bit % 8)) >> (64 - bits)) as f64; bit += u64::from(bits); - let wide = scale.map_or(f64::INFINITY, |(s, ten)| (r + x * s) / ten); + let sum = two.map_or(f64::INFINITY, |s| r + x * s); + let wide = ten.map_or(f64::INFINITY, |ten| sum / ten); if wide.is_finite() { wide - } else if x == 0.0 { - base + } else if sum.is_finite() { + scaled_by(sum, 0, d) } else { base + x * step } @@ -926,12 +933,12 @@ fn constant( (r, d): (f64, i64), count: usize, mask: Option<&[u8]>, - points: usize, + at: (usize, &Grid), uncounted: Uncounted, ) -> std::result::Result<(Vec, u64, u64), Skip> { reference(r)?; let v = decimal(d).map_or_else(|| scaled_by(r, 0, d), |ten| r / ten); - field_values(points, mask, count, uncounted, || v) + field_values(at, mask, count, uncounted, || v) } /// `n` bitmap bits set among the first `points`. @@ -1017,9 +1024,9 @@ fn grib1(b: &[u8], room: usize, first: Option, uncounted: Uncounted) -> st let count = bitmap.map_or(points, |m| kept(m, points)); let data = bds.get(11..).unwrap_or_default(); let (values, rounded, past) = if bits == 0 { - constant((r, d), count, bitmap, points, uncounted)? + constant((r, d), count, bitmap, (points, &grid), uncounted)? } else { - unpack(data, (count, bits), (r, e, d), bitmap, points, uncounted)? + unpack(data, (count, bits), (r, e, d), bitmap, (points, &grid), uncounted)? }; Ok(Field { name, grid, values, rounded, past }) } @@ -1189,9 +1196,9 @@ fn grib2(b: &[u8], room: usize, mut first: Option, uncounted: Uncounted) - return Err(Skip::Damaged("a field whose values don't fill its grid".to_string())); } let (values, rounded, past) = if bits == 0 { - constant((r, d), count, mask, points, uncounted)? + constant((r, d), count, mask, (points, &grid), uncounted)? } else { - unpack(s.get(5..).unwrap_or_default(), (count, bits), (r, e, d), mask, points, uncounted)? + unpack(s.get(5..).unwrap_or_default(), (count, bits), (r, e, d), mask, (points, &grid), uncounted)? }; held += points; first.get_or_insert(grid); diff --git a/crates/data/src/raster/grib_tests.rs b/crates/data/src/raster/grib_tests.rs index 91a36d7826..410b44b7f7 100644 --- a/crates/data/src/raster/grib_tests.rs +++ b/crates/data/src/raster/grib_tests.rs @@ -683,6 +683,52 @@ fn a_repeated_first_column_is_left_out_and_the_globe_laid_out_from_180() { ); } +#[test] +fn a_repeated_first_column_is_not_counted_as_rounded_or_past_the_range() { + // 7 columns of 60° from 0° to 360°, the last left out: only the 6 laid out are counted. + // 0.1 to 0.7 less 0.5 (which f32 holds), each rounded by f32: 6, not 7. + let mut g = G1::new(7, 1, vec![1, 2, 3, 4, 6, 7, 1]); + (g.lat1, g.lat2, g.lon1, g.lon2, g.di, g.dj, g.d) = (0, 0, 0, 0, 60_000, 60_000, 1); + assert_eq!(read_bytes(&g.bytes(), "t").unwrap().rounded, vec![6]); + // Past f32's range: 6 values said, not 7. + let mut g = G1::new(7, 1, vec![1, 2, 3, 4, 5, 6, 1]); + (g.lat1, g.lat2, g.lon1, g.lon2, g.di, g.dj, g.d) = (0, 0, 0, 0, 60_000, 60_000, -400); + let r = read_bytes(&g.bytes(), "t").unwrap(); + assert!(r.lost.contains(&"6 values past the range of 32-bit floats (±3.4 × 10^38) have no value".to_string()), "{:?}", r.lost); +} + +#[test] +fn fine_global_grids_a_step_short_of_360_have_no_repeated_column() { + // 1440 columns of 0.25° and 3600 of 0.1° from 0°, ending a step short of 360°: all read, the + // 180° column first, from −180°. + for (di, ni) in [(250, 1440), (100, 3600)] { + let mut g = G1::new(ni, 1, (0..ni as u32).collect()); + (g.lat1, g.lat2, g.lon1, g.lon2, g.di, g.dj) = (0, 0, 0, (ni as i64 - 1) * di as i64, di, di); + let r = read_bytes(&g.bytes(), "t").unwrap(); + assert_eq!(r.width as usize, ni); + assert!(!r.lost.iter().any(|l| l.contains("repeats the first")), "{:?}", r.lost); + assert_eq!(r.bands[0].data[0], (ni / 2) as f32); + assert!((r.transform.origin_x - (-180.0 - di as f64 / 2000.0)).abs() < 1e-9, "{}", r.transform.origin_x); + } + // One column more, at 360°: the first again, left out. + let mut g = G1::new(1441, 1, (0..1441).collect()); + (g.lat1, g.lat2, g.lon1, g.lon2, g.di, g.dj) = (0, 0, 0, 360_000, 250, 250); + let r = read_bytes(&g.bytes(), "t").unwrap(); + assert_eq!(r.width, 1440); + assert!(r.lost.iter().any(|l| l.contains("repeats the first")), "{:?}", r.lost); +} + +#[test] +fn a_sum_of_0_past_f64s_decimal_scale_is_0() { + // R = −1, D = −400: X = 1 gives (−1 + 1) × 10^400, exactly 0; X = 0 gives −10^400, past f32. + let mut g = G1::new(2, 1, vec![1, 0]); + (g.r, g.d, g.bits) = (0xC110_0000, -400, 16); + let r = read_bytes(&g.bytes(), "t").unwrap(); + assert_eq!(r.bands[0].data[0], 0.0); + assert!(r.bands[0].data[1].is_nan()); + assert!(r.lost.contains(&"1 value past the range of 32-bit floats (±3.4 × 10^38) has no value".to_string()), "{:?}", r.lost); +} + #[test] fn header_counts_a_last_constant_field() { // A constant field's data section is 5 octets, just before "7777". diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5152af5d1b..75137b3425 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -5972,13 +5972,20 @@ impl RustGisApp { let bytes = std::sync::Arc::new(bytes); let mine = bytes.clone(); let spawned = std::thread::Builder::new().name("download-read".into()).spawn(move || { - let read = match window_turn(&leaving) { + let turn = window_turn(&leaving); + let read = match turn { // On a thread no command's catch reaches: a bug must not leave it running forever. - Some(_turn) => read_download(&name, &bytes, page.as_deref(), place, &leaving), + Some(_) => read_download(&name, &bytes, page.as_deref(), place, &leaving), None => Err(tl!("given up before it was read: it was cancelled, or its project was closed").to_string()), }; let bytes = std::sync::Arc::try_unwrap(bytes).unwrap_or_else(|shared| (*shared).clone()); *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(read.map(|r| (bytes, r))); + // As a window's read: the next read waits for the frame to take this one (or for it to + // be cancelled, or the app to be gone), so one read raster at most waits to be added. + while std::sync::Arc::strong_count(&land) > 1 && land.lock().unwrap_or_else(|e| e.into_inner()).is_some() { + std::thread::sleep(std::time::Duration::from_millis(20)); + } + drop(turn); }); match spawned { Ok(_) => { From d9aa65557871a08c4441f893b2a7e2b5e63c14b1 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sat, 21 Nov 2026 20:08:02 -0300 Subject: [PATCH 17/17] fix(data): GRIB review round 16 (#2428) - A packed 0 is R whatever E is: past f64's binary scale it no longer becomes 1 + 0 x inf (NaN, said as past the range). - A value that isn't 0 divided down past f64 to 0 (unpacked or constant) is made by scaled_by, so it is counted as rounded. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/raster/grib.rs | 10 +++++++--- crates/data/src/raster/grib_tests.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/crates/data/src/raster/grib.rs b/crates/data/src/raster/grib.rs index 9061b6838e..ddd92ee1c7 100644 --- a/crates/data/src/raster/grib.rs +++ b/crates/data/src/raster/grib.rs @@ -878,9 +878,12 @@ fn unpack( let word = (0..8).fold(0u64, |w, i| (w << 8) | u64::from(data.get(byte + i).copied().unwrap_or(0))); let x = ((word << (bit % 8)) >> (64 - bits)) as f64; bit += u64::from(bits); - let sum = two.map_or(f64::INFINITY, |s| r + x * s); + // X = 0 is R whatever E is (never 0 × ∞). + let sum = if x == 0.0 { r } else { two.map_or(f64::INFINITY, |s| r + x * s) }; let wide = ten.map_or(f64::INFINITY, |ten| sum / ten); - if wide.is_finite() { + // A sum that isn't 0 divided down to 0 is made by `scaled_by`, so it is counted as + // rounded, never read as an exact 0. + if wide.is_finite() && (wide != 0.0 || sum == 0.0) { wide } else if sum.is_finite() { scaled_by(sum, 0, d) @@ -937,7 +940,8 @@ fn constant( uncounted: Uncounted, ) -> std::result::Result<(Vec, u64, u64), Skip> { reference(r)?; - let v = decimal(d).map_or_else(|| scaled_by(r, 0, d), |ten| r / ten); + // As in `unpack`: an `R` that isn't 0 divided down to 0 is counted as rounded. + let v = decimal(d).map(|ten| r / ten).filter(|v| *v != 0.0 || r == 0.0).unwrap_or_else(|| scaled_by(r, 0, d)); field_values(at, mask, count, uncounted, || v) } diff --git a/crates/data/src/raster/grib_tests.rs b/crates/data/src/raster/grib_tests.rs index 410b44b7f7..42c3f935c8 100644 --- a/crates/data/src/raster/grib_tests.rs +++ b/crates/data/src/raster/grib_tests.rs @@ -729,6 +729,33 @@ fn a_sum_of_0_past_f64s_decimal_scale_is_0() { assert!(r.lost.contains(&"1 value past the range of 32-bit floats (±3.4 × 10^38) has no value".to_string()), "{:?}", r.lost); } +#[test] +fn a_packed_0_past_f64s_binary_scale_is_the_reference_value() { + // R = 1, E = 1100, D = 0: X = 0 is 1; X = 1 is 1 + 2^1100, past f32. + let mut g = G1::new(2, 1, vec![0, 1]); + (g.r, g.e, g.d, g.bits) = (0x4110_0000, 1100, 0, 16); + let r = read_bytes(&g.bytes(), "t").unwrap(); + assert_eq!(r.bands[0].data[0], 1.0); + assert!(r.bands[0].data[1].is_nan()); + assert!(r.lost.contains(&"1 value past the range of 32-bit floats (±3.4 × 10^38) has no value".to_string()), "{:?}", r.lost); +} + +#[test] +fn values_divided_down_past_f64_to_0_are_counted_as_rounded() { + // R = 0, E = −1000, D = 300: X = 1 is about 9 × 10^−602, 0 in f32 and counted; X = 0 is 0. + let mut g = G1::new(2, 1, vec![1, 0]); + (g.e, g.d, g.bits) = (-1000, 300, 16); + let r = read_bytes(&g.bytes(), "t").unwrap(); + assert_eq!(r.bands[0].data, vec![0.0, 0.0]); + assert_eq!(r.rounded, vec![1]); + // A constant field of R = 16^−65 (about 5 × 10^−79) with D = 300: both points counted. + let mut g = G1::new(2, 1, vec![]); + (g.r, g.d, g.bits) = (0x0010_0000, 300, 0); + let r = read_bytes(&g.bytes(), "t").unwrap(); + assert_eq!(r.bands[0].data, vec![0.0, 0.0]); + assert_eq!(r.rounded, vec![2]); +} + #[test] fn header_counts_a_last_constant_field() { // A constant field's data section is 5 octets, just before "7777".