C++20 facade#

<cugeo/raster/raster.hpp> provides header-only C++20 wrappers over the C ABI in <cugeo/raster/raster.h>. Move-only objects manage native dataset, plan, session, and execution handles for host and CUDA operations. Link to libcugeo_raster; no separate compiled C++ library is required.

<cugeo/raster/raster.hpp> includes every domain header. A consumer that needs one domain can include its header alone; each includes its dependencies:

Header

Declares

<cugeo/raster/error.hpp>

error_code, error, the error category, CUDA context and stream references and resource_lease

<cugeo/raster/memory.hpp>

residency, layout, memory resources, admission and leases, and memory::prepared_layout_copy

<cugeo/raster/buffers.hpp>

window, raster_view<T>, raster_view_mut<T>, const_bytes and mutable_bytes

<cugeo/raster/read.hpp>

Metadata and receipt aliases, raster_write_plan, read_policy, read requests, read_cancellation, read_batch_outcome and read_batch_error

<cugeo/raster/dataset.hpp>

dataset and read_batch_plan

<cugeo/raster/metadata.hpp>

Copied metadata_catalog, domain, item and optional text records

<cugeo/raster/warp.hpp>

interpolation, affine_warp, host affine_xy and affine_rowcol

<cugeo/raster/rpc.hpp>

rpc_transformer, specialist rpc_model, rpc_uncertainty and their asynchronous execution owners

<cugeo/raster/composite.hpp>

composite::host_session

<cugeo/raster/ortho.hpp>

ortho::file_execution and ortho::file_execution_error

<cugeo/raster/cuda.hpp>

The cuda namespace: layout copy, BIP allocation, affine, reproject, orthorectification, composite and sample-minimum owners

<cugeo/raster/io.hpp>

The io read and write aliases, io::nvtiff and io::nvimagecodec

<cugeo/raster/jpeg2000.hpp>

io::jpeg2000

<cugeo/raster/jpeg2000.hpp>

Core io::sentinel2 catalog, assets, readers and groups

<cugeo/raster/extensions/sentinel2/surface_reflectance.hpp>

extensions::sentinel2::surface_reflectance radiometry

<cugeo/raster/cuda_driver.hpp> adds context_ref(CUcontext) and stream_ref(CUstream) over <cuda.h>.

Coordinate request records take complete UTF-8 CRS definition strings. The reprojection, terrain and orthorectification constructors borrow those strings only during creation; the native owners retain their definitions afterward. Use the shared cugeo-proj supported operation subset and traditional X/Y units. Parsing a definition does not establish that a coordinate route can execute it.

Install a native development prefix#

Cargo remains the source-build owner. First install cugeo-proj’s native package into /tmp/cugeo-raster-prefix, using a host library built with cargo build --release --locked. Raster’s CMake package requires the shared cugeo_proj package in that prefix. Its packaging-only CMake project stages the raster library, headers and relocatable package metadata. It installs LICENSE, NOTICE and THIRD_PARTY_NOTICES.md under the default share/licenses/cugeo-raster directory.

export CUGEO_PROJ_LIBRARY=/tmp/cugeo-raster-prefix/lib/libcugeo_proj.so
cargo build --release --locked
cmake -S . -B /tmp/cugeo-raster-package \
  -DCUGEO_RASTER_LIBRARY_FILE="$PWD/target/release/libcugeo_raster.so" \
  -DCMAKE_INSTALL_PREFIX=/tmp/cugeo-raster-prefix
cmake --install /tmp/cugeo-raster-package

A consumer resolves the installed package without a source-tree path:

find_package(cugeo_raster CONFIG REQUIRED)
target_link_libraries(my_raster PRIVATE cugeo::raster_cpp)

cugeo::raster_cpp requires ISO C++20 and links cugeo::raster, the imported shared-library target. The execution engine is not header-only.

Ownership and memory#

dataset.metadata(image_index), io::jpeg2000::source.metadata(), and io::sentinel2::product.metadata() return detached metadata_catalog values. Their strings and vectors remain valid after source close. Domains retain order, storage kind, origin, availability and listing visibility. Native band_index=-1 is dataset scope; nonnegative indexes are zero-based bands. descriptions and units retain per-band status alongside optional text. An unavailable discovery state cannot establish that an unknown namespace is absent. These calls inspect metadata without initializing CUDA or decoding pixels. The Python metadata reference describes admitted sources, reference differences and unavailable domains shared by the native APIs.

