1use 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
33static NETCDF: Mutex<()> = Mutex::new(());
41
42pub fn needs_serial_access(name: &Path) -> bool {
45 name.to_string_lossy().starts_with("NETCDF:")
46}
47
48pub fn netcdf_guard() -> MutexGuard<'static, ()> {
50 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#[derive(Debug, Clone, Default)]
69pub struct BandInfo {
70 pub number: usize,
71 pub description: String,
72 pub metadata: HashMap<String, String>,
73 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
86pub struct Dataset {
89 handle: GDALDatasetH,
90 width: usize,
91 height: usize,
92}
93
94impl Dataset {
95 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 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 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 unsafe { VSIFree(text.cast()) };
171 wkt
172 }
173
174 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 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
262unsafe impl Send for Dataset {}
266
267pub 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 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
330pub(crate) fn as_gdalinfo_json(value: f64) -> f64 {
344 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
353fn 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 let before = dot - 1 - usize::from(s[0] == b'-');
368 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
391fn 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
419fn 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 #[test]
461 fn a_coefficient_reads_as_gdalinfo_prints_it() {
462 let cases = [
463 (0.012500000000000292, 0.0125),
465 (-0.012500000000000018, -0.0125),
466 (25.991950000000003, 25.99195),
467 (122.60185, 122.60185),
468 (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 (-84128361028.39314, -84128361028.39314),
476 (343187.2543801, 343187.2543801),
477 (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}