oxigeo_wasm/lib.rs
1//! # OxiGeo WASM - WebAssembly Bindings for Browser-based Geospatial Processing
2//!
3//! This crate provides comprehensive WebAssembly bindings for OxiGeo, enabling
4//! high-performance browser-based geospatial data processing with a focus on
5//! Cloud Optimized GeoTIFF (COG) visualization and manipulation.
6//!
7//! ## Features
8//!
9//! ### Core Capabilities
10//! - **COG Viewing**: Efficient viewing of Cloud Optimized GeoTIFFs
11//! - **Tile Management**: Advanced tile caching and pyramid management
12//! - **Progressive Rendering**: Smooth progressive loading with adaptive quality
13//! - **Image Processing**: Color manipulation, contrast enhancement, filters
14//! - **Performance Profiling**: Built-in profiling and bottleneck detection
15//! - **Worker Pool**: Parallel tile loading using Web Workers
16//! - **Streaming**: Adaptive tile streaming with bandwidth estimation
17//!
18//! ### Advanced Features
19//! - **Compression**: Multiple compression algorithms for bandwidth reduction
20//! - **Color Operations**: Extensive color space conversions and palettes
21//! - **TypeScript Bindings**: Auto-generated TypeScript definitions
22//! - **Error Handling**: Comprehensive error types and recovery
23//! - **Viewport Management**: Advanced viewport transformations and history
24//!
25//! ## Architecture
26//!
27//! The crate is organized into several modules:
28//!
29//! - `bindings`: TypeScript type definitions and documentation generation
30//! - `canvas`: Image processing, resampling, and canvas rendering utilities
31//! - `color`: Advanced color manipulation, palettes, and color correction
32//! - `compression`: Tile compression algorithms (RLE, Delta, Huffman, LZ77)
33//! - `error`: Comprehensive error types for all operations
34//! - `fetch`: HTTP fetching with retry logic and parallel requests
35//! - `profiler`: Performance profiling and bottleneck detection
36//! - `rendering`: Canvas rendering, double buffering, and progressive rendering
37//! - `streaming`: Adaptive tile streaming with bandwidth management
38//! - `tile`: Tile coordinate systems, caching, and pyramid management
39//! - `worker`: Web Worker pool for parallel processing
40//!
41//! ## Basic Usage Example (JavaScript)
42//!
43//! ```javascript
44//! import init, { WasmCogViewer } from '@cooljapan/oxigeo';
45//!
46//! async function viewCog(url) {
47//! // Initialize the WASM module
48//! await init();
49//!
50//! // Create a viewer instance
51//! const viewer = new WasmCogViewer();
52//!
53//! // Open a COG file
54//! await viewer.open(url);
55//!
56//! // Get image metadata
57//! console.log(`Image size: ${viewer.width()}x${viewer.height()}`);
58//! console.log(`Tile size: ${viewer.tile_width()}x${viewer.tile_height()}`);
59//! console.log(`Bands: ${viewer.band_count()}`);
60//! console.log(`Overviews: ${viewer.overview_count()}`);
61//!
62//! // Read a tile as ImageData for canvas rendering
63//! const imageData = await viewer.read_tile_as_image_data(0, 0, 0);
64//!
65//! // Render to canvas
66//! const canvas = document.getElementById('map-canvas');
67//! const ctx = canvas.getContext('2d');
68//! ctx.putImageData(imageData, 0, 0);
69//! }
70//! ```
71//!
72//! ## Advanced Usage Example (JavaScript)
73//!
74//! ```javascript
75//! import init, {
76//! AdvancedCogViewer,
77//! WasmImageProcessor,
78//! WasmColorPalette,
79//! WasmProfiler,
80//! WasmTileCache
81//! } from '@cooljapan/oxigeo';
82//!
83//! async function advancedProcessing() {
84//! await init();
85//!
86//! // Create an advanced viewer with caching
87//! const viewer = new AdvancedCogViewer();
88//! await viewer.open('https://example.com/image.tif', 100); // 100MB cache
89//!
90//! // Setup profiling
91//! const profiler = new WasmProfiler();
92//! profiler.startTimer('tile_load');
93//!
94//! // Load and process a tile
95//! const imageData = await viewer.readTileAsImageData(0, 0, 0);
96//! profiler.stopTimer('tile_load');
97//!
98//! // Apply color palette
99//! const palette = WasmColorPalette.createViridis();
100//! const imageBytes = new Uint8Array(imageData.data.buffer);
101//! palette.applyToGrayscale(imageBytes);
102//!
103//! // Apply image processing
104//! WasmImageProcessor.linearStretch(imageBytes, imageData.width, imageData.height);
105//!
106//! // Get cache statistics
107//! const cacheStats = viewer.getCacheStats();
108//! console.log('Cache hit rate:', JSON.parse(cacheStats).hit_count);
109//!
110//! // Get profiling statistics
111//! const profStats = profiler.getAllStats();
112//! console.log('Performance:', profStats);
113//! }
114//! ```
115//!
116//! ## Progressive Loading Example (JavaScript)
117//!
118//! ```javascript
119//! async function progressiveLoad(url, canvas) {
120//! const viewer = new AdvancedCogViewer();
121//! await viewer.open(url, 100);
122//!
123//! // Start with low quality for quick feedback
124//! viewer.setViewportSize(canvas.width, canvas.height);
125//! viewer.fitToImage();
126//!
127//! const ctx = canvas.getContext('2d');
128//!
129//! // Load visible tiles progressively
130//! const viewport = JSON.parse(viewer.getViewport());
131//! for (let level = viewer.overview_count(); level >= 0; level--) {
132//! // Load tiles at this level
133//! const imageData = await viewer.readTileAsImageData(level, 0, 0);
134//! ctx.putImageData(imageData, 0, 0);
135//!
136//! // Allow UI updates
137//! await new Promise(resolve => setTimeout(resolve, 0));
138//! }
139//! }
140//! ```
141//!
142//! ## Performance Considerations
143//!
144//! ### Memory Management
145//! - The tile cache automatically evicts old tiles using LRU strategy
146//! - Configure cache size based on available memory
147//! - Use compression to reduce memory footprint
148//!
149//! ### Network Optimization
150//! - HTTP range requests are used for partial file reads
151//! - Retry logic handles network failures gracefully
152//! - Parallel requests improve throughput
153//! - Adaptive streaming adjusts quality based on bandwidth
154//!
155//! ### Rendering Performance
156//! - Double buffering prevents flickering
157//! - Progressive rendering provides quick feedback
158//! - Web Workers enable parallel tile processing
159//! - Canvas operations are optimized for WASM
160//!
161//! ## Error Handling
162//!
163//! All operations return `Result` types that can be converted to JavaScript
164//! exceptions. Errors are categorized by type:
165//!
166//! - `FetchError`: Network and HTTP errors
167//! - `CanvasError`: Canvas and rendering errors
168//! - `WorkerError`: Web Worker errors
169//! - `TileCacheError`: Cache management errors
170//! - `JsInteropError`: JavaScript interop errors
171//!
172//! ```javascript
173//! try {
174//! await viewer.open(url);
175//! } catch (error) {
176//! if (error.message.includes('HTTP 404')) {
177//! console.error('File not found');
178//! } else if (error.message.includes('CORS')) {
179//! console.error('Cross-origin request blocked');
180//! } else {
181//! console.error('Unknown error:', error);
182//! }
183//! }
184//! ```
185//!
186//! ## Browser Compatibility
187//!
188//! This crate requires:
189//! - WebAssembly support
190//! - Fetch API with range request support
191//! - Canvas API
192//! - Web Workers (optional, for parallel processing)
193//! - Performance API (optional, for profiling)
194//!
195//! Supported browsers:
196//! - Chrome 57+
197//! - Firefox 52+
198//! - Safari 11+
199//! - Edge 16+
200//!
201//! ## Building for Production
202//!
203//! ```bash
204//! # Optimize for size
205//! wasm-pack build --target web --release -- --features optimize-size
206//!
207//! # Optimize for speed
208//! wasm-pack build --target web --release -- --features optimize-speed
209//!
210//! # Generate TypeScript definitions
211//! wasm-pack build --target bundler --release
212//! ```
213//!
214//! ## License
215//!
216//! This crate is part of the OxiGeo project and follows the same licensing terms.
217
218#![warn(missing_docs)]
219#![warn(clippy::all)]
220#![deny(clippy::unwrap_used)]
221// WASM crate allows - for internal implementation patterns
222#![allow(clippy::needless_range_loop)]
223#![allow(clippy::expect_used)]
224#![allow(clippy::should_implement_trait)]
225#![allow(clippy::new_without_default)]
226#![allow(clippy::ptr_arg)]
227#![allow(clippy::type_complexity)]
228
229mod animation;
230mod anomaly;
231mod bindings;
232mod buffered_source;
233mod canvas;
234mod cog_reader;
235mod color;
236mod compression;
237mod error;
238mod fetch;
239mod memory_source;
240mod profiler;
241mod rendering;
242mod streaming;
243mod terrain;
244#[cfg(test)]
245mod tests;
246mod tile;
247mod vault;
248mod worker;
249
250// Extracted from this file's own inline definitions (COOLJAPAN <2000-line
251// policy) — see the `pub use` block below for what each re-exports.
252mod advancedcogviewer_traits;
253mod functions;
254mod types;
255mod types_4;
256mod types_5;
257mod types_6;
258mod wasmcogviewer_traits;
259
260// WASM Component Model (wasm32-wasip2) support
261pub mod component;
262pub mod wasm_memory;
263
264// GeoSentinel — in-browser Sentinel-2 change detection (UTM, STAC, COG pipeline)
265pub mod sentinel;
266
267pub use animation::{
268 Animation, Easing, EasingFunction, PanAnimation, SpringAnimation, ZoomAnimation,
269};
270pub use bindings::{
271 DocGenerator, TsClass, TsFunction, TsInterface, TsModule, TsParameter, TsType, TsTypeAlias,
272 create_oxigeo_wasm_docs,
273};
274pub use canvas::{
275 ChannelHistogramJson, ContrastMethod, CustomBinHistogramJson, Histogram, HistogramJson, Hsv,
276 ImageProcessor, ImageStats, ResampleMethod, Resampler, Rgb, WasmImageProcessor, YCbCr,
277};
278pub use color::{
279 ChannelOps, ColorCorrectionMatrix, ColorPalette, ColorQuantizer, ColorTemperature,
280 GradientGenerator, PaletteEntry, WasmColorPalette, WhiteBalance,
281};
282pub use compression::{
283 CompressionAlgorithm, CompressionBenchmark, CompressionSelector, CompressionStats,
284 DeltaCompressor, HuffmanCompressor, Lz77Compressor, RleCompressor, TileCompressor,
285};
286pub use error::{
287 CanvasError, FetchError, JsInteropError, TileCacheError, WasmError, WasmResult, WorkerError,
288};
289pub use fetch::{
290 EnhancedFetchBackend, FetchBackend, FetchStats, PrioritizedRequest, RequestPriority,
291 RequestQueue, RetryConfig,
292};
293pub use functions::{decode_elevation, init, is_tiff_url, to_js_error, version};
294pub use memory_source::MemorySource;
295pub use profiler::{
296 Bottleneck, BottleneckDetector, CounterStats, FrameRateStats, FrameRateTracker, MemoryMonitor,
297 MemorySnapshot, MemoryStats, PerformanceCounter, Profiler, ProfilerSummary, WasmProfiler,
298};
299pub use rendering::{
300 AnimationManager, AnimationStats, CanvasBuffer, CanvasRenderer, ProgressiveRenderStats,
301 ProgressiveRenderer, RenderQuality, ViewportHistory, ViewportState, ViewportTransform,
302};
303pub use streaming::{
304 BandwidthEstimator, ImportanceCalculator, LoadStrategy, MultiResolutionStreamer,
305 PrefetchScheduler, ProgressiveLoader, QualityAdapter, StreamBuffer, StreamBufferStats,
306 StreamingQuality, StreamingStats, TileStreamer,
307};
308pub use terrain::WasmTerrain;
309pub use tile::{
310 CacheStats, CachedTile, PrefetchStrategy, TileBounds, TileCache, TileCoord, TilePrefetcher,
311 TilePyramid, WasmTileCache,
312};
313pub use types::{BatchTileLoader, GeoJsonExporter};
314pub use types_4::AdvancedCogViewer;
315pub use types_5::Viewport;
316pub use types_6::WasmCogViewer;
317pub use worker::{
318 JobId, JobStatus, PendingJob, PoolStats, WasmWorkerPool, WorkerInfo, WorkerJobRequest,
319 WorkerJobResponse, WorkerPool, WorkerRequestType, WorkerResponseType,
320};