Every facade handle is a move-only RAII owner. Destructors and moves are noexcept, cleanup is null-safe, and close() may be called more than once. Calling an operation on a closed or moved-from owner throws cugeo::raster::error with error_code::invalid_argument. native_handle() returns a borrowed C handle only; it does not transfer ownership, and the C release/close function must not be called while the C++ owner remains open.

The batch policy and owners also appear under cugeo::raster::io as backend_policy, read_policy, read_batch_plan, and read_cancellation. These are aliases of the portable owners, not a second lifetime system. The typed backend policy contains only automatic and native_tiff, matching the qualified public same-dataset host ABI. The original numeric read_policy fields remain source-compatible for C-shaped integration.

A batch plan is bound to the exact native dataset that created it. The facade keeps that dataset state alive until the last dependent batch plan closes, so it is safe to close or move the dataset facade before executing its plan. No request specification or caller pixel buffer is retained. Scalar reads, batch reads, and host warps are synchronous; their views borrow memory only for the call. CUDA and codec enqueue calls retain their native prepared/session state. cugeo::raster::resource_lease can additionally retain up to eight caller-supplied std::shared_ptr owners in the C++ execution object. A failed retryable close retains the lease; a successful close releases it. Raw allocations and the caller-owned stream must remain valid through successful close.

raster_view<T> and its mutable alias raster_view_mut<T> never allocate or replace the supplied pointer. The factories require explicit logical shape, byte strides (for strided), layout, residency, and forward-accessible extent. Packed BIP, BIL, and BSQ factories derive the strides but still require the caller’s element capacity. Positive, sample-aligned strides and the addressed extent are checked in C++ and the C ABI. Writable addressing must be injective and imagery buffers must be disjoint where required; these are caller preconditions without runtime alias validation. The host dataset reader requires host residency. The host warp accepts host and pinned-host views.

Errors and typed records#

Every non-success C return becomes cugeo::raster::error. code() retains the numeric stable ABI error code and what() copies the bounded C diagnostic, so it never refers to a temporary cugeo_raster_error. Cleanup does not throw and no C callback is installed, so a C++ exception cannot cross a C boundary. cugeo::raster::error_code is registered with std::is_error_code_enum, cugeo::raster::make_error_code uses the cugeo-raster error category, and a caught exception exposes the same value through system_code(). The existing code() return type is unchanged. This throwing facade requires language exceptions and does not support builds compiled with -fno-exceptions; such consumers should call <cugeo/raster/raster.h> directly.

Metadata, read plans, per-request results, and receipts are returned as the exact typed ABI-v1 records under short C++ aliases such as image_info, read_plan, read_result, and read_batch_receipt. Typed facts do not pass through diagnostic JSON. Batch requests and results retain vector order and the original request_id. read_many_into exposes result capacity directly; read_request and read_request_spec are aliases of the frozen C records, and make_read_request/make_read_request_spec initialize them from checked typed views. Their vectors are therefore native contiguous arrays and are passed directly without marshalling, copying, or allocation. The convenience read_many allocates exactly its typed result vector and returns the receipt with it; read_many_into performs no C++ allocation on success. A failed result-vector allocation propagates the standard std::bad_alloc (or std::length_error) before native execution. On a native execution failure, read_many throws read_batch_error, whose outcome() preserves the C-populated partial results and receipt.

Prepared and asynchronous owners#

rpc_model::from_geotiff(values, correction) creates the specialist native sensor owner. uncertainty_host allocates a rpc_uncertainty result; uncertainty_host_into fills caller spans. enqueue_uncertainty borrows packed device arrays and returns a rpc_uncertainty_execution with query/wait/close. The sensor state is retained natively; the caller keeps arrays, stream and context alive through successful close. The options, noise layout, result row order, units and statistical assumptions are the same as the callable uncertainty contract.

The advanced owners mirror, rather than reinterpret, the C lifecycle:

  • cugeo::raster::memory::prepared_layout_copy owns the synchronous prepared host layout-copy handle.

  • cugeo::raster::cuda contains layout_copy_prepared/layout_copy_execution, bip_allocation, affine_prepared/affine_execution, reproject_prepared/reproject_execution, orthorect_prepared/orthorect_geometry/orthorect_execution, and composite_prepared/composite_session/composite_execution, plus the deliberately narrow sample_minimum_prepared/sample_minimum_execution.

  • cugeo::raster::composite::host_session and cugeo::raster::ortho::file_execution own the existing synchronous C handles.

  • Explicit scalar codec forcing is isolated under cugeo::raster::io::nvtiff::{prepared,decode} and cugeo::raster::io::nvimagecodec::decode.

  • cugeo::raster::io::nvtiff also contains device_read_plan, device_read_prepared, device_read_execution, and device_read_pool for the public generic device-read C handles forced to the nvTIFF backend.

