1#![warn(clippy::all)]
95#![deny(clippy::unwrap_used)]
98#![allow(clippy::module_name_repetitions)]
99#![allow(dead_code)]
101#![allow(clippy::expect_used)]
103#![allow(clippy::too_many_arguments)]
105#![allow(clippy::manual_clamp)]
107#![allow(clippy::vec_init_then_push)]
109#![allow(missing_docs)]
111
112pub mod adaptive_tiling;
113pub mod band_algebra;
114pub mod band_read;
115pub mod cog;
116pub mod color_space;
117pub mod compression;
118pub mod geokeys;
119pub mod jpeg_codec;
120pub mod lerc_codec;
121pub mod overviews;
122pub mod tiff;
123pub mod writer;
124
125pub use cog::CogReader;
127pub use geokeys::{GeoKey, GeoKeyDirectory, ModelType, RasterType};
128pub use tiff::{
129 ByteOrderType, Compression, ImageInfo, PhotometricInterpretation, TiffFile, TiffHeader, TiffTag,
130};
131pub use writer::{
132 CogWriter, CogWriterOptions, GeoTiffWriter, GeoTiffWriterOptions, OverviewResampling,
133 WriterConfig,
134};
135
136use crate::tiff::Predictor;
137use oxigeo_core::buffer::RasterBuffer;
138use oxigeo_core::error::{FormatError, OxiGeoError, Result};
139use oxigeo_core::io::DataSource;
140use oxigeo_core::types::{
141 ColorInterpretation, GeoTransform, NoDataValue, RasterDataType, RasterMetadata,
142};
143
144const MAX_BAND_BYTES: usize = {
157 const FOUR_GIB: u64 = 4 * 1024 * 1024 * 1024;
158 if FOUR_GIB <= usize::MAX as u64 {
159 FOUR_GIB as usize
160 } else {
161 usize::MAX / 4
162 }
163};
164
165fn checked_band_bytes(
173 width: usize,
174 height: usize,
175 bytes_per_sample: usize,
176 samples_per_pixel: usize,
177) -> Result<usize> {
178 let band_bytes = width
179 .checked_mul(height)
180 .and_then(|v| v.checked_mul(bytes_per_sample))
181 .and_then(|v| v.checked_mul(samples_per_pixel))
182 .ok_or_else(|| {
183 OxiGeoError::Format(FormatError::InvalidHeader {
184 message: format!(
185 "raster dimensions overflow usize: {width}x{height} x {bytes_per_sample} \
186 bytes x {samples_per_pixel} samples"
187 ),
188 })
189 })?;
190 if band_bytes > MAX_BAND_BYTES {
191 return Err(OxiGeoError::Format(FormatError::InvalidHeader {
192 message: format!(
193 "raster band size ({band_bytes} bytes) exceeds the maximum supported \
194 ({MAX_BAND_BYTES} bytes); refusing to allocate (possible malformed or \
195 hostile header)"
196 ),
197 }));
198 }
199 Ok(band_bytes)
200}
201
202const fn decoded_needs_native_swap(
225 byte_order: ByteOrderType,
226 bytes_per_sample: usize,
227 compression: Compression,
228) -> bool {
229 if !matches!(bytes_per_sample, 2 | 4 | 8) {
230 return false;
231 }
232 if matches!(compression, Compression::Lerc) {
233 return false;
234 }
235 match byte_order {
236 ByteOrderType::LittleEndian => cfg!(target_endian = "big"),
237 ByteOrderType::BigEndian => cfg!(target_endian = "little"),
238 }
239}
240
241fn reject_undefined_predictor(compression: Compression, predictor: Predictor) -> Result<()> {
269 if matches!(predictor, Predictor::None) || !matches!(compression, Compression::Lerc) {
270 return Ok(());
271 }
272 Err(
273 OxiGeoError::not_supported_builder("a TIFF Predictor combined with LERC compression")
274 .with_operation("decode block")
275 .with_parameter("compression", "LERC (34887)")
276 .with_parameter("predictor", format!("{predictor:?} ({})", predictor as u16))
277 .with_suggestion(
278 "No encoder defines this combination (libtiff's LERC codec ignores tag 317 and \
279 GDAL refuses PREDICTOR for LERC), so the block's pixels cannot be reconstructed \
280 unambiguously. Re-encode the file without the Predictor tag, or with a codec \
281 that defines it (LZW, DEFLATE, ZSTD).",
282 )
283 .build(),
284 )
285}
286
287fn swap_sample_bytes<const N: usize>(data: &mut [u8]) {
292 for chunk in data.chunks_exact_mut(N) {
293 let mut sample = [0u8; N];
294 sample.copy_from_slice(chunk);
295 sample.reverse();
296 chunk.copy_from_slice(&sample);
297 }
298}
299
300fn normalize_samples_to_native(
314 data: &mut [u8],
315 bytes_per_sample: usize,
316 byte_order: ByteOrderType,
317 compression: Compression,
318) {
319 if !decoded_needs_native_swap(byte_order, bytes_per_sample, compression) {
320 return;
321 }
322 match bytes_per_sample {
323 2 => swap_sample_bytes::<2>(data),
324 4 => swap_sample_bytes::<4>(data),
325 8 => swap_sample_bytes::<8>(data),
326 _ => {}
329 }
330}
331
332fn parse_geokeys_to_wkt(geo_keys: Option<&GeoKeyDirectory>) -> Option<String> {
340 let geo_keys = geo_keys?;
341 let epsg_code = geo_keys.epsg_code()?;
342
343 Some(match epsg_code {
346 4326 => {
348 r#"GEOGCS["WGS 84",
349 DATUM["WGS_1984",
350 SPHEROID["WGS 84",6378137,298.257223563,
351 AUTHORITY["EPSG","7030"]],
352 AUTHORITY["EPSG","6326"]],
353 PRIMEM["Greenwich",0,
354 AUTHORITY["EPSG","8901"]],
355 UNIT["degree",0.0174532925199433,
356 AUTHORITY["EPSG","9122"]],
357 AXIS["Latitude",NORTH],
358 AXIS["Longitude",EAST],
359 AUTHORITY["EPSG","4326"]]"#
360 .to_string()
361 }
362 3857 => {
364 r#"PROJCS["WGS 84 / Pseudo-Mercator",
365 GEOGCS["WGS 84",
366 DATUM["WGS_1984",
367 SPHEROID["WGS 84",6378137,298.257223563,
368 AUTHORITY["EPSG","7030"]],
369 AUTHORITY["EPSG","6326"]],
370 PRIMEM["Greenwich",0,
371 AUTHORITY["EPSG","8901"]],
372 UNIT["degree",0.0174532925199433,
373 AUTHORITY["EPSG","9122"]],
374 AUTHORITY["EPSG","4326"]],
375 PROJECTION["Mercator_1SP"],
376 PARAMETER["central_meridian",0],
377 PARAMETER["scale_factor",1],
378 PARAMETER["false_easting",0],
379 PARAMETER["false_northing",0],
380 UNIT["metre",1,
381 AUTHORITY["EPSG","9001"]],
382 AXIS["Easting",EAST],
383 AXIS["Northing",NORTH],
384 EXTENSION["PROJ4","+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null +wktext +no_defs"],
385 AUTHORITY["EPSG","3857"]]"#
386 .to_string()
387 }
388 32601..=32660 => {
390 let zone = epsg_code - 32600;
391 format!(
392 r#"PROJCS["WGS 84 / UTM zone {}N",
393 GEOGCS["WGS 84",
394 DATUM["WGS_1984",
395 SPHEROID["WGS 84",6378137,298.257223563,
396 AUTHORITY["EPSG","7030"]],
397 AUTHORITY["EPSG","6326"]],
398 PRIMEM["Greenwich",0,
399 AUTHORITY["EPSG","8901"]],
400 UNIT["degree",0.0174532925199433,
401 AUTHORITY["EPSG","9122"]],
402 AUTHORITY["EPSG","4326"]],
403 PROJECTION["Transverse_Mercator"],
404 PARAMETER["latitude_of_origin",0],
405 PARAMETER["central_meridian",{}],
406 PARAMETER["scale_factor",0.9996],
407 PARAMETER["false_easting",500000],
408 PARAMETER["false_northing",0],
409 UNIT["metre",1,
410 AUTHORITY["EPSG","9001"]],
411 AXIS["Easting",EAST],
412 AXIS["Northing",NORTH],
413 AUTHORITY["EPSG","{}""]]"#,
414 zone,
415 zone as i32 * 6 - 183,
416 epsg_code
417 )
418 }
419 32701..=32760 => {
421 let zone = epsg_code - 32700;
422 format!(
423 r#"PROJCS["WGS 84 / UTM zone {}S",
424 GEOGCS["WGS 84",
425 DATUM["WGS_1984",
426 SPHEROID["WGS 84",6378137,298.257223563,
427 AUTHORITY["EPSG","7030"]],
428 AUTHORITY["EPSG","6326"]],
429 PRIMEM["Greenwich",0,
430 AUTHORITY["EPSG","8901"]],
431 UNIT["degree",0.0174532925199433,
432 AUTHORITY["EPSG","9122"]],
433 AUTHORITY["EPSG","4326"]],
434 PROJECTION["Transverse_Mercator"],
435 PARAMETER["latitude_of_origin",0],
436 PARAMETER["central_meridian",{}],
437 PARAMETER["scale_factor",0.9996],
438 PARAMETER["false_easting",500000],
439 PARAMETER["false_northing",10000000],
440 UNIT["metre",1,
441 AUTHORITY["EPSG","9001"]],
442 AXIS["Easting",EAST],
443 AXIS["Northing",NORTH],
444 AUTHORITY["EPSG","{}""]]"#,
445 zone,
446 zone as i32 * 6 - 183,
447 epsg_code
448 )
449 }
450 4269 => {
452 r#"GEOGCS["NAD83",
453 DATUM["North_American_Datum_1983",
454 SPHEROID["GRS 1980",6378137,298.257222101,
455 AUTHORITY["EPSG","7019"]],
456 AUTHORITY["EPSG","6269"]],
457 PRIMEM["Greenwich",0,
458 AUTHORITY["EPSG","8901"]],
459 UNIT["degree",0.0174532925199433,
460 AUTHORITY["EPSG","9122"]],
461 AXIS["Latitude",NORTH],
462 AXIS["Longitude",EAST],
463 AUTHORITY["EPSG","4269"]]"#
464 .to_string()
465 }
466 4267 => {
468 r#"GEOGCS["NAD27",
469 DATUM["North_American_Datum_1927",
470 SPHEROID["Clarke 1866",6378206.4,294.978698213898,
471 AUTHORITY["EPSG","7008"]],
472 AUTHORITY["EPSG","6267"]],
473 PRIMEM["Greenwich",0,
474 AUTHORITY["EPSG","8901"]],
475 UNIT["degree",0.0174532925199433,
476 AUTHORITY["EPSG","9122"]],
477 AXIS["Latitude",NORTH],
478 AXIS["Longitude",EAST],
479 AUTHORITY["EPSG","4267"]]"#
480 .to_string()
481 }
482 _ => format!("EPSG:{}", epsg_code),
484 })
485}
486
487fn parse_photometric_interpretation(
496 photometric: PhotometricInterpretation,
497 samples_per_pixel: u16,
498) -> Vec<ColorInterpretation> {
499 match photometric {
500 PhotometricInterpretation::WhiteIsZero | PhotometricInterpretation::BlackIsZero => {
501 if samples_per_pixel == 1 {
503 vec![ColorInterpretation::Gray]
504 } else if samples_per_pixel == 2 {
505 vec![ColorInterpretation::Gray, ColorInterpretation::Alpha]
506 } else {
507 vec![ColorInterpretation::Gray; samples_per_pixel as usize]
509 }
510 }
511 PhotometricInterpretation::Rgb => {
512 match samples_per_pixel {
514 1 => vec![ColorInterpretation::Red],
515 2 => vec![ColorInterpretation::Red, ColorInterpretation::Green],
516 3 => vec![
517 ColorInterpretation::Red,
518 ColorInterpretation::Green,
519 ColorInterpretation::Blue,
520 ],
521 4 => vec![
522 ColorInterpretation::Red,
523 ColorInterpretation::Green,
524 ColorInterpretation::Blue,
525 ColorInterpretation::Alpha,
526 ],
527 _ => {
528 let mut interp = vec![
530 ColorInterpretation::Red,
531 ColorInterpretation::Green,
532 ColorInterpretation::Blue,
533 ];
534 if samples_per_pixel > 3 {
535 interp.push(ColorInterpretation::Alpha);
536 }
537 for _ in 4..samples_per_pixel {
538 interp.push(ColorInterpretation::Undefined);
539 }
540 interp
541 }
542 }
543 }
544 PhotometricInterpretation::Palette => {
545 if samples_per_pixel == 1 {
547 vec![ColorInterpretation::PaletteIndex]
548 } else if samples_per_pixel == 2 {
549 vec![
550 ColorInterpretation::PaletteIndex,
551 ColorInterpretation::Alpha,
552 ]
553 } else {
554 vec![ColorInterpretation::PaletteIndex; samples_per_pixel as usize]
555 }
556 }
557 PhotometricInterpretation::Cmyk => {
558 match samples_per_pixel {
560 1 => vec![ColorInterpretation::Cyan],
561 2 => vec![ColorInterpretation::Cyan, ColorInterpretation::Magenta],
562 3 => vec![
563 ColorInterpretation::Cyan,
564 ColorInterpretation::Magenta,
565 ColorInterpretation::Yellow,
566 ],
567 4 => vec![
568 ColorInterpretation::Cyan,
569 ColorInterpretation::Magenta,
570 ColorInterpretation::Yellow,
571 ColorInterpretation::Black,
572 ],
573 _ => {
574 let mut interp = vec![
576 ColorInterpretation::Cyan,
577 ColorInterpretation::Magenta,
578 ColorInterpretation::Yellow,
579 ColorInterpretation::Black,
580 ];
581 for _ in 4..samples_per_pixel {
582 interp.push(ColorInterpretation::Undefined);
583 }
584 interp
585 }
586 }
587 }
588 PhotometricInterpretation::YCbCr => {
589 match samples_per_pixel {
591 1 => vec![ColorInterpretation::YCbCrY],
592 2 => vec![ColorInterpretation::YCbCrY, ColorInterpretation::YCbCrCb],
593 3 => vec![
594 ColorInterpretation::YCbCrY,
595 ColorInterpretation::YCbCrCb,
596 ColorInterpretation::YCbCrCr,
597 ],
598 _ => {
599 let mut interp = vec![
601 ColorInterpretation::YCbCrY,
602 ColorInterpretation::YCbCrCb,
603 ColorInterpretation::YCbCrCr,
604 ];
605 if samples_per_pixel > 3 {
606 interp.push(ColorInterpretation::Alpha);
607 }
608 for _ in 4..samples_per_pixel {
609 interp.push(ColorInterpretation::Undefined);
610 }
611 interp
612 }
613 }
614 }
615 _ => vec![ColorInterpretation::Undefined; samples_per_pixel as usize],
617 }
618}
619
620pub struct GeoTiffReader<S: DataSource> {
622 cog_reader: CogReader<S>,
623 geo_transform: Option<GeoTransform>,
624 nodata: NoDataValue,
625}
626
627impl<S: DataSource> GeoTiffReader<S> {
628 pub fn open(source: S) -> Result<Self> {
644 let cog_reader = CogReader::open(source)?;
645
646 let geo_transform = cog_reader.geo_transform()?;
648
649 let nodata = cog_reader.nodata()?;
651
652 Ok(Self {
653 cog_reader,
654 geo_transform,
655 nodata,
656 })
657 }
658
659 #[must_use]
661 pub fn width(&self) -> u64 {
662 self.cog_reader.width()
663 }
664
665 #[must_use]
667 pub fn height(&self) -> u64 {
668 self.cog_reader.height()
669 }
670
671 #[must_use]
673 pub fn band_count(&self) -> u32 {
674 u32::from(self.cog_reader.primary_info().samples_per_pixel)
675 }
676
677 #[must_use]
679 pub fn data_type(&self) -> Option<RasterDataType> {
680 self.cog_reader.primary_info().data_type()
681 }
682
683 #[must_use]
685 pub fn tile_size(&self) -> Option<(u32, u32)> {
686 self.cog_reader.tile_size()
687 }
688
689 #[must_use]
691 pub fn overview_count(&self) -> usize {
692 self.cog_reader.overview_count()
693 }
694
695 #[must_use]
697 pub fn geo_transform(&self) -> Option<&GeoTransform> {
698 self.geo_transform.as_ref()
699 }
700
701 #[must_use]
703 pub const fn nodata(&self) -> NoDataValue {
704 self.nodata
705 }
706
707 #[must_use]
709 pub fn epsg_code(&self) -> Option<u32> {
710 self.cog_reader.epsg_code()
711 }
712
713 #[must_use]
715 pub fn compression(&self) -> Compression {
716 self.cog_reader.primary_info().compression
717 }
718
719 #[must_use]
730 pub fn byte_order(&self) -> ByteOrderType {
731 self.cog_reader.tiff().byte_order()
732 }
733
734 #[must_use]
736 pub fn tile_count(&self) -> (u32, u32) {
737 self.cog_reader.tile_count()
738 }
739
740 pub fn read_tile(&self, level: usize, tile_x: u32, tile_y: u32) -> Result<Vec<u8>> {
753 self.cog_reader.read_tile(level, tile_x, tile_y)
754 }
755
756 pub fn level_size(&self, level: usize) -> Result<(u64, u64)> {
779 let info = self.level_info(level)?;
780 Ok((info.width, info.height))
781 }
782
783 fn level_info(&self, level: usize) -> Result<ImageInfo> {
796 let primary = self.cog_reader.primary_info();
797 if level == 0 {
798 return Ok(primary.clone());
799 }
800 let out_of_bounds = || OxiGeoError::OutOfBounds {
801 message: format!("Overview level {level} out of bounds"),
802 };
803 if level > self.cog_reader.overview_count() {
804 return Err(out_of_bounds());
805 }
806
807 let byte_order = self.cog_reader.tiff().byte_order();
808 let ifd = self.cog_reader.level_ifd(level).ok_or_else(out_of_bounds)?;
813 let scalar = |tag: TiffTag| ifd.get_entry(tag).and_then(|e| e.get_u64(byte_order).ok());
814
815 let mut info = primary.clone();
816 info.width =
817 scalar(TiffTag::ImageWidth).ok_or(OxiGeoError::Format(FormatError::MissingTag {
818 tag: "ImageWidth",
819 }))?;
820 info.height =
821 scalar(TiffTag::ImageLength).ok_or(OxiGeoError::Format(FormatError::MissingTag {
822 tag: "ImageLength",
823 }))?;
824 info.tile_width = scalar(TiffTag::TileWidth).and_then(|v| u32::try_from(v).ok());
827 info.tile_height = scalar(TiffTag::TileLength).and_then(|v| u32::try_from(v).ok());
828 info.rows_per_strip = scalar(TiffTag::RowsPerStrip).and_then(|v| u32::try_from(v).ok());
829 if let Some(v) = scalar(TiffTag::SamplesPerPixel) {
830 info.samples_per_pixel = v as u16;
831 }
832 if let Some(v) = scalar(TiffTag::BitsPerSample) {
833 info.bits_per_sample = vec![v as u16];
834 }
835 Ok(info)
836 }
837
838 pub fn read_tile_buffer(&self, level: usize, tile_x: u32, tile_y: u32) -> Result<RasterBuffer> {
848 self.read_tile_band_buffer(level, 0, tile_x, tile_y)
849 }
850
851 pub fn read_tile_band_buffer(
881 &self,
882 level: usize,
883 band: usize,
884 tile_x: u32,
885 tile_y: u32,
886 ) -> Result<RasterBuffer> {
887 let info = self.level_info(level)?;
888
889 let band_count = info.samples_per_pixel as usize;
890 if band >= band_count {
891 return Err(OxiGeoError::invalid_parameter_builder(
892 "band",
893 "band index is out of range for this raster",
894 )
895 .with_operation("read_tile_band_buffer")
896 .with_parameter("band", band.to_string())
897 .with_parameter("band_count", band_count.to_string())
898 .with_parameter("level", level.to_string())
899 .with_suggestion("Band indices are zero-based; use GeoTiffReader::band_count()")
900 .build());
901 }
902
903 let data_type =
904 info.data_type()
905 .ok_or(OxiGeoError::Format(FormatError::InvalidDataType {
906 type_id: 0,
907 }))?;
908 let bytes_per_sample = data_type.size_bytes() as u64;
909
910 let (block_width, block_height) = if info.is_tiled() {
913 (
914 u64::from(info.tile_width.unwrap_or_default()),
915 u64::from(info.tile_height.unwrap_or_default()),
916 )
917 } else {
918 (
919 info.width,
920 u64::from(info.rows_per_strip.unwrap_or(info.height as u32)),
921 )
922 };
923 if block_width == 0 || block_height == 0 {
924 return Err(OxiGeoError::Format(FormatError::InvalidHeader {
925 message: format!(
926 "level {level} declares zero-sized blocks ({block_width}x{block_height})"
927 ),
928 }));
929 }
930
931 let (blocks_across, blocks_down) = (info.tiles_across(), info.tiles_down());
933 if tile_x >= blocks_across || tile_y >= blocks_down {
934 return Err(OxiGeoError::OutOfBounds {
935 message: format!(
936 "Tile/strip ({tile_x}, {tile_y}) out of bounds at level {level} \
937 ({blocks_across}x{blocks_down} blocks)"
938 ),
939 });
940 }
941
942 let x0 = u64::from(tile_x) * block_width;
943 let y0 = u64::from(tile_y) * block_height;
944 let rows = if info.is_tiled() {
947 block_height
948 } else {
949 block_height.min(info.height.saturating_sub(y0))
950 };
951 let valid_width = block_width.min(info.width.saturating_sub(x0));
952 let valid_height = rows.min(info.height.saturating_sub(y0));
953
954 let to_usize = |v: u64| {
955 usize::try_from(v).map_err(|_| {
956 OxiGeoError::Format(FormatError::InvalidHeader {
957 message: format!("block size {v} does not fit in usize on this target"),
958 })
959 })
960 };
961 let buffer_len = checked_band_bytes(
964 to_usize(block_width)?,
965 to_usize(rows)?,
966 to_usize(bytes_per_sample)?,
967 1,
968 )?;
969 let mut data = vec![0u8; buffer_len];
970
971 if valid_width > 0 && valid_height > 0 {
972 let row_bytes = to_usize(valid_width * bytes_per_sample)?;
973 let dst_stride = to_usize(block_width * bytes_per_sample)?;
974 if valid_width == block_width {
975 let len = row_bytes * to_usize(valid_height)?;
977 self.read_window_into(
978 level,
979 band,
980 x0,
981 y0,
982 valid_width,
983 valid_height,
984 &mut data[..len],
985 )?;
986 } else {
987 let mut window = vec![0u8; row_bytes * to_usize(valid_height)?];
988 self.read_window_into(level, band, x0, y0, valid_width, valid_height, &mut window)?;
989 for row in 0..to_usize(valid_height)? {
990 let src = row * row_bytes;
991 let dst = row * dst_stride;
992 data[dst..dst + row_bytes].copy_from_slice(&window[src..src + row_bytes]);
993 }
994 }
995 }
996
997 RasterBuffer::new(data, block_width, rows, data_type, self.nodata)
998 }
999
1000 #[must_use]
1002 pub fn metadata(&self) -> RasterMetadata {
1003 let info = self.cog_reader.primary_info();
1004
1005 let crs_wkt = parse_geokeys_to_wkt(self.cog_reader.geo_keys());
1007
1008 let color_interpretation =
1010 parse_photometric_interpretation(info.photometric, info.samples_per_pixel);
1011
1012 RasterMetadata {
1013 width: info.width,
1014 height: info.height,
1015 band_count: u32::from(info.samples_per_pixel),
1016 data_type: info.data_type().unwrap_or(RasterDataType::UInt8),
1017 geo_transform: self.geo_transform,
1018 crs_wkt,
1019 nodata: self.nodata,
1020 color_interpretation,
1021 layout: oxigeo_core::types::PixelLayout::Tiled {
1022 tile_width: info.tile_width.unwrap_or(256),
1023 tile_height: info.tile_height.unwrap_or(256),
1024 },
1025 driver_metadata: Vec::new(),
1026 statistics: None,
1027 }
1028 }
1029
1030 pub fn new(source: S) -> Result<Self> {
1035 Self::open(source)
1036 }
1037}
1038
1039#[must_use]
1041pub fn is_tiff(data: &[u8]) -> bool {
1042 if data.len() < 4 {
1043 return false;
1044 }
1045
1046 (data[0] == 0x49 && data[1] == 0x49 && data[2] == 0x2A && data[3] == 0x00) || (data[0] == 0x4D && data[1] == 0x4D && data[2] == 0x00 && data[3] == 0x2A) || (data[0] == 0x49 && data[1] == 0x49 && data[2] == 0x2B && data[3] == 0x00) || (data[0] == 0x4D && data[1] == 0x4D && data[2] == 0x00 && data[3] == 0x2B) }
1052
1053pub fn is_cog<S: DataSource>(source: &S) -> Result<bool> {
1055 let tiff = TiffFile::parse(source)?;
1056 let validation = cog::validate_cog(&tiff, source);
1057 Ok(validation.is_valid)
1058}
1059
1060#[cfg(test)]
1061mod tests {
1062 use super::*;
1063 use crate::geokeys::GeoKeyEntry;
1064
1065 #[test]
1066 fn test_is_tiff() {
1067 assert!(is_tiff(&[0x49, 0x49, 0x2A, 0x00, 0x08, 0x00, 0x00, 0x00]));
1069
1070 assert!(is_tiff(&[0x4D, 0x4D, 0x00, 0x2A, 0x00, 0x00, 0x00, 0x08]));
1072
1073 assert!(is_tiff(&[0x49, 0x49, 0x2B, 0x00, 0x08, 0x00, 0x00, 0x00]));
1075
1076 assert!(!is_tiff(&[0x89, 0x50, 0x4E, 0x47])); assert!(!is_tiff(&[0xFF, 0xD8, 0xFF])); assert!(!is_tiff(&[]));
1080 }
1081
1082 const HOST: ByteOrderType = if cfg!(target_endian = "big") {
1084 ByteOrderType::BigEndian
1085 } else {
1086 ByteOrderType::LittleEndian
1087 };
1088
1089 const FOREIGN: ByteOrderType = if cfg!(target_endian = "big") {
1091 ByteOrderType::LittleEndian
1092 } else {
1093 ByteOrderType::BigEndian
1094 };
1095
1096 #[test]
1097 fn native_swap_is_skipped_when_the_file_matches_the_host() {
1098 for width in [0usize, 1, 2, 3, 4, 6, 8, 16] {
1100 assert!(
1101 !decoded_needs_native_swap(HOST, width, Compression::None),
1102 "width {width} must not be swapped for a host-order file"
1103 );
1104 }
1105 }
1106
1107 #[test]
1108 fn native_swap_covers_exactly_the_two_four_and_eight_byte_widths() {
1109 for width in [2usize, 4, 8] {
1110 assert!(
1111 decoded_needs_native_swap(FOREIGN, width, Compression::None),
1112 "width {width} of a foreign-order file must be swapped"
1113 );
1114 }
1115 for width in [0usize, 1, 3, 5, 6, 7, 9, 12] {
1119 assert!(
1120 !decoded_needs_native_swap(FOREIGN, width, Compression::None),
1121 "width {width} must be passed through untouched"
1122 );
1123 }
1124 }
1125
1126 #[test]
1127 fn native_swap_never_touches_lerc_blocks() {
1128 for width in [2usize, 4, 8] {
1132 assert!(!decoded_needs_native_swap(
1133 FOREIGN,
1134 width,
1135 Compression::Lerc
1136 ));
1137 assert!(!decoded_needs_native_swap(HOST, width, Compression::Lerc));
1138 }
1139 }
1140
1141 #[test]
1142 fn native_swap_reverses_whole_samples_and_leaves_a_partial_tail_alone() {
1143 let mut two = [1u8, 2, 3, 4, 9];
1144 swap_sample_bytes::<2>(&mut two);
1145 assert_eq!(two, [2, 1, 4, 3, 9], "trailing odd byte must be untouched");
1146
1147 let mut four = [1u8, 2, 3, 4, 5, 6, 7, 8, 0xaa, 0xbb];
1148 swap_sample_bytes::<4>(&mut four);
1149 assert_eq!(four, [4, 3, 2, 1, 8, 7, 6, 5, 0xaa, 0xbb]);
1150
1151 let mut eight = [1u8, 2, 3, 4, 5, 6, 7, 8];
1152 swap_sample_bytes::<8>(&mut eight);
1153 assert_eq!(eight, [8, 7, 6, 5, 4, 3, 2, 1]);
1154
1155 let original = [0x12u8, 0x34, 0x56, 0x78];
1158 let mut round_trip = original;
1159 swap_sample_bytes::<4>(&mut round_trip);
1160 swap_sample_bytes::<4>(&mut round_trip);
1161 assert_eq!(round_trip, original);
1162 }
1163
1164 #[test]
1165 fn normalize_samples_to_native_is_a_no_op_for_a_host_order_file() {
1166 let original: Vec<u8> = (0..32).collect();
1167 let mut data = original.clone();
1168 normalize_samples_to_native(&mut data, 4, HOST, Compression::None);
1169 assert_eq!(data, original);
1170
1171 normalize_samples_to_native(&mut data, 4, FOREIGN, Compression::None);
1173 assert_eq!(&data[..4], &[3, 2, 1, 0]);
1174 }
1175
1176 #[test]
1177 fn checked_band_bytes_accepts_reasonable_dimensions() {
1178 let n = checked_band_bytes(4096, 4096, 2, 3);
1180 assert!(matches!(n, Ok(v) if v == 4096 * 4096 * 2 * 3));
1181 assert!(matches!(checked_band_bytes(0, 0, 4, 1), Ok(0)));
1183 }
1184
1185 #[test]
1186 fn checked_band_bytes_rejects_oversized_dimensions() {
1187 let err = checked_band_bytes(65535, 65535, 8, 4);
1189 assert!(matches!(
1190 err,
1191 Err(OxiGeoError::Format(FormatError::InvalidHeader { .. }))
1192 ));
1193 }
1194
1195 #[test]
1196 fn checked_band_bytes_rejects_multiplication_overflow() {
1197 let err = checked_band_bytes(usize::MAX, 2, 1, 1);
1200 assert!(matches!(
1201 err,
1202 Err(OxiGeoError::Format(FormatError::InvalidHeader { .. }))
1203 ));
1204 }
1205
1206 #[test]
1207 fn test_parse_geokeys_to_wkt_none() {
1208 let wkt = parse_geokeys_to_wkt(None);
1210 assert!(wkt.is_none());
1211 }
1212
1213 #[test]
1214 fn test_parse_geokeys_to_wkt_epsg_4326() {
1215 let geo_dir = GeoKeyDirectory {
1217 version: 1,
1218 key_revision_major: 1,
1219 key_revision_minor: 0,
1220 entries: vec![GeoKeyEntry {
1221 key_id: GeoKey::GeographicType as u16,
1222 tiff_tag_location: 0,
1223 count: 1,
1224 value_offset: 4326,
1225 }],
1226 double_params: Vec::new(),
1227 ascii_params: String::new(),
1228 };
1229
1230 let wkt = parse_geokeys_to_wkt(Some(&geo_dir));
1231 assert!(wkt.is_some());
1232 let wkt_str = wkt.unwrap_or_default();
1233 assert!(wkt_str.contains("WGS 84"));
1234 assert!(wkt_str.contains("EPSG"));
1235 assert!(wkt_str.contains("4326"));
1236 }
1237
1238 #[test]
1239 fn test_parse_geokeys_to_wkt_epsg_3857() {
1240 let geo_dir = GeoKeyDirectory {
1242 version: 1,
1243 key_revision_major: 1,
1244 key_revision_minor: 0,
1245 entries: vec![GeoKeyEntry {
1246 key_id: GeoKey::ProjectedCsType as u16,
1247 tiff_tag_location: 0,
1248 count: 1,
1249 value_offset: 3857,
1250 }],
1251 double_params: Vec::new(),
1252 ascii_params: String::new(),
1253 };
1254
1255 let wkt = parse_geokeys_to_wkt(Some(&geo_dir));
1256 assert!(wkt.is_some());
1257 let wkt_str = wkt.unwrap_or_default();
1258 assert!(wkt_str.contains("Pseudo-Mercator"));
1259 assert!(wkt_str.contains("3857"));
1260 }
1261
1262 #[test]
1263 fn test_parse_geokeys_to_wkt_utm_north() {
1264 let geo_dir = GeoKeyDirectory {
1266 version: 1,
1267 key_revision_major: 1,
1268 key_revision_minor: 0,
1269 entries: vec![GeoKeyEntry {
1270 key_id: GeoKey::ProjectedCsType as u16,
1271 tiff_tag_location: 0,
1272 count: 1,
1273 value_offset: 32632,
1274 }],
1275 double_params: Vec::new(),
1276 ascii_params: String::new(),
1277 };
1278
1279 let wkt = parse_geokeys_to_wkt(Some(&geo_dir));
1280 assert!(wkt.is_some());
1281 let wkt_str = wkt.unwrap_or_default();
1282 assert!(wkt_str.contains("UTM zone 32N"));
1283 assert!(wkt_str.contains("32632"));
1284 assert!(wkt_str.contains("central_meridian"));
1285 }
1286
1287 #[test]
1288 fn test_parse_geokeys_to_wkt_utm_south() {
1289 let geo_dir = GeoKeyDirectory {
1291 version: 1,
1292 key_revision_major: 1,
1293 key_revision_minor: 0,
1294 entries: vec![GeoKeyEntry {
1295 key_id: GeoKey::ProjectedCsType as u16,
1296 tiff_tag_location: 0,
1297 count: 1,
1298 value_offset: 32732,
1299 }],
1300 double_params: Vec::new(),
1301 ascii_params: String::new(),
1302 };
1303
1304 let wkt = parse_geokeys_to_wkt(Some(&geo_dir));
1305 assert!(wkt.is_some());
1306 let wkt_str = wkt.unwrap_or_default();
1307 assert!(wkt_str.contains("UTM zone 32S"));
1308 assert!(wkt_str.contains("32732"));
1309 assert!(wkt_str.contains("false_northing"));
1310 }
1311
1312 #[test]
1313 fn test_parse_geokeys_to_wkt_nad83() {
1314 let geo_dir = GeoKeyDirectory {
1316 version: 1,
1317 key_revision_major: 1,
1318 key_revision_minor: 0,
1319 entries: vec![GeoKeyEntry {
1320 key_id: GeoKey::GeographicType as u16,
1321 tiff_tag_location: 0,
1322 count: 1,
1323 value_offset: 4269,
1324 }],
1325 double_params: Vec::new(),
1326 ascii_params: String::new(),
1327 };
1328
1329 let wkt = parse_geokeys_to_wkt(Some(&geo_dir));
1330 assert!(wkt.is_some());
1331 let wkt_str = wkt.unwrap_or_default();
1332 assert!(wkt_str.contains("NAD83"));
1333 assert!(wkt_str.contains("4269"));
1334 }
1335
1336 #[test]
1337 fn test_parse_geokeys_to_wkt_unknown_epsg() {
1338 let geo_dir = GeoKeyDirectory {
1340 version: 1,
1341 key_revision_major: 1,
1342 key_revision_minor: 0,
1343 entries: vec![GeoKeyEntry {
1344 key_id: GeoKey::ProjectedCsType as u16,
1345 tiff_tag_location: 0,
1346 count: 1,
1347 value_offset: 9999,
1348 }],
1349 double_params: Vec::new(),
1350 ascii_params: String::new(),
1351 };
1352
1353 let wkt = parse_geokeys_to_wkt(Some(&geo_dir));
1354 assert!(wkt.is_some());
1355 assert_eq!(wkt.unwrap_or_default(), "EPSG:9999");
1356 }
1357
1358 #[test]
1359 fn test_parse_photometric_gray_single() {
1360 let interp = parse_photometric_interpretation(PhotometricInterpretation::BlackIsZero, 1);
1361 assert_eq!(interp.len(), 1);
1362 assert_eq!(interp[0], ColorInterpretation::Gray);
1363 }
1364
1365 #[test]
1366 fn test_parse_photometric_gray_with_alpha() {
1367 let interp = parse_photometric_interpretation(PhotometricInterpretation::WhiteIsZero, 2);
1368 assert_eq!(interp.len(), 2);
1369 assert_eq!(interp[0], ColorInterpretation::Gray);
1370 assert_eq!(interp[1], ColorInterpretation::Alpha);
1371 }
1372
1373 #[test]
1374 fn test_parse_photometric_rgb() {
1375 let interp = parse_photometric_interpretation(PhotometricInterpretation::Rgb, 3);
1376 assert_eq!(interp.len(), 3);
1377 assert_eq!(interp[0], ColorInterpretation::Red);
1378 assert_eq!(interp[1], ColorInterpretation::Green);
1379 assert_eq!(interp[2], ColorInterpretation::Blue);
1380 }
1381
1382 #[test]
1383 fn test_parse_photometric_rgba() {
1384 let interp = parse_photometric_interpretation(PhotometricInterpretation::Rgb, 4);
1385 assert_eq!(interp.len(), 4);
1386 assert_eq!(interp[0], ColorInterpretation::Red);
1387 assert_eq!(interp[1], ColorInterpretation::Green);
1388 assert_eq!(interp[2], ColorInterpretation::Blue);
1389 assert_eq!(interp[3], ColorInterpretation::Alpha);
1390 }
1391
1392 #[test]
1393 fn test_parse_photometric_palette() {
1394 let interp = parse_photometric_interpretation(PhotometricInterpretation::Palette, 1);
1395 assert_eq!(interp.len(), 1);
1396 assert_eq!(interp[0], ColorInterpretation::PaletteIndex);
1397 }
1398
1399 #[test]
1400 fn test_parse_photometric_cmyk() {
1401 let interp = parse_photometric_interpretation(PhotometricInterpretation::Cmyk, 4);
1402 assert_eq!(interp.len(), 4);
1403 assert_eq!(interp[0], ColorInterpretation::Cyan);
1404 assert_eq!(interp[1], ColorInterpretation::Magenta);
1405 assert_eq!(interp[2], ColorInterpretation::Yellow);
1406 assert_eq!(interp[3], ColorInterpretation::Black);
1407 }
1408
1409 #[test]
1410 fn test_parse_photometric_ycbcr() {
1411 let interp = parse_photometric_interpretation(PhotometricInterpretation::YCbCr, 3);
1412 assert_eq!(interp.len(), 3);
1413 assert_eq!(interp[0], ColorInterpretation::YCbCrY);
1414 assert_eq!(interp[1], ColorInterpretation::YCbCrCb);
1415 assert_eq!(interp[2], ColorInterpretation::YCbCrCr);
1416 }
1417
1418 #[test]
1419 fn test_parse_photometric_ycbcr_with_alpha() {
1420 let interp = parse_photometric_interpretation(PhotometricInterpretation::YCbCr, 4);
1421 assert_eq!(interp.len(), 4);
1422 assert_eq!(interp[0], ColorInterpretation::YCbCrY);
1423 assert_eq!(interp[1], ColorInterpretation::YCbCrCb);
1424 assert_eq!(interp[2], ColorInterpretation::YCbCrCr);
1425 assert_eq!(interp[3], ColorInterpretation::Alpha);
1426 }
1427
1428 #[test]
1429 fn test_parse_photometric_rgb_extra_bands() {
1430 let interp = parse_photometric_interpretation(PhotometricInterpretation::Rgb, 6);
1431 assert_eq!(interp.len(), 6);
1432 assert_eq!(interp[0], ColorInterpretation::Red);
1433 assert_eq!(interp[1], ColorInterpretation::Green);
1434 assert_eq!(interp[2], ColorInterpretation::Blue);
1435 assert_eq!(interp[3], ColorInterpretation::Alpha);
1436 assert_eq!(interp[4], ColorInterpretation::Undefined);
1437 assert_eq!(interp[5], ColorInterpretation::Undefined);
1438 }
1439
1440 #[test]
1441 fn test_parse_photometric_undefined() {
1442 let interp =
1444 parse_photometric_interpretation(PhotometricInterpretation::TransparencyMask, 2);
1445 assert_eq!(interp.len(), 2);
1446 assert_eq!(interp[0], ColorInterpretation::Undefined);
1447 assert_eq!(interp[1], ColorInterpretation::Undefined);
1448 }
1449}