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-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/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/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/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 new file mode 100644 index 0000000000..ddd92ee1c7 --- /dev/null +++ b/crates/data/src/raster/grib.rs @@ -0,0 +1,1364 @@ +//! 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), 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, Exact, GeoTransform, Raster, Uncounted, 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()) +} + +/// 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; + +/// 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}")) +} + +/// 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(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(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 mut fields: Vec = Vec::new(); + let mut skipped = Skipped::default(); + let mut at = 0u64; + 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)); + // 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 { + 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) { + // 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.message(format!("not GRIB 1 or 2 (edition {e})")); + (at, in_skipped) = (start + 4, true); + continue; + } + (Some(_), len) if len < MIN_MESSAGE => { + 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 + // read before it stands, and the cut is said. + (None, _) => { + 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 => { + (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. + (Some(_), len) if !ends_message(&mut source, start + len)? => { + skipped.message("damaged".to_string()); + (at, in_skipped) = (start + 4, true); + continue; + } + _ => {} + } + // 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 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 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); + continue; + } + Header::TooManySections => { + skipped.message(format!("damaged (more than {MAX_SECTIONS} sections)")); + continue; + } + 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); + 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))?; + source.by_ref().take(len).read_to_end(&mut bytes)?; + 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) => { + 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::OtherGrid) => skipped.other_grid += 1, + Err(Skip::Other(why)) => skipped.add(why), + Err(Skip::Damaged(why)) => skipped.damaged(why), + } + } + } + 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" })); + } + if fields.is_empty() { + 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). 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 { + 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); + r.lost.extend(skipped.notes(limit)); + Ok(r) +} + +/// 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], + counted: &mut Counted, +) -> 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)?; + // 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") { + 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) }; + 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; + } + Ok((None, junk)) +} + +/// 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; + 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, 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, 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); + +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)) + } +} + +/// What a message's headers say before its body is read. +#[derive(Debug, PartialEq)] +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, 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, or don't chain to its + /// end: 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. + 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 { + 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, 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); + } + // 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, 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; + 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)); + 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); + if ni == 0xffff || nj == 0xffff || ni == 0 || nj == 0 { + return Ok(Header::Refused("quasi-regular grids".to_string())); + } + return Ok(Header::Points(ni.saturating_mul(nj))); + } + 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. 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 { + return Ok(Header::WrongLength); + } + 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, + 7 => fewest = Some(fewest.map_or(points, |n| n.min(points))), + _ => {} + } + at += size; + } + if at != end - 4 { + return Ok(Header::WrongLength); + } + 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 +/// the sections' headers alone. +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); + 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)?; + 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, 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, + /// 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), +} + +/// 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)>, + /// 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, + /// 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, +} + +impl Skipped { + fn add(&mut self, why: String) { + tally(&mut self.reasons, why); + } + + fn message(&mut self, why: String) { + 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}") + })); + 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); split the file with a GRIB tool (wgrib2 or CDO) and add its parts", + 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()); + } + 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 + } +} + +/// 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) { + 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)); + } +} + +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 { + /// 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.north(), o.north()) + && close(self.west(), o.west()) + && close(self.dx, o.dx) + && close(self.dy, o.dy) + } + + 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.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.dx) + } + + /// 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. + 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 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")); + } + out + } +} + +/// 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. 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). +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: 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 +/// looked at before each band is placed; one band's placement (at most `max_samples` values, one +/// 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.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°. + 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 = 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()); + 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) = 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; + } + let col = (col + roll) % w.max(1); + if let Some(cell) = band.get_mut(row * w + col) { + *cell = *v; + } + } + 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); + } + 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; + } + 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) +} + +/// 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) +} + +/// 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, `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), 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, grid): (usize, &Grid), + mask: Option<&[u8]>, + count: usize, + uncounted: Uncounted, + 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 => { + 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 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 += laid; + out.push(f32::NAN); + } + // A value that became the no-data value. + Some(false) => { + rounded += laid; + out.push(v); + } + None => { + rounded += laid * u64::from(f64::from(v) != wide); + out.push(v); + } + } + } else { + out.push(f32::NAN); + } + } + Ok((out, rounded, past)) +} + +/// 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]>, + at: (usize, &Grid), + uncounted: Uncounted, +) -> std::result::Result<(Vec, u64, 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::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), `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(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); + // 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); + // 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) + } else { + base + x * step + } + }) +} + +/// 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) +} + +/// `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 +/// 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]>, + at: (usize, &Grid), + uncounted: Uncounted, +) -> std::result::Result<(Vec, u64, u64), Skip> { + reference(r)?; + // 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) +} + +/// `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::Damaged("a damaged section".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, 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())); + } + 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)?; + if first.is_some_and(|g| !g.same(&grid)) { + return Err(Skip::OtherGrid); + } + 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)?; + // 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())); + } + at += bms.len(); + Some(bms.get(6..).unwrap_or_default()) + } else { + None + }; + let bds = section1(b, at)?; + // 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())); + } + 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[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, d), count, bitmap, (points, &grid), uncounted)? + } else { + unpack(data, (count, bits), (r, e, d), bitmap, (points, &grid), uncounted)? + }; + Ok(Field { name, grid, values, rounded, past }) +} + +/// 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::Damaged("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 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 { 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. 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 + // 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())); + } + 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 + && 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::Damaged("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. 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 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(); + 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: Option = None; + let mut packing: Option> = None; + let mut bitmap: Option, Skip>> = None; + let mut previous_bitmap: Option<&[u8]> = 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(); + // 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( + 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 = Some(grib2_product(s)), + 5 => packing = Some(grib2_packing(s)), + 6 => { + 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)) + } + 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 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()))??; + if first.is_some_and(|g| !g.same(&grid)) { + return Err(Skip::OtherGrid); + } + 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, d), count, mask, (points, &grid), uncounted)? + } else { + unpack(s.get(5..).unwrap_or_default(), (count, bits), (r, e, d), mask, (points, &grid), uncounted)? + }; + held += points; + first.get_or_insert(grid); + Ok(Field { name: format!("{reference}:discipline={discipline}:{product}"), grid, values, rounded, past }) + })(); + out.push(field); + } + _ => {} + } + } + // 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()))); + } + 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(Skip::Other("predefined grids".to_string())); + } + if s.get(10).copied().unwrap_or(0) != 0 { + return Err(Skip::Other("quasi-regular grids".to_string())); + } + let template = be(s, 12, 2); + if template != 0 { + return Err(Skip::Other(format!("GRIB2 grid template 3.{template} (not regular latitude/longitude)"))); + } + if s.len() < 72 { + return Err(Skip::Damaged("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(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(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 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 { 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. 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 scaled value is unsigned. + if template <= 15 && s.len() >= 28 { + 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={}", 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> { + 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(Skip::Other(format!("GRIB2 {kind} (template 5.{template})"))); + } + if s.len() < 21 { + 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]))) +} + +#[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..42c3f935c8 --- /dev/null +++ b/crates/data/src/raster/grib_tests.rs @@ -0,0 +1,1280 @@ +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); + // Sections of an even number of octets (GRIB1's rule), padded, with their unused bits said. + if let Some(keep) = &self.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([(bits.len() * 8 - keep.len()) as u8, 0, 0]); + bms.extend(bits); + body.extend(bms); + } + 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 | (unused as u8 & 0x0f)); + 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); + // 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)); + 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 { + 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; + 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)); + 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"]); + // 10.1 and 10.2 change in `f32`; 10, 13, 14 and 15 don't. + assert_eq!(r.rounded, vec![2]); +} + +#[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"); +} + +#[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]); + // 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] +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); +} + +#[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)); +} + +#[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_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); + g.x = vec![u32::MAX, 1]; + 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] +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 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 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 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". + 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 = header(&mut std::io::Cursor::new(&msg), 0, msg.len() as u64, true).unwrap(); + // 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)); +} + +#[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. + 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"))); +} + +#[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); +} + +#[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")); +} + +#[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])); +} + +#[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/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index 9424473bbf..f74a66b893 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,10 @@ 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_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. @@ -1245,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"))) { @@ -1258,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)?; @@ -1687,6 +1695,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/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)}"#), diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index 5dcdec2525..ddf580034b 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)}"#, ), @@ -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..f609606aa3 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -45308,6 +45308,23 @@ 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"}); + // 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(); + 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 1340849086..75137b3425 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -285,6 +285,27 @@ 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 { @@ -4250,6 +4271,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"))] @@ -5671,7 +5697,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); @@ -5682,7 +5709,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(); @@ -5711,7 +5738,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. @@ -5786,8 +5813,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 + // once the message or band under way is done ([`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)?; @@ -5916,15 +5944,17 @@ 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 /// [`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 once the message or + /// band it is on is done ([`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"))] @@ -5941,17 +5971,21 @@ 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 read = match window_turn(&leaving) { + let spawned = std::thread::Builder::new().name("download-read".into()).spawn(move || { + 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) => 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()), + 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(_) => { @@ -7644,6 +7678,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/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/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 { diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 57acb0bc54..2a27b3b3e1 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° (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 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 |