Execution and geometry owners expose nonblocking query(), fallible wait(), and close(). Layout-copy prepared/execution, CUDA BIP allocation, composite session/execution, and orthorect execution close() use their existing fallible destroy/release operation and retain the exact handle when the C ABI says retry is possible. They do not first call wait() or materialize an optional result: the native fallible release is the drain boundary. Affine and reprojection execution, orthorect geometry, nvTIFF decode, and nvImageCodec decode use the pointer-to-pointer *_close_v1 entry points directly. These temporarily activate the captured context and preserve the exact native handle when activation, completion, or teardown fails. The legacy void releases remain ABI-compatible destructor fallbacks only. Prepared owners with void release close synchronously and infallibly.

An asynchronous destructor is last-resort cleanup, not an error-reporting boundary. It attempts the native drain/release. If completion cannot be proven where the ABI permits detection, it calls std::terminate() rather than let caller-owned storage, a stream, or prepared state appear reusable. The same rule applies when move-assigning over a still-open asynchronous owner. Call wait() and close() explicitly while the owning CUDA context is current so errors can be caught and retryable handles remain available.

Prepared constructors that accept a const cugeo_raster_*_plan * borrow it only for the create call; the native prepared handle applies the C ABI’s own plan retention. All operation arguments remain exact C descriptors so the wrapper cannot silently allocate storage, change strides, choose a stream, or add a fallback. Receipt accessors return the existing typed C records. The sample-minimum wrapper consumes the exact versioned spec/I/O records and retains their C foreign-owner callbacks natively through completion. It does not allocate raster storage, infer a stream, generalize the four-scene UInt16/C3 BIP contract, or fall back to the modular pipeline. If the synchronous orthorectification file workflow returns a failure handle, cugeo::raster::ortho::file_execution_error copies its partial JSON receipt before RAII cleanup and makes it available through receipt().

For example, given caller-created CUDA context/stream values and an exact C cugeo_raster_warp_io descriptor:

auto warp = cugeo::raster::affine_warp::create<std::uint16_t>(
    width, height, width, height, bands, {0, 1, 0, 0, 0, 1});
auto prepared = cugeo::raster::cuda::affine_prepared::create(
    warp, cugeo::raster::cuda_context_ref(cuda_context));
cugeo::raster::resource_lease lease;
lease.retain(source_owner).retain(destination_owner);
auto execution = prepared.enqueue(
    io, cugeo::raster::cuda_stream_ref(stream), std::move(lease));
if (!execution.query()) {
  execution.wait();
}
const auto receipt = execution.receipt();
execution.close();
prepared.close();

The native affine and reprojection owners validate the bound context and admit CUDA default-stream handles 0, 1 and 2. The lease retains the supplied C++ allocation owners, but the context and stream remain caller-owned and must stay valid through close.

Generic nvTIFF device reads#

cugeo::raster::io::nvtiff::device_read_plan::create accepts the exact pointer-free cugeo_raster_device_read_request_spec_v1 array and always writes an nvTIFF policy with fallback and subbatch splitting disabled. It never exposes an nvTIFF library handle or backend-specific native descriptor. The native C plan copies the specifications and retains its own dataset authority; the C++ array and source dataset are borrowed only for the create call.

device_read_plan::prepare accepts a caller-selected stream plus the generic device resource, pinned resource, and admission owners, either as the exact C options record or through the typed overload. prepare_pool accepts the exact bounded pool options record. Pool member arrays are call-only, every member names a distinct live stream and distinct resource owners in the same current context/device, and the only policy is explicit round-robin. Native preparation retains the plan, resources, and admission gate. Stream handles remain caller-owned and must not be destroyed or recycled until all derived executions successfully close.

Prepared and pool enqueue methods pass the exact request/result arrays to C without allocating destinations, converting layouts, splitting work, or selecting a fallback. Every result-capacity element, including any tail, must enter with exact abi_size and zero flags/reserved. The request and result array pointers are borrowed only for each call, but every addressed CUDA destination remains live through successful execution close(). The submission receipt is available from submission_receipt(); wait() copies final ordered results into caller storage and returns the final typed receipt. A pool execution additionally exposes its typed round-robin selection through pool_receipt().

