From 5e7ba70eaa1b14f03c04673a2c8fbcce02ad6f6d Mon Sep 17 00:00:00 2001 From: meawoppl <579782+meawoppl@users.noreply.github.com> Date: Thu, 8 Oct 2026 20:14:17 -0700 Subject: [PATCH] Encode GZIP_1 and RICE_1 tiles with fitsio-pure fitsio-pure's compress module is a pure-Rust (no_std, wasm32) port of cfitsio's Rice encoder and tile quantization, checked against cfitsio in its CI. rice.rs and gzip.rs (461 lines) and the miniz_oxide dependency go. HCOMPRESS_1, the tile grid and the global f32 quantization step stay here and are passed through exactly, so every builder setting behaves as before. Checked against 1.0.0-pre6 on 17 codec x type x tiling cases, at 57x23 and at 26 MP: - Every file is the same size, and astropy decodes every case, quantized f32 included, to identical values. Metadata cards are unchanged. - Write time is within about 10% either way; u8 is faster. Lossless GZIP_1 floats now carry ZQUANTIZ = 'NONE', as cfitsio writes them, so the float_compresses_both_ways test checks for that. --- CHANGELOG.MD | 13 ++ Cargo.lock | 13 +- Cargo.toml | 2 +- README.MD | 1 + src/fits/card.rs | 21 ++- src/fits/compress.rs | 181 ++++++------------- src/fits/gzip.rs | 58 ------- src/fits/hdu.rs | 49 ++---- src/fits/mod.rs | 109 +++++++++--- src/fits/rice.rs | 403 ------------------------------------------- src/fits/tests.rs | 5 +- 11 files changed, 200 insertions(+), 655 deletions(-) delete mode 100644 src/fits/gzip.rs delete mode 100644 src/fits/rice.rs diff --git a/CHANGELOG.MD b/CHANGELOG.MD index 5a1563e..e2d3fbf 100644 --- a/CHANGELOG.MD +++ b/CHANGELOG.MD @@ -2,6 +2,19 @@ ## Changes +### Unreleased + +- `GZIP_1` and `RICE_1` tiles are now encoded by + [`fitsio-pure`](https://crates.io/crates/fitsio-pure)'s `compress` module, a + pure-Rust (no_std, wasm32) port of cfitsio's encoders that is checked against + cfitsio in its CI. The crate's own `rice.rs` and `gzip.rs` are removed, and so is + the `miniz_oxide` dependency. `HCOMPRESS_1`, the tile grid and the global `f32` + quantization step are still computed here, so every builder setting behaves as + before. Output is the same size and decodes to the same values in astropy, + quantized `f32` included. Lossless `GZIP_1` floats now carry + `ZQUANTIZ = 'NONE'`, as cfitsio writes them. +- `FitsError::Compression` reports a `fitsio-pure` encoding failure. + ### 1.0.0-pre6 (2026-09-03) - **Breaking:** `PixelType` now has only the six variants the crate can actually diff --git a/Cargo.lock b/Cargo.lock index 27398f5..6098575 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -215,6 +215,17 @@ dependencies = [ "libc", ] +[[package]] +name = "fitsio-pure" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a69aab257aa782d25d7437befdb8ec3b597e36eecb4bf42a4744ddaa5aeb287c" +dependencies = [ + "bytemuck", + "libm", + "miniz_oxide 0.9.1", +] + [[package]] name = "fitsio-sys" version = "0.5.7" @@ -684,9 +695,9 @@ dependencies = [ "chrono", "crc32fast", "fitsio", + "fitsio-pure", "image", "indexmap", - "miniz_oxide 0.8.9", "num-traits", "paste", "rand 0.10.2", diff --git a/Cargo.toml b/Cargo.toml index 74e2018..30fb1a3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,8 +30,8 @@ include = [ bytemuck = "1.23" chrono = { version = "0.4.31", default-features = false, features = ["alloc", "serde"] } crc32fast = "1.5" +fitsio-pure = "0.21.1" indexmap = { version = "2", features = ["serde"] } -miniz_oxide = "0.8" num-traits = "0.2.19" paste = "1.0" serde = { version = "1.0", features = ["derive"] } diff --git a/README.MD b/README.MD index bb73bd3..00ea535 100644 --- a/README.MD +++ b/README.MD @@ -124,6 +124,7 @@ assert_eq!((luma.width(), luma.height()), (48, 48)); `GenericImageRef` / `GenericImageOwned` can be stored to FITS via the `FitsWrite` trait. It writes uncompressed images (`FitsCompression::NONE`) and the tile-compression convention through the builder structs `Gzip`, `Rice` and `Hcompress` (anything `Into`). `Gzip` is lossless for any pixel type; `Rice` and `Hcompress` are lossless for `u8`/`u16` and quantize `f32` with `SUBTRACTIVE_DITHER_1`. +`Gzip` and `Rice` tiles are encoded by the pure-Rust [`fitsio-pure`](https://crates.io/crates/fitsio-pure) crate, whose encoders are checked against cfitsio. Tile shape is set with `tile_rows(n)` or `tile_dims([nx, ny])`, defaulting to one image row per tile for `Rice`/`Gzip` and one whole channel plane for `Hcompress` (the H-transform + quadtree coder, min. tile 4×4); `Rice`/`Hcompress` also take a `Quantize` (level / dither seed) and `Hcompress` a `scale` / `smooth`. Multi-channel images are stored planar, `u16` carries `BZERO = 32768`, and metadata is stored in header cards (`HIERARCH` for long keys, `CONTINUE` for long strings). `FitsWrite::fits_bytes` returns a single image as a `Vec` (in-memory), and `create_fits_to(sink, compression)` builds a multi-HDU file into a `Write` sink (`create_fits` is the on-disk equivalent). diff --git a/src/fits/card.rs b/src/fits/card.rs index 0fd0b1d..bdf0ecd 100644 --- a/src/fits/card.rs +++ b/src/fits/card.rs @@ -7,7 +7,7 @@ use super::{FitsError, FitsResult}; const CARD: usize = 80; -const BLOCK: usize = 2880; +pub(super) const BLOCK: usize = 2880; /// Structural keywords a caller must not shadow with metadata. pub(super) const RESERVED: &[&str] = &[ @@ -185,16 +185,21 @@ impl Header { } /// Emit `END` and pad the header to a 2880-byte boundary with spaces. - pub(super) fn finish(mut self) -> Vec { - self.raw("END"); - let rem = self.buf.len() % BLOCK; - if rem != 0 { - self.buf.resize(self.buf.len() + (BLOCK - rem), b' '); - } - self.buf + pub(super) fn finish(self) -> Vec { + end_block(self.buf) } } +/// Whole 80-byte `cards` followed by `END`, padded to a 2880-byte boundary with +/// spaces. +pub(super) fn end_block(mut cards: Vec) -> Vec { + let start = cards.len(); + cards.extend_from_slice(b"END"); + cards.resize(start + CARD, b' '); + cards.resize(cards.len().div_ceil(BLOCK) * BLOCK, b' '); + cards +} + /// Pad a string to at least 8 characters with trailing spaces (FITS minimum string /// value width). fn pad8(s: &str) -> String { diff --git a/src/fits/compress.rs b/src/fits/compress.rs index 59441d3..37c79ca 100644 --- a/src/fits/compress.rs +++ b/src/fits/compress.rs @@ -1,32 +1,31 @@ -//! The tile-compressed `BINTABLE` HDU (`ZIMAGE` convention). +//! Tile grids and float quantization for the compressed writers, and the +//! `HCOMPRESS_1` tile-compressed `BINTABLE` HDU (`ZIMAGE` convention). //! -//! Tiling is resolved here from the caller's [`Tiling`] choice and the concrete image +//! `GZIP_1` and `RICE_1` tiles are compressed by `fitsio_pure::compress` +//! (`mod.rs`); `HCOMPRESS_1` is built here. Both take their tile grid and their +//! float quantization from this module, so the three algorithms tile and quantize +//! alike. +//! +//! Tiling is resolved from the caller's [`Tiling`] choice and the concrete image //! size: the default is one image row per tile for `GZIP_1` / `RICE_1` and one whole //! channel plane for `HCOMPRESS_1`, but [`Rice::tile_rows`](super::Rice::tile_rows) / //! [`Rice::tile_dims`](super::Rice::tile_dims) (and the same on the other builders) pick //! any rectangular grid. Tiles are numbered fastest-FITS-axis-first; edge tiles are -//! clipped, not padded. Each tile is compressed independently; the bytes are -//! concatenated into the table heap and pointed at by a `1PB` variable-length-array -//! descriptor per row. +//! clipped, not padded. //! -//! Integer images (`u8` / `u16`) compress losslessly. `f32` + `Rice` / `Hcompress` -//! quantizes each tile to 32-bit integers first ([`quantize`]); `ZSCALE` is constant and -//! `ZZERO` is per-tile, both written as `1D` columns alongside `COMPRESSED_DATA`. +//! `f32` + `Rice` / `Hcompress` is quantized to 32-bit integers with one global step +//! for the whole image ([`quantize::global_delta`]); `ZSCALE` is constant and `ZZERO` +//! is per-tile, both written as `1D` columns alongside `COMPRESSED_DATA`. -use super::config::{DitherSeed, Method, Quantize, Tiling}; -use super::hdu::{ImageView, Tile}; -use super::{gzip, hcompress, quantize, rice, FitsError, FitsResult}; +use super::config::{DitherSeed, Quantize, Tiling}; +use super::hdu::ImageView; +use super::{hcompress, quantize, FitsError, FitsResult}; -/// Everything `mod.rs` needs to emit a compressed image HDU. +/// Everything `mod.rs` needs to emit an `HCOMPRESS_1` image HDU. pub(super) struct Compressed { - pub zcmptype: &'static str, pub zbitpix: i64, pub zaxes: Vec, pub ztiles: Vec, - pub bytepix: usize, - pub is_rice: bool, - /// `true` for `HCOMPRESS_1` — emits the `SCALE` / `SMOOTH` `ZNAME` cards. - pub is_hcompress: bool, /// HCOMPRESS scale factor (`ZVAL1`); `0` = lossless. pub hscale: i64, /// HCOMPRESS `SMOOTH` flag (`ZVAL2`). @@ -41,71 +40,21 @@ pub(super) struct Compressed { pub data: Vec, } -/// The chosen algorithm plus its resolved settings. -enum Algo { - Gzip { - level: u8, - }, - Rice(Quantize), - Hcompress { - scale: i32, - smooth: bool, - quantize: Quantize, - }, -} - -impl Algo { - fn is_hcompress(&self) -> bool { - matches!(self, Algo::Hcompress { .. }) - } - fn hscale(&self) -> i32 { - match self { - Algo::Hcompress { scale, .. } => *scale, - _ => 0, - } - } - fn quantize(&self) -> Option { - match self { - Algo::Gzip { .. } => None, - Algo::Rice(q) => Some(*q), - Algo::Hcompress { quantize, .. } => Some(*quantize), - } - } -} - -pub(super) fn build(view: &ImageView<'_>, method: &Method) -> FitsResult { - let (tiling, algo) = match method { - Method::None => unreachable!("caller handles None"), - Method::Gzip { tiling, level } => (tiling, Algo::Gzip { level: *level }), - Method::Rice { tiling, quantize } => (tiling, Algo::Rice(*quantize)), - Method::Hcompress { - tiling, - scale, - smooth, - quantize, - } => ( - tiling, - Algo::Hcompress { - scale: *scale, - smooth: *smooth, - quantize: *quantize, - }, - ), - }; - build_tiled(view, tiling, &algo) -} - /// The tile grid, resolved against the image size. -struct Grid { +pub(super) struct Grid { tx: usize, ty: usize, ntx: usize, nty: usize, /// `ZTILE1..ZTILEn`. - ztile: Vec, + pub ztile: Vec, } -fn resolve_grid(view: &ImageView<'_>, tiling: &Tiling, hcompress: bool) -> FitsResult { +pub(super) fn resolve_grid( + view: &ImageView<'_>, + tiling: &Tiling, + hcompress: bool, +) -> FitsResult { let axes = view.axes(); let (mut tx, mut ty) = match tiling { Tiling::Default => { @@ -157,26 +106,30 @@ fn resolve_grid(view: &ImageView<'_>, tiling: &Tiling, hcompress: bool) -> FitsR }) } -fn build_tiled(view: &ImageView<'_>, tiling: &Tiling, algo: &Algo) -> FitsResult { - let grid = resolve_grid(view, tiling, algo.is_hcompress())?; - - // Global quantization parameters (only for `f32` + Rice/Hcompress). - let quant = match algo.quantize() { - Some(q) if view.is_float() => { - let planar = view.planar_f32(); - let delta = quantize::global_delta(&planar, view.w, view.h * view.ch, q.level); - let seed = match q.seed { - DitherSeed::Auto => { - let tw = grid.tx.min(view.w); - let th = grid.ty.min(view.h); - quantize::dither_seed(&view.rect_f32(0, 0, 0, tw, th)) - } - DitherSeed::Fixed(n) => n.clamp(1, 10_000), - }; - Some((delta, seed)) +/// The global quantization step and the dither seed (`ZDITHER0`) for an `f32` image. +pub(super) fn global_quant(view: &ImageView<'_>, grid: &Grid, q: &Quantize) -> (f64, u32) { + let planar = view.planar_f32(); + let delta = quantize::global_delta(&planar, view.w, view.h * view.ch, q.level); + let seed = match q.seed { + DitherSeed::Auto => { + let tw = grid.tx.min(view.w); + let th = grid.ty.min(view.h); + quantize::dither_seed(&view.rect_f32(0, 0, 0, tw, th)) } - _ => None, + DitherSeed::Fixed(n) => n.clamp(1, 10_000), }; + (delta, seed) +} + +pub(super) fn hcompress( + view: &ImageView<'_>, + tiling: &Tiling, + scale: i32, + smooth: bool, + q: &Quantize, +) -> FitsResult { + let grid = resolve_grid(view, tiling, true)?; + let quant = view.is_float().then(|| global_quant(view, &grid, q)); let quantized = quant.is_some(); let row_bytes = if quantized { 24 } else { 8 }; @@ -196,30 +149,12 @@ fn build_tiled(view: &ImageView<'_>, tiling: &Tiling, algo: &Algo) -> FitsResult let (compressed, zzero) = if let Some((delta, seed)) = quant { let f = view.rect_f32(plane, x0, y0, tw, th); - let q = quantize::quantize_tile(&f, delta, tile_index, seed); - let bytes = if algo.is_hcompress() { - let mut d = q.idata; - hcompress::compress(&mut d, tw, th, algo.hscale()) - } else { - rice::encode_int(&q.idata) - }; + let mut q = quantize::quantize_tile(&f, delta, tile_index, seed); + let bytes = hcompress::compress(&mut q.idata, tw, th, scale); (bytes, Some(q.zzero)) } else { - let bytes = match algo { - Algo::Gzip { level } => { - gzip::gzip(&view.rect_tile(plane, x0, y0, tw, th).to_be_bytes(), *level) - } - Algo::Rice(_) => match view.rect_tile(plane, x0, y0, tw, th) { - Tile::I16(v) => rice::encode_short(&v), - Tile::I8(v) => rice::encode_byte(&v), - Tile::F32(_) => unreachable!("float is quantized"), - }, - Algo::Hcompress { scale, .. } => { - let mut d = view.rect_i32(plane, x0, y0, tw, th); - hcompress::compress(&mut d, tw, th, *scale) - } - }; - (bytes, None) + let mut d = view.rect_i32(plane, x0, y0, tw, th); + (hcompress::compress(&mut d, tw, th, scale), None) }; let offset = heap.len() as i32; @@ -240,26 +175,12 @@ fn build_tiled(view: &ImageView<'_>, tiling: &Tiling, algo: &Algo) -> FitsResult let mut data = table; data.extend_from_slice(&heap); - let (zcmptype, is_rice, is_hcompress, hscale, hsmooth) = match algo { - Algo::Gzip { .. } => ("GZIP_1", false, false, 0i64, false), - Algo::Rice(_) => ("RICE_1", true, false, 0, false), - Algo::Hcompress { scale, smooth, .. } => { - ("HCOMPRESS_1", false, true, *scale as i64, *smooth) - } - }; - // BYTEPIX for Rice: 4 for quantized floats, else the pixel width. - let bytepix = if quantized { 4 } else { view.bytepix() }; - Ok(Compressed { - zcmptype, zbitpix: view.bitpix(), zaxes: view.axes(), ztiles: grid.ztile, - bytepix, - is_rice, - is_hcompress, - hscale, - hsmooth, + hscale: scale as i64, + hsmooth: smooth, quant: quant.map(|(_, seed)| seed), naxis2: n_tiles, pcount, diff --git a/src/fits/gzip.rs b/src/fits/gzip.rs deleted file mode 100644 index 5175061..0000000 --- a/src/fits/gzip.rs +++ /dev/null @@ -1,58 +0,0 @@ -//! Minimal gzip-stream encoder (RFC 1952) for the `GZIP_1` tile-compression type. -//! -//! `astropy.io.fits` decompresses `GZIP_1` tiles with `zlib.decompress(data, 31)`, i.e. -//! it expects a full gzip member: 10-byte header, raw DEFLATE body, CRC-32 and ISIZE -//! trailer. - -use miniz_oxide::deflate::compress_to_vec; - -/// gzip-compress `data` into one gzip member at DEFLATE effort `level` (0..=9). -pub(super) fn gzip(data: &[u8], level: u8) -> Vec { - let deflated = compress_to_vec(data, level); - - let mut out = Vec::with_capacity(deflated.len() + 18); - out.extend_from_slice(&[ - 0x1f, 0x8b, // magic - 0x08, // CM = deflate - 0x00, // FLG - 0x00, 0x00, 0x00, 0x00, // MTIME = 0 - 0x00, // XFL - 0xff, // OS = unknown - ]); - out.extend_from_slice(&deflated); - out.extend_from_slice(&crc32fast::hash(data).to_le_bytes()); - out.extend_from_slice(&(data.len() as u32).to_le_bytes()); - out -} - -#[cfg(test)] -mod tests { - use super::*; - use miniz_oxide::inflate::decompress_to_vec; - - #[test] - fn roundtrips_through_raw_inflate() { - let src: Vec = (0..4096u32).map(|i| (i * 31) as u8).collect(); - let comp = gzip(&src, 6); - assert_eq!(&comp[..2], &[0x1f, 0x8b]); - // Body between the 10-byte header and the 8-byte trailer is raw DEFLATE. - let body = &comp[10..comp.len() - 8]; - assert_eq!(decompress_to_vec(body).unwrap(), src); - let isize_le = &comp[comp.len() - 4..]; - assert_eq!( - u32::from_le_bytes(isize_le.try_into().unwrap()), - src.len() as u32 - ); - } - - #[test] - fn level_zero_stores_and_still_roundtrips() { - let src: Vec = (0..2048u32).map(|i| (i * 7) as u8).collect(); - let stored = gzip(&src, 0); - let best = gzip(&src, 9); - // Level 0 does no compression; level 9 must not be larger. - assert!(best.len() <= stored.len()); - let body = &stored[10..stored.len() - 8]; - assert_eq!(decompress_to_vec(body).unwrap(), src); - } -} diff --git a/src/fits/hdu.rs b/src/fits/hdu.rs index 600d1d8..6156f7e 100644 --- a/src/fits/hdu.rs +++ b/src/fits/hdu.rs @@ -34,27 +34,14 @@ enum Pixels<'a> { F32(&'a [f32]), } -/// One image tile (a single row of one plane) in its FITS-native form. -pub(super) enum Tile { - /// Signed 16-bit (`u16` image, already offset by `-32768`). - I16(Vec), - /// Signed 8-bit (`u8` image reinterpreted). - I8(Vec), - /// 32-bit float values (`f32` image). +/// The image's pixels in planar order (`NAXIS1` fastest, one channel plane after +/// another), as `fitsio_pure::compress` takes them. +pub(super) enum Planar { + U8(Vec), + U16(Vec), F32(Vec), } -impl Tile { - /// FITS-native big-endian bytes for this tile. - pub(super) fn to_be_bytes(&self) -> Vec { - match self { - Tile::I8(v) => v.iter().map(|&x| x as u8).collect(), - Tile::I16(v) => v.iter().flat_map(|x| x.to_be_bytes()).collect(), - Tile::F32(v) => v.iter().flat_map(|x| x.to_be_bytes()).collect(), - } - } -} - impl<'a> ImageView<'a> { pub(super) fn from_ref(img: &'a DynamicImageRef<'_>) -> Self { let (w, h, ch) = (img.width(), img.height(), img.channels() as usize); @@ -149,21 +136,19 @@ impl<'a> ImageView<'a> { }) } - /// A rectangular tile of one plane, row-major, in FITS-native form. `u8` is - /// reinterpreted signed, `u16` is offset by `-32768`, `f32` passes through. - pub(super) fn rect_tile( - &self, - plane: usize, - x0: usize, - y0: usize, - tw: usize, - th: usize, - ) -> Tile { - let idx = self.rect_indices(plane, x0, y0, tw, th); + /// The whole image de-interleaved into planar order, pixel values unchanged. + pub(super) fn planar(&self) -> Planar { + fn deinterleave(p: &[T], ch: usize) -> Vec { + let mut out = Vec::with_capacity(p.len()); + for plane in 0..ch { + out.extend(p[plane..].iter().step_by(ch).copied()); + } + out + } match self.pixels { - Pixels::U8(p) => Tile::I8(idx.map(|i| p[i] as i8).collect()), - Pixels::U16(p) => Tile::I16(idx.map(|i| (p[i] as i32 - 32768) as i16).collect()), - Pixels::F32(p) => Tile::F32(idx.map(|i| p[i]).collect()), + Pixels::U8(p) => Planar::U8(deinterleave(p, self.ch)), + Pixels::U16(p) => Planar::U16(deinterleave(p, self.ch)), + Pixels::F32(p) => Planar::F32(deinterleave(p, self.ch)), } } diff --git a/src/fits/mod.rs b/src/fits/mod.rs index cd7abc4..410164d 100644 --- a/src/fits/mod.rs +++ b/src/fits/mod.rs @@ -65,11 +65,9 @@ mod card; mod compress; mod config; mod datetime; -mod gzip; mod hcompress; mod hdu; mod quantize; -mod rice; use chrono::{DateTime, Utc}; use std::fs::OpenOptions; @@ -81,7 +79,8 @@ use crate::{GenericLineItem, GenericValue, Metadata, EXPOSURE_KEY, FRAMEID_KEY}; use card::Header; use config::Method; -use hdu::{bayer_pattern, colorspace_str, ImageView}; +use fitsio_pure::compress::{compress_image_hdu, TileCompression}; +use hdu::{bayer_pattern, colorspace_str, ImageView, Planar}; pub use config::{ AutoTile, DitherSeed, FitsCompression, FitsCompressionKind, FixedTile, Gzip, Hcompress, @@ -110,6 +109,9 @@ pub enum FitsError { /// A tile specification could not be applied to the image. #[error("invalid tile specification: {0}")] InvalidTiling(String), + /// `fitsio-pure` could not tile-compress the image. + #[error("tile compression failed: {0}")] + Compression(String), } /// `Result` alias for [`FitsError`]. @@ -226,7 +228,18 @@ fn write_one( if lead_primary { sink.write_all(&primary_empty())?; } - write_compressed(view, meta, method, &mut sink)?; + match method { + Method::Hcompress { + tiling, + scale, + smooth, + quantize, + } => { + let c = compress::hcompress(view, tiling, *scale, *smooth, quantize)?; + write_hcompress(view, meta, &c, &mut sink)?; + } + _ => write_tiled(view, meta, method, &mut sink)?, + } } } Ok(()) @@ -369,14 +382,78 @@ fn write_uncompressed( Ok(()) } -/// A tile-compressed image HDU (`BINTABLE` with `ZIMAGE = T`), streamed to `sink`. -fn write_compressed( +/// A `GZIP_1` or `RICE_1` tile-compressed image HDU (`BINTABLE` with `ZIMAGE = T`), +/// written to `sink`. `fitsio_pure::compress` writes the table and its compression +/// keywords; this crate's own cards follow them, before `END`. +fn write_tiled( view: &ImageView<'_>, meta: &Metadata, method: &Method, sink: &mut W, ) -> FitsResult<()> { - let c = compress::build(view, method)?; + let (tiling, opts, quantize) = match method { + Method::Gzip { tiling, level } => ( + tiling, + TileCompression::gzip().gzip_level(*level).lossless(), + None, + ), + Method::Rice { tiling, quantize } => (tiling, TileCompression::rice(), Some(quantize)), + Method::None | Method::Hcompress { .. } => unreachable!("written elsewhere"), + }; + let grid = compress::resolve_grid(view, tiling, false)?; + let mut opts = opts.tile_dims(&grid.ztile); + if let Some(q) = quantize.filter(|_| view.is_float()) { + let (delta, seed) = compress::global_quant(view, &grid, q); + // One global step in every tile, as `HCOMPRESS_1` uses. + opts = opts.quantize( + fitsio_pure::compress::Quantize::new() + .step(delta) + .seed(fitsio_pure::compress::DitherSeed::Fixed(seed as u16)), + ); + } + let naxes = view.axes(); + let hdu = match view.planar() { + Planar::U8(p) => compress_image_hdu(&naxes, &p, &opts, &[]), + Planar::U16(p) => compress_image_hdu(&naxes, &p, &opts, &[]), + Planar::F32(p) => compress_image_hdu(&naxes, &p, &opts, &[]), + } + .map_err(|e| FitsError::Compression(e.to_string()))?; + + // `fitsio-pure` writes `BZERO`/`BSCALE` for `u16` itself. + let mut h = Header::new(); + if let Some(bits) = view.adc_bits { + h.integer("BITADC", bits as i64, Some("meaningful ADC bits per sample"))?; + } + write_common_cards(&mut h, view, meta.timestamp())?; + write_metadata(&mut h, meta)?; + let ours = h.finish(); + + let theirs = header_cards(&hdu); + let data = &hdu[(theirs.len() + 80).div_ceil(card::BLOCK) * card::BLOCK..]; + let mut header = theirs.to_vec(); + header.extend_from_slice(header_cards(&ours)); + sink.write_all(&card::end_block(header))?; + sink.write_all(data)?; + Ok(()) +} + +/// The 80-byte cards of the header at the start of `bytes`, `END` excluded. +fn header_cards(bytes: &[u8]) -> &[u8] { + let end = bytes + .chunks(80) + .position(|c| c.starts_with(b"END ")) + .expect("a serialised header ends with END"); + &bytes[..end * 80] +} + +/// An `HCOMPRESS_1` tile-compressed image HDU (`BINTABLE` with `ZIMAGE = T`), +/// streamed to `sink`. +fn write_hcompress( + view: &ImageView<'_>, + meta: &Metadata, + c: &compress::Compressed, + sink: &mut W, +) -> FitsResult<()> { let quantized = c.quant.is_some(); let mut h = Header::new(); @@ -402,7 +479,7 @@ fn write_compressed( } h.logical("ZIMAGE", true, Some("tile-compressed image"))?; - h.string("ZCMPTYPE", c.zcmptype, Some("compression algorithm"))?; + h.string("ZCMPTYPE", "HCOMPRESS_1", Some("compression algorithm"))?; h.integer("ZBITPIX", c.zbitpix, Some("data type of original image"))?; h.integer("ZNAXIS", c.zaxes.len() as i64, None)?; for (i, &n) in c.zaxes.iter().enumerate() { @@ -411,18 +488,10 @@ fn write_compressed( for (i, &n) in c.ztiles.iter().enumerate() { h.integer(&format!("ZTILE{}", i + 1), n as i64, None)?; } - if c.is_rice { - h.string("ZNAME1", "BLOCKSIZE", None)?; - h.integer("ZVAL1", 32, None)?; - h.string("ZNAME2", "BYTEPIX", None)?; - h.integer("ZVAL2", c.bytepix as i64, None)?; - } - if c.is_hcompress { - h.string("ZNAME1", "SCALE", Some("HCOMPRESS scale factor"))?; - h.real("ZVAL1", c.hscale as f64, Some("HCOMPRESS scale factor"))?; - h.string("ZNAME2", "SMOOTH", Some("HCOMPRESS smooth option"))?; - h.integer("ZVAL2", c.hsmooth as i64, Some("HCOMPRESS smooth option"))?; - } + h.string("ZNAME1", "SCALE", Some("HCOMPRESS scale factor"))?; + h.real("ZVAL1", c.hscale as f64, Some("HCOMPRESS scale factor"))?; + h.string("ZNAME2", "SMOOTH", Some("HCOMPRESS smooth option"))?; + h.integer("ZVAL2", c.hsmooth as i64, Some("HCOMPRESS smooth option"))?; if let Some(zdither0) = c.quant { h.string( "ZQUANTIZ", diff --git a/src/fits/rice.rs b/src/fits/rice.rs deleted file mode 100644 index 7c21be8..0000000 --- a/src/fits/rice.rs +++ /dev/null @@ -1,403 +0,0 @@ -//! Rice compression for the `RICE_1` tile-compression type. -//! -//! Ported from the encode and decode paths of cfitsio's public-domain `ricecomp.c` -//! (R. White, STScI): 8-bit (`fits_rcomp_byte`), 16-bit (`fits_rcomp_short`) and -//! 32-bit (`fits_rcomp`), the last used for quantized floating-point tiles. The block -//! size is fixed at 32 (`ZVAL1 = BLOCKSIZE = 32`). -//! -//! The decoder is retained alongside the encoder so unit tests can round-trip a tile -//! without a reference reader; it is otherwise unused until a `FitsRead` exists. -#![allow(dead_code)] // `decode_*` are exercised only by the round-trip tests for now. -#![allow(clippy::int_plus_one)] // kept 1:1 with cfitsio `ricecomp.c` - -const NBLOCK: usize = 32; - -const NONZERO_COUNT: [i32; 256] = { - let mut t = [0i32; 256]; - let mut i = 1usize; - while i < 256 { - let mut v = i; - let mut n = 0i32; - while v != 0 { - v >>= 1; - n += 1; - } - t[i] = n; - i += 1; - } - t -}; - -/// Parameters that vary with pixel width. -struct Params { - fsbits: i32, - fsmax: i32, - /// bits for the raw first pixel and for direct (high-entropy) coding. - nbits: i32, - /// `& mask` applied to the block sum before choosing the split (`u16`/`u8`/`u32` - /// cast in C). - psum_mask: u32, - /// truncate a difference to the pixel width (`d as i16 as i32`, etc.). - trunc_bits: u32, -} - -const BYTE: Params = Params { - fsbits: 3, - fsmax: 6, - nbits: 8, - psum_mask: 0xff, - trunc_bits: 8, -}; -const SHORT: Params = Params { - fsbits: 4, - fsmax: 14, - nbits: 16, - psum_mask: 0xffff, - trunc_bits: 16, -}; -const INT: Params = Params { - fsbits: 5, - fsmax: 25, - nbits: 32, - psum_mask: u32::MAX, - trunc_bits: 32, -}; - -/// Rice-encode 8-bit (FITS-native) pixel values. -pub(super) fn encode_byte(a: &[i8]) -> Vec { - encode(&a.iter().map(|&x| x as i32).collect::>(), &BYTE) -} - -/// Rice-encode 16-bit (FITS-native) pixel values. -pub(super) fn encode_short(a: &[i16]) -> Vec { - encode(&a.iter().map(|&x| x as i32).collect::>(), &SHORT) -} - -/// Rice-encode 32-bit values (quantized floating-point tiles). -pub(super) fn encode_int(a: &[i32]) -> Vec { - encode(a, &INT) -} - -/// Rice-decode into 8-bit values. -pub(super) fn decode_byte(c: &[u8], nx: usize) -> Vec { - decode(c, nx, &BYTE).into_iter().map(|v| v as u8).collect() -} - -/// Rice-decode into 16-bit values. -pub(super) fn decode_short(c: &[u8], nx: usize) -> Vec { - decode(c, nx, &SHORT) - .into_iter() - .map(|v| v as u16) - .collect() -} - -/// Rice-decode into 32-bit values. -pub(super) fn decode_int(c: &[u8], nx: usize) -> Vec { - decode(c, nx, &INT).into_iter().map(|v| v as i32).collect() -} - -/// Truncate `d` to `bits` low bits, sign-extended back to `i32` (C's `(short) d` etc.). -fn trunc(d: i32, bits: u32) -> i32 { - if bits >= 32 { - d - } else { - let sh = 32 - bits; - (d << sh) >> sh - } -} - -fn mask(n: i32) -> u32 { - if n <= 0 { - 0 - } else if n >= 32 { - u32::MAX - } else { - (1u32 << n) - 1 - } -} - -/// `x << k`, yielding 0 when `k >= 32` (C's `int` shift wraps; the callers only care -/// about the low 8 bits they subsequently mask). -fn shl(x: u32, k: i32) -> u32 { - if !(0..32).contains(&k) { - 0 - } else { - x << k - } -} - -struct BitWriter { - buf: Vec, - acc: u32, - free: i32, -} - -impl BitWriter { - fn new() -> Self { - Self { - buf: Vec::new(), - acc: 0, - free: 8, - } - } - - /// `output_nbits` from cfitsio (`n <= 32`). - fn put(&mut self, bits: u32, mut n: i32) { - if self.free + n > 32 { - // Large n: flush the top `free` bits first (0 < free <= 8). - self.acc = shl(self.acc, self.free); - self.acc |= (bits >> (n - self.free)) & mask(self.free); - self.buf.push((self.acc & 0xff) as u8); - n -= self.free; - self.free = 8; - } - self.acc = shl(self.acc, n); - self.acc |= bits & mask(n); - self.free -= n; - while self.free <= 0 { - self.buf - .push((self.acc.wrapping_shr((-self.free) as u32) & 0xff) as u8); - self.free += 8; - } - } - - fn done(&mut self) { - if self.free < 8 { - self.buf.push((shl(self.acc, self.free) & 0xff) as u8); - } - } -} - -fn encode(a: &[i32], p: &Params) -> Vec { - let nx = a.len(); - let mut w = BitWriter::new(); - if nx == 0 { - return w.buf; - } - - w.put(a[0] as u32 & mask(p.nbits), p.nbits); - let mut lastpix = a[0]; - - let bbits = 1i32 << p.fsbits; - let mut diff = [0u32; NBLOCK]; - - let mut i = 0; - while i < nx { - let thisblock = (nx - i).min(NBLOCK); - let mut pixelsum = 0.0f64; - for j in 0..thisblock { - let nextpix = a[i + j]; - let pdiff = trunc(nextpix.wrapping_sub(lastpix), p.trunc_bits); - let shifted = pdiff.wrapping_shl(1); - let mapped = if pdiff < 0 { !shifted } else { shifted } as u32; - diff[j] = mapped; - pixelsum += mapped as f64; - lastpix = nextpix; - } - - let mut dpsum = (pixelsum - (thisblock / 2) as f64 - 1.0) / thisblock as f64; - if dpsum < 0.0 { - dpsum = 0.0; - } - let mut psum = (dpsum as u32 & p.psum_mask) >> 1; - let mut fs = 0i32; - while psum > 0 { - fs += 1; - psum >>= 1; - } - - if fs >= p.fsmax { - w.put((p.fsmax + 1) as u32, p.fsbits); - for &d in &diff[..thisblock] { - w.put(d, bbits); - } - } else if fs == 0 && pixelsum == 0.0 { - w.put(0, p.fsbits); - } else { - w.put((fs + 1) as u32, p.fsbits); - let fsmask = mask(fs); - for &v in &diff[..thisblock] { - let mut top = (v >> fs) as i32; - if w.free >= top + 1 { - w.acc = shl(w.acc, top + 1) | 1; - w.free -= top + 1; - } else { - w.acc = shl(w.acc, w.free); - w.buf.push((w.acc & 0xff) as u8); - top -= w.free; - while top >= 8 { - w.buf.push(0); - top -= 8; - } - w.acc = 1; - w.free = 7 - top; - } - if fs > 0 { - w.acc = shl(w.acc, fs) | (v & fsmask); - w.free -= fs; - while w.free <= 0 { - w.buf - .push((w.acc.wrapping_shr((-w.free) as u32) & 0xff) as u8); - w.free += 8; - } - } - } - } - i += NBLOCK; - } - w.done(); - w.buf -} - -fn decode(c: &[u8], nx: usize, p: &Params) -> Vec { - let mut out = vec![0u32; nx]; - if nx == 0 { - return out; - } - let bbits = 1i32 << p.fsbits; - - let head = (p.nbits / 8) as usize; - let mut lastpix: u32 = 0; - for &byte in &c[..head] { - lastpix = (lastpix << 8) | byte as u32; - } - let mut pos = head; - - let mut b = c[pos] as u32; - pos += 1; - let mut nbits = 8i32; - - let mut i = 0usize; - while i < nx { - nbits -= p.fsbits; - while nbits < 0 { - b = (b << 8) | c[pos] as u32; - pos += 1; - nbits += 8; - } - let fs = (b >> nbits) as i32 - 1; - b &= mask(nbits); - - let imax = (i + NBLOCK).min(nx); - if fs < 0 { - for slot in out.iter_mut().take(imax).skip(i) { - *slot = lastpix; - } - i = imax; - } else if fs == p.fsmax { - while i < imax { - let mut k = bbits - nbits; - let mut d = shl(b, k); - k -= 8; - while k >= 0 { - b = c[pos] as u32; - pos += 1; - d |= shl(b, k); - k -= 8; - } - if nbits > 0 { - b = c[pos] as u32; - pos += 1; - d |= b >> (-k); - b &= mask(nbits); - } else { - b = 0; - } - let d = if d & 1 == 0 { d >> 1 } else { !(d >> 1) }; - lastpix = d.wrapping_add(lastpix); - out[i] = lastpix; - i += 1; - } - } else { - while i < imax { - while b == 0 { - nbits += 8; - b = c[pos] as u32; - pos += 1; - } - let nzero = nbits - NONZERO_COUNT[b as usize]; - nbits -= nzero + 1; - b ^= 1u32 << nbits; - nbits -= fs; - while nbits < 0 { - b = (b << 8) | c[pos] as u32; - pos += 1; - nbits += 8; - } - let d = (shl(nzero as u32, fs)) | (b >> nbits); - b &= mask(nbits); - let d = if d & 1 == 0 { d >> 1 } else { !(d >> 1) }; - lastpix = d.wrapping_add(lastpix); - out[i] = lastpix; - i += 1; - } - } - } - out -} - -#[cfg(test)] -mod tests { - use super::*; - - fn rt_byte(v: &[i8]) { - let dec = decode_byte(&encode_byte(v), v.len()); - let want: Vec = v.iter().map(|&x| x as u8).collect(); - assert_eq!(dec, want, "input {v:?}"); - } - - fn rt_short(v: &[i16]) { - let dec = decode_short(&encode_short(v), v.len()); - let want: Vec = v.iter().map(|&x| x as u16).collect(); - assert_eq!(dec, want, "input {v:?}"); - } - - fn rt_int(v: &[i32]) { - let dec = decode_int(&encode_int(v), v.len()); - assert_eq!(dec, v, "input {v:?}"); - } - - #[test] - fn byte_roundtrips() { - rt_byte(&[]); - rt_byte(&[42]); - rt_byte(&[0i8; 80]); - rt_byte(&(-128..127i8).collect::>()); - rt_byte(&(0..300i32).map(|i| (i * 97) as i8).collect::>()); - } - - #[test] - fn short_roundtrips() { - rt_short(&[]); - rt_short(&[0]); - rt_short(&[7; 1]); - rt_short(&[0i16; 100]); - rt_short(&(0..200i16).collect::>()); - rt_short(&(0..500i32).map(|i| (i * 277) as i16).collect::>()); - rt_short(&[i16::MIN, i16::MAX, 0, -1, 1, i16::MIN, i16::MAX]); - } - - #[test] - fn int_roundtrips() { - rt_int(&[]); - rt_int(&[123_456]); - rt_int(&[0i32; 100]); - rt_int(&(0..200i32).collect::>()); - rt_int( - &(0..500i32) - .map(|i| i.wrapping_mul(1_234_577)) - .collect::>(), - ); - rt_int(&[ - i32::MIN, - i32::MAX, - 0, - -1, - 1, - i32::MIN, - i32::MAX, - -12345, - 67890, - ]); - } -} diff --git a/src/fits/tests.rs b/src/fits/tests.rs index 1cc31ec..669e2ae 100644 --- a/src/fits/tests.rs +++ b/src/fits/tests.rs @@ -154,9 +154,10 @@ fn float_compresses_both_ways() { DynamicImageOwned::from(ImageOwned::from_owned(data, 64, 8, ColorSpace::Gray).unwrap()); let g = GenericImageOwned::new(ts(), Duration::ZERO, img); - // Gzip: lossless raw float bytes, no quantization keywords. + // Gzip: lossless raw float bytes, marked `ZQUANTIZ = 'NONE'` as cfitsio marks them. let gz = g.fits_bytes(Gzip::new()).unwrap(); - assert!(find_card(&gz, "ZQUANTIZ").is_none()); + assert!(find_card(&gz, "ZQUANTIZ").unwrap().contains("'NONE ")); + assert!(find_card(&gz, "ZDITHER0").is_none()); // Rice: quantized, so ZQUANTIZ / ZDITHER0 / ZSCALE column appear. let rc = g.fits_bytes(Rice::new()).unwrap();