You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sis.apache.org by de...@apache.org on 2024/09/09 17:22:30 UTC
(sis) 01/01: Initial version of a GDAL datastore using Panama for the binding to the native GDAL library. Work by Quentin Bialota, refactored as below (the original commit is not in this history):
This is an automated email from the ASF dual-hosted git repository.
desruisseaux pushed a commit to branch geoapi-4.0
in repository https://gitbox.apache.org/repos/asf/sis.git
commit 1914e05f851a51588c753a947f29ffc1c94975c7
Author: qbialota <qu...@geomatys.com>
AuthorDate: Fri Aug 30 17:23:59 2024 +0200
Initial version of a GDAL datastore using Panama for the binding to the native GDAL library.
Work by Quentin Bialota, refactored as below (the original commit is not in this history):
* Group bindings in a single `org.apache.sis.storage.gdal` package.
* Remove unused and unimplemented methods, constants and enumerations.
* Make GDAL methods static and merge PanamaUtils and GdalOgr with GDAL.
* Remove redundant GDAL or other prefixes in class and method names.
* Remove `GdalSampleDimension` because its `dataType` is not applicable.
* Split `GdalResource` in a few classes, and make package-private.
* Use `java.lang.ref.Cleaner` as a safety if user does not call `close()`.
* Use `StorageConnector` in `GDALStore` constructor.
* Move some methods to dedicated `Driver` class.
* Add missing license headers.
---
.../apache/sis/buildtools/gradle/Dependency.java | 1 +
.../org.apache.sis.feature/main/module-info.java | 1 +
.../apache/sis/coverage/privy/RasterFactory.java | 2 +-
.../main/module-info.java | 2 +
.../org/apache/sis/storage/geotiff/DataCube.java | 2 +-
.../org.apache.sis.storage/main/module-info.java | 2 +
.../apache/sis/storage/base/TiledGridCoverage.java | 83 ++-
.../apache/sis/storage/base/TiledGridResource.java | 19 +-
.../src/org.apache.sis.util/main/module-info.java | 2 +
incubator/build.gradle.kts | 15 +
.../org.apache.sis.storage.DataStoreProvider | 4 +
.../main/module-info.java | 59 ++
.../main/org/apache/sis/storage/gdal/Band.java | 295 ++++++++++
.../sis/storage/gdal/ColorInterpretation.java | 78 +++
.../main/org/apache/sis/storage/gdal/DataType.java | 193 +++++++
.../main/org/apache/sis/storage/gdal/Driver.java | 263 +++++++++
.../main/org/apache/sis/storage/gdal/GDAL.java | 598 +++++++++++++++++++++
.../org/apache/sis/storage/gdal/GDALStore.java | 499 +++++++++++++++++
.../apache/sis/storage/gdal/GDALStoreProvider.java | 343 ++++++++++++
.../main/org/apache/sis/storage/gdal/OpenFlag.java | 153 ++++++
.../main/org/apache/sis/storage/gdal/Opener.java | 179 ++++++
.../org/apache/sis/storage/gdal/Subdataset.java | 69 +++
.../apache/sis/storage/gdal/SubdatasetList.java | 155 ++++++
.../org/apache/sis/storage/gdal/TiledCoverage.java | 106 ++++
.../org/apache/sis/storage/gdal/TiledResource.java | 491 +++++++++++++++++
.../org/apache/sis/storage/gdal/package-info.java | 41 ++
.../apache/sis/storage/panama/LibraryLoader.java | 221 ++++++++
.../apache/sis/storage/panama/LibraryStatus.java | 84 +++
.../apache/sis/storage/panama/NativeFunctions.java | 201 +++++++
.../apache/sis/storage/panama/package-info.java | 27 +
.../org/apache/sis/storage/gdal/GDALStoreTest.java | 143 +++++
.../test/org/apache/sis/storage/gdal/test.tiff | Bin 0 -> 4009 bytes
netbeans-project/nbproject/project.properties | 1 +
33 files changed, 4319 insertions(+), 13 deletions(-)
diff --git a/buildSrc/src/main/java/org/apache/sis/buildtools/gradle/Dependency.java b/buildSrc/src/main/java/org/apache/sis/buildtools/gradle/Dependency.java
index 45f821fdd7..d67105e2ed 100644
--- a/buildSrc/src/main/java/org/apache/sis/buildtools/gradle/Dependency.java
+++ b/buildSrc/src/main/java/org/apache/sis/buildtools/gradle/Dependency.java
@@ -74,6 +74,7 @@ public final class Dependency {
Map.entry("storage.shapefile", "core:sis-shapefile"),
Map.entry("storage.gimi", "core:sis-gimi"),
Map.entry("storage.gsf", "core:sis-gsf"),
+ Map.entry("storage.gdal", "core:sis-gdal"),
Map.entry("storage.geopackage", "core:sis-geopackage"),
Map.entry("storage.coveragejson", "core:sis-coveragejson"),
Map.entry("portrayal.map", "core:sis-portrayal-map"),
diff --git a/endorsed/src/org.apache.sis.feature/main/module-info.java b/endorsed/src/org.apache.sis.feature/main/module-info.java
index 6daf162d76..a99f398169 100644
--- a/endorsed/src/org.apache.sis.feature/main/module-info.java
+++ b/endorsed/src/org.apache.sis.feature/main/module-info.java
@@ -79,6 +79,7 @@ module org.apache.sis.feature {
org.apache.sis.storage.netcdf,
org.apache.sis.storage.geotiff,
org.apache.sis.portrayal,
+ org.apache.sis.storage.gdal, // In the "incubator" sub-project.
org.apache.sis.gui; // In the "optional" sub-project.
exports org.apache.sis.image.processing.isoline to
diff --git a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/privy/RasterFactory.java b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/privy/RasterFactory.java
index 17f8ee70a6..880d7f993d 100644
--- a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/privy/RasterFactory.java
+++ b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/privy/RasterFactory.java
@@ -239,7 +239,7 @@ public final class RasterFactory extends Static {
case DataBuffer.TYPE_INT: buffer = IntBuffer .wrap(((DataBufferInt) data).getData(bank)); break;
case DataBuffer.TYPE_FLOAT: buffer = FloatBuffer .wrap(((DataBufferFloat) data).getData(bank)); break;
case DataBuffer.TYPE_DOUBLE: buffer = DoubleBuffer.wrap(((DataBufferDouble) data).getData(bank)); break;
- default: throw new AssertionError();
+ default: throw new IllegalArgumentException();
}
final int lower = data.getOffsets()[bank];
final int upper = lower + data.getSize();
diff --git a/endorsed/src/org.apache.sis.referencing/main/module-info.java b/endorsed/src/org.apache.sis.referencing/main/module-info.java
index 93ad403d91..e9624507c4 100644
--- a/endorsed/src/org.apache.sis.referencing/main/module-info.java
+++ b/endorsed/src/org.apache.sis.referencing/main/module-info.java
@@ -182,6 +182,7 @@ module org.apache.sis.referencing {
org.apache.sis.storage.geotiff,
org.apache.sis.storage.earthobservation,
org.apache.sis.storage.gimi, // In the "incubator" sub-project.
+ org.apache.sis.storage.gdal, // In the "incubator" sub-project.
org.apache.sis.portrayal,
org.apache.sis.console,
org.apache.sis.openoffice,
@@ -191,6 +192,7 @@ module org.apache.sis.referencing {
org.apache.sis.referencing.gazetteer,
org.apache.sis.storage.geotiff,
org.apache.sis.storage.netcdf,
+ org.apache.sis.storage.gdal, // In the "incubator" sub-project.
org.apache.sis.storage.earthobservation,
org.apache.sis.profile.japan;
diff --git a/endorsed/src/org.apache.sis.storage.geotiff/main/org/apache/sis/storage/geotiff/DataCube.java b/endorsed/src/org.apache.sis.storage.geotiff/main/org/apache/sis/storage/geotiff/DataCube.java
index f61b2cd8fb..505f122f78 100644
--- a/endorsed/src/org.apache.sis.storage.geotiff/main/org/apache/sis/storage/geotiff/DataCube.java
+++ b/endorsed/src/org.apache.sis.storage.geotiff/main/org/apache/sis/storage/geotiff/DataCube.java
@@ -63,7 +63,7 @@ abstract class DataCube extends TiledGridResource implements ResourceOnFileSyste
* @param reader information about the input stream to read, the metadata and the character encoding.
*/
DataCube(final Reader reader) {
- super(reader.store.listeners());
+ super(reader.store);
this.reader = reader;
}
diff --git a/endorsed/src/org.apache.sis.storage/main/module-info.java b/endorsed/src/org.apache.sis.storage/main/module-info.java
index f407ccc84a..17d69b0ed1 100644
--- a/endorsed/src/org.apache.sis.storage/main/module-info.java
+++ b/endorsed/src/org.apache.sis.storage/main/module-info.java
@@ -57,6 +57,7 @@ module org.apache.sis.storage {
org.apache.sis.storage.gimi, // In the "incubator" sub-project.
org.apache.sis.storage.shapefile, // In the "incubator" sub-project.
org.apache.sis.storage.geopackage, // In the "incubator" sub-project.
+ org.apache.sis.storage.gdal, // In the "incubator" sub-project.
org.apache.sis.util, // For the "About" command.
org.apache.sis.console,
org.apache.sis.openoffice,
@@ -71,6 +72,7 @@ module org.apache.sis.storage {
org.apache.sis.storage.gimi, // In the "incubator" sub-project.
org.apache.sis.storage.shapefile, // In the "incubator" sub-project.
org.apache.sis.storage.geopackage, // In the "incubator" sub-project.
+ org.apache.sis.storage.gdal, // In the "incubator" sub-project.
org.apache.sis.cloud.aws,
org.apache.sis.console,
org.apache.sis.gui; // In the "optional" sub-project.
diff --git a/endorsed/src/org.apache.sis.storage/main/org/apache/sis/storage/base/TiledGridCoverage.java b/endorsed/src/org.apache.sis.storage/main/org/apache/sis/storage/base/TiledGridCoverage.java
index 30ef8a4108..489ab117f3 100644
--- a/endorsed/src/org.apache.sis.storage/main/org/apache/sis/storage/base/TiledGridCoverage.java
+++ b/endorsed/src/org.apache.sis.storage/main/org/apache/sis/storage/base/TiledGridCoverage.java
@@ -20,12 +20,14 @@ import java.util.Map;
import java.util.Locale;
import java.io.IOException;
import java.awt.Point;
+import java.awt.Rectangle;
import java.awt.image.DataBuffer;
import java.awt.image.ColorModel;
import java.awt.image.SampleModel;
import java.awt.image.MultiPixelPackedSampleModel;
import java.awt.image.RenderedImage;
import java.awt.image.Raster;
+import java.awt.image.WritableRaster;
import static java.lang.Math.addExact;
import static java.lang.Math.subtractExact;
import static java.lang.Math.multiplyExact;
@@ -35,6 +37,7 @@ import static java.lang.Math.decrementExact;
import static java.lang.Math.toIntExact;
import static java.lang.Math.floorDiv;
import org.opengis.util.GenericName;
+import org.opengis.metadata.spatial.DimensionNameType;
import org.apache.sis.coverage.grid.GridCoverage;
import org.apache.sis.coverage.grid.GridExtent;
import org.apache.sis.coverage.grid.DisjointExtentException;
@@ -224,6 +227,7 @@ public abstract class TiledGridCoverage extends GridCoverage {
tmcOfFirstTile = new long[dimension];
tileStrides = new int [dimension];
final int[] subSize = new int [dimension];
+
@SuppressWarnings("LocalVariableHidesMemberVariable")
long indexOfFirstTile = 0;
int tileStride = 1;
@@ -300,6 +304,8 @@ public abstract class TiledGridCoverage extends GridCoverage {
* @param dimension dimension of the coordinate.
* @return coordinate in this {@code TiledGridCoverage} as if no subsampling was applied.
* @throws ArithmeticException if the coordinate cannot be represented as a long integer.
+ *
+ * @see #toFullResolution(Rectangle)
*/
private long toFullResolution(final long coordinate, final int dimension) {
return addExact(multiplyExact(coordinate, subsampling[dimension]), subsamplingOffsets[dimension]);
@@ -536,14 +542,14 @@ public abstract class TiledGridCoverage extends GridCoverage {
final int count = subtractExact(tileUpper[i], lower);
indexInTileVector = addExact(indexInTileVector, multiplyExact(tileStrides[i], lower));
tileCountInQuery = multiplyExact(tileCountInQuery, count);
- tileOffsetFull[i] = multiplyFull(offsetAOI[i], subsampling[i]);
+ tileOffsetFull[i] = multiplyFull(offsetAOI[i], getSubsampling(i));
/*
* Following is the pixel coordinate after the last pixel in current dimension.
* This is not stored; the intent is to get a potential `ArithmeticException`
* now instead of in a call to `next()` during iteration. A negative value
* would mean that the AOI does not intersect the region requested by user.
*/
- final int max = addExact(offsetAOI[i], multiplyExact(tileSize[i], count));
+ final int max = addExact(offsetAOI[i], multiplyExact(getTileSize(i), count));
assert max > Math.max(offsetAOI[i], 0) : max;
}
this.tileCountInQuery = tileCountInQuery;
@@ -571,7 +577,7 @@ public abstract class TiledGridCoverage extends GridCoverage {
if (s > base) {
lower[i] = s;
// Use of `ceilDiv(…)` is for consistency with `getTileOrigin(int)`.
- offset[i] = addExact(offset[i], ceilDiv(multiplyExact(s - base, tileSize[i]), subsampling[i]));
+ offset[i] = addExact(offset[i], ceilDiv(multiplyExact(s - base, getTileSize(i)), getSubsampling(i)));
}
}
final int[] upper = this.tileUpper.clone();
@@ -601,6 +607,34 @@ public abstract class TiledGridCoverage extends GridCoverage {
return coordinate;
}
+ /**
+ * Returns the extent of this tile in units of the full coverage resource (without subsampling).
+ * This method is a generalization to <var>n</var> dimensions of the rectangle computed by the
+ * following code:
+ *
+ * {@snippet lang="java" :
+ * WritableRaster tile = createRaster();
+ * Rectangle bounds = tile.getBounds();
+ * toFullResolution(bounds); // Convert in-place.
+ * }
+ *
+ * @return extent of this tile in units of the full coverage resource.
+ *
+ * @see #toFullResolution(Rectangle)
+ */
+ public final GridExtent getExtentInSource() {
+ final int dimension = tileOffsetFull.length;
+ final var axes = new DimensionNameType[dimension];
+ final long[] lower = new long[dimension];
+ final long[] upper = new long[dimension];
+ for (int i=0; i<dimension; i++) {
+ lower[i] = toFullResolution(getTileOrigin(i), i);
+ upper[i] = Math.addExact(lower[i], getTileSize(i));
+ axes [i] = readExtent.getAxisType(i).orElse(null);
+ }
+ return new GridExtent(axes, lower, upper, true);
+ }
+
/**
* Returns the current iterator position as an index in the array of tiles to be returned
* by {@link #readTiles(AOI)}. The initial position is zero.
@@ -682,7 +716,24 @@ public abstract class TiledGridCoverage extends GridCoverage {
* At first the index values seem inconsistent, but after we discard the tiles where
* `getRegionInsideTile(…)` returns `false` they become consistent.
*/
- return toIntExact(ceilDiv(tileOffsetFull[dimension], subsampling[dimension]));
+ return toIntExact(ceilDiv(tileOffsetFull[dimension], getSubsampling(dimension)));
+ }
+
+ /**
+ * Creates an initially empty raster for the tile at the current iterator position.
+ * The sample model is {@link #model} and the minimum <var>x</var> and <var>y</var>
+ * coordinates are the values returned by {@link #getTileOrigin(int)} for dimensions
+ * of two-dimensional slices.
+ *
+ * <p>The raster is <em>not</em> filled with {@link #fillValue}.
+ * Filling, if needed, should be done by the caller.</p>
+ *
+ * @return a newly created, initially empty raster.
+ */
+ public WritableRaster createRaster() {
+ final int x = getTileOrigin(X_DIMENSION);
+ final int y = getTileOrigin(Y_DIMENSION);
+ return Raster.createWritableRaster(model, new Point(x, y));
}
/**
@@ -714,13 +765,13 @@ public abstract class TiledGridCoverage extends GridCoverage {
for (int i=0; i<tmcInSubset.length; i++) {
indexInTileVector += tileStrides[i];
if (++tmcInSubset[i] < tileUpper[i]) {
- tileOffsetFull[i] += tileSize[i];
+ tileOffsetFull[i] += getTileSize(i);
break;
}
// Rewind to index for tileLower[i].
indexInTileVector -= (tmcInSubset[i] - tileLower[i]) * tileStrides[i];
tmcInSubset [i] = tileLower[i];
- tileOffsetFull[i] = multiplyFull(offsetAOI[i], subsampling[i]);
+ tileOffsetFull[i] = multiplyFull(offsetAOI[i], getSubsampling(i));
}
return true;
}
@@ -796,7 +847,7 @@ public abstract class TiledGridCoverage extends GridCoverage {
public boolean getRegionInsideTile(final long[] lower, final long[] upper, final int[] subsampling, int dimension) {
System.arraycopy(coverage.subsampling, 0, subsampling, 0, dimension);
while (--dimension >= 0) {
- final int tileSize = coverage.tileSize[dimension];
+ final int tileSize = coverage.getTileSize(dimension);
final long tileIndex = addExact(coverage.tmcOfFirstTile[dimension], tmcInSubset[dimension]);
final long tileBase = multiplyExact(tileIndex, tileSize);
/*
@@ -905,4 +956,22 @@ public abstract class TiledGridCoverage extends GridCoverage {
* (too many exception types to list them all).
*/
protected abstract Raster[] readTiles(AOI iterator) throws IOException, DataStoreException;
+
+ /**
+ * Converts raster coordinate from this {@code TiledGridCoverage} coordinate space to full resolution.
+ * This method removes the subsampling effect. Note that since this {@code TiledGridCoverage} uses the
+ * same coordinate space as {@link TiledGridResource}, the converted coordinates should be valid in
+ * the full resource as well.
+ *
+ * @param bounds the rectangle to convert. Will be modified in-place.
+ * @throws ArithmeticException if the coordinate cannot be represented as an integer.
+ *
+ * @see AOI#getExtentInSource()
+ */
+ protected final void toFullResolution(final Rectangle bounds) {
+ bounds.x = Math.toIntExact(toFullResolution(bounds.x, X_DIMENSION));
+ bounds.y = Math.toIntExact(toFullResolution(bounds.y, Y_DIMENSION));
+ bounds.width = Math.multiplyExact(bounds.width, subsampling[X_DIMENSION]);
+ bounds.height = Math.multiplyExact(bounds.height, subsampling[Y_DIMENSION]);
+ }
}
diff --git a/endorsed/src/org.apache.sis.storage/main/org/apache/sis/storage/base/TiledGridResource.java b/endorsed/src/org.apache.sis.storage/main/org/apache/sis/storage/base/TiledGridResource.java
index b813562f82..9299edd0e1 100644
--- a/endorsed/src/org.apache.sis.storage/main/org/apache/sis/storage/base/TiledGridResource.java
+++ b/endorsed/src/org.apache.sis.storage/main/org/apache/sis/storage/base/TiledGridResource.java
@@ -34,6 +34,7 @@ import org.apache.sis.coverage.grid.GridExtent;
import org.apache.sis.coverage.grid.GridGeometry;
import org.apache.sis.coverage.grid.GridRoundingMode;
import org.apache.sis.coverage.privy.RangeArgument;
+import org.apache.sis.storage.Resource;
import org.apache.sis.storage.AbstractGridCoverageResource;
import org.apache.sis.storage.DataStoreException;
import org.apache.sis.storage.RasterLoadingStrategy;
@@ -105,7 +106,7 @@ public abstract class TiledGridResource extends AbstractGridCoverageResource {
* @see TiledGridCoverage#rasters
* @see TiledGridCoverage.AOI#getCachedTile()
*/
- private final WeakValueHashMap<CacheKey, Raster> rasters;
+ private final WeakValueHashMap<CacheKey, Raster> rasters = new WeakValueHashMap<>(CacheKey.class);
/**
* Whether all tiles should be loaded at {@code read(…)} method call or deferred to a later time.
@@ -116,16 +117,26 @@ public abstract class TiledGridResource extends AbstractGridCoverageResource {
*/
private RasterLoadingStrategy loadingStrategy;
+ /**
+ * Creates a new resource.
+ *
+ * @param parent the parent resource, or {@code null} if none.
+ */
+ protected TiledGridResource(final Resource parent) {
+ super(parent);
+ }
+
/**
* Creates a new resource.
*
* @param parent listeners of the parent resource, or {@code null} if none.
* This is usually the listeners of the {@link org.apache.sis.storage.DataStore}
* that created this resource.
+ * @param hidden {@code false} if this resource shall use its own {@link StoreListeners}
+ * with the specified parent, or {@code true} for using {@code parentListeners} directly.
*/
- protected TiledGridResource(final StoreListeners parent) {
- super(parent, false);
- rasters = new WeakValueHashMap<>(CacheKey.class);
+ protected TiledGridResource(final StoreListeners parent, final boolean hidden) {
+ super(parent, hidden);
}
/**
diff --git a/endorsed/src/org.apache.sis.util/main/module-info.java b/endorsed/src/org.apache.sis.util/main/module-info.java
index 150970c359..612114cee6 100644
--- a/endorsed/src/org.apache.sis.util/main/module-info.java
+++ b/endorsed/src/org.apache.sis.util/main/module-info.java
@@ -100,6 +100,7 @@ module org.apache.sis.util {
org.apache.sis.storage.netcdf,
org.apache.sis.storage.geotiff,
org.apache.sis.storage.earthobservation,
+ org.apache.sis.storage.gdal, // In the "incubator" sub-project.
org.apache.sis.portrayal,
org.apache.sis.cloud.aws,
org.apache.sis.console,
@@ -122,6 +123,7 @@ module org.apache.sis.util {
org.apache.sis.cql, // In the "incubator" sub-project.
org.apache.sis.portrayal.map, // In the "incubator" sub-project.
org.apache.sis.portrayal,
+ org.apache.sis.storage.gdal, // In the "incubator" sub-project.
org.apache.sis.storage.gsf, // In the "incubator" sub-project.
org.apache.sis.cloud.aws,
org.apache.sis.console,
diff --git a/incubator/build.gradle.kts b/incubator/build.gradle.kts
index a60706f6ae..6a4a938e89 100644
--- a/incubator/build.gradle.kts
+++ b/incubator/build.gradle.kts
@@ -139,6 +139,8 @@ fun addExportForTests(args : MutableList<String>) {
*/
tasks.test {
val args = mutableListOf("-enableassertions")
+ args.add("--enable-native-access")
+ args.add("org.apache.sis.storage.gdal")
addExportForTests(args)
addExport(args, "org.apache.sis.cql", "org.apache.sis.cql", "ALL-UNNAMED")
setAllJvmArgs(args)
@@ -204,6 +206,19 @@ publishing {
description = "Read and write files in the GeoPackage format."
}
}
+ create<MavenPublication>("storage.gdal") {
+ var module = "org.apache.sis.storage.gdal"
+ groupId = "org.apache.sis.storage"
+ artifactId = "sis-gdal"
+ artifact(layout.buildDirectory.file("libs/${module}.jar"))
+ artifact(layout.buildDirectory.file("docs/${module}-sources.jar")) {classifier = "sources"}
+ artifact(layout.buildDirectory.file("docs/${module}-javadoc.jar")) {classifier = "javadoc"}
+ pom {
+ name = "Apache SIS storage using GDAL through Panama"
+ description = "Read and write files using the GDAL library. " +
+ "This module assumes that GDAL is pre-installed."
+ }
+ }
create<MavenPublication>("storage.gsf") {
var module = "org.apache.sis.storage.gsf"
groupId = "org.apache.sis.storage"
diff --git a/incubator/src/org.apache.sis.storage.gdal/main/META-INF.services/org.apache.sis.storage.DataStoreProvider b/incubator/src/org.apache.sis.storage.gdal/main/META-INF.services/org.apache.sis.storage.DataStoreProvider
new file mode 100644
index 0000000000..25f274232b
--- /dev/null
+++ b/incubator/src/org.apache.sis.storage.gdal/main/META-INF.services/org.apache.sis.storage.DataStoreProvider
@@ -0,0 +1,4 @@
+# Workaround for Maven bug https://issues.apache.org/jira/browse/MNG-7855
+# The content of this file is automatically derived from module-info.class file.
+# Should be used only if the JAR file was on class-path rather than module-path.
+org.apache.sis.storage.gdal.GdalStoreProvider
diff --git a/incubator/src/org.apache.sis.storage.gdal/main/module-info.java b/incubator/src/org.apache.sis.storage.gdal/main/module-info.java
new file mode 100644
index 0000000000..df04713494
--- /dev/null
+++ b/incubator/src/org.apache.sis.storage.gdal/main/module-info.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Bridge to the <abbr>GDAL</abbr> library for reading rasters.
+ * This module assumes that <abbr>GDAL</abbr> is preinstalled.
+ * The <abbr>GDAL</abbr> C/C++ functions are invoked by using the {@link java.lang.foreign} package.
+ * <em>Accesses to native functions are restricted by default in Java and requires user's authorization.</em>
+ * This authorization can be granted by the following option on the command-line:
+ *
+ * {@snippet lang="java" :
+ * java --enable-native-access org.apache.sis.storage.gdal <other options>
+ * }
+ *
+ * <h2>When to use</h2>
+ * <abbr>GDAL</abbr> supports a wider range of formats and compression methods than Apache <abbr>SIS</abbr>.
+ * Therefore, <abbr>GDAL</abbr> is a useful fallback when a format is not supported directly by <abbr>SIS</abbr>.
+ * However, <abbr>GDAL</abbr> is not necessarily faster or more capable than pure Java implementations.
+ * When a pure Java implementation exists, we recommend to test it before to fallback on native code.
+ * The performances of Apache <abbr>SIS</abbr> data stores are often comparable to <abbr>GDAL</abbr>,
+ * and the <abbr>SIS</abbr> modules dedicated to a format (GeoTIFF, netCDF, Earth Observation, …)
+ * have more extensive support than this module for some features such as <abbr>ISO</abbr> 19115 metadata
+ * and non-linear transforms.
+ *
+ * <h2>Memory consumption</h2>
+ * <abbr>GDAL</abbr> and Apache <abbr>SIS</abbr> both have their own cache mechanism.
+ * For reducing the amount of memory consumed by the same data cached twice,
+ * it may be useful to set the {@code GDAL_CACHEMAX} environment variable to a lower value.
+ * The value can be specified in megabytes or as a percentage (e.g. "5%").
+ *
+ * @author Quentin Bialota (Geomatys)
+ * @author Martin Desruisseaux (Geomatys)
+ * @version 1.5
+ * @since 1.5
+ */
+module org.apache.sis.storage.gdal {
+ // Dependencies used in public API.
+ requires transitive org.apache.sis.referencing;
+ requires transitive org.apache.sis.storage;
+
+ exports org.apache.sis.storage.gdal;
+
+ provides org.apache.sis.storage.DataStoreProvider
+ with org.apache.sis.storage.gdal.GDALStoreProvider;
+}
diff --git a/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/Band.java b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/Band.java
new file mode 100644
index 0000000000..0d21b8ac63
--- /dev/null
+++ b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/Band.java
@@ -0,0 +1,295 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.storage.gdal;
+
+import java.util.List;
+import java.awt.Rectangle;
+import java.awt.image.ComponentSampleModel;
+import java.awt.image.DataBuffer;
+import java.awt.image.Raster;
+import java.awt.image.WritableRaster;
+import java.lang.foreign.Arena;
+import java.lang.foreign.MemorySegment;
+import java.lang.foreign.ValueLayout;
+import java.lang.invoke.MethodHandle;
+import javax.measure.Unit;
+import javax.measure.format.MeasurementParseException;
+import org.opengis.referencing.operation.MathTransform1D;
+import org.apache.sis.referencing.operation.transform.MathTransforms;
+import org.apache.sis.storage.DataStoreException;
+import org.apache.sis.coverage.SampleDimension;
+import org.apache.sis.coverage.privy.RasterFactory;
+import org.apache.sis.measure.NumberRange;
+import org.apache.sis.measure.Units;
+
+
+/**
+ * Information about a single band in a <abbr>GDAL</abbr> raster.
+ * Instances of {@code Band} should never escape {@link TiledResource} in order to avoid the risk that
+ * {@code GDALRasterBandH} exist after the parent {@link GDALStore} has been garbage collected.
+ *
+ * @author Quentin Bialota (Geomatys)
+ * @author Martin Desruisseaux (Geomatys)
+ */
+final class Band {
+ /**
+ * Pointer to the <abbr>GDAL</abbr> object in native memory.
+ * This is a {@code GDALRasterBandH} in the C/C++ <abbr>API</abbr>.
+ */
+ private final MemorySegment handle;
+
+ /**
+ * Creates a new instance.
+ *
+ * @param handle pointer to the <abbr>GDAL</abbr> band in native memory.
+ */
+ Band(final MemorySegment handle) {
+ this.handle = handle;
+ }
+
+ /**
+ * Returns whether the given Boolean flag is {@code true}.
+ */
+ static boolean isTrue(final MemorySegment flag) {
+ return flag.get(ValueLayout.JAVA_INT, 0) != 0;
+ }
+
+ /**
+ * Returns the minimum, maximum or fill value of the band.
+ * In the minimum or maximum is not explicitly defined,
+ * <abbr>GDAL</abbr> derives the value from the data type.
+ *
+ * @param getter the getter for minimum, maximum of fill value.
+ * @param flag a pointer to a single {@code int} where to store <abbr>GDAL</abbr> status.
+ * @return the requested value.
+ */
+ final double getValue(final MethodHandle getter, final MemorySegment flag) {
+ final double value;
+ try {
+ value = (double) getter.invokeExact(handle, flag);
+ } catch (Throwable e) {
+ throw GDAL.propagate(e);
+ }
+ return value;
+ }
+
+ /**
+ * Creates the sample dimension. Must be invoked in a synchronized block.
+ * Caller should cache the returned value so that this method is invoked only once.
+ *
+ * @param parent the data set which contains the raster which contains this band.
+ * @param gdal set of handles for invoking <abbr>GDAL</abbr> functions.
+ * @param flag a pointer to a single {@code int} where to store <abbr>GDAL</abbr> status.
+ * @return the sample dimension.
+ * @throws DataStoreException if <var>GDAL</var> reported a fatal error.
+ */
+ final SampleDimension createSampleDimension(final GDALStore parent, final GDAL gdal, final MemorySegment flag)
+ throws DataStoreException
+ {
+ /*
+ * The minimum, maximum and "no data" values are in units of the sample data type.
+ * They are not converted values.
+ */
+ final int band;
+ final double minimum, maximum, nodata, scale, offset;
+ boolean hasRange, hasNoData, convert;
+ final MemorySegment names, uom;
+ try {
+ gdal.errorReset();
+ band = (int) gdal.getBandNumber .invokeExact(handle);
+ minimum = (double) gdal.getRasterMinimum .invokeExact(handle, flag); hasRange = isTrue(flag);
+ maximum = (double) gdal.getRasterMaximum .invokeExact(handle, flag); hasRange &= isTrue(flag);
+ nodata = (double) gdal.getRasterNoDataValue.invokeExact(handle, flag); hasNoData = isTrue(flag);
+ scale = (double) gdal.getRasterScale .invokeExact(handle, flag); convert = isTrue(flag);
+ offset = (double) gdal.getRasterOffset .invokeExact(handle, flag); convert &= isTrue(flag);
+ uom = (MemorySegment) gdal.getRasterUnitType.invokeExact(handle);
+ names = (MemorySegment) gdal.getRasterCategoryNames.invokeExact(handle);
+ } catch (Throwable e) {
+ throw GDAL.propagate(e);
+ }
+ gdal.checkCPLErr(parent, "getSampleDimensions", false);
+ /*
+ * If a unit of measurement is given, we consider that the band is quantitative
+ * even if the transfer function (scale and offset) was not specified. The GDAL
+ * default when there is no scale/offset corresponds to the identity transform.
+ */
+ final List<String> categories = GDAL.toStringArray(names);
+ final String symbol = GDAL.toString(uom);
+ Unit<?> units = null;
+ if (symbol != null && !symbol.isBlank()) try {
+ convert = true;
+ units = Units.valueOf(symbol);
+ } catch (MeasurementParseException e) {
+ parent.warning("getSampleDimensions", e.getMessage(), e);
+ }
+ /*
+ * Sample dimension is quantitative if a unit of measurement and/or a transfer function is specified.
+ * The first non-blank name inside the valid range is taken as the name of the quantitative category.
+ * Other names in the same range are discarded, because SIS can associate only one name per range.
+ *
+ * If the sample dimension is not quantitative, then it is qualitative. All category names are added.
+ * The range of values, if present, is added only as a fallback of there is no category names.
+ */
+ final var builder = new SampleDimension.Builder();
+ if (hasNoData) {
+ builder.setBackground(nodata);
+ }
+ if (hasRange | convert) {
+ final var range = NumberRange.create(minimum, true, maximum, true);
+ if (convert) {
+ String name = null;
+ if (categories != null && minimum <= maximum) { // Comparison is for excluding NaN.
+ int index = Math.max((int) Math.ceil (minimum), 0);
+ int limit = Math.min((int) Math.floor(maximum), categories.size() - 1); // Inclusive.
+ while (index <= limit) {
+ final String item = categories.set(index, "");
+ if (name == null && !item.isBlank()) {
+ name = item;
+ }
+ }
+ }
+ builder.addQuantitative(name, range, (MathTransform1D) MathTransforms.linear(scale, offset), units);
+ } else if (categories == null) {
+ builder.addQualitative(null, range);
+ }
+ }
+ /*
+ * If the main category was quantitative, then the remaining non-blank names
+ * are categories that were outside the declared range.
+ */
+ if (categories != null) {
+ final int n = categories.size();
+ for (int i=0; i<n; i++) {
+ final String item = categories.get(i);
+ if (!item.isEmpty()) {
+ builder.addQualitative(item, i);
+ }
+ }
+ }
+ if (band > 0) {
+ builder.setName(band);
+ }
+ return builder.build();
+ }
+
+ /**
+ * Returns the color interpretation of this band.
+ *
+ * @param gdal set of handles for invoking <abbr>GDAL</abbr> functions.
+ * @return color interpretation of this band.
+ */
+ final ColorInterpretation getColorInterpretation(final GDAL gdal) {
+ final int n;
+ try {
+ n = (int) gdal.getColorInterpretation.invokeExact(handle);
+ } catch (Throwable e) {
+ throw GDAL.propagate(e);
+ }
+ return ColorInterpretation.valueOf(n);
+ }
+
+ /**
+ * Returns the ARGB codes of the band. Caller may need to combine somehow the ARGB
+ * codes of all bands in order to produce a Java2D {@link java.awt.image.ColorModel}.
+ *
+ * @param gdal set of handles for invoking <abbr>GDAL</abbr> functions.
+ * @return ARGB codes, or {@code null} if none.
+ */
+ final int[] getARGB(final GDAL gdal) {
+ try (Arena arena = Arena.ofConfined()) {
+ final MemorySegment colorEntry = arena.allocate(ValueLayout.JAVA_SHORT, 4);
+ final var colors = (MemorySegment) gdal.getRasterColorTable.invokeExact(handle);
+ if (!GDAL.isNull(colors)) {
+ final int count = (int) gdal.getColorEntryCount.invokeExact(colors);
+ final int[] ARGB = new int[count];
+ for (int i=0; i<count; i++) {
+ final int err = (int) gdal.getColorEntryAsRGB.invokeExact(colors, i, colorEntry);
+ final short c1 = colorEntry.get(ValueLayout.JAVA_SHORT, Short.BYTES * 0); // gray, red, cyan or hue
+ final short c2 = colorEntry.get(ValueLayout.JAVA_SHORT, Short.BYTES * 1); // green, magenta, or lightness
+ final short c3 = colorEntry.get(ValueLayout.JAVA_SHORT, Short.BYTES * 2); // blue, yellow, or saturation
+ final short c4 = colorEntry.get(ValueLayout.JAVA_SHORT, Short.BYTES * 3); // alpha or blackband
+ ARGB[i] = (Short.toUnsignedInt(c4) << 24)
+ | (Short.toUnsignedInt(c1) << 16)
+ | (Short.toUnsignedInt(c2) << 8)
+ | (Short.toUnsignedInt(c3));
+ }
+ return ARGB;
+ }
+ } catch (Throwable e) {
+ throw GDAL.propagate(e);
+ }
+ return null;
+ }
+
+ /**
+ * Transfers (reads or writes) sample values between <abbr>GDAL</abbr> raster and Java2D raster for one band.
+ * The full area of the Java2D raster is transferred. It may corresponds to a sub-area of the GDAL raster.
+ *
+ * <h4>Prerequisites</h4>
+ * <ul>
+ * <li>The Java2D raster shall use a {@link ComponentSampleModel}.</li>
+ * <li>In read mode, the given raster shall be an instance of {@link WritableRaster}.</li>
+ * </ul>
+ *
+ * @param gdal set of handles for invoking <abbr>GDAL</abbr> functions.
+ * @param rwFlag {@link OpenFlag#READ} or {@link OpenFlag#WRITE}.
+ * @param image the <abbr>GDAL</abbr> raster which contains the band to read or write.
+ * @param aoi region of the image to read or write. (0,0) is the upper-left pixel.
+ * @param raster the Java2D raster where to store of fetch the values to read or write.
+ * @param band band of sample values in the Java2D raster.
+ * @throws ClassCastException if an above-documented prerequisite is not true.
+ * @throws DataStoreException if <var>GDAL</var> reported a warning or fatal error.
+ */
+ final void transfer(final GDAL gdal, final int rwFlag,
+ final TiledResource image, final Rectangle aoi, // GDAL model
+ final Raster raster, final int band) // Java2D model
+ throws DataStoreException
+ {
+ if (rwFlag == OpenFlag.READ && !(raster instanceof WritableRaster)) {
+ throw new ClassCastException();
+ }
+ final var model = (ComponentSampleModel) raster.getSampleModel(); // See prerequisites in Javadoc.
+ final var data = raster.getDataBuffer();
+ final int dataSize = DataBuffer.getDataTypeSize(data.getDataType()) / Byte.SIZE;
+ final var buffer = RasterFactory.createBuffer(data, model.getBankIndices()[band]);
+ buffer.position(model.getOffset(raster.getMinX() - raster.getSampleModelTranslateX(),
+ raster.getMinY() - raster.getSampleModelTranslateY(), band));
+ final int err;
+ try (Arena arena = Arena.ofConfined()) {
+ /*
+ * TODO: we wanted to use `MemorySegment.ofBuffer` but it does not work.
+ * We get an "IllegalArgumentException: Heap segment not allowed" error.
+ * For now we copy in a temporary array as a workaround, but it needs to
+ * be replaced by a call to GetLockedBlockRef.
+ */
+ MemorySegment tmp = arena.allocate(Math.multiplyFull(buffer.remaining(), dataSize));
+ err = (int) gdal.rasterIO.invokeExact(handle, rwFlag,
+ aoi.x, aoi.y, aoi.width, aoi.height,
+ tmp,
+ raster.getWidth(),
+ raster.getHeight(),
+ image.dataType.forDataBufferType(data.getDataType()).ordinal(),
+ Math.multiplyExact(dataSize, model.getPixelStride()),
+ Math.multiplyExact(dataSize, model.getScanlineStride()));
+
+ MemorySegment.ofBuffer(buffer).copyFrom(tmp);
+ } catch (Throwable e) {
+ throw GDAL.propagate(e);
+ }
+ gdal.checkCPLErr(image.parent, (rwFlag == OpenFlag.READ) ? "read" : "write", false, err);
+ }
+}
diff --git a/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/ColorInterpretation.java b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/ColorInterpretation.java
new file mode 100644
index 0000000000..52977d48b0
--- /dev/null
+++ b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/ColorInterpretation.java
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.storage.gdal;
+
+import java.awt.color.ColorSpace;
+import java.awt.image.ComponentColorModel;
+
+
+/**
+ * Color interpretation for a band.
+ * This enumeration mirrors the C/C++ {@code GDALColorInterp} enumeration in the GDAL's API.
+ * The {@linkplain #ordinal() ordinal} values shall be equal to the GDAL enumeration values.
+ *
+ * @author Martin Desruisseaux (Geomatys)
+ */
+enum ColorInterpretation {
+ /** Undefined. In GDAL: {@code GCI_Undefined = 0}. */ UNDEFINED (-1),
+ /** Greyscale. In GDAL: {@code GCI_GrayIndex = 1}. */ GRAYSCALE (ColorSpace.TYPE_GRAY),
+ /** Paletted (uses color table). In GDAL: {@code GCI_PaletteIndex = 2}. */ PALETTE (-1),
+ /** Red band of ARGB image. In GDAL: {@code GCI_RedBand = 3}. */ RED (ColorSpace.TYPE_RGB),
+ /** Green band of ARGB image. In GDAL: {@code GCI_GreenBand = 4}. */ GREEN (ColorSpace.TYPE_RGB),
+ /** Blue band of ARGB image. In GDAL: {@code GCI_BlueBand = 5}. */ BLUE (ColorSpace.TYPE_RGB),
+ /** Alpha (255=opaque). In GDAL: {@code GCI_AlphaBand = 6}. */ ALPHA (ColorSpace.TYPE_RGB),
+ /** Hue band of HLS image. In GDAL: {@code GCI_HueBand = 7}. */ HUE (ColorSpace.TYPE_HLS),
+ /** Saturation band of HLS image. In GDAL: {@code GCI_SaturationBand = 8}. */ SATURATION(ColorSpace.TYPE_HLS),
+ /** Lightness band of HLS image. In GDAL: {@code GCI_LightnessBand = 9}. */ LIGHTNESS (ColorSpace.TYPE_HLS),
+ /** Cyan band of CMYK image. In GDAL: {@code GCI_CyanBand = 10}. */ CYAN (ColorSpace.TYPE_CMYK),
+ /** Magenta band of CMYK image. In GDAL: {@code GCI_MagentaBand = 11}. */ MAGENTA (ColorSpace.TYPE_CMYK),
+ /** Yellow band of CMYK image. In GDAL: {@code GCI_YellowBand = 12}. */ YELLOW (ColorSpace.TYPE_CMYK),
+ /** Black band of CMYK image. In GDAL: {@code GCI_BlackBand = 13}. */ BLACK (ColorSpace.TYPE_CMYK),
+ /** Y Luminance. In GDAL: {@code GCI_YCbCr_YBand = 14}. */ LUMINANCE (ColorSpace.TYPE_YCbCr),
+ /** Cb Chroma. In GDAL: {@code GCI_YCbCr_CbBand = 15}. */ CB_CHROMA (ColorSpace.TYPE_YCbCr),
+ /** Cr Chroma. In GDAL: {@code GCI_YCbCr_CrBand = 16}. */ CR_CHROMA (ColorSpace.TYPE_YCbCr);
+
+ /**
+ * Java2D identifier of the color space as one of {@code ColorSpace.TYPE_*} constants.
+ * The name of the color space type reflects the order of the component in a {@link ComponentColorModel}.
+ * For example, for {@code TYPE_RGB}, index 0 corresponds to red, index 1 to green, and index 2 to blue.
+ * The value of this field may be -1 if this enumeration cannot be mapped to a Java2D type of color space.
+ */
+ private final int colorSpaceType;
+
+ /**
+ * Creates a new enumeration value.
+ *
+ * @param colorSpaceType Java2D identifier of the color space as one of {@code ColorSpace.CS_*} constants.
+ */
+ private ColorInterpretation(final int colorSpaceType) {
+ this.colorSpaceType = colorSpaceType;
+ }
+
+ /**
+ * For fetching enumeration instances from ordinal values.
+ */
+ private static final ColorInterpretation[] VALUES = values();
+
+ /**
+ * Returns an enumeration instance from the given <abbr>GDAL</abbr> value.
+ * If the given value is unknown to this method, then {@link #UNDEFINED} is returned.
+ */
+ static ColorInterpretation valueOf(final int ordinal) {
+ return (ordinal >= 0 && ordinal < VALUES.length) ? VALUES[ordinal] : UNDEFINED;
+ }
+}
diff --git a/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/DataType.java b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/DataType.java
new file mode 100644
index 0000000000..1fb9b2c944
--- /dev/null
+++ b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/DataType.java
@@ -0,0 +1,193 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.storage.gdal;
+
+import java.awt.image.DataBuffer;
+
+
+/**
+ * Type of data loaded by <abbr>GDAL</abbr>.
+ * This enumeration mirrors the C/C++ {@code GDALDataType} enumeration in the GDAL's API.
+ * The {@linkplain #ordinal() ordinal} values shall be equal to the GDAL enumeration values.
+ *
+ * @author Quentin Bialota (Geomatys)
+ * @author Martin Desruisseaux (Geomatys)
+ */
+enum DataType {
+ /**
+ * Unknown or unspecified type.
+ * In <abbr>GDAL</abbr>: {@code GDT_Unknown} = 0.
+ */
+ UNKNOWN((short) DataBuffer.TYPE_UNDEFINED, (short) 0),
+
+ /**
+ * 8 bits unsigned integer.
+ * In <abbr>GDAL</abbr>: {@code GDT_Byte} = 1.
+ */
+ UNSIGNED_BYTE((short) DataBuffer.TYPE_BYTE, (short) Byte.SIZE),
+
+ /**
+ * 16 bits unsigned integer.
+ * In <abbr>GDAL</abbr>: {@code GDT_UInt16} = 2.
+ */
+ UNSIGNED_SHORT((short) DataBuffer.TYPE_USHORT, (short) Short.SIZE),
+
+ /**
+ * 16 bits signed integer.
+ * In <abbr>GDAL</abbr>: {@code GDT_Int16} = 3.
+ */
+ SHORT((short) DataBuffer.TYPE_SHORT, (short) Short.SIZE),
+
+ /**
+ * 32 bits unsigned integer.
+ * In <abbr>GDAL</abbr>: {@code GDT_UInt32} = 4.
+ * Note that both this value and {@link #INT} can be assigned to the Java2D {@code TYPE_INT}.
+ */
+ UNSIGNED_INT((short) DataBuffer.TYPE_INT, (short) Integer.SIZE),
+
+ /**
+ * 32 bits signed integer.
+ * In <abbr>GDAL</abbr>: {@code GDT_Int32} = 5.
+ * Note that both this value and {@link #UNSIGNED_INT} can be assigned to the Java2D {@code TYPE_INT}.
+ */
+ INT((short) DataBuffer.TYPE_INT, (short) Integer.SIZE),
+
+ /**
+ * 32 bit floating point value.
+ * In <abbr>GDAL</abbr>: {@code GDT_Float32} = 6.
+ */
+ FLOAT((short) DataBuffer.TYPE_FLOAT, (short) Float.SIZE),
+
+ /**
+ * 64 bits floating point value.
+ * In <abbr>GDAL</abbr>: {@code GDT_Float64} = 7.
+ */
+ DOUBLE((short) DataBuffer.TYPE_DOUBLE, (short) Double.SIZE),
+
+ /**
+ * Two 16 bits integers for a complex number.
+ * In <abbr>GDAL</abbr>: {@code GDT_CInt16} = 8.
+ * This is undefined in Java 2D image <abbr>API</abbr>.
+ */
+ COMPLEX_SHORT((short) DataBuffer.TYPE_UNDEFINED, (short) (2 * Short.SIZE)),
+
+ /**
+ * Two 32 bits integers for a complex number.
+ * In <abbr>GDAL</abbr>: {@code GDT_CInt32} = 9.
+ * This is undefined in Java 2D image <abbr>API</abbr>.
+ */
+ COMPLEX_INT((short) DataBuffer.TYPE_UNDEFINED, (short) (2 * Integer.SIZE)),
+
+ /**
+ * Two 32 bits floating point values for a complex number.
+ * In <abbr>GDAL</abbr>: {@code GDT_CFloat32} = 10.
+ * This is undefined in Java 2D image <abbr>API</abbr>.
+ */
+ COMPLEX_FLOAT((short) DataBuffer.TYPE_UNDEFINED, (short) (2 * Float.SIZE)),
+
+ /**
+ * Two 64 bits floating point values for a complex number.
+ * In <abbr>GDAL</abbr>: {@code GDT_CFloat64} = 11.
+ * This is undefined in Java 2D image <abbr>API</abbr>.
+ */
+ COMPLEX_DOUBLE((short) DataBuffer.TYPE_UNDEFINED, (short) (2 * Double.SIZE)),
+
+ /**
+ * 64 bits unsigned integer.
+ * In <abbr>GDAL</abbr>: {@code GDT_UInt64} = 12.
+ * This is undefined in Java 2D image <abbr>API</abbr>.
+ */
+ UNSIGNED_LONG((short) DataBuffer.TYPE_UNDEFINED, (short) Long.SIZE),
+
+ /**
+ * 64 bits signed integer.
+ * In <abbr>GDAL</abbr>: {@code GDT_Int64} = 13.
+ * This is undefined in Java 2D image <abbr>API</abbr>.
+ */
+ LONG((short) DataBuffer.TYPE_UNDEFINED, (short) Long.SIZE),
+
+ /**
+ * 8 bits signed integer.
+ * In <abbr>GDAL</abbr>: {@code GDT_Int8} = 14.
+ * This is undefined in Java 2D image <abbr>API</abbr>.
+ *
+ * @see #UNSIGNED_BYTE
+ */
+ BYTE((short) DataBuffer.TYPE_UNDEFINED, (short) (Byte.SIZE));
+
+ /**
+ * The {@code DataBuffer.TYPE_*} constant equivalent to this <abbr>GDAL</abbr> data type.
+ * This is {@link DataBuffer#TYPE_UNDEFINED} if there is no direct Java 2D equivalence.
+ */
+ final short imageType;
+
+ /**
+ * Size in bits of this data type, or 0 if undefined.
+ */
+ final short numBits;
+
+ /**
+ * Creates a new enumeration value.
+ *
+ * @param imageType the {@code DataBuffer.TYPE_*} constant equivalent to this <abbr>GDAL</abbr> data type.
+ * @param numBits size in bits of this data type, or 0 if undefined.
+ */
+ private DataType(final short imageType, final short numBits) {
+ this.imageType = imageType;
+ this.numBits = numBits;
+ }
+
+ /**
+ * All values with, for each element, the index equals to the ordinal value.
+ */
+ private static final DataType[] VALUES = values();
+
+ /**
+ * Returns the enumeration constant for the given <abbr>GDAL</abbr> enumeration value.
+ *
+ * @param ordinal the <abbr>GDAL</abbr> enumeration value.
+ * @return constant equivalent to the given value, or {@link #UNKNOWN} if the given value is not recognized.
+ */
+ public static DataType valueOf(final int ordinal) {
+ return (ordinal >= 0 && ordinal < VALUES.length) ? VALUES[ordinal] : UNKNOWN;
+ }
+
+ /**
+ * Gets the <abbr>GDAL</abbr> data type corresponding to the given {@code DataBuffer.TYPE_*} value.
+ * In case of ambiguity, this enumeration instance is used for resolving the type.
+ *
+ * @param type a {@code DataBuffer.TYPE_*} value.
+ * @return the equivalent <abbr>GDAL</abbr> value, or {@link #UNKNOWN} if the given type is not recognized.
+ *
+ * @see org.apache.sis.image.DataType#forDataBufferType(int)
+ */
+ public DataType forDataBufferType(final int type) {
+ if (type == imageType) {
+ // For resolving the `INT` versus `UNSIGNED_INT` ambiguity.
+ return this;
+ }
+ switch (type) {
+ case DataBuffer.TYPE_BYTE: return UNSIGNED_BYTE;
+ case DataBuffer.TYPE_USHORT: return UNSIGNED_SHORT;
+ case DataBuffer.TYPE_SHORT: return SHORT;
+ case DataBuffer.TYPE_INT: return INT;
+ case DataBuffer.TYPE_FLOAT: return FLOAT;
+ case DataBuffer.TYPE_DOUBLE: return DOUBLE;
+ default: return UNKNOWN;
+ }
+ }
+}
diff --git a/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/Driver.java b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/Driver.java
new file mode 100644
index 0000000000..3b0842a556
--- /dev/null
+++ b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/Driver.java
@@ -0,0 +1,263 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.storage.gdal;
+
+import java.util.List;
+import java.util.AbstractList;
+import java.util.Objects;
+import java.lang.foreign.Arena;
+import java.lang.foreign.FunctionDescriptor;
+import java.lang.foreign.Linker;
+import java.lang.foreign.MemorySegment;
+import java.lang.foreign.ValueLayout;
+import java.lang.invoke.MethodHandle;
+import org.apache.sis.util.CharSequences;
+import org.apache.sis.util.collection.DefaultTreeTable;
+import org.apache.sis.util.collection.TableColumn;
+import org.apache.sis.util.collection.TreeTable;
+import org.apache.sis.util.resources.Vocabulary;
+import org.apache.sis.util.logging.Logging;
+import org.apache.sis.util.privy.Strings;
+import org.apache.sis.storage.DataStoreException;
+
+
+/**
+ * Information about a <abbr>GDAL</abbr> driver.
+ *
+ * @author Quentin Bialota (Geomatys)
+ * @author Martin Desruisseaux (Geomatys)
+ * @version 1.5
+ * @since 1.5
+ */
+public final class Driver {
+ /**
+ * Owner of the set of handles that this class will use for invoking <abbr>GDAL</abbr> functions.
+ * Another purpose of this reference is to prevent premature garbage-collection,
+ * because it would unload the <abbr>GDAL</abbr> library.
+ */
+ private final GDALStoreProvider owner;
+
+ /**
+ * Pointer to the <abbr>GDAL</abbr> object in native memory.
+ * This is a {@code GDALDriverH} in the C/C++ <abbr>API</abbr>.
+ */
+ private final MemorySegment handle;
+
+ /**
+ * Creates a new instance.
+ *
+ * @param owner owner of the set of handles for invoking <abbr>GDAL</abbr> functions.
+ * @param handle pointer to the <abbr>GDAL</abbr> driver in native memory.
+ */
+ Driver(final GDALStoreProvider owner, final MemorySegment handle) {
+ this.owner = owner;
+ this.handle = handle;
+ }
+
+ /**
+ * Returns the long name of the driver. For the GeoTIFF driver, this is {@code "GeoTIFF"}.
+ *
+ * @return the driver long name, or {@code null}.
+ * @throws DataStoreException if an error occurred while invoking a <abbr>GDAL</abbr> function.
+ */
+ public String getName() throws DataStoreException {
+ final var gdal = owner.GDAL().getName;
+ final MemorySegment result;
+ try {
+ result = (MemorySegment) gdal.invokeExact(handle);
+ } catch (Throwable e) {
+ throw GDAL.propagate(e);
+ }
+ return GDAL.toString(result);
+ }
+
+ /**
+ * Returns the short name of the driver. For the GeoTIFF driver, this is {@code "GTiff"}.
+ * This is the name used by <abbr>GDAL</abbr> for identifying a driver on the command-line.
+ *
+ * @return the driver short name, or {@code null}.
+ * @throws DataStoreException if an error occurred while invoking a <abbr>GDAL</abbr> function.
+ *
+ * @see GDALStoreProvider#DRIVERS_OPTION_KEY
+ */
+ public String getIdentifier() throws DataStoreException {
+ final var gdal = owner.GDAL().getIdentifier;
+ final MemorySegment result;
+ try {
+ result = (MemorySegment) gdal.invokeExact(handle);
+ } catch (Throwable e) {
+ throw GDAL.propagate(e);
+ }
+ return GDAL.toString(result);
+ }
+
+ /**
+ * Returns the MIME type handled by the driver.
+ *
+ * @return the MIME type handled by the driver, or {@code null} if unspecified.
+ * @throws DataStoreException if an error occurred while invoking a <abbr>GDAL</abbr> function.
+ */
+ public String getMIMEType() throws DataStoreException {
+ return getMetadataItem("DMD_MIMETYPE", null);
+ }
+
+ /**
+ * Returns the file extensions handled by the driver.
+ *
+ * @return the file extensions handled by the driver, or an empty array if none.
+ * @throws DataStoreException if an error occurred while invoking a <abbr>GDAL</abbr> function.
+ *
+ * @see javax.imageio.spi.ImageReaderWriterSpi#ImageReaderWriterSpi()
+ */
+ public String[] getFileSuffixes() throws DataStoreException {
+ return (String[]) CharSequences.split(getMetadataItem("DMD_EXTENSIONS", null), ' ');
+ }
+
+ /**
+ * Returns whether the driver has raster capability.
+ *
+ * @return whether the driver has raster capability.
+ * @throws DataStoreException if an error occurred while invoking a <abbr>GDAL</abbr> function.
+ */
+ public boolean supportRasters() throws DataStoreException {
+ return "YES".equalsIgnoreCase(getMetadataItem("DCAP_RASTER", null));
+ }
+
+ /**
+ * Fetches a single metadata item. The following table lists some metadata:
+ *
+ * <table class="sis">
+ * <caption>Some metadata keys</caption>
+ * <tr><th>Key</th> <th>Description</th></tr>
+ * <tr><td>{@code "DMD_MIMETYPE"}</td> <td>MIME type handled by the driver.</td></tr>
+ * <tr><td>{@code "DMD_EXTENSIONS"}</td> <td>space separated list of file extensions handled by the driver.</td></tr>
+ * <tr><td>{@code "DCAP_RASTER"}</td> <td>Whether the driver has raster capability.</td></tr>
+ * </table>
+ *
+ * @param name the key for the metadata item to fetch.
+ * @param domain the domain to fetch for, or {@code null} for the default domain.
+ * @return the metadata item value, or {@code null} if none.
+ * @throws DataStoreException if an error occurred while invoking a <abbr>GDAL</abbr> function.
+ */
+ public String getMetadataItem(final String name, final String domain) throws DataStoreException {
+ final var gdal = owner.GDAL().getMetadataItem;
+ final MemorySegment result;
+ try (var arena = Arena.ofConfined()) {
+ final MemorySegment opt = (domain != null) ? arena.allocateFrom(domain) : MemorySegment.NULL;
+ result = (MemorySegment) gdal.invokeExact(handle, arena.allocateFrom(name), opt);
+ } catch (Throwable e) {
+ throw GDAL.propagate(e);
+ }
+ return GDAL.toString(result);
+ }
+
+ /**
+ * Returns the <abbr>GDAL</abbr> version number together with the list of drivers.
+ * See {@link GDALStoreProvider#configuration()} for the public documentation.
+ *
+ * @param owner owner of the set of handles to <abbr>GDAL</abbr> functions.
+ * @param gdal handles to <abbr>GDAL</abbr> native functions, or {@code null} if none.
+ * @return a table of available <abbr>GDAL</abbr> drivers.
+ */
+ static TreeTable configuration(final GDALStoreProvider owner, final GDAL gdal) {
+ final var longNameColumn = TableColumn.NAME;
+ final var shortNameColumn = TableColumn.IDENTIFIER;
+ final var table = new DefaultTreeTable(shortNameColumn, longNameColumn);
+ final TreeTable.Node root = table.getRoot();
+ final String version = (gdal != null) ? gdal.version("--version").orElse(null) : null;
+ root.setValue(shortNameColumn, (gdal != null) ? gdal.libraryName : "GDAL library not found");
+ root.setValue(longNameColumn, (version != null) ? version : Vocabulary.format(Vocabulary.Keys.NotKnown));
+
+ DataStoreException error = null;
+ for (final Driver driver : list(owner, gdal)) {
+ try {
+ if (driver.supportRasters()) {
+ final TreeTable.Node node = root.newChild();
+ node.setValue(shortNameColumn, driver.getIdentifier());
+ node.setValue (longNameColumn, driver.getName());
+ }
+ } catch (DataStoreException e) {
+ if (error == null) error = e;
+ else error.addSuppressed(e);
+ }
+ }
+ if (error != null) {
+ Logging.unexpectedException(GDALStoreProvider.LOGGER, GDALStoreProvider.class, "configuration", error);
+ }
+ return table;
+ }
+
+ /**
+ * Returns an unmodifiable list of all <abbr>GDAL</abbr> drivers currently available.
+ *
+ * @param owner owner of the set of handles to <abbr>GDAL</abbr> functions.
+ * @param gdal handles to <abbr>GDAL</abbr> native functions, or {@code null} if none.
+ * @return all <abbr>GDAL</abbr> drivers, or an empty list if the <abbr>GDAL</abbr> library has not been found.
+ * @throws DataStoreException if an error occurred while invoking a <abbr>GDAL</abbr> function.
+ */
+ static List<Driver> list(final GDALStoreProvider owner, final GDAL gdal) {
+ final MemorySegment address;
+ if (gdal == null || (address = gdal.symbols.find("GDALGetDriver").orElse(null)) == null) {
+ return List.of();
+ }
+ final Linker linker = Linker.nativeLinker();
+ @SuppressWarnings("restricted")
+ final MethodHandle getDriver = linker.downcallHandle(address,
+ FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.JAVA_INT));
+ final int count = gdal.invokeGetInt(linker, "GDALGetDriverCount").orElse(0);
+ return new AbstractList<Driver>() {
+ /** Returns the number of drivers. */
+ @Override public int size() {
+ return count;
+ }
+
+ /** Fetches a driver by index. */
+ @Override public Driver get(final int index) {
+ final MemorySegment handle;
+ try {
+ handle = (MemorySegment) getDriver.invokeExact(Objects.checkIndex(index, count));
+ } catch (Throwable e) {
+ throw GDAL.propagate(e);
+ }
+ return GDAL.isNull(handle) ? null : new Driver(owner, handle); // The check for null is paranoiac.
+ }
+ };
+ }
+
+ /**
+ * Returns a string representation of this driver for debugging purposes.
+ *
+ * @return a string representation of this driver.
+ */
+ @Override
+ public String toString() {
+ Object[] properties;
+ try {
+ properties = new Object[] {
+ "name", getName(),
+ "identifier", getIdentifier(),
+ "MIME", getMIMEType(),
+ "suffixes", getFileSuffixes()
+ };
+ } catch (DataStoreException e) {
+ properties = new Object[] {
+ "error", e
+ };
+ }
+ return Strings.toString(getClass(), properties);
+ }
+}
diff --git a/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/GDAL.java b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/GDAL.java
new file mode 100644
index 0000000000..349612edff
--- /dev/null
+++ b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/GDAL.java
@@ -0,0 +1,598 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.storage.gdal;
+
+import java.nio.file.Path;
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Optional;
+import java.util.NoSuchElementException;
+import java.util.logging.Level;
+import java.util.logging.LogRecord;
+import java.lang.foreign.Linker;
+import java.lang.foreign.ValueLayout;
+import java.lang.foreign.SymbolLookup;
+import java.lang.foreign.MemorySegment;
+import java.lang.foreign.FunctionDescriptor;
+import java.lang.invoke.MethodHandle;
+import org.apache.sis.storage.DataStoreException;
+import org.apache.sis.storage.panama.LibraryLoader;
+import org.apache.sis.storage.panama.LibraryStatus;
+import org.apache.sis.storage.panama.NativeFunctions;
+import org.apache.sis.util.logging.Logging;
+
+
+/**
+ * Handlers to <abbr>GDAL</abbr> native functions needed by this package.
+ * The <abbr>GDAL</abbr> library can be unloaded by invoking {@link #run()}.
+ *
+ * @author Quentin Bialota (Geomatys)
+ * @author Martin Desruisseaux (Geomatys)
+ */
+final class GDAL extends NativeFunctions implements Runnable {
+ /**
+ * The global instance, created when first needed.
+ * This field shall be read and updated in a synchronized block.
+ * It may be reset to {@code null} if <abbr>GDAL</abbr> reported a fatal error.
+ *
+ * @see #global(boolean)
+ */
+ private static GDAL global;
+
+ /**
+ * Whether an error occurred during initialization of {@link #global}.
+ * Shall be read and updated in the same synchronization block as {@link #global}.
+ */
+ private static LibraryStatus globalStatus;
+
+ /**
+ * <abbr>GDAL</abbr> {@code const char *GDALGetDriverLongName(GDALDriverH)}.
+ * Returns the long name of a driver. For the GeoTIFF driver, this is "GeoTIFF"
+ */
+ final MethodHandle getName;
+
+ /**
+ * <abbr>GDAL</abbr> {@code const char *GDALGetDriverShortName(GDALDriverH)}.
+ * Returns the short name of a driver. This is the string that can be passed to the
+ * {@code GDALGetDriverByName()} function. For the GeoTIFF driver, this is "GTiff".
+ */
+ final MethodHandle getIdentifier;
+
+ /**
+ * <abbr>GDAL</abbr> {@code char **GDALGetMetadata(GDALMajorObjectH, const char*)}.
+ * Fetches all metadata in a domain. This function can be invoked on various kinds of <abbr>GDAL</abbr> objects.
+ */
+ final MethodHandle getMetadata;
+
+ /**
+ * <abbr>GDAL</abbr> {@code const char *GDALGetMetadataItem(GDALMajorObjectH, const char*, const char*)}.
+ * Fetches a single metadata item. This function can be invoked on various kinds of <abbr>GDAL</abbr> objects.
+ *
+ * @see Driver#getMetadataItem(String, String)
+ */
+ final MethodHandle getMetadataItem;
+
+ /**
+ * <abbr>GDAL</abbr> {@code GDALDatasetH GDALOpenEx(const char *pszFilename, …)}.
+ * Opens a raster or vector file by invoking the open method of each driver in turn.
+ */
+ final MethodHandle open;
+
+ /**
+ * <abbr>GDAL</abbr> {@code CPLErr GDALClose(GDALDatasetH)}.
+ * For non-shared {@code GDALStore}s (the default), the {@code GDALStore} is closed and all resources are released.
+ * For {@linkplain OpenFlag#SHARED shared} {@code GDALStore}s, the {@code GDALStore} is dereferenced and closed
+ * only if the referenced count has dropped below 1.
+ */
+ final MethodHandle close;
+
+ /**
+ * <abbr>GDAL</abbr> {@code GDALDriverH GDALGetDatasetDriver(GDALDatasetH)}.
+ * Fetches the driver to which a dataset relates.
+ */
+ final MethodHandle getDatasetDriver;
+
+ /**
+ * <abbr>GDAL</abbr> {@code OGRSpatialReferenceH GDALGetSpatialRef(GDALDatasetH)}.
+ * Fetches the spatial reference for this dataset in <abbr>WKT</abbr> format.
+ *
+ * @todo Replace {@code "GDALGetProjectionRef"} by {@code "GDALGetSpatialRef"},
+ * which returns {@code OGRSpatialReference}.
+ */
+ final MethodHandle getSpatialRef;
+
+ /**
+ * <abbr>GDAL</abbr> {@code CPLErr GDALGetGeoTransform(GDALDatasetH, double*)}.
+ * Fetches the affine transformation coefficients in an array of length 6.
+ */
+ final MethodHandle getGeoTransform;
+
+ /**
+ * <abbr>GDAL</abbr> {@code int GDALGetRasterX/YSize(GDALDatasetH)}.
+ * Fetches raster width and height in pixels.
+ */
+ final MethodHandle getRasterXSize, getRasterYSize;
+
+ /**
+ * <abbr>GDAL</abbr> {@code int int GDALGetRasterBandX/YSize(GDALRasterBandH)}.
+ * Fetches band width and height in pixels. Should have the same size as the raster,
+ * except if the band has lower resolution.
+ */
+ final MethodHandle getRasterBandXSize, getRasterBandYSize;
+
+ /**
+ * <abbr>GDAL</abbr> {@code int GDALGetRasterCount(GDALDatasetH)}.
+ * Fetches the number of raster bands on this dataset.
+ */
+ final MethodHandle getRasterCount;
+
+ /**
+ * <abbr>GDAL</abbr> {@code GDALRasterBandH GDALGetRasterBand(GDALDatasetH, int)}.
+ * Fetches a band object for a dataset. Band index starts at 1 (not zero).
+ */
+ final MethodHandle getRasterBand;
+
+ /**
+ * <abbr>GDAL</abbr> {@code int GDALGetBandNumber(GDALRasterBandH)}.
+ * Fetches the band number, starting at 1. A value 0 means that the
+ * band is not directly part of the data set.
+ */
+ final MethodHandle getBandNumber;
+
+ /**
+ * <abbr>GDAL</abbr> {@code GDALDataType GDALGetRasterDataType(GDALRasterBandH)}.
+ * Fetches the pixel data type for a band.
+ */
+ final MethodHandle getRasterDataType;
+
+ /**
+ * <abbr>GDAL</abbr> {@code double GDALGetRasterMinimum/Maximum(GDALRasterBandH, int *pbSuccess)}.
+ * Fetches the minimum or maximum value for a band in units of the sample data (not converted values).
+ * If none, the value is determined from the data type. "No data" values are excluded from the range.
+ */
+ final MethodHandle getRasterMinimum, getRasterMaximum;
+
+ /**
+ * <abbr>GDAL</abbr> {@code double GDALGetRasterNoDataValue(GDALRasterBandH, int *pbSuccess)}.
+ * Fetches the no data value for a band. The value is not converted by the scale and offset.
+ */
+ final MethodHandle getRasterNoDataValue;
+
+ /**
+ * <abbr>GDAL</abbr> {@code double GDALGetRasterScale/Offset(GDALRasterBandH, int *pbSuccess)}.
+ * Fetches the raster value scale or offset. Those two values define the transfer function.
+ * If unspecified in the data file, the default values are for the identity transform.
+ */
+ final MethodHandle getRasterScale, getRasterOffset;
+
+ /**
+ * <abbr>GDAL</abbr> {@code const char *GDALGetRasterUnitType(GDALRasterBandH)}.
+ * Returns raster unit type, or an empty string if none.
+ */
+ final MethodHandle getRasterUnitType;
+
+ /**
+ * <abbr>GDAL</abbr> {@code char **GDALGetRasterCategoryNames(GDALRasterBandH)}.
+ * etch the list of category names for this raster.
+ */
+ final MethodHandle getRasterCategoryNames;
+
+ /**
+ * <abbr>GDAL</abbr> {@code GDALColorTableH GDALGetRasterColorTable(GDALRasterBandH)}.
+ * Fetches the color table associated with a band.
+ */
+ final MethodHandle getRasterColorTable;
+
+ /**
+ * <abbr>GDAL</abbr> {@code int GDALGetColorEntryCount(GDALColorTableH)}.
+ * Gets number of color entries in table.
+ */
+ final MethodHandle getColorEntryCount;
+
+ /**
+ * <abbr>GDAL</abbr> {@code GDALGetColorEntryAsRGB(GDALColorTableH, int, GDALColorEntry*)}.
+ * Fetches a table entry in RGB format.
+ */
+ final MethodHandle getColorEntryAsRGB;
+
+ /**
+ * <abbr>GDAL</abbr> {@code GDALColorInterp GDALGetRasterColorInterpretation(GDALRasterBandH)}.
+ * Specifies how a band should be interpreted as color.
+ */
+ final MethodHandle getColorInterpretation;
+
+ /**
+ * <abbr>GDAL</abbr> {@code void GDALGetBlockSize(GDALRasterBandH, int *pnXSize, int *pnYSize)}.
+ * Fetches the "natural" block size of a band.
+ */
+ final MethodHandle getBlockSize;
+
+ /**
+ * <abbr>GDAL</abbr> {@code CPLErr GDALRasterIO(GDALRasterBandH hRBand, ...)}.
+ * Read/write a region of image data for this band.
+ */
+ final MethodHandle rasterIO;
+
+ /**
+ * <abbr>GDAL</abbr> {@code void CPLErrorReset(void)}.
+ * Erase any traces of previous errors. Used to ensure that an error which has been
+ * recovered from does not appear to be still in play with high level functions.
+ *
+ * @see #errorReset()
+ */
+ private final MethodHandle errorReset;
+
+ /**
+ * <abbr>GDAL</abbr> {@code CPLErr CPLGetLastErrorType(void)}.
+ * Fetches the last error type that hasn't been cleared by {@link #errorReset}.
+ *
+ * @see #checkCPLErr(GDALStore, String, boolean)
+ */
+ private final MethodHandle getLastErrorType;
+
+ /**
+ * <abbr>GDAL</abbr> {@code const char *CPLGetLastErrorMsg(void)}.
+ * Fetches the last error message that hasn't been cleared by {@link #errorReset}
+ *
+ * @todo Replace by a call to {@code CPLSetErrorHandler}.
+ */
+ final MethodHandle getLastErrorMsg;
+
+ /**
+ * Creates the handles for all <abbr>GDAL</abbr> functions which will be needed.
+ *
+ * @param loader the object used for loading the library.
+ * @throws NoSuchElementException if a <abbr>GDAL</abbr> function has not been found in the library.
+ */
+ private GDAL(final LibraryLoader<GDAL> loader) {
+ super(loader);
+
+ // A few frequently-used function signatures.
+ final var acceptPointerReturnPointer = FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.ADDRESS);
+ final var acceptPointerReturnInt = FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS);
+ final var acceptTwoPtrsReturnDouble = FunctionDescriptor.of(ValueLayout.JAVA_DOUBLE, ValueLayout.ADDRESS, ValueLayout.ADDRESS);
+ final Linker linker = Linker.nativeLinker();
+
+ // For Driver and/or all major objects
+ getName = lookup(linker, "GDALGetDriverLongName", acceptPointerReturnPointer);
+ getIdentifier = lookup(linker, "GDALGetDriverShortName", acceptPointerReturnPointer);
+ getMetadata = lookup(linker, "GDALGetMetadata", FunctionDescriptor.of(
+ ValueLayout.ADDRESS, // const char* (return type)
+ ValueLayout.ADDRESS, // GDALMajorObject
+ ValueLayout.ADDRESS)); // const char* domain
+
+ getMetadataItem = lookup(linker, "GDALGetMetadataItem", FunctionDescriptor.of(
+ ValueLayout.ADDRESS, // const char* (return type)
+ ValueLayout.ADDRESS, // GDALMajorObject
+ ValueLayout.ADDRESS, // const char* name
+ ValueLayout.ADDRESS)); // const char* domain
+
+ // For Opener
+ close = lookup(linker, "GDALClose", acceptPointerReturnInt);
+ open = lookup(linker, "GDALOpenEx", FunctionDescriptor.of(ValueLayout.ADDRESS,
+ ValueLayout.ADDRESS, // const char *pszFilename
+ ValueLayout.JAVA_INT, // unsigned int nOpenFlags
+ ValueLayout.ADDRESS, // const char *const *papszAllowedDrivers
+ ValueLayout.ADDRESS, // const char *const *papszOpenOptions
+ ValueLayout.ADDRESS)); // const char *const *papszSiblingFiles
+
+ // For all data set
+ getDatasetDriver = lookup(linker, "GDALGetDatasetDriver", acceptPointerReturnPointer);
+ getSpatialRef = lookup(linker, "GDALGetProjectionRef", acceptPointerReturnPointer);
+
+ // For TiledResource (GDAL Raster)
+ getGeoTransform = lookup(linker, "GDALGetGeoTransform", FunctionDescriptor.of(
+ ValueLayout.JAVA_INT, // CPLErr error code (return value)
+ ValueLayout.ADDRESS, // GDALDataSetH dataset
+ ValueLayout.ADDRESS)); // double *padfTransform
+
+ getRasterXSize = lookup(linker, "GDALGetRasterXSize", acceptPointerReturnInt);
+ getRasterYSize = lookup(linker, "GDALGetRasterYSize", acceptPointerReturnInt);
+ getRasterCount = lookup(linker, "GDALGetRasterCount", acceptPointerReturnInt);
+ getRasterBandXSize = lookup(linker, "GDALGetRasterBandXSize", acceptPointerReturnInt);
+ getRasterBandYSize = lookup(linker, "GDALGetRasterBandYSize", acceptPointerReturnInt);
+ getRasterBand = lookup(linker, "GDALGetRasterBand", FunctionDescriptor.of(
+ ValueLayout.ADDRESS, // GDALRasterBandH (return value)
+ ValueLayout.ADDRESS, // GDALDataSetH dataset
+ ValueLayout.JAVA_INT)); // Band index, starting with 1.
+
+ // For Band
+ getBandNumber = lookup(linker, "GDALGetBandNumber", acceptPointerReturnInt);
+ getColorInterpretation = lookup(linker, "GDALGetRasterColorInterpretation", acceptPointerReturnInt);
+ getRasterDataType = lookup(linker, "GDALGetRasterDataType", acceptPointerReturnInt);
+ getRasterMinimum = lookup(linker, "GDALGetRasterMinimum", acceptTwoPtrsReturnDouble);
+ getRasterMaximum = lookup(linker, "GDALGetRasterMaximum", acceptTwoPtrsReturnDouble);
+ getRasterNoDataValue = lookup(linker, "GDALGetRasterNoDataValue", acceptTwoPtrsReturnDouble);
+ getRasterScale = lookup(linker, "GDALGetRasterScale", acceptTwoPtrsReturnDouble);
+ getRasterOffset = lookup(linker, "GDALGetRasterOffset", acceptTwoPtrsReturnDouble);
+ getRasterUnitType = lookup(linker, "GDALGetRasterUnitType", acceptPointerReturnPointer);
+ getRasterCategoryNames = lookup(linker, "GDALGetRasterCategoryNames", acceptPointerReturnPointer);
+ getRasterColorTable = lookup(linker, "GDALGetRasterColorTable", acceptPointerReturnPointer);
+ getColorEntryCount = lookup(linker, "GDALGetColorEntryCount", acceptPointerReturnInt);
+ getColorEntryAsRGB = lookup(linker, "GDALGetColorEntryAsRGB", FunctionDescriptor.of(
+ ValueLayout.JAVA_INT,
+ ValueLayout.ADDRESS,
+ ValueLayout.JAVA_INT,
+ ValueLayout.ADDRESS));
+
+ // Band I/O
+ getBlockSize = lookup(linker, "GDALGetBlockSize", FunctionDescriptor.ofVoid(
+ ValueLayout.ADDRESS, // GDALRasterBandH
+ ValueLayout.ADDRESS, // int *pnXSize
+ ValueLayout.ADDRESS)); // int *pnYSize
+
+ rasterIO = lookup(linker, "GDALRasterIO", FunctionDescriptor.of(
+ ValueLayout.JAVA_INT, // CPLErr error code (return value)
+ ValueLayout.ADDRESS, // GDALRasterBandH hRBand
+ ValueLayout.JAVA_INT, // GDALRWFlag eRWFlag
+ ValueLayout.JAVA_INT, // int nDSXOff
+ ValueLayout.JAVA_INT, // int nDSYOff
+ ValueLayout.JAVA_INT, // int nDSXSize
+ ValueLayout.JAVA_INT, // int nDSYSize
+ ValueLayout.ADDRESS, // void *pBuffer
+ ValueLayout.JAVA_INT, // int nBXSize
+ ValueLayout.JAVA_INT, // int nBYSize
+ ValueLayout.JAVA_INT, // GDALDataType eBDataType
+ ValueLayout.JAVA_INT, // int nPixelSpace
+ ValueLayout.JAVA_INT)); // int nLineSpace
+
+ // Error handling
+ errorReset = lookup(linker, "CPLErrorReset", FunctionDescriptor.ofVoid());
+ getLastErrorType = lookup(linker, "CPLGetLastErrorType", FunctionDescriptor.of(ValueLayout.JAVA_INT));
+ getLastErrorMsg = lookup(linker, "CPLGetLastErrorMsg", FunctionDescriptor.of(ValueLayout.ADDRESS));
+
+ // Initialize GDAL after we found all functions.
+ if (!invoke("GDALAllRegister")) {
+ final LogRecord record = new LogRecord(Level.WARNING, "Could not initialize GDAL.");
+ log("open", record);
+ }
+ }
+
+ /**
+ * Returns the helper class for loading the <abbr>GDAL</abbr> library.
+ * If {@code def} is true, then this method tries to load the library
+ * now and stores the result in {@link #global} and {@link #globalStatus}.
+ *
+ * @param now whether this method is invoked for the default (global) library.
+ * In such case, the caller must be synchronized and {@link #global} must be initially null.
+ * @return the library loader for <abbr>GDAL</abbr>.
+ */
+ private static LibraryLoader<GDAL> load(final boolean now) {
+ final var loader = new LibraryLoader<>(GDAL::new);
+ if (now) {
+ try {
+ global = loader.global("gdal");
+ } finally {
+ globalStatus = loader.status();
+ }
+ if (global != null) {
+ if (GDALStoreProvider.LOGGER.isLoggable(Level.CONFIG)) {
+ global.version("--version").ifPresent((version) -> {
+ log("open", new LogRecord(Level.CONFIG, version));
+ });
+ }
+ }
+ }
+ return loader;
+ }
+
+ /**
+ * Loads the <abbr>GDAL</abbr> library from the given file.
+ * Callers should register the returned instance in a {@link java.lang.ref.Cleaner}.
+ *
+ * @param library the library to load.
+ * @return handles to native functions needed by this module.
+ * @throws IllegalArgumentException if the GDAL library has not been found.
+ * @throws NoSuchElementException if a <abbr>GDAL</abbr> function has not been found in the library.
+ * @throws IllegalCallerException if this Apache SIS module is not authorized to call native methods.
+ */
+ static GDAL load(final Path library) {
+ return load(false).load(library);
+ }
+
+ /**
+ * Returns an instance using the <abbr>GDAL</abbr> library loaded from the default library path.
+ * The handles are valid for the Java Virtual Machine lifetime, i.e. it uses the global arena.
+ * If this method has already been invoked, this method returns the previously created instance.
+ *
+ * <p>If the <abbr>GDAL</abbr> library is not found, the current default is {@link SymbolLookup#loaderLookup()}
+ * for allowing users to invoke {@link System#loadLibrary(String)} as a fallback. This policy may be revised in
+ * any future version of Apache <abbr>SIS</abbr>.</p>
+ *
+ * @return handles to native functions needed by this module.
+ * @throws DataStoreException if the native library has not been found or if SIS is not allowed to call
+ * native functions, and {@code onError} is null.
+ */
+ static synchronized GDAL global() throws DataStoreException {
+ if (globalStatus == null) {
+ load(true).validate();
+ }
+ globalStatus.report(null);
+ return global;
+ }
+
+ /**
+ * Same as {@link #global}, but logs a warning instead of throwing an exception in case of error.
+ *
+ * @param caller the name of the method which is invoking this method.
+ * @return handles to native functions needed by this module, or empty if not available.
+ */
+ static synchronized Optional<GDAL> tryGlobal(final String caller) {
+ if (globalStatus == null) {
+ load(true).getError(GDALStoreProvider.NAME).ifPresent((record) -> log(caller, record));
+ }
+ return Optional.ofNullable(global);
+ }
+
+ /**
+ * Logs the given record as if was produced by the {@link GDALStoreProvider}, which is the public class.
+ *
+ * @param caller the method name to report as the caller.
+ * @param record the error to log.
+ */
+ private static void log(final String caller, final LogRecord record) {
+ Logging.completeAndLog(GDALStoreProvider.LOGGER, GDALStoreProvider.class, caller, record);
+ }
+
+ /**
+ * Returns the <abbr>GDAL</abbr> version. The request can be:
+ *
+ * <ul>
+ * <li>{@code "LICENSE"}: content of the {@code LICENSE.TXT} file from the {@code GDAL_DATA} directory.</li>
+ * <li>{@code "VERSION_NUM"}: version packed in a string. Example: "30603000" for GDAL 3.6.3.0.</li>
+ * <li>{@code "RELEASE_DATE"}: release packed in a string. Example: "20230312".</li>
+ * <li>{@code "--version"}: </li>
+ * </ul>
+ *
+ * @param request the desired version information.
+ * @return the <abbr>GDAL</abbr> version, or a message saying that the library was not found.
+ */
+ final Optional<String> version(final String request) {
+ return invokeGetString(Linker.nativeLinker(), "GDALVersionInfo", request);
+ }
+
+ /**
+ * Returns a {@code NULL}-terminated array as a modifiable list of strings.
+ * This way to encode arrays of strings is specific to <abbr>GDAL</abbr>.
+ * The list cannot contain any value (not possible with null-terminated arrays).
+ * Instead, <abbr>GDAL</abbr> sometime represents missing values by empty strings.
+ *
+ * @param result the result of a native method call, or {@code null}.
+ * @return the results as strings, or {@code null} if the result was null.
+ */
+ @SuppressWarnings("restricted")
+ static List<String> toStringArray(MemorySegment result) {
+ if (isNull(result)) {
+ return null;
+ }
+ result = result.reinterpret(Integer.MAX_VALUE);
+ final var items = new ArrayList<String>();
+ final long stride = ValueLayout.ADDRESS.byteSize();
+ String item;
+ for (long offset = 0; (item = toString(result.get(ValueLayout.ADDRESS, offset))) != null; offset += stride) {
+ items.add(item);
+ }
+ return items;
+ }
+
+ /**
+ * Resets the <abbr>GDAL</abbr> Common Portability Library (<abbr>CPL</abbr>) error code.
+ * This method should be invoked before functions returning a value other than {@code CPLErr}.
+ *
+ * @see #checkCPLErr(GDALStore, String, boolean, int)
+ */
+ final void errorReset() throws Throwable {
+ errorReset.invokeExact();
+ }
+
+ /**
+ * Handles the <abbr>GDAL</abbr> Common Portability Library error code of the last invoked function.
+ * This method assumes that no other <var>GDAL</var> function has been invoked since the last error.
+ *
+ * <h4>Race conditions</h4>
+ * <em>Despite synchronization, this method is not thread-safe.</em> If another {@code GDALStore}
+ * is performing an action concurrently, even on unrelated data, the GDAL message may be confusing.
+ *
+ * @param caller the store that performed a <abbr>GDAL</abbr> operation.
+ * @param method the {@code GDALStore} method executed, or null for throwing an exception instead of logging.
+ * @param mandatory whether a failure should throw an exception. If not, only a warning will be logged.
+ * @return whether the operation was successful, possibly with warnings.
+ * @throws DataStoreException if the error category is {@code CE_Failure} and {@code mandatory} is true,
+ * or if the error category is {@code CE_Fatal} or higher.
+ *
+ * @see #errorReset()
+ */
+ final boolean checkCPLErr(final GDALStore caller, final String method, final boolean mandatory)
+ throws DataStoreException
+ {
+ final int err;
+ try {
+ err = (int) getLastErrorType.invokeExact();
+ } catch (Throwable e) {
+ throw propagate(e);
+ }
+ return checkCPLErr(caller, method, mandatory, err);
+ }
+
+ /**
+ * Handles a <abbr>GDAL</abbr> Common Portability Library error code ({@code CPLErr}).
+ * The possible values are:
+ *
+ * <ul>
+ * <li>{@code CE_None} = 0: No error or warning occurred.</li>
+ * <li>{@code CE_Debug} = 1: The result contains debug information that users can ignore.</li>
+ * <li>{@code CE_Warning} = 2: The result contains informational warning.</li>
+ * <li>{@code CE_Failure} = 3: The action failed.</li>
+ * <li>{@code CE_Fatal} = 4: A fatal error has occurred and <abbr>GDAL</abbr> should not be used anymore.
+ * The default GDAL behavior is to report errors to {@code stderr} and to abort the application.</li>
+ * </ul>
+ *
+ * If the error level is debug or warning, a message is sent to the {@linkplain #listeners}.
+ * If the error level is failure or fatal, a {@link DataStoreException} is thrown.
+ *
+ * @param caller the store that performed a <abbr>GDAL</abbr> operation.
+ * @param method the {@code GDALStore} method executed.c
+ * @param mandatory whether a failure should throw an exception. If not, only a warning will be logged.
+ * @param err the {@code CPLErr} enumeration value returned by <abbr>GDAL</abbr>.
+ * @return whether the operation was successful, possibly with warnings.
+ * @throws DataStoreException if the error category is {@code CE_Failure} and {@code mandatory} is true,
+ * or if the error category is {@code CE_Fatal} or higher.
+ *
+ * @see #errorReset()
+ */
+ final boolean checkCPLErr(final GDALStore caller, final String method, final boolean mandatory, final int err)
+ throws DataStoreException
+ {
+ final Level level;
+ switch (err) {
+ case 0: return true;
+ case 1: level = Level.FINE; break;
+ case 2: level = Level.WARNING; break;
+ case 3: level = mandatory ? null : Level.WARNING; break;
+ default: {
+ caller.getProvider().fatalError();
+ throw new DataStoreException("GDAL fatal error. Cannot use GDAL anymore.");
+ }
+ }
+ MemorySegment msg = null;
+ try {
+ msg = (MemorySegment) getLastErrorMsg.invokeExact();
+ } catch (Throwable e) {
+ throw propagate(e);
+ }
+ final String message = toString(msg);
+ if (level == null) {
+ throw new DataStoreException(message);
+ }
+ caller.warning(method, new LogRecord(level, message));
+ return err < 3;
+ }
+
+ /**
+ * Unloads the <abbr>GDAL</abbr> library. If the arena is global,
+ * then this method should not be invoked before <abbr>JVM</abbr> shutdown.
+ * Otherwise, this method is invoked when {@link GDALStoreProvider} is garbage-collected.
+ */
+ @Override
+ public void run() {
+ try {
+ invoke("GDALDestroy");
+ } finally {
+ super.run();
+ }
+ }
+}
diff --git a/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/GDALStore.java b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/GDALStore.java
new file mode 100644
index 0000000000..e43fa2ee45
--- /dev/null
+++ b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/GDALStore.java
@@ -0,0 +1,499 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.storage.gdal;
+
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.logging.Level;
+import java.util.logging.LogRecord;
+import java.text.ParseException;
+import java.net.URI;
+import java.io.IOException;
+import java.nio.file.DirectoryStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.lang.ref.Cleaner;
+import java.lang.foreign.Arena;
+import java.lang.foreign.MemorySegment;
+import org.opengis.util.NameSpace;
+import org.opengis.util.GenericName;
+import org.opengis.util.NameFactory;
+import org.opengis.metadata.Metadata;
+import org.opengis.parameter.ParameterValueGroup;
+import org.opengis.referencing.crs.CoordinateReferenceSystem;
+import org.apache.sis.parameter.Parameters;
+import org.apache.sis.io.wkt.WKTFormat;
+import org.apache.sis.io.wkt.Convention;
+import org.apache.sis.io.stream.IOUtilities;
+import org.apache.sis.storage.Resource;
+import org.apache.sis.storage.Aggregate;
+import org.apache.sis.storage.DataStore;
+import org.apache.sis.storage.DataStoreException;
+import org.apache.sis.storage.DataStoreClosedException;
+import org.apache.sis.storage.InternalDataStoreException;
+import org.apache.sis.storage.StorageConnector;
+import org.apache.sis.storage.base.MetadataBuilder;
+import org.apache.sis.storage.base.ResourceOnFileSystem;
+import org.apache.sis.storage.base.URIDataStore;
+import org.apache.sis.util.privy.UnmodifiableArrayList;
+import org.apache.sis.util.iso.DefaultNameFactory;
+
+
+/**
+ * A data store using the <abbr>GDAL</abbr> library for all data accesses.
+ *
+ * @author Johann Sorel (Geomatys)
+ * @author Quentin Bialota (Geomatys)
+ * @author Martin Desruisseaux (Geomatys)
+ * @version 1.5
+ * @since 1.5
+ */
+public class GDALStore extends DataStore implements Aggregate, ResourceOnFileSystem {
+ /**
+ * The {@link GDALStoreProvider#LOCATION} parameter value, or {@code null} if none.
+ *
+ * @see #getOpenParameters()
+ */
+ private final URI location;
+
+ /**
+ * Path of the file opened by this data store, or {@code null} if none.
+ *
+ * @see #getComponentFiles()
+ */
+ private final Path path;
+
+ /**
+ * The factory to use for creating the identifiers.
+ */
+ final NameFactory factory;
+
+ /**
+ * The identifier of this resource as a name space, or {@code null} if none.
+ * This field should not be modified after construction.
+ *
+ * @see #getIdentifier()
+ */
+ NameSpace namespace;
+
+ /**
+ * Pointer to the <abbr>GDAL</abbr> object in native memory, or {@code null} if disposed.
+ * This is a {@code GDALDatasetH} in the C/C++ <abbr>API</abbr>.
+ *
+ * @see #handle()
+ * @see #dispose()
+ */
+ private MemorySegment handle;
+
+ /**
+ * The action to execute for closing the {@link GDALStore}.
+ */
+ private final Cleaner.Cleanable closer;
+
+ /**
+ * A description of this data set, or {@code null} if none.
+ * This can be used as the {@linkplain #metadata} title.
+ */
+ String description;
+
+ /**
+ * A description of this resource as an unmodifiable metadata, or {@code null} if not yet computed.
+ *
+ * @see #getMetadata()
+ */
+ private Metadata metadata;
+
+ /**
+ * The components of this data set, created when first requested.
+ *
+ * @see #components()
+ */
+ private List<? extends Resource> components;
+
+ /**
+ * The object to use for parsing and formatting <abbr>CRS</abbr> definitions from/to <abbr>GDAL</abbr>.
+ * This object must be used in a block synchronized on {@code this}. This is created when first needed.
+ *
+ * @see #wktFormat()
+ * @see #parseCRS(GDAL, String)
+ */
+ private WKTFormat wktFormat;
+
+ /**
+ * Creates a new data store for reading the file specified by the given connector.
+ * The {@code provider} argument is mandatory for this data store,
+ * because it provides the links to the <var>GDAL</var> library.
+ *
+ * @param provider the factory that created this {@code GDALStore} instance.
+ * @param connector information about the storage. Should be convertible to a URL.
+ * @throws DataStoreException if an error occurred while creating the data store for the given storage.
+ */
+ @SuppressWarnings("this-escape")
+ public GDALStore(final GDALStoreProvider provider, final StorageConnector connector) throws DataStoreException {
+ super(Objects.requireNonNull(provider), connector);
+ factory = DefaultNameFactory.provider();
+ final String filename = IOUtilities.filename(connector.getStorage());
+ if (filename != null) {
+ namespace = factory.createNameSpace(factory.createLocalName(null, filename), null);
+ }
+ final String[] drivers;
+ final Opener opener;
+ drivers = connector.getOption(GDALStoreProvider.DRIVERS_OPTION_KEY);
+ path = connector.getStorageAs(Path.class);
+ location = connector.commit(URI.class, GDALStoreProvider.NAME);
+ opener = Opener.read(provider, Opener.toURL(location, path), drivers);
+ closer = GDALStoreProvider.CLEANERS.register(this, opener); // Must do now in case of exception before completion.
+ handle = opener.handle;
+ }
+
+ /**
+ * Creates a new data store as a child of the given store.
+ * This constructor is the {@link Subdataset} constructor only.
+ *
+ * @param parent the parent data store.
+ * @param url <abbr>URL</abbr> for <var>GDAL</var> of the data store to open.
+ * @param driver name of the driver to use.
+ * @throws DataStoreException if an error occurred while creating the data store for the given storage.
+ */
+ @SuppressWarnings("this-escape")
+ GDALStore(final GDALStore parent, final String url, final String driver) throws DataStoreException {
+ super(parent, parent.getProvider(), new StorageConnector(url), false);
+ final Opener opener;
+ path = parent.path;
+ location = parent.location;
+ factory = parent.factory;
+ opener = Opener.read(getProvider(), url, driver);
+ closer = GDALStoreProvider.CLEANERS.register(this, opener); // Must do now in case of exception before completion.
+ handle = opener.handle;
+ }
+
+ /**
+ * Returns the <abbr>GDAL</abbr> handle, or throws an exception if the data set is closed.
+ * Must be invoked from a method synchronized on {@code this}.
+ *
+ * @see #close()
+ */
+ final MemorySegment handle() throws DataStoreClosedException {
+ assert Thread.holdsLock(this);
+ if (handle != null) return handle;
+ throw new DataStoreClosedException("Data store is closed.");
+ }
+
+ /**
+ * Returns the factory that created this {@code DataStore} instance.
+ * The provider determines which <abbr>GDAL</abbr> library is used.
+ *
+ * @return the factory that created this {@code DataStore} instance.
+ */
+ @Override
+ public final GDALStoreProvider getProvider() {
+ return (GDALStoreProvider) super.getProvider();
+ }
+
+ /**
+ * Returns the <abbr>GDAL</abbr> driver used for opening the file.
+ *
+ * @return the <abbr>GDAL</abbr> driver used for opening the file.
+ * @throws DataStoreException if this data store is closed.
+ */
+ public synchronized Driver getDriver() throws DataStoreException {
+ final GDAL gdal = getProvider().GDAL();
+ final MemorySegment driver;
+ try {
+ driver = (MemorySegment) gdal.getDatasetDriver.invokeExact(handle());
+ } catch (Throwable e) {
+ throw GDAL.propagate(e);
+ }
+ // Should never be null, but verify as a safety.
+ return GDAL.isNull(driver) ? null : new Driver(getProvider(), driver);
+ }
+
+ /**
+ * Returns the name of the driver used for opening the file.
+ * This name can be used as driver identifier for opening sub-components.
+ *
+ * @param gdal set of handles for invoking <abbr>GDAL</abbr> functions.
+ * @return name of the <abbr>GDAL</abbr> driver used for opening the file.
+ * @throws DataStoreException if the driver name cannot be fetched.
+ */
+ final String getDriverName(final GDAL gdal) throws DataStoreException {
+ try {
+ var result = (MemorySegment) gdal.getDatasetDriver.invokeExact(handle());
+ if (!GDAL.isNull(result)) { // Paranoiac check.
+ result = (MemorySegment) gdal.getName.invokeExact(result);
+ return GDAL.toString(result);
+ }
+ } catch (Throwable e) {
+ throw GDAL.propagate(e);
+ }
+ throw new InternalDataStoreException("Cannot get the driver name.");
+ }
+
+ /**
+ * Returns the parameters used for opening this <abbr>GDAL</abbr> data store.
+ * The parameters are described by {@link GDALStoreProvider#getOpenParameters()} and contains at least
+ * a parameter named {@value org.apache.sis.storage.DataStoreProvider#LOCATION} with a {@link URI} value.
+ * The return value may be empty if the storage input cannot be described by a URI.
+ *
+ * @return parameters used for opening this data store.
+ */
+ @Override
+ public Optional<ParameterValueGroup> getOpenParameters() {
+ final Parameters param = Parameters.castOrWrap(URIDataStore.parameters(provider, location));
+ if (param != null) try {
+ param.getOrCreate(GDALStoreProvider.DRIVERS_PARAM).setValue(new String[] {
+ getDriver().getIdentifier()}
+ );
+ } catch (DataStoreException e) {
+ listeners.warning(e);
+ }
+ return Optional.ofNullable(param);
+ }
+
+ /**
+ * Returns an identifier for the root resource of this data store, or an empty value if none.
+ *
+ * @return an identifier for the root resource of this data store.
+ * @throws DataStoreException if an error occurred while fetching the identifier.
+ */
+ @Override
+ public final Optional<GenericName> getIdentifier() throws DataStoreException {
+ return (namespace != null) ? Optional.of(namespace.name()) : Optional.empty();
+ }
+
+ /**
+ * Returns information about the data store as a whole.
+ *
+ * @return information about resources in the data store.
+ * @throws DataStoreException if an error occurred while reading the metadata.
+ */
+ @Override
+ public synchronized Metadata getMetadata() throws DataStoreException {
+ if (metadata == null) {
+ final var builder = new MetadataBuilder();
+ builder.addTitle(description);
+ builder.addIdentifier(getIdentifier().orElse(null), MetadataBuilder.Scope.RESOURCE);
+ // TODO: add more information.
+ return builder.buildAndFreeze();
+ }
+ return metadata;
+ }
+
+ /**
+ * Returns the children resources of this aggregate.
+ *
+ * @return the resources that are contained in this aggregate.
+ * @throws DataStoreException if an error occurred in a <abbr>GDAL</abbr> function.
+ */
+ @Override
+ @SuppressWarnings("ReturnOfCollectionOrArrayField") // Because unmodifable.
+ public synchronized Collection<? extends Resource> components() throws DataStoreException {
+ if (components == null) {
+ final GDAL gdal = getProvider().GDAL();
+ final List<Subdataset> subdatasets = groupBySubset(gdal);
+ if (subdatasets != null && !subdatasets.isEmpty()) {
+ components = subdatasets;
+ } else {
+ final TiledResource[] rasters = TiledResource.groupBySizeAndType(this, gdal, handle);
+ if (gdal.checkCPLErr(this, "components", true)) {
+ components = UnmodifiableArrayList.wrap(rasters);
+ } else {
+ components = List.of();
+ }
+ }
+ }
+ return components;
+ }
+
+ /**
+ * If the data set declares sub-components, creates sub-data stores for those sub-components.
+ * The sub-components are defined in a <abbr>GDAL</abbr> metadata having a content like below:
+ *
+ * <pre>SUBDATASET_1_NAME=NETCDF:"/run/media/.../C1_2020.nc":elevation
+ * SUBDATASET_1_DESC=[9004x9482] geoid_height_above_reference_ellipsoid (32-bit floating-point)
+ * SUBDATASET_2_NAME=NETCDF:"/run/media/.../C1_2020.nc":value_count
+ * SUBDATASET_2_DESC=[9004x9482] value_count (32-bit integer)</pre>
+ *
+ * @param gdal set of handles for invoking <abbr>GDAL</abbr> functions.
+ * @return the sub-components, or {@code null} if none. May be empty if no metadata has been recognized.
+ */
+ List<Subdataset> groupBySubset(final GDAL gdal) throws DataStoreException {
+ final MemorySegment result;
+ try (var arena = Arena.ofConfined()) {
+ final MemorySegment domain = arena.allocateFrom("SUBDATASETS");
+ result = (MemorySegment) gdal.getMetadata.invokeExact(handle, domain);
+ } catch (Throwable e) {
+ throw GDAL.propagate(e);
+ }
+ final List<String> all = GDAL.toStringArray(result);
+ if (all != null) {
+ final String driver = getDriverName(gdal);
+ if (driver != null) { // Should never be null.
+ return new SubdatasetList(gdal, this, all);
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Gets the paths to files potentially used by this resource.
+ * This method returns the path to the main file opened by the <abbr>GDAL</abbr> driver,
+ * and applies heuristic rules for guessing which other paths may be part of the format.
+ * Heuristic rules are used because <abbr>GDAL</abbr> provides no <abbr>API</abbr> for
+ * listing which files are used.
+ *
+ * @return files used by this resource, or an empty array if unknown.
+ * @throws DataStoreException if an error on the file system prevent the creation of the list.
+ */
+ @Override
+ public Path[] getComponentFiles() throws DataStoreException {
+ @SuppressWarnings("LocalVariableHidesMemberVariable")
+ final Path path = this.path;
+ if (path == null) {
+ return new Path[0];
+ }
+ final DirectoryStream.Filter<Path> filter;
+ switch (getDriver().getIdentifier()) {
+ default: {
+ return new Path[] {path};
+ }
+ case "AIG": { // Arc/Info Binary Grid
+ // Special case: we must take "metadata.xml" and all "*.adf" in the folder.
+ filter = (Path entry) -> ("metadata.xml".equalsIgnoreCase(entry.getFileName().toString())
+ || "adf".equalsIgnoreCase(IOUtilities.extension(entry)));
+ break;
+ }
+ // TODO: list more case where we want the same default as GeoTIFF.
+ case "GTiff": {
+ // List all existing paths with the same file name but possibly with different suffixes.
+ final String filename = path.getFileName().toString();
+ final int s = filename.lastIndexOf('.');
+ final String base = (s >= 0) ? filename.substring(0, s+1) : filename;
+ filter = (Path entry) -> entry.getFileName().toString().startsWith(base);
+ break;
+ }
+ }
+ final var paths = new ArrayList<Path>();
+ paths.addFirst(path);
+ try (DirectoryStream<Path> stream = Files.newDirectoryStream(path.getParent(),
+ (entry) -> !entry.equals(path) && filter.accept(entry) && Files.isRegularFile(entry)))
+ {
+ stream.forEach(paths::add);
+ } catch (IOException ex) {
+ throw cannotExecute(ex);
+ }
+ // Ensure that the main path is first.
+ return paths.toArray(Path[]::new);
+ }
+
+ /**
+ * Returns the object to use for parsing and formatting <abbr>CRS</abbr> definitions from/to <abbr>GDAL</abbr>.
+ * This object must be used in a block synchronized on {@code this}.
+ */
+ private WKTFormat wktFormat() {
+ if (wktFormat == null) {
+ wktFormat = new WKTFormat(null, null);
+ wktFormat.setConvention(Convention.WKT1_COMMON_UNITS);
+ }
+ return wktFormat;
+ }
+
+ /**
+ * Gets the <abbr>CRS</abbr> of the data set by parsing its <abbr>WKT</abbr> representation.
+ * This method must be invoked from a method synchronized on {@code this}.
+ *
+ * @param gdal set of handles for invoking <abbr>GDAL</abbr> functions.
+ * @param caller name of the {@code GDALStore} method invoking this method.
+ * @return the parsed <abbr>CRS</abbr>, or {@code null} if none.
+ * @throws DataStoreException if a fatal error occurred according <abbr>GDAL</abbr>.
+ */
+ final CoordinateReferenceSystem parseCRS(final GDAL gdal, final String caller) throws DataStoreException {
+ MemorySegment result = null;
+ try {
+ gdal.errorReset();
+ result = (MemorySegment) gdal.getSpatialRef.invokeExact(handle());
+ } catch (Throwable e) {
+ throw GDAL.propagate(e);
+ }
+ if (gdal.checkCPLErr(this, caller, false)) {
+ final String wkt = GDAL.toString(result);
+ if (wkt != null && !wkt.isBlank()) try {
+ return (CoordinateReferenceSystem) wktFormat().parseObject(wkt);
+ } catch (ParseException | ClassCastException e) {
+ warning(caller, "Cannot parse the CRS of " + getDisplayName(), e);
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns the exception to throw for the given cause.
+ *
+ * @param cause the cause of the error. Cannot be null.
+ * @return the data store exception to throw.
+ */
+ private static DataStoreException cannotExecute(final Exception cause) {
+ return new DataStoreException(cause.getMessage(), cause);
+ }
+
+ /**
+ * Sends a warning to the listeners registered in the {@code GDALStore}.
+ *
+ * @param caller the method to report as the emitted of the warning.
+ * @param message the message.
+ * @param cause the cause of the warning.
+ */
+ final void warning(final String caller, final String message, final Exception cause) {
+ var record = new LogRecord(Level.WARNING, message);
+ record.setThrown(cause);
+ warning(caller, record);
+ }
+
+ /**
+ * Sends a warning to the listeners, or log the warning if there is no listeners.
+ * This method set the logger name, source class and method class on the record.
+ *
+ * @param caller the {@code GDALStore} method to report as the emitter.
+ * @param record the warning to report.
+ */
+ final void warning(final String caller, final LogRecord record) {
+ record.setLoggerName(GDALStoreProvider.LOGGER.getName());
+ record.setSourceClassName(GDALStore.class.getCanonicalName());
+ record.setSourceMethodName(caller);
+ listeners.warning(record);
+ }
+
+ /**
+ * Closes this data store and releases any underlying resources.
+ * A {@link CloseEvent} is sent to listeners before the data store is closed.
+ * Any attempt to use this store after closing will result in {@link DataStoreClosedException}.
+ */
+ @Override
+ public void close() throws DataStoreException {
+ try {
+ listeners.close(); // Should never fail.
+ } finally {
+ synchronized (this) {
+ handle = null;
+ closer.clean();
+ }
+ }
+ }
+}
diff --git a/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/GDALStoreProvider.java b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/GDALStoreProvider.java
new file mode 100644
index 0000000000..ce9e3ce455
--- /dev/null
+++ b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/GDALStoreProvider.java
@@ -0,0 +1,343 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.storage.gdal;
+
+import java.util.List;
+import java.util.Optional;
+import java.util.logging.Logger;
+import java.util.function.Function;
+import java.time.LocalDate;
+import java.lang.ref.Cleaner;
+import java.nio.file.Path;
+import org.opengis.parameter.ParameterDescriptor;
+import org.opengis.parameter.ParameterDescriptorGroup;
+import org.opengis.parameter.ParameterValueGroup;
+import org.apache.sis.storage.Aggregate;
+import org.apache.sis.storage.DataStore;
+import org.apache.sis.storage.DataStoreException;
+import org.apache.sis.storage.DataStoreProvider;
+import org.apache.sis.storage.GridCoverageResource;
+import org.apache.sis.storage.ProbeResult;
+import org.apache.sis.storage.StorageConnector;
+import org.apache.sis.storage.base.StoreMetadata;
+import org.apache.sis.storage.base.Capability;
+import org.apache.sis.storage.base.URIDataStoreProvider;
+import org.apache.sis.storage.panama.LibraryStatus;
+import org.apache.sis.io.stream.InternalOptionKey;
+import org.apache.sis.parameter.ParameterBuilder;
+import org.apache.sis.parameter.Parameters;
+import org.apache.sis.setup.OptionKey;
+import org.apache.sis.util.Version;
+import org.apache.sis.util.collection.TreeTable;
+
+
+/**
+ * The provider of {@code GDALStore} instances.
+ * Given a {@link StorageConnector} input, this class tries to instantiate a {@link GDALStore}.
+ * This data store uses the <abbr>GDAL</abbr> native library for loading data.
+ *
+ * <p>Each {@code GDALStoreProvider} instance is linked to a <abbr>GDAL</abbr> library specified
+ * at construction time, or to a <abbr>JVM</abbr>-wide shared <abbr>GDAL</abbr> library if the
+ * no-argument constructor is used. In the non-shared case, <abbr>GDAL</abbr> will be unloaded
+ * when this {@code GDALStoreProvider} instance is garbage collected.</p>
+ *
+ * @author Quentin Bialota (Geomatys)
+ * @author Martin Desruisseaux (Geomatys)
+ * @version 1.5
+ * @since 1.5
+ */
+@StoreMetadata(formatName = GDALStoreProvider.NAME,
+ capabilities = {Capability.READ},
+ resourceTypes = {Aggregate.class, GridCoverageResource.class},
+ yieldPriority = true) // For trying Java implementations before GDAL.
+public class GDALStoreProvider extends DataStoreProvider {
+ /**
+ * The name of this data store provider.
+ */
+ static final String NAME = "GDAL";
+
+ /**
+ * The logger used by <abbr>GDAL</abbr> stores.
+ *
+ * @see #getLogger()
+ */
+ static final Logger LOGGER = Logger.getLogger("org.apache.sis.storage.gdal");
+
+ /**
+ * Key for declaring <abbr>GDAL</abbr> drivers that may be used for opening the file.
+ * Drivers are identified by their {@linkplain Driver#getIdentifier() short names}.
+ * The drivers will be tested in the order they are specified.
+ *
+ * @see Driver#getIdentifier()
+ */
+ public static final OptionKey<String[]> DRIVERS_OPTION_KEY = new InternalOptionKey<>("DRIVERS", String[].class);
+
+ /**
+ * Parameter for declaring <abbr>GDAL</abbr> drivers that may be used for opening the file.
+ * Drivers are identified by their {@linkplain Driver#getIdentifier() short names}.
+ * The drivers will be tested in the order they are specified.
+ *
+ * @see Driver#getIdentifier()
+ */
+ static final ParameterDescriptor<String[]> DRIVERS_PARAM;
+
+ /**
+ * The parameter descriptor to be returned by {@link #getOpenParameters()}.
+ */
+ private static final ParameterDescriptorGroup OPEN_DESCRIPTOR;
+ static {
+ final var builder = new ParameterBuilder();
+ DRIVERS_PARAM = builder.addName("drivers").setDescription("GDAL drivers that may be used for opening the file.").create(String[].class, null);
+ OPEN_DESCRIPTOR = builder.addName(NAME).createGroup(URIDataStoreProvider.LOCATION_PARAM, DRIVERS_PARAM);
+ }
+
+ /**
+ * Handles to <abbr>GDAL</abbr> native functions, or {@code null} for global.
+ * Can also be reset to {@code null} if <abbr>GDAL</abbr> reported a fatal error.
+ */
+ private GDAL nativeFunctions;
+
+ /**
+ * The status of {@link #nativeFunctions}, or {@code null} if the global set of functions is used.
+ */
+ private LibraryStatus status;
+
+ /**
+ * Actions to execute on garbage-collection of {@link GDALStore} or {@code GDALStoreProvider}.
+ *
+ * @todo Move in a package shared by the rest of Apache SIS.
+ */
+ static final Cleaner CLEANERS = Cleaner.create();
+
+ /**
+ * Creates a new provider which will load the <abbr>GDAL</abbr> library from the default library path.
+ */
+ public GDALStoreProvider() {
+ }
+
+ /**
+ * Creates a new provider which will load the <abbr>GDAL</abbr> library from the specified file.
+ * The library will be unloaded when this provider will be garbage-collected.
+ *
+ * @throws IllegalArgumentException if the GDAL library has not been found.
+ * @throws NoSuchElementException if a <abbr>GDAL</abbr> function has not been found in the library.
+ * @throws IllegalCallerException if this Apache SIS module is not authorized to call native methods.
+ */
+ @SuppressWarnings("this-escape")
+ public GDALStoreProvider(final Path library) {
+ CLEANERS.register(this, nativeFunctions = GDAL.load(library));
+ status = LibraryStatus.LOADED;
+ }
+
+ /**
+ * Returns the set of <abbr>GDAL</abbr> native functions.
+ *
+ * @return the set of native functions.
+ * @throws DataStoreException if the native library is not available.
+ */
+ final synchronized GDAL GDAL() throws DataStoreException {
+ if (status == null) {
+ return GDAL.global(); // Fetch each time (no cache) because may have changed outside this class.
+ }
+ status.report(null); // Should never return if `nativeFunctions` is null.
+ return nativeFunctions;
+ }
+
+ /**
+ * Tries to load <abbr>GDAL</abbr> if not already done, without throwing an exception in case of error.
+ * Instead, the error is logged and {@code null} is returned. This is used for probing.
+ *
+ * @param caller the name of the method which is invoking this method.
+ * @return the set of native functions, or {@code null} if not available.
+ */
+ final synchronized Optional<GDAL> tryGDAL(final String caller) {
+ if (status == null) {
+ return GDAL.tryGlobal(caller);
+ }
+ return Optional.ofNullable(nativeFunctions);
+ }
+
+ /**
+ * Invoked when <abbr>GDAL</abbr> reported a fatal error and tells us that we should not use it anymore.
+ *
+ * @todo Not sure it is effective, because <abbr>GDAL</abbr> documentation of {@code CPLSetErrorHandler}
+ * said that it invokes {@code abort()} on fatal errors. The call to {@code abort()} can be avoided
+ * by a {@code longjmp()}, but it seems unlikely that we can do that.
+ */
+ final synchronized void fatalError() {
+ nativeFunctions = null;
+ status = LibraryStatus.FATAL_ERROR;
+ }
+
+ /**
+ * Returns a generic name for this data store, used mostly in warnings or error messages.
+ *
+ * @return a short name or abbreviation for the data store.
+ */
+ @Override
+ public String getShortName() {
+ return NAME;
+ }
+
+ /**
+ * Returns a value from the <abbr>GDAL</abbr> {@code GDALVersionInfo} function.
+ *
+ * @param <V> type of object to build from the version information.
+ * @param caller the name of the method which is invoking this method.
+ * @param request the desired version information. See {@link GDAL#version(String)} for more information.
+ * @param mapper the function for converting the string to the desired object.
+ * @return the version information computed from the string provided by GDAL.
+ */
+ private <V> Optional<V> version(final String caller, final String request, final Function<String, V> mapper) {
+ return tryGDAL(caller).flatMap((gdal) -> gdal.version(request)).map(mapper);
+ }
+
+ /**
+ * Returns the version number of the <abbr>GDAL</abbr> library.
+ * The returned version contains 4 components. Example: 3.6.3.0.
+ *
+ * @return <abbr>GDAL</abbr> version, or empty if the <abbr>GDAL</abbr> library has not been found.
+ */
+ public Optional<Version> getVersion() {
+ return version("getVersion", "VERSION_NUM", (version) -> {
+ int n = Integer.parseInt(version);
+ final int[] components = new int[4];
+ for (int i=components.length; --i >= 0;) {
+ components[i] = n % 100;
+ n /= 100;
+ }
+ return Version.valueOf(components);
+ });
+ }
+
+ /**
+ * Returns the release date of the <abbr>GDAL</abbr> library.
+ *
+ * @return the release date, or empty if the <abbr>GDAL</abbr> library has not been found.
+ */
+ public Optional<LocalDate> getReleaseDate() {
+ return version("getReleaseDate", "RELEASE_DATE", (version) -> {
+ int year = Integer.parseInt(version);
+ int day = year % 100; year /= 100;
+ int month = year % 100; year /= 100;
+ return LocalDate.of(year, month, day);
+ });
+ }
+
+ /**
+ * Returns an unmodifiable list of all <abbr>GDAL</abbr> drivers currently available.
+ *
+ * @return all <abbr>GDAL</abbr> drivers, or an empty list if the <abbr>GDAL</abbr> library has not been found.
+ */
+ public List<Driver> getDrivers() {
+ return Driver.list(this, tryGDAL("getDrivers").orElse(null));
+ }
+
+ /**
+ * Returns the <abbr>GDAL</abbr> version number together with the list of drivers.
+ * The <abbr>GDAL</abbr> {@linkplain #getVersion() version} is in the root node,
+ * and drivers are listed as children. The table contains the following columns:
+ *
+ * <ol>
+ * <li>{@link TableColumn#NAME} for the value returned by {@link #getName()}.</li>
+ * <li>{@link TableColumn#IDENTIFIER} for the value returned by {@link #getIdentifier()}.</li>
+ * </ol>
+ *
+ * The current version lists only the drivers having raster capability,
+ * because this is the only type of data supported by the current implementation of this module.
+ *
+ * @return a table of available <abbr>GDAL</abbr> drivers.
+ * @throws DataStoreException if an error occurred while querying <abbr>GDAL</abbr> metadata.
+ */
+ public TreeTable configuration() throws DataStoreException {
+ return Driver.configuration(this, tryGDAL("configuration").orElse(null));
+ }
+
+ /**
+ * Returns a description of all parameters accepted by this provider for opening a file with GDAL.
+ *
+ * @return description of available parameters for opening a file with <abbr>GDAL</abbr>.
+ */
+ @Override
+ public ParameterDescriptorGroup getOpenParameters() {
+ return OPEN_DESCRIPTOR;
+ }
+
+ /**
+ * Returns the MIME type if the given storage appears to be supported by this data store.
+ * A {@linkplain ProbeResult#isSupported() supported} status does not guarantee that reading
+ * or writing will succeed, only that there appears to be a reasonable chance according GDAL.
+ *
+ * @param connector information about the storage (URL, stream, <i>etc</i>).
+ * @return a {@linkplain ProbeResult#isSupported() supported} status with the MIME type
+ * if the given storage seems to be readable by {@code GDALStore} instances.
+ * @throws DataStoreException if an I/O error occurred.
+ *
+ * @todo Need to check whether GDAL library has been found.
+ * @todo Need better check. Does GDAL provides a probe API?
+ */
+ @Override
+ public ProbeResult probeContent(final StorageConnector connector) throws DataStoreException {
+ final Path path = connector.getStorageAs(Path.class);
+ if (path != null) {
+ final GDAL gdal = tryGDAL("probeContent").orElse(null);
+ if (gdal != null) {
+ final String mimeType = null; // TODO
+ return new ProbeResult(true, mimeType, null);
+ }
+ }
+ return ProbeResult.UNSUPPORTED_STORAGE;
+ }
+
+ /**
+ * Creates a {@code GDALStore} instance associated with this provider.
+ *
+ * @param connector information about the storage (URL, stream, <i>etc</i>).
+ * @return a data store implementation associated with this provider for the given storage.
+ * @throws DataStoreException if an error occurred while creating the data store instance.
+ */
+ @Override
+ public DataStore open(final StorageConnector connector) throws DataStoreException {
+ return new GDALStore(this, connector);
+ }
+
+ /**
+ * Creates a {@code GDALStore} instance from the given parameters.
+ *
+ * @param parameters opening parameters as defined by {@link #getOpenParameters()}.
+ * @return a data store instance associated with this provider for the given parameters.
+ * @throws DataStoreException if an error occurred while creating the data store instance.
+ */
+ @Override
+ public DataStore open(final ParameterValueGroup parameters) throws DataStoreException {
+ final var p = Parameters.castOrWrap(parameters);
+ final var connector = new StorageConnector(p.getValue(URIDataStoreProvider.LOCATION_PARAM));
+ final String[] drivers = p.getValue(DRIVERS_PARAM);
+ if (drivers != null) {
+ connector.setOption(DRIVERS_OPTION_KEY, drivers);
+ }
+ return open(connector);
+ }
+
+ /**
+ * Returns the logger used by <abbr>GDAL</abbr> stores.
+ */
+ @Override
+ public Logger getLogger() {
+ return LOGGER;
+ }
+}
diff --git a/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/OpenFlag.java b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/OpenFlag.java
new file mode 100644
index 0000000000..35dc78ebb1
--- /dev/null
+++ b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/OpenFlag.java
@@ -0,0 +1,153 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.storage.gdal;
+
+
+/**
+ * <abbr>GDAL</abbr> open options.
+ * This enumeration mirrors the C/C++ {@code GDAL_OF_*} enumeration in the GDAL's API.
+ * The following flags are intentionally omitted:
+ *
+ * <ul>
+ * <li>{@code READONLY}: this is the default when {@link #UPDATE} is not present.</li>
+ * <li>{@code ALL}: this is the default when {@link #VECTOR}, {@link #RASTER},
+ * {@link #MULTIDIM_RASTER} and {@link #NETWORK_MODEL} are not present.</li>
+ * <li>{@code DEFAULT_BLOCK_ACCESS}: this is the default when {@link #ARRAY_BLOCK_ACCESS}
+ * and {@link #HASHSET_BLOCK_ACCESS} are not present.</li>
+ * </ul>
+ *
+ * @author Quentin Bialota (Geomatys)
+ * @author Martin Desruisseaux (Geomatys)
+ */
+enum OpenFlag {
+ /*
+ * DECLARATION ORDER MATTER: we want the ordinal values to be the position of the bit to set.
+ * Note also that READONLY, ALL and DEFAULT_BLOCK_ACCESS are intentionally omitted (see Javadoc).
+ */
+
+ /**
+ * Open in update mode.
+ *
+ * <p>C/C++ source: {@code GDAL_OF_UPDATE = 0x01}.</p>
+ */
+ UPDATE,
+
+ /**
+ * Allow raster drivers to be used.
+ * {@code RASTER} and {@link #MULTIDIM_RASTER} are generally mutually exclusive.
+ * This type is included by default if none of {@link #VECTOR}, {@code RASTER},
+ * {@link #MULTIDIM_RASTER} and {@link #NETWORK_MODEL} is specified.
+ *
+ * <p>C/C++ source: {@code GDAL_OF_RASTER = 0x02}.</p>
+ */
+ RASTER,
+
+ /**
+ * Allow vector drivers to be used.
+ * This type is included by default if none of {@code VECTOR}, {@link #RASTER},
+ * {@link #MULTIDIM_RASTER} and {@link #NETWORK_MODEL} is specified.
+ *
+ * <p>C/C++ source: {@code GDAL_OF_VECTOR = 0x04}.</p>
+ */
+ VECTOR,
+
+ /**
+ * Allow Geographic Network Model (<abbr>GNM</abbr>) drivers to be used.
+ * This type is included by default if none of {@link #VECTOR}, {@link #RASTER},
+ * {@link #MULTIDIM_RASTER} and {@code NETWORK_MODEL} is specified.
+ *
+ * <p>C/C++ source: {@code GDAL_OF_GNM = 0x08}.</p>
+ */
+ NETWORK_MODEL,
+
+ /**
+ * Allow multidimensional raster drivers to be used.
+ * {@link #RASTER} and {@code MULTIDIM_RASTER} are generally mutually exclusive.
+ * This type is <em>not</em> included by default.
+ *
+ * <p>C/C++ source: {@code GDAL_OF_MULTIDIM_RASTER = 0x10}.</p>
+ */
+ MULTIDIM_RASTER,
+
+ /**
+ * Open in shared mode.
+ * If set, it allows the sharing of {@link GDALStore} with other callers that have set {@code SHARED}.
+ * <abbr>GDAL</abbr> will first consult its list of currently open and shared data sets,
+ * and if the description for one exactly matches the filename passed to {@code open}
+ * it will be referenced and returned, if {@code open} is called from the same thread.
+ *
+ * <p>C/C++ source: {@code GDAL_OF_SHARED = 0x20}.</p>
+ */
+ SHARED,
+
+ /**
+ * Emit error message in case of failed open.
+ * If set, a failed attempt to open the file will lead to an error message to be reported.
+ *
+ * <p>C/C++ source: {@code GDAL_OF_VERBOSE_ERROR = 0x40}.</p>
+ */
+ VERBOSE_ERROR,
+
+ /**
+ * Open as internal dataset. Such dataset is not registered in the global list of opened dataset.
+ *
+ * <p>C/C++ source: {@code GDAL_OF_INTERNAL = 0x80}.</p>
+ */
+ INTERNAL,
+
+ /**
+ * Use a array-based storage strategy for cached blocks.
+ *
+ * <p>C/C++ source: {@code GDAL_OF_ARRAY_BLOCK_ACCESS = 0x100}.</p>
+ */
+ ARRAY_BLOCK_ACCESS,
+
+ /**
+ * Use a hashset-based storage strategy for cached blocks.
+ *
+ * <p>C/C++ source: {@code GDAL_OF_HASHSET_BLOCK_ACCESS = 0x200}.</p>
+ */
+ HASHSET_BLOCK_ACCESS;
+
+ /**
+ * The {@code GDALRWFlag.GF_Read} value.
+ * <abbr>GDAL</abbr> intentionally fix this value to an absence of open flags.
+ */
+ static final int READ = 0;
+
+ /**
+ * The {@code GDALRWFlag.GF_Write} value.
+ * <abbr>GDAL</abbr> intentionally fix this value to the {@link #UPDATE} mask.
+ */
+ static final int WRITE = 1;
+
+ /**
+ * Returns the bitmask to give to <abbr>GDAL</abbr> for a given array of open flags.
+ *
+ * @param flags the open flags, or {@code null} if none.
+ * @return the bitmask to give to <abbr>GDAL</abbr>.
+ */
+ static int mask(final OpenFlag[] flags) {
+ int mask = 0;
+ if (flags != null) {
+ for (OpenFlag flag : flags) {
+ mask |= (1 << flag.ordinal());
+ }
+ }
+ return mask;
+ }
+}
diff --git a/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/Opener.java b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/Opener.java
new file mode 100644
index 0000000000..d8cb47ae8a
--- /dev/null
+++ b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/Opener.java
@@ -0,0 +1,179 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.storage.gdal;
+
+import java.util.Set;
+import java.util.Locale;
+import java.net.URI;
+import java.nio.file.Path;
+import java.lang.foreign.Arena;
+import java.lang.foreign.ValueLayout;
+import java.lang.foreign.MemorySegment;
+import org.apache.sis.util.privy.Constants;
+import org.apache.sis.storage.DataStoreException;
+
+
+/**
+ * Opens a <abbr>GDAL</abbr> {@code GDALStore} and provides an action for closing it.
+ * The close action is a safety in case the user does not call {@code close()} explicitly.
+ * In the latter case, the {@code GDALStore} is closed when the {@link GDALStore} is garbage-collected.
+ *
+ * <h2>Constraint</h2>
+ * This class shall not contain any reference to {@link GDALStore}, including indirect references such as
+ * {@link org.apache.sis.storage.event.StoreListeners}. This is required by {@link java.lang.ref.Cleaner}.
+ *
+ * @author Quentin Bialota (Geomatys)
+ * @author Martin Desruisseaux (Geomatys)
+ */
+final class Opener implements Runnable {
+ /**
+ * Schemes of URLs to open with <var>GDAL</var> Virtual File Systems backed by <abbr>CURL</abbr>.
+ */
+ private static final Set<String> VSICURL = Set.of(Constants.HTTP, Constants.HTTPS, "ftp", "ftps");
+
+ /**
+ * Owner of the set of handles that this class will use for invoking <abbr>GDAL</abbr> functions.
+ * Another purpose of this reference is to prevent premature garbage-collection,
+ * because it would unload the <abbr>GDAL</abbr> library.
+ */
+ private final GDALStoreProvider owner;
+
+ /**
+ * Pointer to the <abbr>GDAL</abbr> object in native memory.
+ * This is a {@code GDALDatasetH} in the C/C++ <abbr>API</abbr>.
+ */
+ final MemorySegment handle;
+
+ /**
+ * Creates a new instance for the given file or <abbr>URL</abbr>.
+ * The {@code options} argument is driver-specific, except for the
+ * following values that are supported by all <abbr>GDAL</abbr> drivers:
+ *
+ * <table class="sis">
+ * <caption>Options supported by all <abbr>GDAL</abbr> drivers</caption>
+ * <tr><th>Option</th> <th>Description</th></tr>
+ * <tr><td>{@code OVERVIEW_LEVEL=n}</td> <td>Start the pyramid at the given level where <var>n</var> ≥ 0.</td></tr>
+ * <tr><td>{@code VALIDATE_OPEN_OPTIONS=NO}</td> <td>Do not emit a warning if an option is not recognized.</td></tr>
+ * </table>
+ *
+ * @param owner owner of the set of handles for invoking <abbr>GDAL</abbr> functions.
+ * @param url <abbr>URL</abbr> for <var>GDAL</var> of the data store to open.
+ * @param openFlags open flags to give to <abbr>GDAL</abbr>.
+ * @param allowedDrivers short names (identifiers) of drivers that may be used, or {@code null} for any driver.
+ * @param driverOptions driver-dependent options, or {@code null} if none.
+ * @param siblingFiles names of auxiliary files in the directory of the main file, or {@code null} for automatic.
+ * @throws DataStoreException if <var>GDAL</var> cannot open the data set.
+ */
+ Opener(final GDALStoreProvider owner,
+ final String url,
+ final OpenFlag[] openFlags,
+ final String[] allowedDrivers,
+ final String[] driverOptions,
+ final String[] siblingFiles) throws DataStoreException
+ {
+ this.owner = owner;
+ final GDAL gdal = owner.GDAL();
+ try (var arena = Arena.ofConfined()) {
+ handle = (MemorySegment) gdal.open.invokeExact(
+ arena.allocateFrom(url),
+ OpenFlag.mask(openFlags),
+ allocateStringArray(arena, allowedDrivers),
+ allocateStringArray(arena, driverOptions),
+ allocateStringArray(arena, siblingFiles));
+ } catch (Throwable e) {
+ throw GDAL.propagate(e);
+ }
+ if (GDAL.isNull(handle)) {
+ throw new DataStoreException(); // TODO: get message from GDAL.
+ }
+ }
+
+ /**
+ * Creates a new instance for read operations on the given file or <abbr>URL</abbr>.
+ *
+ * @param owner owner of the set of handles for invoking <abbr>GDAL</abbr> functions.
+ * @param url <abbr>URL</abbr> for <var>GDAL</var> of the data store to open.
+ * @param allowedDrivers short names (identifiers) of drivers that may be used, or {@code null} for any driver.
+ * @throws DataStoreException if <var>GDAL</var> cannot open the data set.
+ */
+ static Opener read(final GDALStoreProvider owner, final String url, final String... allowedDrivers)
+ throws DataStoreException
+ {
+ return new Opener(owner, url, new OpenFlag[] {OpenFlag.RASTER, OpenFlag.SHARED}, allowedDrivers, null, null);
+ }
+
+ /**
+ * Infers a <var>GDAL</var> <abbr>URL</abbr> from the given location and/or path.
+ *
+ * @param location URL to the file to open (mandatory).
+ * @param path URL as a path on the file system, or {@code null} if none.
+ * @return <abbr>URL</abbr> for <var>GDAL</var>.
+ */
+ static String toURL(final URI location, final Path path) {
+ String url;
+ final String scheme = location.getScheme();
+ if (path != null && "file".equalsIgnoreCase(scheme)) {
+ url = path.toString();
+ } else {
+ url = location.toString();
+ if (scheme != null && VSICURL.contains(scheme.toLowerCase(Locale.US))) {
+ url = "/vsicurl/".concat(url);
+ }
+ }
+ return url;
+ }
+
+ /**
+ * Allocates memory for an array of strings.
+ *
+ * @param arena the arena to allocate memory from.
+ * @param values the array of strings to allocate memory for.
+ * @return the array of pointer, or {@link MemorySegment#NULL} if the array is {@code null} or empty.
+ */
+ private static MemorySegment allocateStringArray(final Arena arena, final String[] values) {
+ if (values == null || values.length == 0) {
+ return MemorySegment.NULL;
+ }
+ final MemorySegment array = arena.allocate(ValueLayout.ADDRESS, values.length);
+ for (int i=0; i < values.length; i++) {
+ array.setAtIndex(ValueLayout.ADDRESS, i, arena.allocateFrom(values[i]));
+ }
+ return array;
+ }
+
+ /**
+ * Invoked by {@link java.lang.ref.Cleaner} when the native resource is ready to be closed.
+ * This method shall not be invoked explicitly. The {@code Cleaner} <abbr>API</abbr> ensures
+ * that this method will be invoked exactly once (except maybe on application termination).
+ */
+ @Override
+ public void run() {
+ owner.tryGDAL("close").ifPresent((gdal) -> {
+ final int err;
+ try {
+ // The constructor verified that `close` is non-null.
+ err = (int) gdal.close.invokeExact(handle);
+ } catch (Throwable e) {
+ throw GDAL.propagate(e);
+ }
+ /*
+ * TODO: report the error, maybe in a ThreadLocal. We may need a Threadlocal
+ * anyway if we provide a error handle with CPLSetErrorHandler.
+ */
+ });
+ }
+}
diff --git a/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/Subdataset.java b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/Subdataset.java
new file mode 100644
index 0000000000..842e3d357f
--- /dev/null
+++ b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/Subdataset.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.storage.gdal;
+
+import java.util.List;
+import java.util.Optional;
+import org.apache.sis.storage.DataStoreException;
+import org.opengis.parameter.ParameterValueGroup;
+
+
+/**
+ * A data store which has been identified as a sub-dataset.
+ *
+ * @author Martin Desruisseaux (Geomatys)
+ */
+final class Subdataset extends GDALStore {
+ /**
+ * Creates a new data store as a child of the given store.
+ *
+ * @param parent the parent data store.
+ * @param url <abbr>URL</abbr> for <var>GDAL</var> of the data store to open.
+ * @param driver name of the driver to use.
+ * @throws DataStoreException if an error occurred while creating the data store for the given storage.
+ */
+ Subdataset(final GDALStore parent, final String url, final String driver) throws DataStoreException {
+ super(parent, url, driver);
+ }
+
+ /**
+ * Returns an empty value, as this data store is opened only indirectly.
+ */
+ @Override
+ public Optional<ParameterValueGroup> getOpenParameters() {
+ return Optional.empty();
+ }
+
+ /**
+ * Does nothing. We do not support at this time aggregates of aggregates,
+ * because we do not know if they happen in practice and we want to avoid
+ * the risk of infinite recursion.
+ */
+ @Override
+ List<Subdataset> groupBySubset(final GDAL gdal) {
+ return null;
+ }
+
+ /**
+ * Does nothing since this resource should be closed by the parent store.
+ * If the user does not close the parent store, this store will be closed
+ * by the garbage collector.
+ */
+ @Override
+ public void close() {
+ }
+}
diff --git a/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/SubdatasetList.java b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/SubdatasetList.java
new file mode 100644
index 0000000000..20378a05e0
--- /dev/null
+++ b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/SubdatasetList.java
@@ -0,0 +1,155 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.storage.gdal;
+
+import java.util.List;
+import java.util.AbstractList;
+import java.util.LinkedHashMap;
+import java.util.Locale;
+import org.apache.sis.util.collection.BackingStoreException;
+import org.apache.sis.storage.DataStoreException;
+
+
+/**
+ * A list of sub-datasets where each element is opened when first requested.
+ *
+ * @author Martin Desruisseaux (Geomatys)
+ */
+final class SubdatasetList extends AbstractList<Subdataset> {
+ /**
+ * Index uses in temporary arrays at construction time.
+ */
+ private static final int URL = 0, DESCRIPTION = 1;
+
+ /**
+ * The data store which owns this list.
+ */
+ private final GDALStore parent;
+
+ /**
+ * The <abbr>URL</abbr>s of all elements.
+ */
+ private final String[] urls;
+
+ /**
+ * The description associated to each <abbr>URL</abbr>.
+ * May contain null values.
+ */
+ private final String[] descriptions;
+
+ /**
+ * The elements of this list. Elements are initially null and created when first requested.
+ */
+ private final Subdataset[] components;
+
+ /**
+ * Name of the <abbr>GDAL</abbr> driver to use for opening the sub-datasets.
+ */
+ private final String driver;
+
+ /**
+ * Creates a list of sub-datasets.
+ *
+ * @param gdal set of handles for invoking <abbr>GDAL</abbr> functions.
+ * @param parent the data store which owns this list.
+ * @param metadata the metadata items for the {@code "SUBDATASETS"} domain.
+ */
+ SubdatasetList(final GDAL gdal, final GDALStore parent, final List<String> metadata) throws DataStoreException {
+ this.parent = parent;
+ this.driver = parent.getDriverName(gdal);
+ /*
+ * URLs of all sub-dataset, optionally associated to their descriptions.
+ * Keys are metadata keys. Values at index 0 are the URLs. Values at index 1 are descriptions.
+ */
+ final var subdatasets = new LinkedHashMap<String, String[]>(metadata.size());
+ for (final String item : metadata) {
+ final int splitAt = item.indexOf('=');
+ if (splitAt > 0) {
+ int index = URL;
+ String key = separateKey(item, splitAt, "_NAME");
+ if (key == null) {
+ key = separateKey(item, splitAt, "_DESC");
+ if (key == null) continue;
+ index = DESCRIPTION;
+ }
+ final String value = item.substring(splitAt+1).trim();
+ subdatasets.computeIfAbsent(key, (_) -> new String[2])[index] = value;
+ }
+ }
+ int i = subdatasets.size();
+ urls = new String[i];
+ descriptions = new String[i];
+ components = new Subdataset[i];
+ i = 0;
+ for (final String[] entry : subdatasets.values()) {
+ urls[i] = entry[0];
+ descriptions[i++] = entry[1];
+ }
+ }
+
+ /**
+ * Separates the key from the values if the metadata item key has the given suffix.
+ *
+ * @param item the <abbr>GDAL</abbr> metadata item to parse.
+ * @param splitAt position item the {@code '='} sign.
+ * @param suffix the expected suffix in the metadata key.
+ * @return the item key without its suffix, or {@code null} if not recognized.
+ */
+ private static String separateKey(final String item, int splitAt, final String suffix) {
+ final int length = suffix.length();
+ if (item.regionMatches(true, splitAt -= length, suffix, 0, length)) {
+ return item.substring(0, splitAt).trim().toUpperCase(Locale.US);
+ }
+ return null;
+ }
+
+ /**
+ * Returns the number of elements in this list.
+ */
+ @Override
+ public int size() {
+ return components.length;
+ }
+
+ /**
+ * Returns the element at the given index.
+ * The data set is opened when the element is requested for the first time.
+ */
+ @Override
+ public Subdataset get(final int index) {
+ synchronized (parent) {
+ Subdataset component = components[index];
+ if (component == null) try {
+ final String url = urls[index];
+ component = new Subdataset(parent, url, driver);
+ component.description = descriptions[index];
+ final int splitAt = url.lastIndexOf(':');
+ if (splitAt >= 0) {
+ final String identifier = url.substring(splitAt + 1).trim();
+ if (!identifier.isBlank()) {
+ final var factory = parent.factory;
+ component.namespace = factory.createNameSpace(factory.createLocalName(parent.namespace, identifier), null);
+ }
+ }
+ components[index] = component;
+ } catch (DataStoreException e) {
+ throw new BackingStoreException(e);
+ }
+ return component;
+ }
+ }
+}
diff --git a/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/TiledCoverage.java b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/TiledCoverage.java
new file mode 100644
index 0000000000..db0852de59
--- /dev/null
+++ b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/TiledCoverage.java
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.storage.gdal;
+
+import java.io.IOException;
+import java.awt.Rectangle;
+import java.awt.image.Raster;
+import java.awt.image.WritableRaster;
+import org.opengis.util.GenericName;
+import org.apache.sis.storage.DataStoreException;
+import org.apache.sis.storage.base.TiledGridCoverage;
+import org.apache.sis.storage.base.TiledGridResource;
+
+
+/**
+ * Coverage read from {@code TiledResource}.
+ *
+ * @author Martin Desruisseaux (Geomatys)
+ */
+final class TiledCoverage extends TiledGridCoverage {
+ /**
+ * The resource from which this coverage has been read.
+ */
+ private final TiledResource owner;
+
+ /**
+ * Creates a new tiled grid coverage.
+ *
+ * @param owner the resource from which this coverage has been read.
+ * @param subset description of the {@link TiledGridResource} subset to cover.
+ */
+ TiledCoverage(final TiledResource owner, final TiledGridResource.Subset subset) {
+ super(subset);
+ this.owner = owner;
+ }
+
+ /**
+ * Returns a unique name that identifies this coverage.
+ * The name shall be unique in the {@code TileMatrixSet}.
+ */
+ @Override
+ protected GenericName getIdentifier() {
+ return owner.getIdentifier().orElse(null);
+ }
+
+ /**
+ * Returns all tiles in the given area of interest. Tile indices (0,0) locates the tile in the upper-left corner
+ * of this {@code TiledGridCoverage} (not necessarily the upper-left corner of the {@link TiledGridResource}).
+ * The {@link Raster#getMinX()} and {@code getMinY()} coordinates of returned rasters
+ * shall start at the given {@code iterator.offsetAOI} values.
+ *
+ * @param iterator an iterator over the tiles that intersect the Area Of Interest specified by user.
+ * @return tiles decoded from the {@link TiledGridResource}.
+ */
+ @Override
+ protected Raster[] readTiles(final AOI iterator) throws IOException, DataStoreException {
+ synchronized (owner.getSynchronizationLock()) {
+ final var result = new Raster[iterator.tileCountInQuery];
+ do {
+ final WritableRaster tile = iterator.createRaster();
+ final Rectangle bounds = tile.getBounds();
+ toFullResolution(bounds);
+ owner.transfer(OpenFlag.READ, bounds, tile, includedBands);
+ result[iterator.getIndexInResultArray()] = tile;
+ } while (iterator.next());
+ return result;
+ }
+ }
+
+ /**
+ * Transfers (reads or writes) sample values between <abbr>GDAL</abbr> raster and Java2D raster for all bands.
+ * The full area of the Java2D raster is transferred. It may corresponds to a sub-area of the GDAL raster.
+ *
+ * <h4>Prerequisites</h4>
+ * <ul>
+ * <li>The Java2D raster shall use a {@link java.awt.image.ComponentSampleModel}.</li>
+ * <li>In read mode, the given raster shall be an instance of {@link WritableRaster}.</li>
+ * </ul>
+ *
+ * @param gdal set of handles for invoking <abbr>GDAL</abbr> functions.
+ * @param rwFlag {@link OpenFlag#READ} or {@link OpenFlag#WRITE}.
+ * @param aoi region of the image to read or write. (0,0) is the upper-left pixel.
+ * @param raster the Java2D raster where to store of fetch the values to read or write.
+ * @throws ClassCastException if a prerequisite about expected classes is not true.
+ * @throws DataStoreException if <var>GDAL</var> reported a warning or fatal error.
+ */
+ private void transfer(final GDAL gdal, final int rwFlag, final Rectangle aoi, final Raster raster)
+ throws DataStoreException
+ {
+
+ }
+}
diff --git a/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/TiledResource.java b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/TiledResource.java
new file mode 100644
index 0000000000..5c3a576b84
--- /dev/null
+++ b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/TiledResource.java
@@ -0,0 +1,491 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.storage.gdal;
+
+import java.util.Map;
+import java.util.List;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.Optional;
+import java.awt.Dimension;
+import java.awt.Rectangle;
+import java.awt.image.ColorModel;
+import java.awt.image.SampleModel;
+import java.awt.image.BandedSampleModel;
+import java.awt.image.Raster;
+import java.lang.foreign.Arena;
+import java.lang.foreign.ValueLayout;
+import java.lang.foreign.MemorySegment;
+import org.opengis.util.GenericName;
+import org.opengis.referencing.crs.CoordinateReferenceSystem;
+import org.apache.sis.referencing.privy.AffineTransform2D;
+import org.apache.sis.coverage.SampleDimension;
+import org.apache.sis.coverage.grid.GridExtent;
+import org.apache.sis.coverage.grid.GridGeometry;
+import org.apache.sis.coverage.grid.GridCoverage;
+import org.apache.sis.coverage.grid.PixelInCell;
+import org.apache.sis.coverage.privy.ImageLayout;
+import org.apache.sis.coverage.privy.ColorModelFactory;
+import org.apache.sis.storage.DataStoreException;
+import org.apache.sis.storage.DataStoreReferencingException;
+import org.apache.sis.storage.base.TiledGridResource;
+import org.apache.sis.util.resources.Vocabulary;
+import org.apache.sis.util.ArraysExt;
+
+
+/**
+ * A {@code DataSet} which has been identified to be a raster.
+ * This class is named {@code Raster} in <abbr>GDAL</abbr>, but we avoid that
+ * name here for avoiding confusion with Java2D {@link java.awt.image.Raster}.
+ *
+ * @author Johann Sorel (Geomatys)
+ * @author Quentin Bialota (Geomatys)
+ * @author Martin Desruisseaux (Geomatys)
+ */
+final class TiledResource extends TiledGridResource {
+ /**
+ * The data set that contains this raster.
+ */
+ final GDALStore parent;
+
+ /**
+ * The identifier of this resource, or {@code null} if none.
+ *
+ * @see #getIdentifier()
+ */
+ private final GenericName identifier;
+
+ /**
+ * The grid geometry of the raster, or {@code null} if not yet computed.
+ */
+ private GridGeometry geometry;
+
+ /**
+ * The image size in pixels.
+ */
+ private final int width, height;
+
+ /**
+ * The tile size in pixels.
+ *
+ * @see #getTileSize()
+ */
+ private final int tileWidth, tileHeight;
+
+ /**
+ * The pixel data type. It shall be the same for all bands in this raster.
+ */
+ final DataType dataType;
+
+ /**
+ * Description of all bands.
+ * Those objects should never escape {@code TiledResource} in order to avoid the risk
+ * that {@code GDALRasterBandH} exist after {@link #parent} has been garbage collected.
+ */
+ private final Band[] bands;
+
+ /**
+ * The sample dimensions, created when first requested.
+ */
+ private List<SampleDimension> sampleDimensions;
+
+ /**
+ * The color model, created when first requested.
+ *
+ * @see #getColorModel()
+ */
+ private ColorModel colorModel;
+
+ /**
+ * The sample model, created when first requested.
+ * Its size is the tile size with no sub-sampling.
+ *
+ * @see #getSampleModel()
+ */
+ private SampleModel sampleModel;
+
+ /**
+ * The fill value, fetched when first requested.
+ *
+ * @see #getFillValue()
+ */
+ private Number fillValue;
+
+ /**
+ * Creates a new instance as a child of the given data set.
+ *
+ * @param parent the parent data set.
+ * @param size the raster width, height and data type.
+ * @param bands description of all bands as an array of {@link Band}.
+ * @param name an identifier for this band.
+ */
+ private TiledResource(final GDALStore parent, final SizeAndType size, final List<Band> bands, final CharSequence name)
+ throws DataStoreException
+ {
+ super(parent);
+ @SuppressWarnings("LocalVariableHidesMemberVariable")
+ GenericName identifier = parent.factory.createLocalName(parent.namespace, name);
+ final GenericName scope = parent.getIdentifier().orElse(null);
+ if (scope != null) {
+ identifier = identifier.push(scope);
+ }
+ final Dimension t = size.tileSize();
+ this.tileWidth = t.width;
+ this.tileHeight = t.height;
+ this.parent = parent;
+ this.identifier = identifier;
+ this.width = size.width();
+ this.height = size.height();
+ this.dataType = DataType.valueOf(size.type());
+ this.bands = bands.toArray(Band[]::new);
+ }
+
+ /**
+ * The raster width, height and data type. This is a short-lived object used only
+ * at construction time, for grouping compatible bands in the same rasters.
+ */
+ private record SizeAndType(int width, int height, int type, int tileWidth, int tileHeight) {
+ /**
+ * Returns the suggested tile size. This is the block size given by <abbr>GDAL</abbr>,
+ * unless that size is the image's width and a height of 1. The latter is GDAL default
+ * when the file format is not tiled. But that default can consume a lot of memory.
+ */
+ Dimension tileSize() {
+ if (tileWidth < width || tileHeight > 1) {
+ return new Dimension(tileWidth, tileHeight);
+ } else {
+ return ImageLayout.DEFAULT.suggestTileSize(width, height, true);
+ }
+ }
+ }
+
+ /**
+ * Returns rasters where each instance have bands of the same size and data type.
+ * The raster having the same size as the {@code GDALDataset} is first.
+ * Rasters having a different size may be lower-resolution images.
+ *
+ * @param caller name of the method invoking this method.
+ * @return pointers to the band ({@code GDALRasterBandH}).
+ * @throws DataStoreException if an error occurred.
+ */
+ static TiledResource[] groupBySizeAndType(final GDALStore parent, final GDAL gdal, final MemorySegment dataset)
+ throws DataStoreException
+ {
+ final var bands = new LinkedHashMap<SizeAndType, ArrayList<Band>>();
+ final int mainWidth, mainHeight;
+ try (Arena arena = Arena.ofConfined()) {
+ final MemorySegment pnXSize = arena.allocate(ValueLayout.JAVA_INT, 2);
+ final MemorySegment pnYSize = pnXSize.asSlice(Integer.BYTES);
+ gdal.errorReset();
+ final int count = (int) gdal.getRasterCount.invokeExact(dataset);
+ for (int i=0; i<count; i++) {
+ final var band = (MemorySegment) gdal.getRasterBand.invokeExact(dataset, i+1);
+ if (GDAL.isNull(band)) continue; // Paranoiac check (should not happen).
+ /*
+ * The following properties may differ in each band and define a `SizeAndType` key.
+ * Those keys and their associated bands are stored in the order they are found.
+ */
+ final int width = (int) gdal.getRasterBandXSize.invokeExact(band);
+ final int height = (int) gdal.getRasterBandYSize.invokeExact(band);
+ final int type = (int) gdal.getRasterDataType .invokeExact(band);
+ gdal.getBlockSize.invokeExact(band, pnXSize, pnYSize);
+ int tileWidth = pnXSize.get(ValueLayout.JAVA_INT, 0);
+ int tileHeight = pnYSize.get(ValueLayout.JAVA_INT, 0);
+ var key = new SizeAndType(width, height, type, tileWidth, tileHeight);
+ bands.computeIfAbsent(key, (_) -> new ArrayList<Band>()).add(new Band(band));
+ }
+ mainWidth = (int) gdal.getRasterXSize.invokeExact(dataset);
+ mainHeight = (int) gdal.getRasterYSize.invokeExact(dataset);
+ } catch (Throwable e) {
+ throw GDAL.propagate(e);
+ }
+ /*
+ * Replaces all list of bands by a single raster instance.
+ * Then, makes sure that the raster having the size of the dataset is first.
+ */
+ final var rasters = new TiledResource[bands.size()];
+ int count = 0;
+ for (Map.Entry<SizeAndType, ArrayList<Band>> entry : bands.entrySet()) {
+ var name = Vocabulary.formatInternational(Vocabulary.Keys.Image_1, count + 1);
+ rasters[count++] = new TiledResource(parent, entry.getKey(), entry.getValue(), name);
+ }
+ for (int i=0; i<count; i++) {
+ final TiledResource main = rasters[i];
+ if (main.width == mainWidth && main.height == mainHeight) {
+ System.arraycopy(rasters, 0, rasters, 1, i);
+ rasters[0] = main;
+ break;
+ }
+ }
+ return ArraysExt.resize(rasters, count);
+ }
+
+ /**
+ * Returns the object on which to perform synchronizations for thread-safety.
+ * We need a single lock per <abbr>GDAL</abbr> {@code GDALStore} for all operations.
+ */
+ @Override
+ protected final Object getSynchronizationLock() {
+ return parent;
+ }
+
+ /**
+ * Returns the resource persistent identifier.
+ * This identifier can be used to uniquely identify a raster in the containing {@link GDALStore}.
+ *
+ * @return a persistent identifier unique within the data set.
+ */
+ @Override
+ public final Optional<GenericName> getIdentifier() {
+ return Optional.ofNullable(identifier);
+ }
+
+ /**
+ * Returns the extent of grid coordinates together with the conversion to real world coordinates.
+ *
+ * @throws DataStoreException if an error occurred during the construction of the grid geometry.
+ */
+ @Override
+ public GridGeometry getGridGeometry() throws DataStoreException {
+ synchronized (getSynchronizationLock()) {
+ if (geometry == null) {
+ final MemorySegment handle = parent.handle(); // Handle to the GDAL dataset.
+ final GDAL gdal = parent.getProvider().GDAL();
+ final CoordinateReferenceSystem crs = parent.parseCRS(gdal, "getGridGeometry");
+ /*
+ * Note that the CRS may be null. Now get the "grid to CRS" transform,
+ * which may also be null if GDAL reported an error. We do not use the
+ * GDAL default, which is the identity transform. Instead, we keep the
+ * information that the transform is missing (null).
+ */
+ AffineTransform2D gridToCRS = null;
+ try (final Arena arena = Arena.ofConfined()) {
+ final var layout = ValueLayout.JAVA_DOUBLE;
+ final MemorySegment m = arena.allocate(layout, 6);
+ int err;
+ try {
+ err = (int) gdal.getGeoTransform.invokeExact(handle, m);
+ } catch (Throwable e) {
+ throw GDAL.propagate(e);
+ }
+ if (gdal.checkCPLErr(parent, "getGridGeometry", false, err)) {
+ gridToCRS = new AffineTransform2D(
+ m.get(layout, Double.BYTES * 1),
+ m.get(layout, Double.BYTES * 4),
+ m.get(layout, Double.BYTES * 2),
+ m.get(layout, Double.BYTES * 5),
+ m.get(layout, Double.BYTES * 0),
+ m.get(layout, Double.BYTES * 3));
+ }
+ }
+ var extent = new GridExtent(Integer.toUnsignedLong(width),
+ Integer.toUnsignedLong(height));
+ /*
+ * According GDAL documentation, the upper left corner of the upper left pixel
+ * is at position (m[0], m[3]). Therefore, we have a "cell corner" convention.
+ */
+ try {
+ geometry = new GridGeometry(extent, PixelInCell.CELL_CORNER, gridToCRS, crs);
+ } catch (NullPointerException | IllegalArgumentException e) {
+ throw new DataStoreReferencingException(e);
+ }
+ }
+ return geometry;
+ }
+ }
+
+ /**
+ * Returns the ranges of sample values together with the conversion from samples to real values.
+ *
+ * @throws DataStoreException if an error occurred during the construction of sample dimensions.
+ */
+ @Override
+ @SuppressWarnings("ReturnOfCollectionOrArrayField") // Because unmodifable.
+ public List<SampleDimension> getSampleDimensions() throws DataStoreException {
+ synchronized (getSynchronizationLock()) {
+ if (sampleDimensions == null) {
+ final GDAL gdal = parent.getProvider().GDAL();
+ final var sd = new SampleDimension[bands.length];
+ try (Arena arena = Arena.ofConfined()) {
+ final MemorySegment flag = arena.allocate(ValueLayout.JAVA_INT);
+ for (int i=0; i<sd.length; i++) {
+ sd[i] = bands[i].createSampleDimension(parent, gdal, flag);
+ }
+ }
+ sampleDimensions = List.of(sd);
+ }
+ return sampleDimensions;
+ }
+ }
+
+ /**
+ * Creates the color model and sample model.
+ */
+ private void createColorAndSampleModel() throws DataStoreException {
+ final GDAL gdal = parent.getProvider().GDAL();
+ int[] palette = null;
+ int paletteIndex = 0;
+ int alpha = -1, red = -1, green = -1, blue = -1, gray = -1;
+ for (int i=0; i < bands.length; i++) {
+ final Band band = bands[i];
+ switch (band.getColorInterpretation(gdal)) {
+ case ALPHA: if (alpha < 0) alpha = i; break;
+ case RED: if (red < 0) red = i; break;
+ case GREEN: if (green < 0) green = i; break;
+ case BLUE: if (blue < 0) blue = i; break;
+ case GRAYSCALE: if (gray < 0) gray = i; break;
+ case PALETTE: {
+ if (palette == null) {
+ paletteIndex = i;
+ palette = band.getARGB(gdal);
+ }
+ break;
+ }
+ }
+ /*
+ * TODO: check if all bands have the same `colorSpaceType`. Use that information for creating a
+ * generic color space (potentially just rendering gray scale with the average value of all bands)
+ * which can return that type in the `getType()` method. Note that there is generic color space types
+ * for all number of bands from 2 to 15.
+ */
+ }
+ int visibleBand = -1;
+ if ((red | green | blue) >= 0) {
+ visibleBand = Math.min(Math.min(red, green), blue);
+ colorModel = ColorModelFactory.createRGB(dataType.numBits, false, alpha >= 0);
+ // TODO: needs custom color model if too many bands, or if order is not (A)RGB.
+ } else if (palette != null) {
+ visibleBand = paletteIndex;
+ colorModel = ColorModelFactory.createIndexColorModel(bands.length, visibleBand, palette, true, -1);
+ } else {
+ visibleBand = Math.max(gray, 0);
+ final Band band = bands[visibleBand];
+ final double min = band.getValue(gdal.getRasterMinimum, MemorySegment.NULL);
+ final double max = band.getValue(gdal.getRasterMaximum, MemorySegment.NULL);
+ colorModel = ColorModelFactory.createGrayScale(dataType.imageType, bands.length, visibleBand, min, max);
+ }
+ sampleModel = new BandedSampleModel(dataType.imageType, width, height, bands.length);
+ /*
+ * Also compute the fill value here because the current method needs the visible band.
+ * TODO: we should compute the fill value for all bands instead, and move this code to
+ * the `getFillValue()` method.
+ */
+ try (final Arena arena = Arena.ofConfined()) {
+ final MemorySegment flag = arena.allocate(ValueLayout.JAVA_INT);
+ final double value = bands[visibleBand].getValue(gdal.getRasterNoDataValue, flag);
+ if (value != 0 && Band.isTrue(flag)) {
+ fillValue = value;
+ }
+ }
+ }
+
+ /**
+ * Returns the Java2D color model for rendering images.
+ */
+ @Override
+ protected ColorModel getColorModel() throws DataStoreException {
+ synchronized (getSynchronizationLock()) {
+ if (colorModel == null) {
+ createColorAndSampleModel();
+ }
+ return colorModel;
+ }
+ }
+
+ /**
+ * Returns the sample model for tiles at full resolution with all their bands.
+ * The raster size is the {@linkplain #getTileSize() tile size} as stored in the resource.
+ */
+ @Override
+ protected SampleModel getSampleModel() throws DataStoreException {
+ synchronized (getSynchronizationLock()) {
+ if (sampleModel == null) {
+ createColorAndSampleModel();
+ }
+ return sampleModel;
+ }
+ }
+
+ /**
+ * Returns the value to use for filling empty spaces in rasters,
+ * or {@code null} if none, not different than zero or not valid for the target data type.
+ * The zero value is excluded because tiles are already initialized to zero by default.
+ */
+ @Override
+ protected Number getFillValue() throws DataStoreException {
+ synchronized (getSynchronizationLock()) {
+ if (fillValue == null) {
+ createColorAndSampleModel();
+ }
+ return fillValue;
+ }
+ }
+
+ /**
+ * Returns the size of tiles (in pixels) in this resource.
+ * The length of the returned array is the number of dimensions.
+ */
+ @Override
+ protected final int[] getTileSize() {
+ return new int[] {tileWidth, tileHeight};
+ }
+
+ /**
+ * Transfers (reads or writes) sample values between <abbr>GDAL</abbr> raster and Java2D raster.
+ * The full area of the Java2D raster is transferred. It may corresponds to a sub-area of the GDAL raster.
+ *
+ * <h4>Prerequisites</h4>
+ * <ul>
+ * <li>The Java2D raster shall use a {@link ComponentSampleModel}.</li>
+ * <li>In read mode, the given raster shall be an instance of {@link WritableRaster}.</li>
+ * </ul>
+ *
+ * @param rwFlag {@link OpenFlag#READ} or {@link OpenFlag#WRITE}.
+ * @param aoi region of the image to read or write. (0,0) is the upper-left pixel.
+ * @param raster the Java2D raster where to store of fetch the values to read or write.
+ * @param bandIndices bands of sample values in the Java2D raster, or {@code null} for all.
+ * @throws ClassCastException if an above-documented prerequisite is not true.
+ * @throws DataStoreException if <var>GDAL</var> reported a warning or fatal error.
+ */
+ final void transfer(final int rwFlag, final Rectangle aoi, final Raster raster, final int[] bandIndices)
+ throws DataStoreException
+ {
+ final GDAL gdal = parent.getProvider().GDAL();
+ final int n = (bandIndices != null) ? bandIndices.length : bands.length;
+ for (int i=0; i<n; i++) {
+ final Band band = bands[(bandIndices != null) ? bandIndices[i] : i];
+ band.transfer(gdal, rwFlag, this, aoi, raster, i);
+ }
+ }
+
+ /**
+ * Loads a subset of the grid coverage represented by this resource.
+ * The actual loading may be deferred until a tile is requested for the first time.
+ *
+ * @param domain desired grid extent and resolution, or {@code null} for reading the whole domain.
+ * @param ranges 0-based indices of sample dimensions to read, or {@code null} or an empty sequence for reading them all.
+ * @return the grid coverage for the specified domain and ranges.
+ */
+ @Override
+ public GridCoverage read(final GridGeometry domain, final int... ranges) throws DataStoreException {
+ synchronized (getSynchronizationLock()) {
+ final var subset = new Subset(domain, ranges);
+ final var result = new TiledCoverage(this, subset);
+ return preload(result);
+ }
+ }
+}
diff --git a/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/package-info.java b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/package-info.java
new file mode 100644
index 0000000000..d756cee2e3
--- /dev/null
+++ b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/gdal/package-info.java
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Bridge to the <abbr>GDAL</abbr> library for reading rasters.
+ * This package assumes that <abbr>GDAL</abbr> is preinstalled.
+ * The <abbr>GDAL</abbr> C/C++ functions are invoked by using the {@link java.lang.foreign} package.
+ * Running this package requires user's authorization to perform native accesses.
+ * See the module Javadoc for more information.
+ *
+ * <p>Having this module on the module-path is sufficient for allowing Apache <abbr>SIS</abbr> to
+ * try <abbr>GDAL</abbr> when {@link org.apache.sis.storage.DataStores#open(Object)} is invoked.
+ * Pure Java implementations are tried first, and <abbr>GDAL</abbr> is tried as a fallback when
+ * no Java implementation can decode a file. When first needed, this module searches on the
+ * library path for a {@code gdal.dll} file on Windows or a {@code libgdal.so} file on Unix.
+ * If a different <abbr>GDAL</abbr> library is desired, it can be specified explicitly
+ * to the {@link org.apache.sis.storage.gdal.GDALStoreProvider} constructor.</p>
+ *
+ * <p>The current implementation can read rasters.
+ * Write operations and support of vector data will be provided in a future version.</p>
+ *
+ * @author Quentin Bialota (Geomatys)
+ * @author Martin Desruisseaux (Geomatys)
+ * @version 1.5
+ * @since 1.5
+ */
+package org.apache.sis.storage.gdal;
diff --git a/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/panama/LibraryLoader.java b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/panama/LibraryLoader.java
new file mode 100644
index 0000000000..f6634777d1
--- /dev/null
+++ b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/panama/LibraryLoader.java
@@ -0,0 +1,221 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.storage.panama;
+
+import java.io.File;
+import java.nio.file.Path;
+import java.util.Optional;
+import java.util.NoSuchElementException;
+import java.util.logging.Level;
+import java.util.logging.LogRecord;
+import java.util.function.Function;
+import java.lang.foreign.Arena;
+import java.lang.foreign.SymbolLookup;
+import org.apache.sis.storage.DataStoreException;
+import org.apache.sis.util.Exceptions;
+
+
+/**
+ * A helper class for loading a native library.
+ * This object exists only for the duration of {@link NativeFunctions} construction.
+ *
+ * @param <F> the class of {@code NativeFunctions} to construct using this loader.
+ *
+ * @author Martin Desruisseaux (Geomatys)
+ */
+public final class LibraryLoader<F extends NativeFunctions> {
+ /**
+ * Value to assign to {@link NativeFunctions#libraryName}.
+ */
+ String filename;
+
+ /**
+ * Value to assign to {@link NativeFunctions#arena}.
+ */
+ Arena arena;
+
+ /**
+ * Value to assign to {@link NativeFunctions#symbols}.
+ */
+ SymbolLookup symbols;
+
+ /**
+ * The constructor to call for building a {@code NativeFunctions}.
+ * This is reset to {@code null} after usage as a way to ensure
+ * that each {@code LibraryLoader} instance is used only once.
+ */
+ private Function<LibraryLoader<F>, F> creator;
+
+ /**
+ * Whether the library has been found.
+ *
+ * @see #status()
+ */
+ private LibraryStatus status;
+
+ /**
+ * Cause of failure to load the library, or {@code null} if none.
+ */
+ private RuntimeException error;
+
+ /**
+ * Creates a new instance.
+ *
+ * @param creator the constructor to call for building a {@code NativeFunctions}.
+ */
+ public LibraryLoader(final Function<LibraryLoader<F>, F> creator) {
+ this.creator = creator;
+ }
+
+ /**
+ * Loads the native library from the given file.
+ * Callers should register the returned instance in a {@link java.lang.ref.Cleaner}.
+ *
+ * @param library the library to load.
+ * @return handles to native functions needed by the data store.
+ * @throws IllegalArgumentException if the native library has not been found.
+ * @throws IllegalCallerException if this Apache SIS module is not authorized to call native methods.
+ */
+ @SuppressWarnings("restricted")
+ public F load(final Path library) {
+ final var c = creator;
+ creator = null;
+ filename = library.getFileName().toString();
+ status = LibraryStatus.LIBRARY_NOT_FOUND; // In case an exception occurs before completion.
+ arena = Arena.ofShared();
+ final F instance;
+ try {
+ symbols = SymbolLookup.libraryLookup(library, arena);
+ status = LibraryStatus.FUNCTION_NOT_FOUND; // Update the status to report if we cannot complete.
+ instance = c.apply(this);
+ status = LibraryStatus.LOADED;
+ } catch (Throwable e) {
+ arena.close();
+ throw e;
+ }
+ return instance;
+ }
+
+ /**
+ * Searches the native library in the default library path. If the native library is not found on the library path,
+ * defaults to {@link SymbolLookup#loaderLookup()} for allowing users to invoke {@link System#loadLibrary(String)}
+ * as a fallback. The method handlers created with this instance are valid for the Java Virtual Machine lifetime,
+ * i.e. they will be associated to the {@linkplain Arena#global() global arena}.
+ *
+ * <p><em>It is caller's responsibility to ensure that this method is invoked at most once per library.</em>
+ * Invoking this method many times for the same library may cause unpredictable behavior.</p>
+ *
+ * <h4>Error handling</h4>
+ * Contrarily to {@link #load(Path)}, this method does not throw exception. Callers should invoke
+ * {@link #validate()} or {@link #getError(String)} after this method call,
+ * depending on whether an error should be fatal or not.
+ *
+ * @param library base filename (without the {@code "lib"} prefix and {@code ".so"} or
+ * {@code ".dll"} suffix) of the native library to load.
+ * @return handles to native functions needed by the data store.
+ */
+ @SuppressWarnings("restricted")
+ public F global(final String library) {
+ final var c = creator;
+ creator = null;
+ filename = (File.separatorChar == '\\') ? (library + ".dll") : ("lib" + library + ".so");
+ status = LibraryStatus.LIBRARY_NOT_FOUND; // Default value if an exception occurs below.
+ F instance = null;
+create: try {
+ try {
+ symbols = SymbolLookup.libraryLookup(filename, Arena.global());
+ } catch (IllegalArgumentException e) {
+ error = e;
+ filename = "system";
+ symbols = SymbolLookup.loaderLookup(); // In case user called `System.loadLibrary(…)`.
+ }
+ try {
+ instance = c.apply(this);
+ status = LibraryStatus.LOADED;
+ } catch (RuntimeException e) {
+ if (error != null) {
+ error.addSuppressed(e);
+ } else {
+ error = e;
+ }
+ break create;
+ }
+ /*
+ * Note: registering a shutdown hook cause a reference to be kept for the JVM lifetime.
+ * But such reference should exist anyway because this `global(String)` method should
+ * be invoked for initialization of a static variable. Furthermore, subclass may need
+ * to do a last native method class for flushing some cache.
+ *
+ * TODO: unregister if the library had a fatal error and should not be used anymore.
+ */
+ Runtime.getRuntime().addShutdownHook(new Thread(instance));
+ } catch (IllegalCallerException e) {
+ error = e;
+ status = LibraryStatus.UNAUTHORIZED;
+ } catch (NoSuchElementException e) {
+ error = e;
+ status = LibraryStatus.FUNCTION_NOT_FOUND;
+ }
+ return instance;
+ }
+
+ /**
+ * Returns the status after a call to {@code load(…)} or {@code global(…)}.
+ * This method can be invoked in a pattern like below, in order to remember
+ * that the loading failed:
+ *
+ * {@snippet lang="java" :
+ * LibraryLoader<?> loader = ...;
+ * try {
+ * loader.global("foo");
+ * } finally {
+ * globalStatus = loader.status();
+ * }
+ * }
+ *
+ * @return the status of the native library.
+ */
+ public final LibraryStatus status() {
+ return status;
+ }
+
+ /**
+ * Throws an exception if the loading of the native library failed.
+ *
+ * @throws DataStoreException if the native library has not been found
+ * or if SIS is not allowed to call native functions.
+ */
+ public void validate() throws DataStoreException {
+ status.report(error);
+ }
+
+ /**
+ * Returns the error as a log message.
+ *
+ * @param name the library name.
+ * @return a log message describing the error, or {@code null} if the operation was successful.
+ */
+ public Optional<LogRecord> getError(final String name) {
+ if (error == null) {
+ return Optional.empty();
+ }
+ String msg = "Cannot initialize the " + name + " library.";
+ var record = new LogRecord(Level.CONFIG, Exceptions.formatChainedMessages(null, msg, error));
+ record.setThrown(error);
+ return Optional.of(record);
+ }
+}
diff --git a/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/panama/LibraryStatus.java b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/panama/LibraryStatus.java
new file mode 100644
index 0000000000..8ac1c46fe6
--- /dev/null
+++ b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/panama/LibraryStatus.java
@@ -0,0 +1,84 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.storage.panama;
+
+import org.apache.sis.storage.DataStoreClosedException;
+
+
+/**
+ * Status of the native library.
+ *
+ * @author Martin Desruisseaux (Geomatys)
+ *
+ * @todo If moved to a shared module, replace all "GDAL" strings.
+ */
+public enum LibraryStatus {
+ /**
+ * The native library is ready for use.
+ */
+ LOADED(null),
+
+ /**
+ * The native library has been unloaded.
+ */
+ UNLOADED("GDAL has been unloaded."),
+
+ /**
+ * The native library has not been found.
+ */
+ LIBRARY_NOT_FOUND("The GDAL library has not been found."),
+
+ /**
+ * The native library was found, but not symbol that we searched.
+ */
+ FUNCTION_NOT_FOUND("A GDAL function has not been found."),
+
+ /**
+ * <abbr>SIS</abbr> is not authorized to perform native function calls.
+ */
+ UNAUTHORIZED("Apache SIS is not authorized to call native functions."),
+
+ /**
+ * A fatal error occurred in the native library and that library should not be used anymore.
+ */
+ FATAL_ERROR("A fatal error occurred and GDAL should not be used anymore in this JVM.");
+
+ /**
+ * An explanatory message, or {@code null} if none.
+ */
+ private final String message;
+
+ /**
+ * Creates a new enumeration value.
+ */
+ private LibraryStatus(final String message) {
+ this.message = message;
+ }
+
+ /**
+ * Throws an exception if the native library is not available.
+ *
+ * @param cause the cause of the error, or {@code null} if none.
+ * @throws DataStoreClosedException if this enumeration value is not {@link #LOADED}
+ * or if the given cause is not null.
+ */
+ public void report(Exception cause) throws DataStoreClosedException {
+ if (message != null || cause != null) {
+ throw new DataStoreClosedException(message, cause);
+ }
+ }
+}
diff --git a/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/panama/NativeFunctions.java b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/panama/NativeFunctions.java
new file mode 100644
index 0000000000..0f8209980b
--- /dev/null
+++ b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/panama/NativeFunctions.java
@@ -0,0 +1,201 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.storage.panama;
+
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.lang.foreign.Arena;
+import java.lang.foreign.Linker;
+import java.lang.foreign.SymbolLookup;
+import java.lang.foreign.FunctionDescriptor;
+import java.lang.foreign.MemorySegment;
+import java.lang.foreign.ValueLayout;
+import java.lang.invoke.MethodHandle;
+import java.lang.reflect.UndeclaredThrowableException;
+
+
+/**
+ * Base class for sets of method handles to native functions.
+ * The native library can be unloaded by invoking {@link #run()}.
+ * This instance can be registered in a shutdown hook or a {@link java.lang.ref.Cleaner}.
+ *
+ * @author Martin Desruisseaux (Geomatys)
+ */
+public abstract class NativeFunctions implements Runnable {
+ /**
+ * Name of the library which has been loaded, for information purposes.
+ */
+ public final String libraryName;
+
+ /**
+ * The arena used for loading the library, or {@code null} for the global arena.
+ * This is the arena to close for unloading the library.
+ */
+ private final Arena arena;
+
+ /**
+ * The lookup for retrieving the address of a symbol in the native library.
+ */
+ public final SymbolLookup symbols;
+
+ /**
+ * Creates a new set of handles to native functions.
+ *
+ * @param loader the object used for loading the library.
+ */
+ protected NativeFunctions(final LibraryLoader<?> loader) {
+ libraryName = loader.filename;
+ arena = loader.arena;
+ symbols = loader.symbols;
+ }
+
+ /**
+ * Returns the method handler for the <abbr>GDAL</abbr> function of given name and signature.
+ * This is a convenience method for initialization of fields in subclasses.
+ *
+ * @param linker {@link Linker#nativeLinker()} (should be fetched only once).
+ * @param function name of the C/C++ <abbr>GDAL</abbr> function to invoke.
+ * @param signature type of arguments and return type.
+ * @return method handler for the <abbr>GDAL</abbr> function.
+ * @throws IllegalArgumentException if the given function has not been found.
+ */
+ @SuppressWarnings("restricted")
+ protected final MethodHandle lookup(final Linker linker, final String function, final FunctionDescriptor signature) {
+ return symbols.find(function).map((method) -> linker.downcallHandle(method, signature)).orElseThrow();
+ }
+
+ /**
+ * Invokes a C/C++ function which expects a {@code char*} argument and returns a {@code char*}.
+ * This method should be used only for rarely invoked C/C++ functions, because it fetches the
+ * method handler and create a confined arena on every calls.
+ *
+ * @param linker {@link Linker#nativeLinker()} (should be fetched only once).
+ * @param function name of the C/C++ <abbr>GDAL</abbr> function to invoke.
+ * @param arg the argument.
+ * @return whether the return value, or empty if the method was not found or returned {@code null}.
+ */
+ protected final Optional<String> invokeGetString(final Linker linker, final String function, final String arg) {
+ return symbols.find(function).map((method) -> {
+ final MethodHandle handle = lookup(linker, function,
+ FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.ADDRESS));
+ final MemorySegment result;
+ try (Arena local = Arena.ofConfined()) {
+ result = (MemorySegment) handle.invokeExact(local.allocateFrom(arg));
+ } catch (Throwable e) {
+ throw propagate(e);
+ }
+ return toString(result);
+ });
+ }
+
+ /**
+ * Invokes a C/C++ function which expects no argument and returns an integer.
+ * This method should be used only for rarely invoked C/C++ functions,
+ * because it fetches the method handler on every calls.
+ *
+ * @param linker {@link Linker#nativeLinker()} (should be fetched only once).
+ * @param function name of the C/C++ <abbr>GDAL</abbr> function to invoke.
+ * @return whether the return value, or empty if the method was not found.
+ */
+ @SuppressWarnings("restricted")
+ public final OptionalInt invokeGetInt(final Linker linker, final String function) {
+ final Optional<MemorySegment> method = symbols.find(function);
+ if (method.isEmpty()) {
+ return OptionalInt.empty();
+ }
+ final MethodHandle handle = linker.downcallHandle(method.get(), FunctionDescriptor.of(ValueLayout.JAVA_INT));
+ final int result;
+ try {
+ result = (int) handle.invokeExact();
+ } catch (Throwable e) {
+ throw propagate(e);
+ }
+ return OptionalInt.of(result);
+ }
+
+ /**
+ * Invokes a C/C++ function which expects no argument and returns no value.
+ * This method should be used only for rarely invoked C/C++ functions,
+ * because it fetches the linker and method handler on every calls.
+ *
+ * @param function name of the C/C++ <abbr>GDAL</abbr> function to invoke.
+ * @return whether the function has been found and executed.
+ */
+ @SuppressWarnings("restricted")
+ protected final boolean invoke(final String function) {
+ final Optional<MemorySegment> method = symbols.find(function);
+ if (method.isEmpty()) {
+ return false;
+ }
+ final MethodHandle handle = Linker.nativeLinker().downcallHandle(method.get(), FunctionDescriptor.ofVoid());
+ try {
+ handle.invokeExact();
+ } catch (Throwable e) {
+ throw propagate(e);
+ }
+ return true;
+ }
+
+ /**
+ * Unloads the native library. If the arena is global,
+ * then this method should not be invoked before <abbr>JVM</abbr> shutdown.
+ */
+ @Override
+ public void run() {
+ if (arena != null) {
+ arena.close();
+ }
+ }
+
+ /**
+ * Returns whether the given result is null.
+ *
+ * @param result the result of a native method call, or {@code null}.
+ * @return whether the given result is null or a C/C++ {@code NULL}.
+ */
+ public static boolean isNull(final MemorySegment result) {
+ return (result == null) || result.address() == 0;
+ }
+
+ /**
+ * Returns the value of a native function returning a null-terminated {@code char*}.
+ * The string is assumed encoded in UTF-8.
+ *
+ * @param result the result of a native method call, or {@code null}.
+ * @return the result as a string, or {@code null} if the result was null.
+ */
+ @SuppressWarnings("restricted")
+ public static String toString(final MemorySegment result) {
+ return isNull(result) ? null : result.reinterpret(Integer.MAX_VALUE).getString(0);
+ }
+
+ /**
+ * Propagates the given exception as an unchecked exception. This method should be invoked only
+ * for exceptions thrown during calls to native methods by {@code MethodHandler.invokeExact(…)},
+ * because it assumes that no checked exception should be thrown.
+ *
+ * @param exception the exception thrown by {@code MethodHandler.invokeExact(…)}.
+ * @return the exception to throw by the caller.
+ */
+ public static RuntimeException propagate(final Throwable exception) {
+ switch (exception) {
+ case Error e: throw e;
+ case RuntimeException e: return e;
+ default: throw new UndeclaredThrowableException(exception);
+ }
+ }
+}
diff --git a/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/panama/package-info.java b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/panama/package-info.java
new file mode 100644
index 0000000000..3a4ab762a1
--- /dev/null
+++ b/incubator/src/org.apache.sis.storage.gdal/main/org/apache/sis/storage/panama/package-info.java
@@ -0,0 +1,27 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Base classes for any storage using native libraries through Panama.
+ * Currently used only for <abbr>GDAL</abbr> bindings, but may move to a shared module in the future.
+ *
+ * @author Quentin Bialota (Geomatys)
+ * @author Martin Desruisseaux (Geomatys)
+ * @version 1.5
+ * @since 1.5
+ */
+package org.apache.sis.storage.panama;
diff --git a/incubator/src/org.apache.sis.storage.gdal/test/org/apache/sis/storage/gdal/GDALStoreTest.java b/incubator/src/org.apache.sis.storage.gdal/test/org/apache/sis/storage/gdal/GDALStoreTest.java
new file mode 100644
index 0000000000..7ea4afcf5d
--- /dev/null
+++ b/incubator/src/org.apache.sis.storage.gdal/test/org/apache/sis/storage/gdal/GDALStoreTest.java
@@ -0,0 +1,143 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.storage.gdal;
+
+import java.awt.image.DataBuffer;
+import java.awt.image.RenderedImage;
+import org.opengis.util.GenericName;
+import org.opengis.referencing.NoSuchAuthorityCodeException;
+import org.opengis.referencing.crs.CoordinateReferenceSystem;
+import org.apache.sis.util.Utilities;
+import org.apache.sis.referencing.CRS;
+import org.apache.sis.referencing.privy.AffineTransform2D;
+import org.apache.sis.coverage.SampleDimension;
+import org.apache.sis.coverage.grid.GridCoverage;
+import org.apache.sis.coverage.grid.GridExtent;
+import org.apache.sis.coverage.grid.GridGeometry;
+import org.apache.sis.coverage.grid.PixelInCell;
+import org.apache.sis.storage.GridCoverageResource;
+import org.apache.sis.storage.Resource;
+import org.apache.sis.storage.DataStores;
+import org.apache.sis.storage.DataStoreProvider;
+import org.apache.sis.storage.StorageConnector;
+
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.*;
+
+
+/**
+ * Tests {@link GDALStore}.
+ *
+ * @author Johann Sorel (Geomatys)
+ * @author Quentin BIALOTA (Geomatys)
+ */
+public final class GDALStoreTest {
+ /**
+ * Creates a new test case.
+ */
+ public GDALStoreTest() {
+ }
+
+ /**
+ * Verifies that the provider is registered.
+ */
+ @Test
+ public void testProviderRegistration() {
+ for (DataStoreProvider provider : DataStores.providers()) {
+ if (provider instanceof GDALStoreProvider) {
+ return;
+ }
+ }
+ fail("Provider not found.");
+ }
+
+ /**
+ * Tests reading an indexed image. The test uses a small image with 1 band and indexed color palette.
+ *
+ * @throws Exception if any error occurred.
+ */
+ @Test
+ public void readIndexedImage() throws Exception {
+ boolean foundGrid = false;
+ boolean foundBand = false;
+ final var input = new StorageConnector(GDALStoreTest.class.getResource("test.tiff"));
+ try (GDALStore store = new GDALStore(new GDALStoreProvider(), input)) {
+ for (final Resource r : store.components()) {
+ assertFalse(foundGrid);
+ foundGrid = true;
+
+ final GenericName name = r.getIdentifier().orElseThrow();
+ assertEquals("test.tiff:Image #1", name.toString());
+ assertSame(r, store.findResource(name.toString()));
+
+ // Test reading fully the coverage.
+ final var gr = assertInstanceOf(GridCoverageResource.class, r);
+ final GridCoverage coverage = gr.read(null);
+
+ // Check the CRS.
+ CoordinateReferenceSystem expectedCRS;
+ try {
+ expectedCRS = CRS.forCode("EPSG:32617");
+ } catch (NoSuchAuthorityCodeException e) {
+ // Happen if the EPSG factory is not available.
+ expectedCRS = null;
+ }
+ final CoordinateReferenceSystem actual = coverage.getCoordinateReferenceSystem();
+ assertNotNull(actual);
+ if (expectedCRS != null) {
+ assertTrue(Utilities.equalsIgnoreMetadata(expectedCRS, actual));
+ }
+
+ // Check the grid geometry.
+ final GridGeometry gridGeometry = coverage.getGridGeometry();
+ final GridExtent extent = gridGeometry.getExtent();
+ assertEquals( 2, extent.getDimension());
+ assertEquals(120, extent.getSize(0));
+ assertEquals( 75, extent.getSize(1));
+ final var gridToCrs = assertInstanceOf(AffineTransform2D.class, gridGeometry.getGridToCRS(PixelInCell.CELL_CORNER));
+ assertEquals( 664769.191709, gridToCrs.getTranslateX(), 1E-9);
+ assertEquals(4600950.488848333, gridToCrs.getTranslateY(), 1E-9);
+ assertEquals( 839.977999999, gridToCrs.getScaleX(), 1E-9);
+ assertEquals( -846.395733333, gridToCrs.getScaleY(), 1E-9);
+ assertEquals( 0.0, gridToCrs.getShearX());
+ assertEquals( 0.0, gridToCrs.getShearY());
+
+ // Check the sample dimension.
+ for (final SampleDimension dimension : coverage.getSampleDimensions()) {
+ assertFalse(foundBand);
+ foundBand = true;
+
+ assertTrue(dimension.getTransferFunction().isEmpty());
+ assertTrue(dimension.getUnits().isEmpty());
+
+ // Check image.
+ final RenderedImage img = coverage.render(null);
+ assertEquals(120, img.getWidth());
+ assertEquals( 75, img.getHeight());
+ assertTrue(img.getSampleModel().getNumBands() == 1);
+
+ final DataBuffer data = img.getData().getDataBuffer();
+ assertEquals(DataBuffer.TYPE_BYTE, data.getDataType());
+ assertEquals(9000, data.getSize());
+ assertEquals(5, data.getElem(2000)); // Check a random value.
+ }
+ }
+ }
+ assertTrue(foundGrid);
+ assertTrue(foundBand);
+ }
+}
diff --git a/incubator/src/org.apache.sis.storage.gdal/test/org/apache/sis/storage/gdal/test.tiff b/incubator/src/org.apache.sis.storage.gdal/test/org/apache/sis/storage/gdal/test.tiff
new file mode 100644
index 0000000000..7c6d960734
Binary files /dev/null and b/incubator/src/org.apache.sis.storage.gdal/test/org/apache/sis/storage/gdal/test.tiff differ
diff --git a/netbeans-project/nbproject/project.properties b/netbeans-project/nbproject/project.properties
index b157430750..84fdb90e9b 100644
--- a/netbeans-project/nbproject/project.properties
+++ b/netbeans-project/nbproject/project.properties
@@ -94,6 +94,7 @@ read.options = --add-reads org.apache.sis.cloud.aws=org.junit.jupiter.api,junit
--add-reads org.apache.sis.storage=org.junit.jupiter.api,junit \
--add-reads org.apache.sis.storage.gimi=org.junit.jupiter.api,junit \
--add-reads org.apache.sis.storage.gsf=org.junit.jupiter.api,junit \
+ --add-reads org.apache.sis.storage.gdal=org.junit.jupiter.api,junit \
--add-reads org.apache.sis.storage.geopackage=org.junit.jupiter.api,junit \
--add-reads org.apache.sis.storage.coveragejson=org.junit.jupiter.api,junit \
--add-reads org.apache.sis.storage.earthobservation=org.junit.jupiter.api,junit \