Prepared, pool, and execution close() map to the pointer-to-pointer fallible C close functions. Failure retains the exact native handle for retry. Their noexcept destructors make one last close attempt and call std::terminate() if the owning CUDA context cannot be restored or cleanup otherwise fails. For JPEG2000, the retained handle is the cuGeo owner: an SDK decode state or parsed stream consumed by a failed destroy is cleared internally. A retry continues the remaining cleanup without destroying that SDK handle again. Plan release is infallible. Keep the prepared context current for enqueue, query, wait, and close; use explicit close while failures can still be caught.

Portable example#

#include <cugeo/raster/raster.hpp>

#include <array>
#include <cstdint>

auto input = cugeo::raster::dataset::open("image.tif");
const auto image = input.image(0);
cugeo::raster::window region(10, 20, 3, 2);
std::array<std::uint16_t, 18> pixels{};
auto output = cugeo::raster::raster_view_mut<std::uint16_t>::packed_bip(
    pixels.data(), pixels.size(), region.width(), region.height(),
    static_cast<std::size_t>(image.bands));
const auto plan = input.plan_read(0, region, output);
if (plan.executable != 0) {
  input.read_into(0, region, output);
}

See examples/native.cpp for the executable golden path: open, inspect, plan and execute one read, execute one native read-many call, perform a caller-owned identity affine warp, and explicitly close every owner. tools/test-cpp.sh builds that consumer against a staged install with strict GCC/Clang warnings; tools/test-wheel.sh builds and runs it again using the headers and shared library extracted from the installed wheel. tests/cpp/async_facade.cpp checks every owner type, retry retention, move/destructor traits, the fail-closed destructor rule, and a real prepared host layout copy against both compilers and the installed wheel. examples/layout_cuda_smoke.cu exercises the C++ layout prepared/execution owners on a non-default stream and validates their query, wait, typed receipt, owner callbacks, close, and context restore.

Bounded CUDA memory#

The facade includes move-only cugeo::raster::memory_resource, cugeo::raster::memory_admission, and cugeo::raster::memory_lease owners. Resource factories select a CUDA async pool, retained preallocated memory, or retained C/C++ callbacks. Resource options supply the CUDA context, device, alignment guarantee, hard byte cap, and fixed record cap. Allocation/free uses the consumer’s operation stream; resource construction selects no execution stream. try_admit returns std::nullopt for immediate backpressure. See bounded memory resources for accounting and cleanup.

Deliberate limits#

The C++ facade does not create a CUDA context or stream, allocate unrequested outputs, or change any underlying feature gate. It retains C++ owners only when the caller explicitly moves a bounded resource_lease into enqueue. Optional wrappers report the same unsupported or cuda_unavailable errors as their C functions when a library lacks the feature. The scalar codec wrappers cover only the existing public scalar/prepared APIs. The public generic device-read family is exposed only under the nvTIFF namespace and has no automatic backend or pool-size default. Private nvImageCodec multi-ROI, allocator, and scheduler experiments remain absent. The bounded-memory owners above are the allocator types exposed by this facade. Backend-specific callers can continue using <cugeo/raster/raster.h> alongside the C++ wrappers and obtain native handles with native_handle() without transferring ownership.

cugeo::raster::io::jpeg2000 exposes source, direct prepared/execution, and composed decode-plus-affine prepared/execution owners. prepare_options requires typed context and stream references. Enqueue accepts exact caller-owned device raster descriptors and an optional resource lease. The wrapper does not choose a backend, allocate output, insert a wait, or fall back when direct nvJPEG2000 is unavailable.

The frozen host ABI exposes dataset georeferencing and an independent affine pixel warp, but no single fused operation that derives a warp from two dataset CRSs/geotransforms. Callers must construct the six-coefficient destination-to-source transform explicitly (or use the existing optional reprojection C API). Warp status and optional validity bitmaps also remain caller-owned buffers; the facade does not hide them behind allocations.

Registered coordinate arrays#

<cugeo/raster/geolocation.hpp> exposes geolocation_grid, geolocation_plan, geolocation_prepared and geolocation_execution. Construct dense/separable geometry from explicit native options, or use geolocation_grid::from_pair for native Rasterio pair normalization. geolocation_field<T> describes borrowed Float32/64 storage without node access. Plans accept the common image dtype, nearest/bilinear and nodata/write policies; preparations use explicit context/stream and bounded workspace. Enqueue borrows the common cugeo_raster_warp_io; execution query/wait/close retains native resources. Optional resource_lease values retain foreign arrays. All owners, including destruction, stay on their creator thread/process. See registered arrays for registration, geometry planning, residency, resource and completion limits.