Skip to main content

xue/encode/
gdalio.rs

1//! A thin safe wrapper over the handful of GDAL C entry points the encoder
2//! needs.
3//!
4//! The Python encoder shells out to `gdalinfo -json` and `gdal_translate -of
5//! ENVI -ot Float64`; this reads the same numbers in process, which is the
6//! whole point of the experiment — a production GFS run wrote and re-read
7//! several gigabytes of intermediate ENVI files per build.
8//!
9//! Only `gdal-sys` (georust's GDAL FFI crate) is used, not the high-level
10//! `gdal` crate: as of `gdal` 0.19 the safe wrapper does not compile against
11//! GDAL 3.13, whose `GDALDataType` and `GDALRasterIOExtraArg` changed shape.
12//! The surface used here is a dozen stable C functions, so binding them
13//! directly costs less than pinning an older GDAL.
14
15use std::collections::HashMap;
16use std::ffi::{CStr, CString};
17use std::path::Path;
18use std::ptr;
19use std::sync::{Mutex, MutexGuard, Once};
20
21use gdal_sys::{
22    CPLErr, CPLGetLastErrorMsg, GDALAccess, GDALAllRegister, GDALClose, GDALDataType, GDALDatasetH,
23    GDALGetDescription, GDALGetGeoTransform, GDALGetMetadata, GDALGetRasterBand,
24    GDALGetRasterCount, GDALGetRasterNoDataValue, GDALGetRasterOffset, GDALGetRasterScale,
25    GDALGetRasterUnitType, GDALGetRasterXSize, GDALGetRasterYSize, GDALGetSpatialRef, GDALOpen,
26    GDALRWFlag, GDALRasterIO, OSRExportToWktEx, VSIFree,
27};
28
29use crate::encode::errors::{EncodeError, Result};
30
31static REGISTER: Once = Once::new();
32
33/// Serializes access to GDAL's netCDF driver.
34///
35/// libnetcdf and the HDF5 library under it are not thread-safe, and GDAL does
36/// not lock for them: opening and reading one file from several threads at
37/// once fails with "netCDF chunk fetch failed: NetCDF: HDF error". The Python
38/// encoder never met this because every extraction was its own
39/// `gdal_translate` process. GRIB reads are unaffected and stay parallel.
40static NETCDF: Mutex<()> = Mutex::new(());
41
42/// Whether a GDAL connection string names a dataset that must be read under
43/// [`netcdf_guard`]. NetCDF subdatasets are spelled `NETCDF:"<file>":<var>`.
44pub fn needs_serial_access(name: &Path) -> bool {
45    name.to_string_lossy().starts_with("NETCDF:")
46}
47
48/// Hold this for as long as a netCDF dataset is open and being read.
49pub fn netcdf_guard() -> MutexGuard<'static, ()> {
50    // A poisoned lock only means some other worker failed mid-read; the driver
51    // itself is no worse off, and the error has already been reported.
52    NETCDF
53        .lock()
54        .unwrap_or_else(std::sync::PoisonError::into_inner)
55}
56
57fn register() {
58    REGISTER.call_once(|| unsafe { GDALAllRegister() });
59}
60
61fn last_error() -> String {
62    let message = unsafe { CStr::from_ptr(CPLGetLastErrorMsg()) };
63    message.to_string_lossy().trim().to_string()
64}
65
66/// One band's default-domain metadata plus its description, the two things
67/// `gdalinfo -json` reports that record matching reads.
68#[derive(Debug, Clone, Default)]
69pub struct BandInfo {
70    pub number: usize,
71    pub description: String,
72    pub metadata: HashMap<String, String>,
73    /// The band's unit string, what `gdalinfo -json` reports as `unit`.
74    pub unit: String,
75    pub scale: f64,
76    pub offset: f64,
77    pub nodata: Option<f64>,
78}
79
80impl BandInfo {
81    pub fn item(&self, key: &str) -> &str {
82        self.metadata.get(key).map_or("", String::as_str)
83    }
84}
85
86/// An open GDAL dataset. Not `Sync`: GDAL dataset handles must not be shared
87/// between threads, so each worker opens its own.
88pub struct Dataset {
89    handle: GDALDatasetH,
90    width: usize,
91    height: usize,
92}
93
94impl Dataset {
95    /// Open a dataset read-only. `name` is a GDAL connection string, not
96    /// necessarily a filesystem path — the observation path passes
97    /// `NETCDF:"file.nc":cref`.
98    pub fn open(name: &Path) -> Result<Self> {
99        register();
100        let text = name.to_string_lossy().into_owned();
101        let c_name = CString::new(text.clone()).map_err(|_| {
102            EncodeError::conversion(format!("dataset name contains a NUL byte: {text}"))
103        })?;
104        let handle = unsafe { GDALOpen(c_name.as_ptr(), GDALAccess::GA_ReadOnly) };
105        if handle.is_null() {
106            return Err(EncodeError::conversion(format!(
107                "cannot open {text}: {}",
108                last_error()
109            )));
110        }
111        let width = unsafe { GDALGetRasterXSize(handle) };
112        let height = unsafe { GDALGetRasterYSize(handle) };
113        if width <= 0 || height <= 0 {
114            unsafe { GDALClose(handle) };
115            return Err(EncodeError::conversion(format!("{text} has an empty grid")));
116        }
117        Ok(Self {
118            handle,
119            width: width as usize,
120            height: height as usize,
121        })
122    }
123
124    pub fn size(&self) -> (usize, usize) {
125        (self.width, self.height)
126    }
127
128    pub fn band_count(&self) -> usize {
129        (unsafe { GDALGetRasterCount(self.handle) }).max(0) as usize
130    }
131
132    /// The geotransform as `gdalinfo -json` reports it (`as_gdalinfo_json`),
133    /// not the doubles GDAL holds: the reference encoder reads its grid out
134    /// of that text, and this is what both the native grid and the wheel's
135    /// `gdal_info` ([`info_json`]) are built from.
136    pub fn geo_transform(&self) -> Result<[f64; 6]> {
137        let mut transform = [0f64; 6];
138        let status = unsafe { GDALGetGeoTransform(self.handle, transform.as_mut_ptr()) };
139        if status != CPLErr::CE_None {
140            return Err(EncodeError::conversion(format!(
141                "dataset has no geotransform: {}",
142                last_error()
143            )));
144        }
145        Ok(transform.map(as_gdalinfo_json))
146    }
147
148    /// The dataset's coordinate system as WKT2, the text `gdalinfo -json`
149    /// prints under `coordinateSystem.wkt` (the same export options:
150    /// `FORMAT=WKT2`, multi-line); empty when the dataset declares none.
151    /// A projected source (HRRR's Lambert conformal grid) is recognised
152    /// from it (`reproject::lambert_conformal_from_wkt`).
153    pub fn projection_wkt(&self) -> String {
154        let reference = unsafe { GDALGetSpatialRef(self.handle) };
155        if reference.is_null() {
156            return String::new();
157        }
158        let format = CString::new("FORMAT=WKT2").expect("static option");
159        let multiline = CString::new("MULTILINE=YES").expect("static option");
160        let options = [format.as_ptr(), multiline.as_ptr(), ptr::null()];
161        let mut text: *mut std::ffi::c_char = ptr::null_mut();
162        let status = unsafe { OSRExportToWktEx(reference, &mut text, options.as_ptr()) };
163        if status != gdal_sys::OGRErr::OGRERR_NONE || text.is_null() {
164            return String::new();
165        }
166        let wkt = unsafe { CStr::from_ptr(text) }
167            .to_string_lossy()
168            .into_owned();
169        // The string is CPLMalloc'd; VSIFree is CPLFree by another name.
170        unsafe { VSIFree(text.cast()) };
171        wkt
172    }
173
174    /// Dataset-level metadata of one domain (`""` is the default domain).
175    pub fn metadata(&self, domain: &str) -> HashMap<String, String> {
176        let domain = CString::new(domain).unwrap_or_default();
177        let list = unsafe { GDALGetMetadata(self.handle.cast(), domain.as_ptr()) };
178        string_list(list)
179    }
180
181    fn band(&self, number: usize) -> Result<gdal_sys::GDALRasterBandH> {
182        let handle = unsafe { GDALGetRasterBand(self.handle, number as i32) };
183        if handle.is_null() {
184            return Err(EncodeError::conversion(format!(
185                "band {number} does not exist"
186            )));
187        }
188        Ok(handle)
189    }
190
191    pub fn band_info(&self, number: usize) -> Result<BandInfo> {
192        let band = self.band(number)?;
193        let empty = CString::new("").expect("empty string");
194        let metadata = string_list(unsafe { GDALGetMetadata(band.cast(), empty.as_ptr()) });
195        let description = unsafe { CStr::from_ptr(GDALGetDescription(band.cast())) }
196            .to_string_lossy()
197            .into_owned();
198        let unit = unsafe { CStr::from_ptr(GDALGetRasterUnitType(band)) }
199            .to_string_lossy()
200            .into_owned();
201        let mut has_scale = 0;
202        let scale = unsafe { GDALGetRasterScale(band, &mut has_scale) };
203        let mut has_offset = 0;
204        let offset = unsafe { GDALGetRasterOffset(band, &mut has_offset) };
205        let mut has_nodata = 0;
206        let nodata = unsafe { GDALGetRasterNoDataValue(band, &mut has_nodata) };
207        Ok(BandInfo {
208            number,
209            description,
210            metadata,
211            unit,
212            scale: if has_scale != 0 { scale } else { 1.0 },
213            offset: if has_offset != 0 { offset } else { 0.0 },
214            nodata: (has_nodata != 0).then_some(nodata),
215        })
216    }
217
218    pub fn bands(&self) -> Result<Vec<BandInfo>> {
219        (1..=self.band_count()).map(|n| self.band_info(n)).collect()
220    }
221
222    /// Read one whole band as float64, in the dataset's own layout — the same
223    /// bytes `gdal_translate -of ENVI -ot Float64` would have written.
224    pub fn read_band_f64(&self, number: usize) -> Result<Vec<f64>> {
225        let band = self.band(number)?;
226        let mut values = vec![0f64; self.width * self.height];
227        let status = unsafe {
228            GDALRasterIO(
229                band,
230                GDALRWFlag::GF_Read,
231                0,
232                0,
233                self.width as i32,
234                self.height as i32,
235                values.as_mut_ptr().cast(),
236                self.width as i32,
237                self.height as i32,
238                GDALDataType::GDT_Float64,
239                0,
240                0,
241            )
242        };
243        if status != CPLErr::CE_None {
244            return Err(EncodeError::conversion(format!(
245                "cannot read band {number}: {}",
246                last_error()
247            )));
248        }
249        Ok(values)
250    }
251}
252
253impl Drop for Dataset {
254    fn drop(&mut self) {
255        if !self.handle.is_null() {
256            unsafe { GDALClose(self.handle) };
257            self.handle = ptr::null_mut();
258        }
259    }
260}
261
262// A Dataset owns its handle exclusively and is never shared between threads by
263// this crate; moving one to the thread that will read it is what the extract
264// pool does.
265unsafe impl Send for Dataset {}
266
267/// The subset of `gdalinfo -json` that `xuebuild` actually reads, from the
268/// linked GDAL rather than the CLI.
269///
270/// `xuebuild/gdal.py` uses this to inspect GRIB and netCDF inputs without a
271/// system `gdalinfo` on PATH — a scheduled build converting through the
272/// native encoder then needs no system GDAL at all. Only the keys the Python
273/// side consumes are emitted; this is deliberately not a general
274/// reimplementation of `gdalinfo`, and the fields are pinned by
275/// `tests/test_gdalinfo.py`, which diffs them against the real CLI.
276///
277/// A dataset with no geotransform simply omits the key, the way `gdalinfo`
278/// does; the caller decides whether that is fatal.
279pub fn info_json(name: &Path) -> Result<serde_json::Value> {
280    let _serial = needs_serial_access(name).then(netcdf_guard);
281    let dataset = Dataset::open(name)?;
282    let (width, height) = dataset.size();
283
284    let mut info = serde_json::Map::new();
285    info.insert("size".into(), serde_json::json!([width, height]));
286    if let Ok(transform) = dataset.geo_transform() {
287        info.insert("geoTransform".into(), serde_json::json!(transform));
288    }
289    let wkt = dataset.projection_wkt();
290    if !wkt.is_empty() {
291        info.insert("coordinateSystem".into(), serde_json::json!({ "wkt": wkt }));
292    }
293    info.insert(
294        "metadata".into(),
295        serde_json::json!({ "": metadata_object(&dataset.metadata("")) }),
296    );
297
298    let mut bands = Vec::with_capacity(dataset.band_count());
299    for band in dataset.bands()? {
300        let mut entry = serde_json::Map::new();
301        entry.insert("band".into(), serde_json::json!(band.number));
302        entry.insert("description".into(), serde_json::json!(band.description));
303        // gdalinfo omits unit when the band declares none, scale and offset
304        // at their identity values, and noDataValue when there is no fill.
305        // The Python readers default all four, so matching the omissions
306        // keeps the two sources indistinguishable rather than merely
307        // equivalent — which is what tests/test_gdalinfo.py asserts.
308        if !band.unit.is_empty() {
309            entry.insert("unit".into(), serde_json::json!(band.unit));
310        }
311        if band.scale != 1.0 {
312            entry.insert("scale".into(), serde_json::json!(band.scale));
313        }
314        if band.offset != 0.0 {
315            entry.insert("offset".into(), serde_json::json!(band.offset));
316        }
317        if let Some(nodata) = band.nodata {
318            entry.insert("noDataValue".into(), serde_json::json!(nodata));
319        }
320        entry.insert(
321            "metadata".into(),
322            serde_json::json!({ "": metadata_object(&band.metadata) }),
323        );
324        bands.push(serde_json::Value::Object(entry));
325    }
326    info.insert("bands".into(), serde_json::Value::Array(bands));
327    Ok(serde_json::Value::Object(info))
328}
329
330/// One geotransform coefficient as `gdalinfo -json` prints it, read back.
331///
332/// `gdalinfo` writes each coefficient with
333/// `json_object_new_double_with_precision(value, 16)`, whose serializer is
334/// `OGRFormatDouble` in fixed notation (3.8 and 3.13 alike): sixteen
335/// decimals, then GDAL's `intelliround`, which takes a trailing `00000x` or
336/// `99999x` for binary noise and cuts it, then trailing zeros dropped. A
337/// netCDF axis GDAL turns into a geotransform carries exactly such noise
338/// (the CWA radar's 0.0125° step arrives as 0.012500000000000292), the
339/// reference sees the cleaned text, and no snap in `grid.rs` cleans a step
340/// that is neither whole thousandths nor whole arc-minutes, so the native
341/// grid reads the same text. Rust's `{:.16}` rounds the exact binary value
342/// half to even, as glibc's `%.16f` does.
343pub(crate) fn as_gdalinfo_json(value: f64) -> f64 {
344    // gdalinfo prints these with %.17g/%.18g, which round-trips exactly.
345    if !value.is_finite() || value.abs() > 1e50 {
346        return value;
347    }
348    let mut text = format!("{value:.16}");
349    intelliround(&mut text);
350    text.parse().unwrap_or(value)
351}
352
353/// GDAL's `intelliround` (`ogr/ogrutils.cpp`), on the fixed-notation text of
354/// [`as_gdalinfo_json`], whose sixteen decimals always leave the last nine
355/// characters digits. The trailing zeros it leaves change no value, so they
356/// are not dropped.
357fn intelliround(text: &mut String) {
358    let s = text.as_bytes();
359    let len = s.len();
360    if len <= 10 {
361        return;
362    }
363    let Some(dot) = text.find('.') else {
364        return;
365    };
366    // GDAL's count is one short of the digits before the point.
367    let before = dot - 1 - usize::from(s[0] == b'-');
368    // Five of `digit` just before the last character; or two of them eight
369    // and nine from the end, with the five after those also `digit` unless
370    // enough digits before the point vouch for them (GDAL's own rule).
371    let short_run = |digit: u8| (2..=6).all(|k| s[len - k] == digit);
372    let long_run = |digit: u8, bound: usize| {
373        dot < len - bound
374            && (3..=7).all(|k| before > k || s[len - k] == digit)
375            && s[len - 8] == digit
376            && s[len - 9] == digit
377    };
378    if short_run(b'0') {
379        text.truncate(len - 1);
380    } else if long_run(b'0', 8) {
381        text.truncate(len - 8);
382    } else if short_run(b'9') {
383        text.truncate(len - 6);
384        round_up_last_digit(text);
385    } else if long_run(b'9', 9) {
386        text.truncate(len - 9);
387        round_up_last_digit(text);
388    }
389}
390
391/// GDAL's `roundup`: one more in the last digit, carrying through nines.
392fn round_up_last_digit(text: &mut String) {
393    let negative = text.starts_with('-');
394    let mut digits: Vec<u8> = text.bytes().skip(usize::from(negative)).collect();
395    let mut carried = true;
396    for digit in digits.iter_mut().rev() {
397        if *digit == b'.' {
398            continue;
399        }
400        if *digit == b'9' {
401            *digit = b'0';
402        } else {
403            *digit += 1;
404            carried = false;
405            break;
406        }
407    }
408    if carried {
409        digits.insert(0, b'1');
410    }
411    let digits = String::from_utf8(digits).expect("ASCII digits");
412    *text = if negative {
413        format!("-{digits}")
414    } else {
415        digits
416    };
417}
418
419/// A metadata domain as a JSON object with its keys in GDAL's own order.
420///
421/// `HashMap` iteration order is arbitrary, and the metadata block ends up in
422/// a report a human reads and a test diffs, so it is sorted rather than left
423/// to vary run to run.
424fn metadata_object(items: &HashMap<String, String>) -> serde_json::Value {
425    let mut keys: Vec<&String> = items.keys().collect();
426    keys.sort();
427    let mut object = serde_json::Map::with_capacity(keys.len());
428    for key in keys {
429        object.insert(key.clone(), serde_json::json!(items[key]));
430    }
431    serde_json::Value::Object(object)
432}
433
434fn string_list(list: *mut *mut std::ffi::c_char) -> HashMap<String, String> {
435    let mut items = HashMap::new();
436    if list.is_null() {
437        return items;
438    }
439    let mut index = 0isize;
440    loop {
441        let entry = unsafe { *list.offset(index) };
442        if entry.is_null() {
443            break;
444        }
445        let text = unsafe { CStr::from_ptr(entry) }.to_string_lossy();
446        if let Some((key, value)) = text.split_once('=') {
447            items.insert(key.to_string(), value.to_string());
448        }
449        index += 1;
450    }
451    items
452}
453
454#[cfg(test)]
455mod tests {
456    use super::as_gdalinfo_json;
457
458    /// Doubles GDAL holds and what `gdalinfo -json` (3.13.3, the same
459    /// formatting as 3.8) printed for each, read back.
460    #[test]
461    fn a_coefficient_reads_as_gdalinfo_prints_it() {
462        let cases = [
463            // The CWA radar series: GDAL's geotransform from its netCDF axes.
464            (0.012500000000000292, 0.0125),
465            (-0.012500000000000018, -0.0125),
466            (25.991950000000003, 25.99195),
467            (122.60185, 122.60185),
468            // A trailing 00000x and 99999x, one decimal from the point too.
469            (40.300000000000004, 40.3),
470            (31.999999999999996, 32.0),
471            (0.9999999999999999, 1.0),
472            (-0.9999999999999999, -1.0),
473            (0.00999999371069204, 0.009999993710692),
474            // The longer runs that count digits before the point.
475            (-84128361028.39314, -84128361028.39314),
476            (343187.2543801, 343187.2543801),
477            // Noise-free or genuinely fine: left as GDAL holds them (the
478            // GFS-Wave grid's origin and step, a hair over 0.25°).
479            (117.87501299367088, 117.87501299367088),
480            (0.2500000126582278, 0.2500000126582278),
481            (12345.000000011, 12345.000000011),
482            (99999.99999999999, 99999.99999999999),
483            (0.0, 0.0),
484            (1e60, 1e60),
485        ];
486        for (held, printed) in cases {
487            assert_eq!(as_gdalinfo_json(held), printed, "{held:?}");
488        }
489        assert!(as_gdalinfo_json(-0.0).is_sign_negative());
490    }
491}