1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
use std::path::{Path, PathBuf};
use std::fs;
use tracing::{info, warn};
use gdal::Dataset;
use std::process::Command;
use serde_json::Value;
/// Resolve an automatic target CRS (EPSG:XXXXX) based on the SAFE product's geolocation.
///
/// Strategy:
/// - Locate any measurement TIFF inside the SAFE `measurement/` folder (prefer VV/VH/HH/HV by name).
/// - Run `gdalinfo -json` on that TIFF to obtain WGS84 coordinates (from `wgs84Extent`, `gcps`, or `cornerCoordinates`).
/// - Compute a representative lon/lat (centroid) and map to UTM EPSG:326xx/327xx, with UPS fallback near poles
/// and Norway/Svalbard UTM exceptions.
pub fn resolve_auto_target_crs<P: AsRef<Path>>(safe_dir: P) -> Option<String> {
let base = safe_dir.as_ref();
let measurement = base.join("measurement");
if !measurement.is_dir() {
warn!("AUTO-CRS: measurement directory not found: {:?}", measurement);
return None;
}
// Find a candidate measurement TIFF (prefer names containing polarization hints)
let mut candidate: Option<PathBuf> = None;
if let Ok(entries) = fs::read_dir(&measurement) {
for entry in entries.flatten() {
let path = entry.path();
if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
let ext_lc = ext.to_lowercase();
if ext_lc == "tiff" || ext_lc == "tif" {
let name_lc = path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("")
.to_lowercase();
// Skip intermediates
if name_lc.contains("_warped.tif") || name_lc.contains("_warped.tiff") {
continue;
}
// Prefer VV/VH then HH/HV, else take the first TIFF
if name_lc.contains("vv") || name_lc.contains("vh") {
candidate = Some(path.clone());
break;
} else if name_lc.contains("hh") || name_lc.contains("hv") {
candidate = Some(path.clone());
} else if candidate.is_none() {
candidate = Some(path.clone());
}
}
}
}
}
let file_path = match candidate {
Some(p) => p,
None => {
warn!("AUTO-CRS: no measurement TIFF found in {:?}", measurement);
return None;
}
};
info!("AUTO-CRS: candidate measurement: {:?}", file_path.file_name());
// Preferred: use GDAL GCP API to read lon/lat from GCPs
let mut lonlat: Option<(f64, f64)> = None;
match Dataset::open(&file_path) {
Ok(ds) => {
let gcp_proj = ds.gcp_projection().unwrap_or_else(|| "".to_string());
let proj_is_geographic = gcp_proj.contains("GEOGCS") || gcp_proj.contains("WGS 84") || gcp_proj.starts_with("EPSG:4326");
if proj_is_geographic {
let gcps = ds.gcps();
if !gcps.is_empty() {
let mut sum_lon = 0.0;
let mut sum_lat = 0.0;
let mut count = 0.0;
for g in gcps {
sum_lon += g.x();
sum_lat += g.y();
count += 1.0;
}
if count > 0.0 {
lonlat = Some((sum_lon / count, sum_lat / count));
info!("AUTO-CRS: centroid from GDAL GCPs: lon={:.6}, lat={:.6}", sum_lon / count, sum_lat / count);
} else {
warn!("AUTO-CRS: GDAL reports zero GCPs");
}
} else {
warn!("AUTO-CRS: no GCPs available via GDAL API");
}
} else {
warn!("AUTO-CRS: GCP projection not geographic or empty; proj='{}'", gcp_proj);
}
}
Err(e) => {
warn!("AUTO-CRS: GDAL open failed for candidate: {}", e);
}
}
// Fallback: gdalinfo -json (parse correct gcps.gcpList)
if lonlat.is_none() {
let output = Command::new("gdalinfo")
.arg("-json")
.arg(file_path.as_os_str())
.output();
if let Ok(out) = output {
if out.status.success() {
if let Ok(json_text) = std::str::from_utf8(&out.stdout) {
if let Ok(v) = serde_json::from_str::<Value>(json_text) {
// Try wgs84Extent
if let Some(ext) = v.get("wgs84Extent") {
if let Some(coords) = ext.get("coordinates").and_then(|c| c.as_array()).and_then(|arr| arr.get(0)).and_then(|ring| ring.as_array()) {
let mut sum_lon = 0.0;
let mut sum_lat = 0.0;
let mut count = 0.0;
for pt in coords {
if let Some(pair) = pt.as_array() {
if pair.len() >= 2 {
if let (Some(lon), Some(lat)) = (pair[0].as_f64(), pair[1].as_f64()) {
sum_lon += lon;
sum_lat += lat;
count += 1.0;
}
}
}
}
if count > 0.0 {
lonlat = Some((sum_lon / count, sum_lat / count));
info!("AUTO-CRS: centroid from wgs84Extent: lon={:.6}, lat={:.6}", sum_lon / count, sum_lat / count);
}
}
}
// GCPs list
if lonlat.is_none() {
if let Some(gcps_obj) = v.get("gcps").and_then(|g| g.as_object()) {
if let Some(list) = gcps_obj.get("gcpList").and_then(|l| l.as_array()) {
let mut sum_lon = 0.0;
let mut sum_lat = 0.0;
let mut count = 0.0;
for gcp in list {
if let (Some(lon), Some(lat)) = (gcp.get("lon").and_then(|x| x.as_f64()), gcp.get("lat").and_then(|x| x.as_f64())) {
sum_lon += lon;
sum_lat += lat;
count += 1.0;
}
}
if count > 0.0 {
lonlat = Some((sum_lon / count, sum_lat / count));
info!("AUTO-CRS: centroid from gdalinfo GCPs: lon={:.6}, lat={:.6}", sum_lon / count, sum_lat / count);
}
}
}
}
}
}
}
}
}
// Map lon/lat to UTM/UPS EPSG string
let (lon, lat) = match lonlat {
Some(v) => v,
None => {
warn!("AUTO-CRS: could not compute lon/lat from GDAL or gdalinfo JSON");
return None;
}
};
let epsg = lonlat_to_epsg(lon, lat);
info!("AUTO-CRS: resolved target CRS = {}", epsg);
Some(epsg)
}
pub fn lonlat_to_epsg(lon: f64, lat: f64) -> String {
// Polar UPS fallback
if lat >= 84.0 {
return "EPSG:32661".to_string();
}
if lat <= -80.0 {
return "EPSG:32761".to_string();
}
// Normalize longitude to [-180, 180)
let mut lon_norm = lon;
if lon_norm < -180.0 || lon_norm >= 180.0 {
lon_norm = ((lon_norm + 180.0) % 360.0 + 360.0) % 360.0 - 180.0;
}
// Norway exception: 56<=lat<64 and 3<=lon<12 -> zone 32
let norway_exception = lat >= 56.0 && lat < 64.0 && lon_norm >= 3.0 && lon_norm < 12.0;
// Svalbard exceptions: 72<=lat<84 and lon bands map to zones 31,33,35,37
let svalbard_exception = lat >= 72.0 && lat < 84.0;
let zone = if norway_exception {
32
} else if svalbard_exception {
if lon_norm >= 0.0 && lon_norm < 9.0 {
31
} else if lon_norm >= 9.0 && lon_norm < 21.0 {
33
} else if lon_norm >= 21.0 && lon_norm < 33.0 {
35
} else if lon_norm >= 33.0 && lon_norm < 42.0 {
37
} else {
// Default zone computation outside special bands within Svalbard range
(((lon_norm + 180.0) / 6.0).floor() as i32 + 1).clamp(1, 60)
}
} else {
(((lon_norm + 180.0) / 6.0).floor() as i32 + 1).clamp(1, 60)
} as i32;
if lat >= 0.0 {
format!("EPSG:326{:02}", zone)
} else {
format!("EPSG:327{:02}", zone)
}
}
/// Resolve an automatic target CRS (EPSG:XXXXX) based on any raster dataset path
/// including GDAL VSI paths (e.g., /vsicurl/, /vsizip//vsicurl/...).
/// Uses the same centroid-from-GCPs or gdalinfo-json fallback strategy.
pub fn resolve_auto_target_crs_from_dataset_path<P: AsRef<std::path::Path>>(dataset_path: P) -> Option<String> {
let path_ref = dataset_path.as_ref();
let mut lonlat: Option<(f64, f64)> = None;
// Preferred: use GDAL GCP API to read lon/lat from GCPs
match gdal::Dataset::open(path_ref) {
Ok(ds) => {
let gcp_proj = ds.gcp_projection().unwrap_or_else(|| "".to_string());
let proj_is_geographic = gcp_proj.contains("GEOGCS")
|| gcp_proj.contains("WGS 84")
|| gcp_proj.starts_with("EPSG:4326");
if proj_is_geographic {
let gcps = ds.gcps();
if !gcps.is_empty() {
let mut sum_lon = 0.0;
let mut sum_lat = 0.0;
let mut count = 0.0;
for g in gcps {
sum_lon += g.x();
sum_lat += g.y();
count += 1.0;
}
if count > 0.0 {
lonlat = Some((sum_lon / count, sum_lat / count));
tracing::info!(
"AUTO-CRS (remote): centroid from GDAL GCPs: lon={:.6}, lat={:.6}",
sum_lon / count,
sum_lat / count
);
} else {
tracing::warn!("AUTO-CRS (remote): GDAL reports zero GCPs");
}
} else {
tracing::warn!("AUTO-CRS (remote): no GCPs available via GDAL API");
}
} else {
tracing::warn!(
"AUTO-CRS (remote): GCP projection not geographic or empty; proj='{}'",
gcp_proj
);
}
}
Err(e) => tracing::warn!("AUTO-CRS (remote): GDAL open failed for candidate: {}", e),
}
// Fallback: gdalinfo -json
if lonlat.is_none() {
let output = std::process::Command::new("gdalinfo")
.arg("-json")
.arg(path_ref.as_os_str())
.output();
if let Ok(out) = output {
if out.status.success() {
if let Ok(json_text) = std::str::from_utf8(&out.stdout) {
if let Ok(v) = serde_json::from_str::<serde_json::Value>(json_text) {
// Try wgs84Extent
if let Some(ext) = v.get("wgs84Extent") {
if let Some(coords) = ext
.get("coordinates")
.and_then(|c| c.as_array())
.and_then(|arr| arr.get(0))
.and_then(|ring| ring.as_array())
{
let mut sum_lon = 0.0;
let mut sum_lat = 0.0;
let mut count = 0.0;
for pt in coords {
if let Some(pair) = pt.as_array() {
if pair.len() >= 2 {
if let (Some(lon), Some(lat)) =
(pair[0].as_f64(), pair[1].as_f64())
{
sum_lon += lon;
sum_lat += lat;
count += 1.0;
}
}
}
}
if count > 0.0 {
lonlat = Some((sum_lon / count, sum_lat / count));
tracing::info!(
"AUTO-CRS (remote): centroid from wgs84Extent: lon={:.6}, lat={:.6}",
sum_lon / count,
sum_lat / count
);
}
}
}
// GCPs list
if lonlat.is_none() {
if let Some(gcps_obj) = v.get("gcps").and_then(|g| g.as_object()) {
if let Some(list) = gcps_obj
.get("gcpList")
.and_then(|l| l.as_array())
{
let mut sum_lon = 0.0;
let mut sum_lat = 0.0;
let mut count = 0.0;
for gcp in list {
if let (Some(lon), Some(lat)) = (
gcp.get("lon").and_then(|x| x.as_f64()),
gcp.get("lat").and_then(|x| x.as_f64()),
) {
sum_lon += lon;
sum_lat += lat;
count += 1.0;
}
}
if count > 0.0 {
lonlat = Some((sum_lon / count, sum_lat / count));
tracing::info!(
"AUTO-CRS (remote): centroid from gdalinfo GCPs: lon={:.6}, lat={:.6}",
sum_lon / count,
sum_lat / count
);
}
}
}
}
}
}
}
}
}
let (lon, lat) = match lonlat {
Some(v) => v,
None => {
tracing::warn!("AUTO-CRS (remote): could not compute lon/lat from GDAL or gdalinfo JSON");
return None;
}
};
let epsg = lonlat_to_epsg(lon, lat);
tracing::info!("AUTO-CRS (remote): resolved target CRS = {}", epsg);
Some(epsg)
}