From 6e4bdb787e5d9e4ea7fc1c813a10cdfe72261934 Mon Sep 17 00:00:00 2001 From: Jon Clayden Date: Thu, 1 Sep 2016 17:29:22 +0000 Subject: [PATCH] version 0.1.0 --- DESCRIPTION | 23 + MD5 | 61 + NAMESPACE | 29 + R/image.R | 182 + R/nifti.R | 148 + R/xform.R | 119 + R/zzz.R | 4 + README.md | 173 + cleanup | 3 + cleanup.win | 1 + inst/extdata/example.nii.gz | Bin 0 -> 233329 bytes inst/include/RNifti.h | 10 + inst/include/RNiftiAPI.h | 192 + inst/include/lib/NiftiImage.h | 1129 +++++ inst/include/lib/print.h | 15 + inst/include/niftilib/nifti1.h | 1490 ++++++ inst/include/niftilib/nifti1_io.h | 556 +++ inst/include/zlib/zconf.h | 511 ++ inst/include/zlib/zlib.h | 1768 +++++++ inst/include/znzlib/znzlib.h | 122 + man/dumpNifti.Rd | 34 + man/internalImage.Rd | 34 + man/ndim.Rd | 22 + man/pixdim.Rd | 52 + man/readNifti.Rd | 45 + man/retrieveNifti.Rd | 34 + man/updateNifti.Rd | 29 + man/voxelToWorld.Rd | 43 + man/writeNifti.Rd | 37 + man/xform.Rd | 50 + src/Makevars | 7 + src/init.cpp | 37 + src/main.cpp | 134 + src/niftilib/nifti1_io.c | 7523 +++++++++++++++++++++++++++++ src/zlib/adler32.c | 179 + src/zlib/compress.c | 80 + src/zlib/crc32.c | 425 ++ src/zlib/crc32.h | 441 ++ src/zlib/deflate.c | 1967 ++++++++ src/zlib/deflate.h | 346 ++ src/zlib/gzclose.c | 25 + src/zlib/gzguts.h | 209 + src/zlib/gzlib.c | 634 +++ src/zlib/gzread.c | 594 +++ src/zlib/gzwrite.c | 577 +++ src/zlib/infback.c | 640 +++ src/zlib/inffast.c | 340 ++ src/zlib/inffast.h | 11 + src/zlib/inffixed.h | 94 + src/zlib/inflate.c | 1512 ++++++ src/zlib/inflate.h | 122 + src/zlib/inftrees.c | 306 ++ src/zlib/inftrees.h | 62 + src/zlib/trees.c | 1226 +++++ src/zlib/trees.h | 128 + src/zlib/uncompr.c | 59 + src/zlib/zutil.c | 324 ++ src/zlib/zutil.h | 253 + src/znzlib/znzlib.c | 323 ++ tests/testthat.R | 4 + tests/testthat/test-05-nifti.R | 30 + tests/testthat/test-10-xform.R | 21 + 62 files changed, 25549 insertions(+) create mode 100644 DESCRIPTION create mode 100644 MD5 create mode 100644 NAMESPACE create mode 100644 R/image.R create mode 100644 R/nifti.R create mode 100644 R/xform.R create mode 100644 R/zzz.R create mode 100644 README.md create mode 100755 cleanup create mode 100755 cleanup.win create mode 100644 inst/extdata/example.nii.gz create mode 100644 inst/include/RNifti.h create mode 100644 inst/include/RNiftiAPI.h create mode 100644 inst/include/lib/NiftiImage.h create mode 100644 inst/include/lib/print.h create mode 100644 inst/include/niftilib/nifti1.h create mode 100644 inst/include/niftilib/nifti1_io.h create mode 100644 inst/include/zlib/zconf.h create mode 100644 inst/include/zlib/zlib.h create mode 100644 inst/include/znzlib/znzlib.h create mode 100644 man/dumpNifti.Rd create mode 100644 man/internalImage.Rd create mode 100644 man/ndim.Rd create mode 100644 man/pixdim.Rd create mode 100644 man/readNifti.Rd create mode 100644 man/retrieveNifti.Rd create mode 100644 man/updateNifti.Rd create mode 100644 man/voxelToWorld.Rd create mode 100644 man/writeNifti.Rd create mode 100644 man/xform.Rd create mode 100644 src/Makevars create mode 100644 src/init.cpp create mode 100644 src/main.cpp create mode 100644 src/niftilib/nifti1_io.c create mode 100644 src/zlib/adler32.c create mode 100644 src/zlib/compress.c create mode 100644 src/zlib/crc32.c create mode 100644 src/zlib/crc32.h create mode 100644 src/zlib/deflate.c create mode 100644 src/zlib/deflate.h create mode 100644 src/zlib/gzclose.c create mode 100644 src/zlib/gzguts.h create mode 100644 src/zlib/gzlib.c create mode 100644 src/zlib/gzread.c create mode 100644 src/zlib/gzwrite.c create mode 100644 src/zlib/infback.c create mode 100644 src/zlib/inffast.c create mode 100644 src/zlib/inffast.h create mode 100644 src/zlib/inffixed.h create mode 100644 src/zlib/inflate.c create mode 100644 src/zlib/inflate.h create mode 100644 src/zlib/inftrees.c create mode 100644 src/zlib/inftrees.h create mode 100644 src/zlib/trees.c create mode 100644 src/zlib/trees.h create mode 100644 src/zlib/uncompr.c create mode 100644 src/zlib/zutil.c create mode 100644 src/zlib/zutil.h create mode 100644 src/znzlib/znzlib.c create mode 100644 tests/testthat.R create mode 100644 tests/testthat/test-05-nifti.R create mode 100644 tests/testthat/test-10-xform.R diff --git a/DESCRIPTION b/DESCRIPTION new file mode 100644 index 0000000..0078a37 --- /dev/null +++ b/DESCRIPTION @@ -0,0 +1,23 @@ +Package: RNifti +Version: 0.1.0 +Date: 2016-09-01 +Title: Fast R and C++ Access to NIfTI Images +Author: Jon Clayden +Maintainer: Jon Clayden +Imports: Rcpp (>= 0.11.0) +Suggests: testthat (>= 0.11.0) +Enhances: oro.nifti, tractor.base +LinkingTo: Rcpp +Description: Provides very fast access to images stored in the NIfTI-1 file + format , with seamless synchronisation + between compiled C and interpreted R code. Not to be confused with RNiftyReg, + which provides tools for image registration. +License: GPL-2 +URL: https://github.com/jonclayden/RNifti +BugReports: https://github.com/jonclayden/RNifti/issues +Encoding: UTF-8 +RoxygenNote: 5.0.1 +NeedsCompilation: yes +Packaged: 2016-09-01 11:49:57 UTC; jon +Repository: CRAN +Date/Publication: 2016-09-01 17:29:22 diff --git a/MD5 b/MD5 new file mode 100644 index 0000000..4b75a15 --- /dev/null +++ b/MD5 @@ -0,0 +1,61 @@ +fb6b2eadbba2d5e0ea958d3e0a8e45f1 *DESCRIPTION +e20469301709fc7383310d95f9e8ab4e *NAMESPACE +2490b4d109b227186f557977ad659dfa *R/image.R +dc7142a5856b0b84ffc44662cf871530 *R/nifti.R +0081869ffb660272f2ca812018d60958 *R/xform.R +33e5b97691485f83c60e3d5c3f3a2cdc *R/zzz.R +eb8256cd53aa01205304e37eb6dc8a53 *README.md +ccc527aa65600337ed5e3f832c0eb443 *cleanup +e1101581081b97d9032639597016d3d8 *cleanup.win +30c091d208079613a19efc08f87849de *inst/extdata/example.nii.gz +55418f98f35198af3318c4282618872c *inst/include/RNifti.h +00aaa92498f68e61f506224a15ed8a4d *inst/include/RNiftiAPI.h +e407ffd378be4080bee8c1f8076cd051 *inst/include/lib/NiftiImage.h +fa8b37f676aab680816c08451fe7b1bd *inst/include/lib/print.h +a34af6ec4b25ecc1a68459bbb5dc76c9 *inst/include/niftilib/nifti1.h +f7137f566bbb76b092b1274e4ab599fe *inst/include/niftilib/nifti1_io.h +5407d4c937d8f925665f71aad35c12fa *inst/include/zlib/zconf.h +1c128a3b0a0fd84c1224754170ee7756 *inst/include/zlib/zlib.h +6f799f7df2f427678edd3abcc5897ad6 *inst/include/znzlib/znzlib.h +2cfd1772edd6b9dd9274a8bda954bb14 *man/dumpNifti.Rd +2fd178c7fd10f45ef39114cd2000ddef *man/internalImage.Rd +309e4f9d81ae01b7ec5804b16c3da953 *man/ndim.Rd +a9eb96edafa817a296cf79e755cec722 *man/pixdim.Rd +2d86c37391f594e57b951da0d28a841f *man/readNifti.Rd +5cb66c2de80021acfeb35bce9767ff8b *man/retrieveNifti.Rd +1f4522b43df68a13b6699029d31ce8d1 *man/updateNifti.Rd +9825b9a8b44206110f5ae2a1ebcf8ad3 *man/voxelToWorld.Rd +d919580d8145b971a7c9ee71b3c5ca86 *man/writeNifti.Rd +bf143f6ef896f3bff808ba60804ea88a *man/xform.Rd +4339fefce4c27fe7c58ef189cb849ac7 *src/Makevars +a6f806acc64eb9b6b2b53b543f1f8b25 *src/init.cpp +fd7273caae3c89c02d9c84ddeeb9ade0 *src/main.cpp +0914eaaf0fca8668ad668d855c23036c *src/niftilib/nifti1_io.c +ae3bbb54820e1d49fb90cbba222e973f *src/zlib/adler32.c +7a734598f9792fee943b70b6da8d932f *src/zlib/compress.c +1339c92938d2594a6eecfa21c374d1b6 *src/zlib/crc32.c +f28d16b67efecdfafa0d816a7d982124 *src/zlib/crc32.h +cd7826278ce9d9d9ed5abdefef50c3e2 *src/zlib/deflate.c +7ceae74a13201f14c91623116af169c3 *src/zlib/deflate.h +29d02cff161bde3e4e717b25a2ab7050 *src/zlib/gzclose.c +715df37bf53af0dee6d018d0f34836ad *src/zlib/gzguts.h +cb70e50d56c980fb8fd2e2e97bb9cd86 *src/zlib/gzlib.c +62164548c5f9c89dc5e7d8ea382ffd8e *src/zlib/gzread.c +cb95538e53e594b0d8a4bf4ecb2b5659 *src/zlib/gzwrite.c +bdb9cc0c602c951ed5f0557798e15299 *src/zlib/infback.c +9c14c1d95cee9f62465dedea7524c5fb *src/zlib/inffast.c +f3669099d3f571dbc0426401ed5f50e3 *src/zlib/inffast.h +7fa3e91804601b6618c915b76a8dc332 *src/zlib/inffixed.h +46cb3a81ac3fa57789eba65cfecf754d *src/zlib/inflate.c +8f1b05cdf36a269882a955071b140162 *src/zlib/inflate.h +3d0a4fce4b156f064e9be2aef36a7897 *src/zlib/inftrees.c +ec87be89b9bcca8ced80a70f857e823b *src/zlib/inftrees.h +bc195d555c24fecff56af6c06bd55b1d *src/zlib/trees.c +51fdcb3e2ccf60ca13c06920c89296a3 *src/zlib/trees.h +eabe905cdd27f5b935e6378cd0253418 *src/zlib/uncompr.c +fff257bc1656eb60fc585a7dc35f963d *src/zlib/zutil.c +de91a463004fd5b944c3d37eab0c1794 *src/zlib/zutil.h +db1082070d31f780ebd9c051b74adc17 *src/znzlib/znzlib.c +d4a2abbb6217055b8900c8d86ac6aa53 *tests/testthat.R +4b0fe74a7776bec4fa562d998fb06226 *tests/testthat/test-05-nifti.R +67e97715d9000e8325d9f2e38351db0b *tests/testthat/test-10-xform.R diff --git a/NAMESPACE b/NAMESPACE new file mode 100644 index 0000000..ccf1258 --- /dev/null +++ b/NAMESPACE @@ -0,0 +1,29 @@ +# Generated by roxygen2: do not edit by hand + +S3method("dim<-",internalImage) +S3method("pixdim<-",default) +S3method("pixunits<-",default) +S3method(as.array,internalImage) +S3method(dim,internalImage) +S3method(pixdim,default) +S3method(pixunits,default) +S3method(print,niftiHeader) +S3method(print,niftiImage) +export("pixdim<-") +export("pixunits<-") +export("qform<-") +export("sform<-") +export(dumpNifti) +export(ndim) +export(pixdim) +export(pixunits) +export(readNifti) +export(retrieveNifti) +export(updateNifti) +export(voxelToWorld) +export(worldToVoxel) +export(writeNifti) +export(xform) +importFrom(Rcpp,evalCpp) +importFrom(utils,object.size) +useDynLib(RNifti) diff --git a/R/image.R b/R/image.R new file mode 100644 index 0000000..900c8d8 --- /dev/null +++ b/R/image.R @@ -0,0 +1,182 @@ +#' Internal images +#' +#' An internal image is a simple R object with a few attributes including a +#' pointer to an internal C structure, which contains the full image data. They +#' are used in the package for efficiency, but can be converted to a normal +#' R array using the \code{as.array} method. Attributes of these objects should +#' not be changed. +#' +#' @param x An \code{"internalImage"} object. +#' @param value Not used. Changing the dimensions of an internal image is +#' invalid, and will produce an error. +#' @param ... Additional parameters to methods. Currently unused. +#' +#' @author Jon Clayden +#' @aliases internalImage +#' @rdname internalImage +#' @export +dim.internalImage <- function (x) +{ + return (attr(x, "imagedim")) +} + +#' @rdname internalImage +#' @export +"dim<-.internalImage" <- function (x, value) +{ + stop("Dimensions of an internal image cannot be changed") +} + +#' @rdname internalImage +#' @export +as.array.internalImage <- function (x, ...) +{ + return (.Call("pointerToArray", x, PACKAGE="RNifti")) +} + +#' @export +print.niftiImage <- function (x, ...) +{ + dim <- dim(x) + ndim <- length(dim) + pixdim <- attr(x, "pixdim") + pixunits <- attr(x, "pixunits") + + if ("internalImage" %in% class(x)) + cat(paste0("Internal image: \"", x, "\"\n")) + else + cat(paste0("Image array of mode \"", storage.mode(x), "\" (", format(object.size(x),"auto"), ")\n")) + + cat(paste("-", paste(dim,collapse=" x "), ifelse(ndim>2,"voxels\n","pixels\n"))) + + if (!is.null(pixdim)) + { + spaceUnit <- grep("m$", pixunits, perl=TRUE, value=TRUE) + cat(paste("-", paste(signif(pixdim[1:min(3,ndim)],4),collapse=" x "))) + if (length(spaceUnit) > 0) + cat(paste0(" ", spaceUnit[1])) + + if (ndim > 3) + { + timeUnit <- grep("s$", pixunits, perl=TRUE, value=TRUE) + cat(paste(" x", signif(pixdim[4],4))) + if (length(timeUnit) > 0) + cat(paste0(" ", timeUnit[1])) + } + if (ndim > 4) + cat(paste(" x", paste(signif(pixdim[5:ndim],4),collapse=" x "))) + + cat(paste(" per", ifelse(ndim>2,"voxel\n","pixel\n"))) + } +} + +#' Number of dimensions +#' +#' This function is shorthand for \code{length(dim(object))}. +#' +#' @param object An R object. +#' @return The dimensionality of the object. Objects without a \code{dim} +#' attribute will produce zero. +#' +#' @author Jon Clayden +#' @export +ndim <- function (object) +{ + length(dim(object)) +} + +#' Pixel dimensions and units +#' +#' By default, these generic functions return or replace the \code{"pixdim"} +#' and \code{"pixunits"} attributes of their arguments. These represent the +#' physical step size between pixel or voxel centre points, and the spatial and +#' temporal units that they are given in. The former defaults to 1 in each +#' dimension, if there is no attribute. +#' +#' @param object An R object, generally an image. +#' @param value Numeric vector of pixel dimensions along each axis, or +#' character vector of abbreviated units. For dimensions, a scalar +#' \code{value} will be recycled if necessary. +#' @return \code{pixdim} returns a numeric vector of pixel dimensions. +#' \code{pixunits} returns a character vector of length up to two, giving the +#' spatial and temporal unit names. +#' +#' @author Jon Clayden +#' @export +pixdim <- function (object) +{ + UseMethod("pixdim") +} + +#' @rdname pixdim +#' @export +pixdim.default <- function (object) +{ + if (!is.null(attr(object, "pixdim"))) + return (attr(object, "pixdim")) + else if (!is.null(dim(object))) + return (rep(1, length(dim(object)))) + else + return (1) +} + +#' @rdname pixdim +#' @export +"pixdim<-" <- function (object, value) +{ + UseMethod("pixdim<-") +} + +#' @rdname pixdim +#' @export +"pixdim<-.default" <- function (object, value) +{ + if ("internalImage" %in% class(object)) + stop("Pixel dimensions of an internal image cannot be changed") + + if (is.numeric(value)) + { + if (length(value) == ndim(object)) + attr(object, "pixdim") <- value + else if (length(value) == 1) + attr(object, "pixdim") <- rep(value, ndim(object)) + } + return (object) +} + +#' @rdname pixdim +#' @export +pixunits <- function (object) +{ + UseMethod("pixunits") +} + +#' @rdname pixdim +#' @export +pixunits.default <- function (object) +{ + if (!is.null(attr(object, "pixunits"))) + return (attr(object, "pixunits")) + else + return ("Unknown") +} + +#' @rdname pixdim +#' @export +"pixunits<-" <- function (object, value) +{ + UseMethod("pixunits<-") +} + +#' @rdname pixdim +#' @export +"pixunits<-.default" <- function (object, value) +{ + if ("internalImage" %in% class(object)) + stop("Pixel units of an internal image cannot be changed") + + if (is.character(value)) + attr(object, "pixunits") <- value + + return (object) +} diff --git a/R/nifti.R b/R/nifti.R new file mode 100644 index 0000000..babda8e --- /dev/null +++ b/R/nifti.R @@ -0,0 +1,148 @@ +#' Read a NIfTI-1 format file +#' +#' This function reads one or more NIfTI-1 files into R, using the standard +#' NIfTI-1 C library. +#' +#' @param file A character vector of file names. +#' @param internal Logical value. If \code{FALSE} (the default), an array +#' of class \code{"niftiImage"}, containing the image pixel or voxel values, +#' will be returned. If \code{TRUE}, the return value will be an object of +#' class \code{"internalImage"}, which contains only minimal metadata about +#' the image. Either way, the return value has an attribute which points to a +#' C data structure containing the full image. +#' @return An array or internal image, with class \code{"niftiImage"}, and +#' possibly also \code{"internalImage"}. +#' +#' @note If the \code{internal} argument is \code{FALSE} (the default), the +#' data type of the image pointer will be set to match one of R's native +#' numeric data types, i.e., 32-bit signed integer or 64-bit double-precision +#' floating-point. In these circumstances the data type reported by the +#' \code{\link{dumpNifti}} function will therefore not, in general, match +#' the storage type used in the file. See also the \code{datatype} argument +#' to \code{\link{writeNifti}}. +#' +#' @author Jon Clayden +#' @seealso \code{\link{writeNifti}} +#' @references The NIfTI-1 standard (\url{http://nifti.nimh.nih.gov/nifti-1}). +#' @export +readNifti <- function (file, internal = FALSE) +{ + if (!is.character(file)) + stop("File name(s) must be specified in a character vector") + if (length(file) == 0) + stop("File name vector is empty") + else if (length(file) > 1) + lapply(file, function(f) .Call("readNifti", path.expand(f), internal, PACKAGE="RNifti")) + else + .Call("readNifti", path.expand(file), internal, PACKAGE="RNifti") +} + +#' Write a NIfTI-1 format file +#' +#' This function writes an image to NIfTI-1 format, using the standard NIfTI-1 +#' C library. +#' +#' @param image An image, in any acceptable form (see +#' \code{\link{retrieveNifti}}). +#' @param file A character string containing a file name. +#' @param template An optional template object to derive NIfTI-1 properties +#' from. Passed to \code{\link{updateNifti}} if \code{image} is an array. +#' @param datatype The NIfTI datatype to use when writing the data out. The +#' default, \code{"auto"} uses the R type or, for internal images, the +#' original datatype. Other possibilities are \code{"float"}, \code{"int16"}, +#' etc., which may be preferred to reduce file size. However, no checks are +#' done to ensure that the coercion maintains precision. +#' +#' @author Jon Clayden +#' @seealso \code{\link{readNifti}}, \code{\link{updateNifti}} +#' @references The NIfTI-1 standard (\url{http://nifti.nimh.nih.gov/nifti-1}). +#' @export +writeNifti <- function (image, file, template = NULL, datatype = "auto") +{ + if (is.array(image) && !is.null(template)) + image <- updateNifti(image, template) + + invisible(.Call("writeNifti", image, file, tolower(datatype), PACKAGE="RNifti")) +} + +#' Obtain an internal NIfTI representation of an object +#' +#' This function converts filenames, arrays and other image classes into an +#' object of class \code{"internalImage"}. +#' +#' If the \code{object} has an internal NIfTI pointer, that will be retrieved +#' directly. Otherwise, if it is a string, it will be taken to be a filename. +#' If it looks like a \code{"nifti"} object (from package \code{oro.nifti}), +#' or an \code{"MriImage"} object (from package \code{tractor.base}), a +#' conversion will be attempted. A list will be assumed to be of the form +#' produced by \code{\link{dumpNifti}}. Finally, a numeric array or matrix +#' will be converted using default image parameters. +#' +#' @param object Any suitable object (see Details). +#' @return An internal image. +#' +#' @author Jon Clayden +#' @seealso \code{\link{readNifti}}, \code{\link{updateNifti}} +#' @export +retrieveNifti <- function (object) +{ + .Call("readNifti", object, TRUE, PACKAGE="RNifti") +} + +#' Update an internal NIfTI-1 object using a template +#' +#' This function adds or updates the internal NIfTI-1 object for an array, +#' using metadata from the template. The dimensions and, if available, pixel +#' dimensions, from the \code{image} will replace those from the template. +#' +#' @param image A numeric array. +#' @param template An image, in any acceptable form (see +#' \code{\link{retrieveNifti}}), or a named list of NIfTI-1 properties like +#' that produced by \code{\link{dumpNifti}}. The default of \code{NULL} will +#' have no effect. +#' @return A copy of the original \code{image}, with its internal image +#' attribute set or updated appropriately. +#' +#' @author Jon Clayden +#' @export +updateNifti <- function (image, template = NULL) +{ + .Call("updateNifti", image, template, PACKAGE="RNifti") +} + +#' Dump the contents of an internal NIfTI-1 object +#' +#' This function extracts the contents of an internal NIfTI-1 object into an R +#' list. No processing is done to the elements. +#' +#' @param image An image, in any acceptable form (see +#' \code{\link{retrieveNifti}}). +#' @param x A \code{"niftiHeader"} object. +#' @param ... Ignored. +#' @return For \code{dumpNifti}, a list of class \code{"niftiHeader"}, with +#' named components corresponding to the elements in a raw NIfTI-1 file. +#' +#' @author Jon Clayden +#' @references The NIfTI-1 standard (\url{http://nifti.nimh.nih.gov/nifti-1}). +#' @export +dumpNifti <- function (image) +{ + .Call("dumpNifti", image, PACKAGE="RNifti") +} + +#' @rdname dumpNifti +#' @export +print.niftiHeader <- function (x, ...) +{ + cat("NIfTI-1 header\n") + widths <- nchar(names(x), "width") + maxWidth <- max(widths) + + for (i in seq_along(widths)) + cat(paste0(paste(rep(" ",maxWidth-widths[i]),collapse=""), names(x)[i], ": ", paste(format(x[[i]],trim=TRUE),collapse=" "), "\n")) +} + +rescaleNifti <- function (image, scales) +{ + .Call("rescaleImage", image, scales, PACKAGE="RNifti") +} diff --git a/R/xform.R b/R/xform.R new file mode 100644 index 0000000..8c654b2 --- /dev/null +++ b/R/xform.R @@ -0,0 +1,119 @@ +#' Obtain or replace the ``xform'' transforms for an image +#' +#' These functions convert the ``qform'' or ``sform'' information in a NIfTI +#' header to or from a corresponding affine matrix. These two ``xform'' +#' mechanisms are defined by the NIfTI standard, and may both be in use in a +#' particular image header. +#' +#' @param image,x An image, in any acceptable form (see +#' \code{\link{retrieveNifti}}). +#' @param useQuaternionFirst A single logical value. If \code{TRUE}, the +#' ``qform'' matrix will be used first, if it is defined; otherwise the +#' ``sform'' matrix will take priority. +#' @param value A new 4x4 qform or sform matrix. If the matrix has a +#' \code{"code"} attribute, the appropriate qform or sform code is also set. +#' @return A affine matrix corresponding to the ``qform'' or ``sform'' +#' information in the image header. This is a plain matrix, which does not +#' have the \code{"affine"} class or \code{source} and \code{target} +#' attributes. +#' +#' @note The qform and sform replacement functions are for advanced users only. +#' Modifying the transforms without knowing what you're doing is usually +#' unwise, as you can make the image object inconsistent. +#' +#' @author Jon Clayden +#' @references The NIfTI-1 standard (\url{http://nifti.nimh.nih.gov/nifti-1}) +#' is the definitive reference on ``xform'' conventions. +#' @export +xform <- function (image, useQuaternionFirst = TRUE) +{ + return (.Call("getXform", image, isTRUE(useQuaternionFirst), PACKAGE="RNifti")) +} + +#' @rdname xform +#' @export +"qform<-" <- function (x, value) +{ + return (.Call("setXform", x, value, TRUE, PACKAGE="RNifti")) +} + +#' @rdname xform +#' @export +"sform<-" <- function (x, value) +{ + return (.Call("setXform", x, value, FALSE, PACKAGE="RNifti")) +} + +#' Transform points between voxel and ``world'' coordinates +#' +#' These functions are used to transform points from dimensionless pixel or +#' voxel coordinates to ``real-world'' coordinates, typically in millimetres, +#' and back. Actual pixel units can be obtained using the +#' \code{\link{pixunits}} function. +#' +#' @param points A vector giving the coordinates of a point, or a matrix with +#' one point per row. +#' @param image The image in whose space the points are given. +#' @param simple A logical value: if \code{TRUE} then the transformation is +#' performed simply by rescaling the points according to the voxel dimensions +#' recorded in the \code{image}. Otherwise the full xform matrix is used. +#' @param ... Additional arguments to \code{\link{xform}}. +#' @return A vector or matrix of transformed points. +#' +#' @note Voxel coordinates are assumed by these functions to use R's indexing +#' convention, beginning from 1. +#' +#' @author Jon Clayden +#' @seealso \code{\link{xform}}, \code{\link{pixdim}}, \code{\link{pixunits}} +#' @export +voxelToWorld <- function (points, image, simple = FALSE, ...) +{ + if (simple) + { + if (!is.matrix(points)) + points <- matrix(points, nrow=1) + voxelDims <- pixdim(image)[seq_len(ncol(points))] + return (drop(t(apply(points-1, 1, function(x) x*abs(voxelDims))))) + } + else + { + if (!is.matrix(points)) + points <- matrix(points, nrow=1) + affine <- xform(image, ...) + + nDims <- ncol(points) + if (nDims != 3) + stop("Points must be three-dimensional") + + points <- cbind(points-1, 1) + newPoints <- affine %*% t(points) + return (drop(t(newPoints[1:nDims,,drop=FALSE]))) + } +} + +#' @rdname voxelToWorld +#' @export +worldToVoxel <- function (points, image, simple = FALSE, ...) +{ + if (simple) + { + if (!is.matrix(points)) + points <- matrix(points, nrow=1) + voxelDims <- pixdim(image)[seq_len(ncol(points))] + return (drop(t(apply(points, 1, function(x) x/abs(voxelDims)) + 1))) + } + else + { + if (!is.matrix(points)) + points <- matrix(points, nrow=1) + affine <- solve(xform(image, ...)) + + nDims <- ncol(points) + if (nDims != 3) + stop("Points must be three-dimensional") + + points <- cbind(points, 1) + newPoints <- affine %*% t(points) + 1 + return (drop(t(newPoints[1:nDims,,drop=FALSE]))) + } +} diff --git a/R/zzz.R b/R/zzz.R new file mode 100644 index 0000000..bdb3d44 --- /dev/null +++ b/R/zzz.R @@ -0,0 +1,4 @@ +#' @importFrom Rcpp evalCpp +#' @importFrom utils object.size +#' @useDynLib RNifti +NULL diff --git a/README.md b/README.md new file mode 100644 index 0000000..c03b545 --- /dev/null +++ b/README.md @@ -0,0 +1,173 @@ +# RNifti: Fast R and C++ Access to NIfTI Images + +The [NIfTI-1 format](http://nifti.nimh.nih.gov/nifti-1) is a popular file format for storing medical imaging data, widely used in medical research and related fields. Conceptually, a NIfTI-1 file incorporates multidimensional numeric data, like an R `array`, but with additional metadata describing the real-space resolution of the image, the physical orientation of the image, and how the image should be interpreted. + +There are several packages available for reading and writing NIfTI-1 files in R, and these are summarised in the [Medical Imaging task view](https://cran.r-project.org/web/views/MedicalImaging.html). However, `RNifti` is distinguished by its + +- [extremely strong performance](#performance), in terms of speed; +- [C/C++ API](#api), allowing access to NIfTI images even in compiled code in other packages; and +- modest dependencies, consisting of only R itself and the very widely-used [Rcpp](https://cran.r-project.org/package=Rcpp) C++ wrapper library. + +The latest development version of the package can always be installed from GitHub using the `devtools` package. + +```r +## install.packages("devtools") +devtools::install_github("jonclayden/RNifti") +``` + +## Usage + +The primary role of `RNifti` is in reading and writing NIfTI-1 files, either `gzip`-compressed or uncompressed, and providing access to image data and metadata. An image may be read into R using the `readNifti` function. + +```r +library(RNifti) +image <- readNifti(system.file("extdata", "example.nii.gz", package="RNifti")) +``` + +This image is an R array with some additional attributes containing information such as its dimensions and the size of its pixels (or voxels, in this case, since it is a 3D image). There are auxiliary functions for extracting this information: the standard `dim()`, plus `pixdim()` and `pixunits()`. + +```r +dim(image) +# [1] 96 96 60 + +pixdim(image) +# [1] 2.5 2.5 2.5 + +pixunits(image) +# [1] "mm" "s" +``` + +So this image is of size 96 x 96 x 60 voxels, with each voxel representing 2.5 x 2.5 x 2.5 mm in real space. (The temporal unit, seconds here, only applies to the fourth dimension, if it is present.) Replacement versions of the latter functions are also available, for modifying the metadata. + +A fuller list of the raw metadata stored in the file can be obtained using the `dumpNifti` function. + +```r +dumpNifti(image) +# NIfTI-1 header +# sizeof_hdr: 348 +# dim_info: 0 +# dim: 3 96 96 60 1 1 1 1 +# intent_p1: 0 +# intent_p2: 0 +# intent_p3: 0 +# intent_code: 0 +# datatype: 64 +# bitpix: 64 +# slice_start: 0 +# pixdim: -1.0 2.5 2.5 2.5 0.0 0.0 0.0 0.0 +# vox_offset: 352 +# scl_slope: 1 +# scl_inter: 0 +# slice_end: 0 +# slice_code: 0 +# xyzt_units: 10 +# cal_max: 2503 +# cal_min: 0 +# slice_duration: 0 +# toffset: 0 +# descrip: FSL5.0 +# aux_file: +# qform_code: 2 +# sform_code: 2 +# quatern_b: 0 +# quatern_c: 1 +# quatern_d: 0 +# qoffset_x: 122.0339 +# qoffset_y: -95.18523 +# qoffset_z: -55.03814 +# srow_x: -2.5000 0.0000 0.0000 122.0339 +# srow_y: 0.00000 2.50000 0.00000 -95.18523 +# srow_z: 0.00000 0.00000 2.50000 -55.03814 +# intent_name: +# magic: n+1 +``` + +Advanced users who know the NIfTI format well may want to alter elements of this metadata directly, and the `updateNifti` function provides a mechanism for this, either by passing a second, "template" image, or by providing lists with elements named as above, as in + +```r +image <- updateNifti(image, list(intent_code=1L)) +``` + +An image can be written back to NIfTI-1 format using the `writeNifti` function. + +```r +writeNifti(image, "file.nii.gz") +``` + +## Performance + +The `RNifti` package uses the robust NIfTI-1 reference implementation, which is written in C, to read and write NIfTI files. It also uses the standard NIfTI-1 data structure as its canonical representation of a file in memory. Together, these make the package extremely fast, as the following benchmark against packages [`AnalyzeFMRI`](https://cran.r-project.org/package=AnalyzeFMRI), [`ANTsR`](https://github.com/stnava/ANTsR), [`neuroim`](https://cran.r-project.org/package=neuroim), [`oro.nifti`](https://cran.r-project.org/package=oro.nifti) and [`tractor.base`](https://cran.r-project.org/package=tractor.base) shows. + +```r +installed.packages()[c("AnalyzeFMRI","ANTsR","neuroim","oro.nifti","RNifti", + "tractor.base"), "Version"] +# AnalyzeFMRI ANTsR neuroim oro.nifti RNifti tractor.base +# "1.1-16" "0.3.3" "0.0.6" "0.5.5.2" "0.1.0" "3.0.5" + +library(microbenchmark) +microbenchmark(AnalyzeFMRI::f.read.volume("example.nii"), + ANTsR::antsImageRead("example.nii"), + neuroim::loadVolume("example.nii"), + oro.nifti::readNIfTI("example.nii"), + RNifti::readNifti("example.nii"), + tractor.base::readImageFile("example.nii")) +# Output level is not set; defaulting to "Info" +# Unit: milliseconds +# expr min lq mean +# AnalyzeFMRI::f.read.volume("example.nii") 25.532280 27.216641 46.646448 +# ANTsR::antsImageRead("example.nii") 1.805555 2.282496 3.430417 +# neuroim::loadVolume("example.nii") 33.639202 36.367228 87.101533 +# oro.nifti::readNIfTI("example.nii") 45.836130 49.692145 126.697245 +# RNifti::readNifti("example.nii") 1.312822 1.646371 7.239342 +# tractor.base::readImageFile("example.nii") 38.091666 39.628323 48.573645 +# median uq max neval +# 28.486199 31.441231 535.60771 100 +# 2.434518 2.614578 96.20713 100 +# 38.556286 56.650639 2071.82043 100 +# 154.908146 162.407670 494.26035 100 +# 1.970080 3.104831 122.78295 100 +# 40.752468 42.635031 249.59664 100 +``` + +With a median runtime of less than 2 ms, `RNifti` is typically at least ten times as fast as the alternatives to read this image into R. The exception is `ANTsR`, which uses a similar low-level pointer-based arrangement as `RNifti`, and is therefore comparable in speed. However, `ANTsR` has substantial dependencies, which may affect its suitability in some applications. + +## Implementation details + +The package does not fully duplicate the NIfTI-1 structure's contents in R-visible objects. Instead, it passes key metadata back to R, such as the image dimensions and pixel dimensions, and it also passes back the pixel values where they are needed. It also creates an [external pointer](http://r-manuals.flakery.org/R-exts.html#External-pointers-and-weak-references) to the native data structure, which is stored in an attribute. This pointer is dereferenced whenever the object is passed back to the C++ code, thereby avoiding unnecessary duplication and ensuring that all metadata remains intact. The full NIfTI-1 header can be obtained using the `dumpNifti` R function, if it is needed. + +This arrangement is efficient and generally works well, but many R operations strip attributes—in which case the external pointer will be removed. The internal structure will be built again when necessary, but using default metadata. In these cases, if it is important to keep the original metadata, the `updateNifti` function should be called explicitly, with a template object. This reconstructs the NIfTI-1 data structure, using the template as a starting point. + +## API + +It is possible to use the package's NIfTI-handling code in other R packages' compiled code, thereby obviating the need to duplicate the reference implementation. Moreover, `RNifti` provides a C++ wrapper class, `NiftiImage`, which simplifies memory management, supports the package's internal image pointers and persistence, and provides syntactic sugar. A package can use this class by including + +``` +LinkingTo: Rcpp, RNifti +``` + +in its `DESCRIPTION` file, and then including the `RNifti.h` header file. For example, + +```c++ +#include "RNifti.h" + +void myfunction () +{ + NiftiImage image("example.nii.gz"); + // Do something with the image +} +``` + +There are also constructors taking a `SEXP` (i.e., an R object), another `NiftiImage`, or a `nifti_image` structure from the reference implementation. `NiftiImage` objects can be implicitly cast to pointers to `nifti_image` structs, meaning that they can be directly used in calls to the reference implementation's own API. The latter is accessed through the separate `RNiftiAPI.h` header file. + +```c++ +#include "RNifti.h" +#include "RNiftiAPI.h" + +void myfunction (SEXP image_) +{ + NiftiImage image(image_); + const size_t volsize = nifti_get_volsize(image); +} +``` + +(`RNifti` will also have to be added to the `Imports` list in the package's `DESCRIPTION` file, as well as `LinkingTo`.) The `RNiftiAPI.h` header should only be included once per package, since it contains function implementations. Multiple includes will lead to duplicate symbol warnings from your linker. Therefore, if multiple source files require access to the NIfTI-1 reference implementation, it is recommended that the API header be included alone in a separate ".c" or ".cpp" file, while others only include the main `RNifti.h`. diff --git a/cleanup b/cleanup new file mode 100755 index 0000000..6c1bf65 --- /dev/null +++ b/cleanup @@ -0,0 +1,3 @@ +#!/bin/sh + +rm -f src/*.o src/niftilib/*.o src/zlib/*.o src/znzlib/*.o diff --git a/cleanup.win b/cleanup.win new file mode 100755 index 0000000..5970e49 --- /dev/null +++ b/cleanup.win @@ -0,0 +1 @@ +rm -f src/*.o src/niftilib/*.o src/zlib/*.o src/znzlib/*.o diff --git a/inst/extdata/example.nii.gz b/inst/extdata/example.nii.gz new file mode 100644 index 0000000000000000000000000000000000000000..9575dbfc671aa6303c172dab32cd43af87d6eb78 GIT binary patch literal 233329 zcmb@ucT`i`w>GSD1Qh|5Ly?xF96?1yL^>oY3MwK;QRxJT)DVzfLWqhKsmG%N(jp)t zH6XnuQlp2G(2@{JL`r}V0wy7lkmTk4{{G!NzWd#8jXm~1d#pXio@?znpZUyZE{c@{_Oc%*w8{96z9D$ZSZ|IcM^_n z+$xOrQEhN>IvQ8-_}0t@8tQaWC@^I_keGVhTsnRVK2>2Z60`{Wt~0Cuk)}RHNAmsP zNC;K6nbBb+LTC2>+NN!bR@$LJ6ew(?+QNS7=ZB(g5lJ#*o{zy%&z(_YZ8@4eiQC1p zQmaAjZ-u1mhfcjb_8)H@@fG0LqY2S>#M~=Au%=CL5B?oYl?a-S558G(F{x3lY!&i-j9W58W@FY&CDgsH zN>nCwTfgMi%)Mv*%_UMiPq+b3FgL3v4$xkTVRV6#$3MEGaa z$-`*TqmN3EV&UcfeZT?nJN(jqiw(X69E-fTfYfC-=c`)xKm(;su6o7uLd_j)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UPSLR8xGw9PKVwLqfCJ<&%zWg<<{Ts zPfnT1zp=CIX7{F*FpQ3wCgg*fr#udDbZXcY1_QOCtrH1^UR5X=g~*Dcf<& zMSCRF`orc2mJZ`LT1`lk7pd_yPJJ{SEbLsl#(ti%%R#$HFLe-OszQEX-Ro$dwo+Q5 zt9O)a+#C(T9#s=PVeoaIx<)8@RNn>T!55rQQfuR4bnLF)$@cqBHo>xgc|yzmSG%`A z8DW7=B+2ooj}>C&=5w;I9*Ir55sM4S3wiBTq(-L} zGco?p>wh`Dj!9N4Zh!B@Ck{tF%em7BuBMvbB6Tf!2F5na(Q*m77fzQ!R3~C3GK*8z zjKX<+(hG*kRSLVdP8S|Jz==t^ycIZpxyF5Kk`-0b^aM1djX!5sS!Y>YSZ8*fGNmYS z?*d-QT^3Hi^Q#SMtg+h4x)|v&qfFl)GvnUJmM;p`cF#5!{Mu2g5wgcQTodDE$P1K% z42e-#)Gzo;Et4h_11FT(Rm<9!;%nv4(IGJwcboNO<|T)~ESgfe)j5e(7uL#8(!aiA z%_A4$jF6)6dec$vy&7$>g$Mq;41BjskEBnxo|6Q8Le(6~t6a%$Bc3RqEY6#UC6=gF z(h(azod`AQ@e07DcGYD2EmC|Pt7xQQwJ~;O4))&5mhBo1f#HzV>)E%Gi>edMlOb)lof92s3wk}0z@y=Mc}VcHj4 zQllfoVKGexg>ZwhLp43csWom#I0zLyzk>ZzG8~okNr-<9L!s9ze{ek>NU*^^#Q(|D V|94;1P`_B(Xpw#V{+Cn#`Cq={)O7#= literal 0 HcmV?d00001 diff --git a/inst/include/RNifti.h b/inst/include/RNifti.h new file mode 100644 index 0000000..ce18d73 --- /dev/null +++ b/inst/include/RNifti.h @@ -0,0 +1,10 @@ +#ifndef _RNIFTI_H_ +#define _RNIFTI_H_ + +#include "niftilib/nifti1_io.h" + +#ifdef __cplusplus +#include "lib/NiftiImage.h" +#endif + +#endif diff --git a/inst/include/RNiftiAPI.h b/inst/include/RNiftiAPI.h new file mode 100644 index 0000000..f85be83 --- /dev/null +++ b/inst/include/RNiftiAPI.h @@ -0,0 +1,192 @@ +#ifndef _RNIFTI_API_H_ +#define _RNIFTI_API_H_ + +#include + +#include "niftilib/nifti1_io.h" + +#ifdef __cplusplus +extern "C" { +#endif + +nifti_1_header * nifti_make_new_header (const int arg_dims[], int arg_dtype) +{ + static nifti_1_header*(*fun)(const int*, int) = NULL; + if (fun == NULL) + fun = (nifti_1_header*(*)(const int*, int)) R_GetCCallable("RNifti","nii_make_new_header"); + return fun(arg_dims, arg_dtype); +} + +nifti_image * nifti_make_new_nim (const int dims[], int datatype, int data_fill) +{ + static nifti_image*(*fun)(const int*, int, int) = NULL; + if (fun == NULL) + fun = (nifti_image*(*)(const int*, int, int)) R_GetCCallable("RNifti","nii_make_new_nim"); + return fun(dims, datatype, data_fill); +} + +nifti_image * nifti_convert_nhdr2nim (struct nifti_1_header nhdr, const char *fname) +{ + static nifti_image*(*fun)(struct nifti_1_header, const char *) = NULL; + if (fun == NULL) + fun = (nifti_image*(*)(struct nifti_1_header, const char *)) R_GetCCallable("RNifti","nii_convert_nhdr2nim"); + return fun(nhdr, fname); +} + +struct nifti_1_header nifti_convert_nim2nhdr (const nifti_image *nim) +{ + static struct nifti_1_header(*fun)(const nifti_image *) = NULL; + if (fun == NULL) + fun = (struct nifti_1_header(*)(const nifti_image *)) R_GetCCallable("RNifti","nii_convert_nim2nhdr"); + return fun(nim); +} + +nifti_image * nifti_copy_nim_info (const nifti_image *src) +{ + static nifti_image*(*fun)(const nifti_image*) = NULL; + if (fun == NULL) + fun = (nifti_image*(*)(const nifti_image*)) R_GetCCallable("RNifti","nii_copy_nim_info"); + return fun(src); +} + +int nifti_copy_extensions (nifti_image *nim_dest, const nifti_image *nim_src) +{ + static int(*fun)(nifti_image*, const nifti_image*) = NULL; + if (fun == NULL) + fun = (int(*)(nifti_image*, const nifti_image*)) R_GetCCallable("RNifti","nii_copy_extensions"); + return fun(nim_dest, nim_src); +} + +void nifti_image_free (nifti_image *nim) +{ + static void(*fun)(nifti_image*) = NULL; + if (fun == NULL) + fun = (void(*)(nifti_image*)) R_GetCCallable("RNifti","nii_image_free"); + fun(nim); +} + +void nifti_datatype_sizes (int datatype, int *nbyper, int *swapsize) +{ + static void(*fun)(int, int*, int*) = NULL; + if (fun == NULL) + fun = (void(*)(int, int*, int*)) R_GetCCallable("RNifti","nii_datatype_sizes"); + return fun(datatype, nbyper, swapsize); +} + +char const * nifti_datatype_string (int dt) +{ + static char const *(*fun)(int) = NULL; + if (fun == NULL) + fun = (char const *(*)(int)) R_GetCCallable("RNifti","nii_datatype_string"); + return fun(dt); +} + +char const * nifti_units_string (int uu) +{ + static char const *(*fun)(int) = NULL; + if (fun == NULL) + fun = (char const *(*)(int)) R_GetCCallable("RNifti","nii_units_string"); + return fun(uu); +} + +size_t nifti_get_volsize (const nifti_image *nim) +{ + static size_t(*fun)(const nifti_image *) = NULL; + if (fun == NULL) + fun = (size_t(*)(const nifti_image *)) R_GetCCallable("RNifti","nii_get_volsize"); + return fun(nim); +} + +int nifti_update_dims_from_array (nifti_image *nim) +{ + static int(*fun)(nifti_image *) = NULL; + if (fun == NULL) + fun = (int(*)(nifti_image *)) R_GetCCallable("RNifti","nii_update_dims_from_array"); + return fun(nim); +} + +int nifti_set_filenames (nifti_image *nim, const char *prefix, int check, int set_byte_order) +{ + static int(*fun)(nifti_image*, const char*, int, int) = NULL; + if (fun == NULL) + fun = (int(*)(nifti_image*, const char*, int, int)) R_GetCCallable("RNifti","nii_set_filenames"); + return fun(nim, prefix, check, set_byte_order); +} + +nifti_image * nifti_image_read (const char *hname, int read_data) +{ + static nifti_image *(*fun)(const char*, int) = NULL; + if (fun == NULL) + fun = (nifti_image *(*)(const char*, int)) R_GetCCallable("RNifti","nii_image_read"); + return fun(hname, read_data); +} + +void nifti_image_write (nifti_image *nim) +{ + static void(*fun)(nifti_image *) = NULL; + if (fun == NULL) + fun = (void(*)(nifti_image *)) R_GetCCallable("RNifti","nii_image_write"); + fun(nim); +} + +float nifti_mat33_determ (mat33 R) +{ + static float(*fun)(mat33) = NULL; + if (fun == NULL) + fun = (float(*)(mat33)) R_GetCCallable("RNifti","nii_mat33_determ"); + return fun(R); +} + +mat33 nifti_mat33_inverse (mat33 R) +{ + static mat33(*fun)(mat33) = NULL; + if (fun == NULL) + fun = (mat33(*)(mat33)) R_GetCCallable("RNifti","nii_mat33_inverse"); + return fun(R); +} + +mat33 nifti_mat33_mul (mat33 A, mat33 B) +{ + static mat33(*fun)(mat33, mat33) = NULL; + if (fun == NULL) + fun = (mat33(*)(mat33, mat33)) R_GetCCallable("RNifti","nii_mat33_mul"); + return fun(A, B); +} + +mat33 nifti_mat33_polar (mat33 A) +{ + static mat33(*fun)(mat33) = NULL; + if (fun == NULL) + fun = (mat33(*)(mat33)) R_GetCCallable("RNifti","nii_mat33_polar"); + return fun(A); +} + +mat44 nifti_mat44_inverse (mat44 R) +{ + static mat44(*fun)(mat44) = NULL; + if (fun == NULL) + fun = (mat44(*)(mat44)) R_GetCCallable("RNifti","nii_mat44_inverse"); + return fun(R); +} + +void nifti_mat44_to_quatern (mat44 R, float *qb, float *qc, float *qd, float *qx, float *qy, float *qz, float *dx, float *dy, float *dz, float *qfac) +{ + static void(*fun)(mat44, float *, float *, float *, float *, float *, float *, float *, float *, float *, float *) = NULL; + if (fun == NULL) + fun = (void(*)(mat44, float *, float *, float *, float *, float *, float *, float *, float *, float *, float *)) R_GetCCallable("RNifti","nii_mat44_to_quatern"); + fun(R, qb, qc, qd, qx, qy, qz, dx, dy, dz, qfac); +} + +mat44 nifti_quatern_to_mat44 (float qb, float qc, float qd, float qx, float qy, float qz, float dx, float dy, float dz, float qfac) +{ + static mat44(*fun)(float, float, float, float, float, float, float, float, float, float) = NULL; + if (fun == NULL) + fun = (mat44(*)(float, float, float, float, float, float, float, float, float, float)) R_GetCCallable("RNifti","nii_quatern_to_mat44"); + return fun(qb, qc, qd, qx, qy, qz, dx, dy, dz, qfac); +} + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif diff --git a/inst/include/lib/NiftiImage.h b/inst/include/lib/NiftiImage.h new file mode 100644 index 0000000..b9c51ce --- /dev/null +++ b/inst/include/lib/NiftiImage.h @@ -0,0 +1,1129 @@ +#ifndef _NIFTI_IMAGE_H_ +#define _NIFTI_IMAGE_H_ + +#include + +#include "niftilib/nifti1_io.h" + +// Thin wrapper around a C-style nifti_image struct that allows C++-style destruction +class NiftiImage +{ +public: + struct Block + { + const NiftiImage ℑ + const int dimension; + const int index; + + Block (const NiftiImage &image, const int dimension, const int index) + : image(image), dimension(dimension), index(index) + { + if (dimension != image->ndim) + throw std::runtime_error("Blocks must be along the last dimension in the image"); + } + + Block & operator= (const NiftiImage &source) + { + if (source->datatype != image->datatype) + throw std::runtime_error("New data does not have the same datatype as the target block"); + + size_t blockSize = 1; + for (int i=1; idim[i]; + + if (blockSize != source->nvox) + throw std::runtime_error("New data does not have the same size as the target block"); + + blockSize *= image->nbyper; + memcpy(static_cast(image->data) + blockSize*index, source->data, blockSize); + return *this; + } + }; + + static short sexpTypeToNiftiType (const int sexpType) + { + if (sexpType == INTSXP || sexpType == LGLSXP) + return DT_INT32; + else if (sexpType == REALSXP) + return DT_FLOAT64; + else + throw std::runtime_error("Array elements must be numeric"); + } + +protected: + nifti_image *image; + bool persistent; + + void copy (nifti_image * const source); + void copy (const NiftiImage &source); + void copy (const Block &source); + + void initFromNiftiS4 (const Rcpp::RObject &object, const bool copyData = true); + void initFromMriImage (const Rcpp::RObject &object, const bool copyData = true); + void initFromList (const Rcpp::RObject &object); + void initFromArray (const Rcpp::RObject &object, const bool copyData = true); + + void updatePixdim (const std::vector &pixdim); + void setPixunits (const std::vector &pixunits); + +public: + NiftiImage () + : image(NULL), persistent(false) {} + + NiftiImage (const NiftiImage &source) + : persistent(false) + { + this->copy(source); +#ifndef NDEBUG + Rprintf("Creating NiftiImage with pointer %p\n", this->image); +#endif + } + + NiftiImage (nifti_image * const image, const bool copy = false) + : image(image), persistent(false) + { + if (copy) + this->copy(image); +#ifndef NDEBUG + Rprintf("Creating NiftiImage with pointer %p\n", this->image); +#endif + } + + NiftiImage (const std::string &path, const bool readData = true) + { + this->image = nifti_image_read(path.c_str(), readData); + if (this->image == NULL) + throw std::runtime_error("Failed to read image from path " + path); +#ifndef NDEBUG + Rprintf("Creating NiftiImage with pointer %p\n", this->image); +#endif + } + + NiftiImage (const SEXP object, const bool readData = true); + + ~NiftiImage () + { + if (!persistent) + { +#ifndef NDEBUG + Rprintf("Freeing NiftiImage with pointer %p\n", this->image); +#endif + nifti_image_free(image); + } + } + + operator nifti_image* () const { return image; } + + nifti_image * operator-> () const { return image; } + + NiftiImage & operator= (const NiftiImage &source) + { + copy(source); + return *this; + } + + NiftiImage & operator= (const Block &source) + { + copy(source); + return *this; + } + + void setPersistence (const bool persistent) + { + this->persistent = persistent; +#ifndef NDEBUG + if (persistent) + Rprintf("Setting NiftiImage with pointer %p to be persistent\n", this->image); +#endif + } + + bool isNull () const { return (image == NULL); } + bool isPersistent () const { return persistent; } + int nDims () const + { + if (image == NULL) + return 0; + else + return image->ndim; + } + + // Note that this function differs from its R equivalent in only dropping unitary dimensions after the last nonunitary one + NiftiImage & drop () + { + int ndim = image->ndim; + while (image->dim[ndim] < 2) + ndim--; + image->dim[0] = image->ndim = ndim; + + return *this; + } + + void rescale (const std::vector &scales); + void update (const SEXP array); + + mat44 xform (const bool preferQuaternion = true) const; + + const Block slice (const int i) const { return Block(*this, 3, i); } + const Block volume (const int i) const { return Block(*this, 4, i); } + + Block slice (const int i) { return Block(*this, 3, i); } + Block volume (const int i) { return Block(*this, 4, i); } + + void toFile (const std::string fileName, const short datatype) const; + void toFile (const std::string fileName, const std::string &datatype) const; + + Rcpp::RObject toArray () const; + Rcpp::RObject toPointer (const std::string label) const; + Rcpp::RObject toArrayOrPointer (const bool internal, const std::string label) const; + Rcpp::RObject headerToList () const; +}; + +inline void NiftiImage::copy (nifti_image * const source) +{ + if (source != NULL) + { + image = nifti_copy_nim_info(source); + if (source->data != NULL) + { + size_t dataSize = nifti_get_volsize(source); + image->data = calloc(1, dataSize); + memcpy(image->data, source->data, dataSize); + } + } +} + +inline void NiftiImage::copy (const NiftiImage &source) +{ + nifti_image *sourceStruct = source; + copy(sourceStruct); +} + +inline void NiftiImage::copy (const Block &source) +{ + nifti_image *sourceStruct = source.image; + if (sourceStruct != NULL) + { + image = nifti_copy_nim_info(sourceStruct); + image->dim[0] = source.image->dim[0] - 1; + image->dim[source.dimension] = 1; + image->pixdim[source.dimension] = 1.0; + nifti_update_dims_from_array(image); + + if (sourceStruct->data != NULL) + { + size_t blockSize = nifti_get_volsize(image); + image->data = calloc(1, blockSize); + memcpy(image->data, static_cast(source.image->data) + blockSize*source.index, blockSize); + } + } +} + +// Convert an S4 "nifti" object, as defined in the oro.nifti package, to a "nifti_image" struct +inline void NiftiImage::initFromNiftiS4 (const Rcpp::RObject &object, const bool copyData) +{ + nifti_1_header header; + header.sizeof_hdr = 348; + + const std::vector dims = object.slot("dim_"); + for (int i=0; i<8; i++) + header.dim[i] = dims[i]; + + header.intent_p1 = object.slot("intent_p1"); + header.intent_p2 = object.slot("intent_p2"); + header.intent_p3 = object.slot("intent_p3"); + header.intent_code = object.slot("intent_code"); + + header.datatype = object.slot("datatype"); + header.bitpix = object.slot("bitpix"); + + header.slice_start = object.slot("slice_start"); + header.slice_end = object.slot("slice_end"); + header.slice_code = Rcpp::as(object.slot("slice_code")); + header.slice_duration = object.slot("slice_duration"); + + const std::vector pixdims = object.slot("pixdim"); + for (int i=0; i<8; i++) + header.pixdim[i] = pixdims[i]; + header.xyzt_units = Rcpp::as(object.slot("xyzt_units")); + + header.vox_offset = object.slot("vox_offset"); + + header.scl_slope = object.slot("scl_slope"); + header.scl_inter = object.slot("scl_inter"); + header.toffset = object.slot("toffset"); + + header.cal_max = object.slot("cal_max"); + header.cal_min = object.slot("cal_min"); + header.glmax = header.glmin = 0; + + strncpy(header.descrip, Rcpp::as(object.slot("descrip")).c_str(), 79); + header.descrip[79] = '\0'; + strncpy(header.aux_file, Rcpp::as(object.slot("aux_file")).c_str(), 23); + header.aux_file[23] = '\0'; + strncpy(header.intent_name, Rcpp::as(object.slot("intent_name")).c_str(), 15); + header.intent_name[15] = '\0'; + strncpy(header.magic, Rcpp::as(object.slot("magic")).c_str(), 3); + header.magic[3] = '\0'; + + header.qform_code = object.slot("qform_code"); + header.sform_code = object.slot("sform_code"); + + header.quatern_b = object.slot("quatern_b"); + header.quatern_c = object.slot("quatern_c"); + header.quatern_d = object.slot("quatern_d"); + header.qoffset_x = object.slot("qoffset_x"); + header.qoffset_y = object.slot("qoffset_y"); + header.qoffset_z = object.slot("qoffset_z"); + + const std::vector srow_x = object.slot("srow_x"); + const std::vector srow_y = object.slot("srow_y"); + const std::vector srow_z = object.slot("srow_z"); + for (int i=0; i<4; i++) + { + header.srow_x[i] = srow_x[i]; + header.srow_y[i] = srow_y[i]; + header.srow_z[i] = srow_z[i]; + } + + if (header.datatype == DT_UINT8 || header.datatype == DT_INT16 || header.datatype == DT_INT32 || header.datatype == DT_INT8 || header.datatype == DT_UINT16 || header.datatype == DT_UINT32) + header.datatype = DT_INT32; + else if (header.datatype == DT_FLOAT32 || header.datatype == DT_FLOAT64) + header.datatype = DT_FLOAT64; // This assumes that sizeof(double) == 8 + else + throw std::runtime_error("Data type is not supported"); + + this->image = nifti_convert_nhdr2nim(header, NULL); + + const SEXP data = PROTECT(object.slot(".Data")); + if (!copyData || Rf_length(data) <= 1) + this->image->data = NULL; + else + { + const size_t dataSize = nifti_get_volsize(this->image); + this->image->data = calloc(1, dataSize); + if (header.datatype == DT_INT32) + { + Rcpp::IntegerVector intData(data); + std::copy(intData.begin(), intData.end(), static_cast(this->image->data)); + } + else + { + Rcpp::DoubleVector doubleData(data); + std::copy(doubleData.begin(), doubleData.end(), static_cast(this->image->data)); + } + } + UNPROTECT(1); +} + +inline void NiftiImage::initFromMriImage (const Rcpp::RObject &object, const bool copyData) +{ + Rcpp::Reference mriImage(object); + Rcpp::Function getXform = mriImage.field("getXform"); + Rcpp::NumericMatrix xform = getXform(); + + this->image = NULL; + + if (Rf_length(mriImage.field("tags")) > 0) + initFromList(mriImage.field("tags")); + + Rcpp::RObject data = mriImage.field("data"); + if (data.inherits("SparseArray")) + { + Rcpp::Language call("Rcpp::as.array", data); + data = call.eval(); + } + + const short datatype = (Rf_isNull(data) ? DT_INT32 : sexpTypeToNiftiType(data.sexp_type())); + + int dims[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + const std::vector dimVector = mriImage.field("imageDims"); + const int nDims = std::min(7, int(dimVector.size())); + dims[0] = nDims; + size_t nVoxels = 1; + for (int i=0; iimage == NULL) + this->image = nifti_make_new_nim(dims, datatype, FALSE); + else + { + std::copy(dims, dims+8, this->image->dim); + this->image->datatype = datatype; + nifti_datatype_sizes(image->datatype, &image->nbyper, NULL); + } + + if (copyData && !Rf_isNull(data)) + { + // NB: nifti_get_volsize() will not be right here if there were tags + const size_t dataSize = nVoxels * image->nbyper; + this->image->data = calloc(1, dataSize); + if (datatype == DT_INT32) + memcpy(this->image->data, INTEGER(data), dataSize); + else + memcpy(this->image->data, REAL(data), dataSize); + } + else + this->image->data = NULL; + + const std::vector pixdimVector = mriImage.field("voxelDims"); + const int pixdimLength = pixdimVector.size(); + for (int i=0; iimage->pixdim[i+1] = std::abs(pixdimVector[i]); + + const std::vector pixunitsVector = mriImage.field("voxelDimUnits"); + setPixunits(pixunitsVector); + + if (xform.rows() != 4 || xform.cols() != 4) + this->image->qform_code = this->image->sform_code = 0; + else + { + mat44 matrix; + for (int i=0; i<4; i++) + { + for (int j=0; j<4; j++) + matrix.m[i][j] = static_cast(xform(i,j)); + } + + this->image->qto_xyz = matrix; + this->image->qto_ijk = nifti_mat44_inverse(image->qto_xyz); + nifti_mat44_to_quatern(image->qto_xyz, &image->quatern_b, &image->quatern_c, &image->quatern_d, &image->qoffset_x, &image->qoffset_y, &image->qoffset_z, NULL, NULL, NULL, &image->qfac); + + this->image->sto_xyz = matrix; + this->image->sto_ijk = nifti_mat44_inverse(image->sto_xyz); + + this->image->qform_code = this->image->sform_code = 2; + } +} + +template +inline void copyIfPresent (const Rcpp::List &list, const std::set names, const std::string &name, TargetType &target) +{ + if (names.count(name) == 1) + target = Rcpp::as(list[name]); +} + +// Special case for char, because Rcpp tries to be too clever and convert it to a string +template <> +inline void copyIfPresent (const Rcpp::List &list, const std::set names, const std::string &name, char &target) +{ + if (names.count(name) == 1) + target = static_cast(Rcpp::as(list[name])); +} + +inline void NiftiImage::initFromList (const Rcpp::RObject &object) +{ + Rcpp::List list(object); + nifti_1_header *header = nifti_make_new_header(NULL, DT_FLOAT64); + + const Rcpp::CharacterVector _names = list.names(); + std::set names; + for (Rcpp::CharacterVector::const_iterator it=_names.begin(); it!=_names.end(); it++) + names.insert(Rcpp::as(*it)); + + copyIfPresent(list, names, "sizeof_hdr", header->sizeof_hdr); + + copyIfPresent(list, names, "dim_info", header->dim_info); + if (names.count("dim") == 1) + { + std::vector dim = list["dim"]; + for (int i=0; idim[i] = dim[i]; + } + + copyIfPresent(list, names, "intent_p1", header->intent_p1); + copyIfPresent(list, names, "intent_p2", header->intent_p2); + copyIfPresent(list, names, "intent_p3", header->intent_p3); + copyIfPresent(list, names, "intent_code", header->intent_code); + + copyIfPresent(list, names, "datatype", header->datatype); + copyIfPresent(list, names, "bitpix", header->bitpix); + + copyIfPresent(list, names, "slice_start", header->slice_start); + if (names.count("pixdim") == 1) + { + std::vector pixdim = list["pixdim"]; + for (int i=0; ipixdim[i] = pixdim[i]; + } + copyIfPresent(list, names, "vox_offset", header->vox_offset); + copyIfPresent(list, names, "scl_slope", header->scl_slope); + copyIfPresent(list, names, "scl_inter", header->scl_inter); + copyIfPresent(list, names, "slice_end", header->slice_end); + copyIfPresent(list, names, "slice_code", header->slice_code); + copyIfPresent(list, names, "xyzt_units", header->xyzt_units); + copyIfPresent(list, names, "cal_max", header->cal_max); + copyIfPresent(list, names, "cal_min", header->cal_min); + copyIfPresent(list, names, "slice_duration", header->slice_duration); + copyIfPresent(list, names, "toffset", header->toffset); + + if (names.count("descrip") == 1) + strcpy(header->descrip, Rcpp::as(list["descrip"]).substr(0,79).c_str()); + if (names.count("aux_file") == 1) + strcpy(header->aux_file, Rcpp::as(list["aux_file"]).substr(0,23).c_str()); + + copyIfPresent(list, names, "qform_code", header->qform_code); + copyIfPresent(list, names, "sform_code", header->sform_code); + copyIfPresent(list, names, "quatern_b", header->quatern_b); + copyIfPresent(list, names, "quatern_c", header->quatern_c); + copyIfPresent(list, names, "quatern_d", header->quatern_d); + copyIfPresent(list, names, "qoffset_x", header->qoffset_x); + copyIfPresent(list, names, "qoffset_y", header->qoffset_y); + copyIfPresent(list, names, "qoffset_z", header->qoffset_z); + + if (names.count("srow_x") == 1) + { + std::vector srow_x = list["srow_x"]; + for (int i=0; isrow_x[i] = srow_x[i]; + } + if (names.count("srow_y") == 1) + { + std::vector srow_y = list["srow_y"]; + for (int i=0; isrow_y[i] = srow_y[i]; + } + if (names.count("srow_z") == 1) + { + std::vector srow_z = list["srow_z"]; + for (int i=0; isrow_z[i] = srow_z[i]; + } + + if (names.count("intent_name") == 1) + strcpy(header->intent_name, Rcpp::as(list["intent_name"]).substr(0,15).c_str()); + if (names.count("magic") == 1) + strcpy(header->magic, Rcpp::as(list["magic"]).substr(0,3).c_str()); + + this->image = nifti_convert_nhdr2nim(*header, NULL); + this->image->data = NULL; + free(header); +} + +inline void NiftiImage::initFromArray (const Rcpp::RObject &object, const bool copyData) +{ + int dims[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + const std::vector dimVector = object.attr("dim"); + + const int nDims = std::min(7, int(dimVector.size())); + dims[0] = nDims; + for (int i=0; iimage = nifti_make_new_nim(dims, datatype, int(copyData)); + + if (copyData) + { + const size_t dataSize = nifti_get_volsize(image); + if (datatype == DT_INT32) + memcpy(this->image->data, INTEGER(object), dataSize); + else + memcpy(this->image->data, REAL(object), dataSize); + } + else + this->image->data = NULL; + + if (object.hasAttribute("pixdim")) + { + const std::vector pixdimVector = object.attr("pixdim"); + const int pixdimLength = pixdimVector.size(); + for (int i=0; iimage->pixdim[i+1] = pixdimVector[i]; + } + + if (object.hasAttribute("pixunits")) + { + const std::vector pixunitsVector = object.attr("pixunits"); + setPixunits(pixunitsVector); + } +} + +inline NiftiImage::NiftiImage (const SEXP object, const bool readData) + : persistent(false) +{ + Rcpp::RObject imageObject(object); + + if (Rf_isNull(object)) + this->image = NULL; + else if (imageObject.hasAttribute(".nifti_image_ptr")) + { + Rcpp::XPtr imagePtr(SEXP(imageObject.attr(".nifti_image_ptr"))); + this->image = *imagePtr; + this->persistent = true; + + if (imageObject.hasAttribute("dim")) + update(object); + } + else if (Rf_isString(object)) + { + const std::string path = Rcpp::as(object); + this->image = nifti_image_read(path.c_str(), readData); + if (this->image == NULL) + throw std::runtime_error("Failed to read image from path " + path); + } + else if (imageObject.inherits("nifti")) + initFromNiftiS4(imageObject, readData); + else if (imageObject.inherits("MriImage")) + initFromMriImage(imageObject, readData); + else if (Rf_isVectorList(object)) + initFromList(imageObject); + else if (imageObject.hasAttribute("dim")) + initFromArray(imageObject, readData); + else + throw std::runtime_error("Cannot convert object of class \"" + Rcpp::as(imageObject.attr("class")) + "\" to a nifti_image"); + + if (this->image != NULL) + nifti_update_dims_from_array(this->image); + +#ifndef NDEBUG + Rprintf("Creating NiftiImage with pointer %p\n", this->image); +#endif +} + +inline mat33 topLeftCorner (const mat44 &matrix) +{ + mat33 newMatrix; + for (int i=0; i<3; i++) + { + for (int j=0; j<3; j++) + newMatrix.m[i][j] = matrix.m[i][j]; + } + + return newMatrix; +} + +inline void NiftiImage::updatePixdim (const std::vector &pixdim) +{ + const int nDims = image->dim[0]; + const std::vector origPixdim(image->pixdim+1, image->pixdim+4); + + for (int i=1; i<8; i++) + image->pixdim[i] = 0.0; + + const int pixdimLength = pixdim.size(); + for (int i=0; ipixdim[i+1] = pixdim[i]; + + if (!std::equal(origPixdim.begin(), origPixdim.begin() + std::min(3,nDims), pixdim.begin())) + { + mat33 scaleMatrix; + for (int i=0; i<3; i++) + { + for (int j=0; j<3; j++) + { + if (i != j) + scaleMatrix.m[i][j] = 0.0; + else if (i >= nDims) + scaleMatrix.m[i][j] = 1.0; + else + scaleMatrix.m[i][j] = pixdim[i] / origPixdim[i]; + } + } + + if (image->qform_code > 0) + { + mat33 prod = nifti_mat33_mul(scaleMatrix, topLeftCorner(image->qto_xyz)); + for (int i=0; i<3; i++) + { + for (int j=0; j<3; j++) + image->qto_xyz.m[i][j] = prod.m[i][j]; + } + image->qto_ijk = nifti_mat44_inverse(image->qto_xyz); + nifti_mat44_to_quatern(image->qto_xyz, &image->quatern_b, &image->quatern_c, &image->quatern_d, &image->qoffset_x, &image->qoffset_y, &image->qoffset_z, NULL, NULL, NULL, &image->qfac); + } + + if (image->sform_code > 0) + { + mat33 prod = nifti_mat33_mul(scaleMatrix, topLeftCorner(image->sto_xyz)); + for (int i=0; i<3; i++) + { + for (int j=0; j<3; j++) + image->sto_xyz.m[i][j] = prod.m[i][j]; + } + image->sto_ijk = nifti_mat44_inverse(image->sto_xyz); + } + } +} + +inline void NiftiImage::setPixunits (const std::vector &pixunits) +{ + for (int i=0; ixyz_units = NIFTI_UNITS_METER; + else if (pixunits[i] == "mm") + image->xyz_units = NIFTI_UNITS_MM; + else if (pixunits[i] == "um") + image->xyz_units = NIFTI_UNITS_MICRON; + else if (pixunits[i] == "s") + image->time_units = NIFTI_UNITS_SEC; + else if (pixunits[i] == "ms") + image->time_units = NIFTI_UNITS_MSEC; + else if (pixunits[i] == "us") + image->time_units = NIFTI_UNITS_USEC; + else if (pixunits[i] == "Hz") + image->time_units = NIFTI_UNITS_HZ; + else if (pixunits[i] == "ppm") + image->time_units = NIFTI_UNITS_PPM; + else if (pixunits[i] == "rad/s") + image->time_units = NIFTI_UNITS_RADS; + } +} + +inline void NiftiImage::rescale (const std::vector &scales) +{ + std::vector pixdim(image->pixdim+1, image->pixdim+4); + + for (int i=0; idim[i+1] = static_cast(std::floor(image->dim[i+1] * scales[i])); + } + } + + updatePixdim(pixdim); + nifti_update_dims_from_array(image); + + // Data vector is now the wrong size, so drop it + free(image->data); +} + +inline void NiftiImage::update (const SEXP array) +{ + Rcpp::RObject object(array); + if (!object.hasAttribute("dim")) + return; + + for (int i=0; i<8; i++) + image->dim[i] = 0; + const std::vector dimVector = object.attr("dim"); + + const int nDims = std::min(7, int(dimVector.size())); + image->dim[0] = nDims; + for (int i=0; idim[i+1] = dimVector[i]; + + if (object.hasAttribute("pixdim")) + { + const std::vector pixdimVector = object.attr("pixdim"); + updatePixdim(pixdimVector); + } + + if (object.hasAttribute("pixunits")) + { + const std::vector pixunitsVector = object.attr("pixunits"); + setPixunits(pixunitsVector); + } + + // This NIfTI-1 library function clobbers dim[0] if the last dimension is unitary; we undo that here + nifti_update_dims_from_array(image); + image->dim[0] = image->ndim = nDims; + + image->datatype = NiftiImage::sexpTypeToNiftiType(object.sexp_type()); + nifti_datatype_sizes(image->datatype, &image->nbyper, NULL); + + free(image->data); + + const size_t dataSize = nifti_get_volsize(image); + image->data = calloc(1, dataSize); + if (image->datatype == DT_INT32) + memcpy(image->data, INTEGER(object), dataSize); + else + memcpy(image->data, REAL(object), dataSize); +} + +inline mat44 NiftiImage::xform (const bool preferQuaternion) const +{ + if (image == NULL) + { + mat44 matrix; + for (int i=0; i<4; i++) + { + for (int j=0; j<4; j++) + matrix.m[i][j] = 0.0; + } + return matrix; + } + else if (image->qform_code <= 0 && image->sform_code <= 0) + { + // No qform or sform so return RAS matrix (NB: other software may assume differently) + mat44 matrix; + for (int i=0; i<4; i++) + { + for (int j=0; j<4; j++) + matrix.m[i][j] = (i==j ? 1.0 : 0.0); + } + return matrix; + } + else if ((preferQuaternion && image->qform_code > 0) || image->sform_code <= 0) + return image->qto_xyz; + else + return image->sto_xyz; +} + +template +inline TargetType convertValue (SourceType value) +{ + return static_cast(value); +} + +template +inline void convertArray (const SourceType *source, const size_t length, TargetType *target) +{ + std::transform(source, source + length, target, convertValue); +} + +template +inline void changeDatatype (nifti_image *image, const short datatype) +{ + TargetType *data; + const size_t dataSize = image->nvox * sizeof(TargetType); + data = static_cast(calloc(1, dataSize)); + + switch (image->datatype) + { + case DT_UINT8: + convertArray(static_cast(image->data), image->nvox, data); + break; + + case DT_INT16: + convertArray(static_cast(image->data), image->nvox, data); + break; + + case DT_INT32: + convertArray(static_cast(image->data), image->nvox, data); + break; + + case DT_FLOAT32: + convertArray(static_cast(image->data), image->nvox, data); + break; + + case DT_FLOAT64: + convertArray(static_cast(image->data), image->nvox, data); + break; + + case DT_INT8: + convertArray(static_cast(image->data), image->nvox, data); + break; + + case DT_UINT16: + convertArray(static_cast(image->data), image->nvox, data); + break; + + case DT_UINT32: + convertArray(static_cast(image->data), image->nvox, data); + break; + + case DT_INT64: + convertArray(static_cast(image->data), image->nvox, data); + break; + + case DT_UINT64: + convertArray(static_cast(image->data), image->nvox, data); + break; + + default: + throw std::runtime_error("Unsupported data type (" + std::string(nifti_datatype_string(image->datatype)) + ")"); + } + + free(image->data); + image->data = data; + image->datatype = datatype; + nifti_datatype_sizes(datatype, &image->nbyper, &image->swapsize); +} + +inline void NiftiImage::toFile (const std::string fileName, const short datatype) const +{ + // Copy the source image only if the datatype will be changed + NiftiImage imageToWrite(image, datatype != DT_NONE); + + switch (datatype) + { + case DT_NONE: + imageToWrite.setPersistence(true); + break; + + case DT_UINT8: + changeDatatype(imageToWrite, datatype); + break; + + case DT_INT16: + changeDatatype(imageToWrite, datatype); + break; + + case DT_INT32: + changeDatatype(imageToWrite, datatype); + break; + + case DT_FLOAT32: + changeDatatype(imageToWrite, datatype); + break; + + case DT_FLOAT64: + changeDatatype(imageToWrite, datatype); + break; + + case DT_INT8: + changeDatatype(imageToWrite, datatype); + break; + + case DT_UINT16: + changeDatatype(imageToWrite, datatype); + break; + + case DT_UINT32: + changeDatatype(imageToWrite, datatype); + break; + + case DT_INT64: + changeDatatype(imageToWrite, datatype); + break; + + case DT_UINT64: + changeDatatype(imageToWrite, datatype); + break; + + default: + throw std::runtime_error("Unsupported data type (" + std::string(nifti_datatype_string(datatype)) + ")"); + } + + const int status = nifti_set_filenames(imageToWrite, fileName.c_str(), false, true); + if (status != 0) + throw std::runtime_error("Failed to set filenames for NIfTI object"); + nifti_image_write(imageToWrite); +} + +inline void NiftiImage::toFile (const std::string fileName, const std::string &datatype) const +{ + static std::map datatypeCodes; + if (datatypeCodes.empty()) + { + datatypeCodes["auto"] = DT_NONE; + datatypeCodes["none"] = DT_NONE; + datatypeCodes["unknown"] = DT_NONE; + datatypeCodes["uint8"] = DT_UINT8; + datatypeCodes["char"] = DT_UINT8; + datatypeCodes["int16"] = DT_INT16; + datatypeCodes["short"] = DT_INT16; + datatypeCodes["int32"] = DT_INT32; + datatypeCodes["int"] = DT_INT32; + datatypeCodes["float32"] = DT_FLOAT32; + datatypeCodes["float"] = DT_FLOAT32; + datatypeCodes["float64"] = DT_FLOAT64; + datatypeCodes["double"] = DT_FLOAT64; + datatypeCodes["int8"] = DT_INT8; + datatypeCodes["uint16"] = DT_UINT16; + datatypeCodes["uint32"] = DT_UINT32; + datatypeCodes["int64"] = DT_INT64; + datatypeCodes["uint64"] = DT_UINT64; + } + + if (datatypeCodes.count(datatype) == 0) + { + std::ostringstream message; + message << "Datatype \"" << datatype << "\" is not valid"; + Rf_warning(message.str().c_str()); + toFile(fileName, DT_NONE); + } + else + toFile(fileName, datatypeCodes[datatype]); +} + +template +inline Rcpp::RObject imageDataToArray (const nifti_image *source) +{ + if (source == NULL) + return Rcpp::RObject(); + else + { + SourceType *original = static_cast(source->data); + Rcpp::Vector array(static_cast(source->nvox)); + + if (SexpType == INTSXP || SexpType == LGLSXP) + std::transform(original, original + source->nvox, array.begin(), convertValue); + else if (SexpType == REALSXP) + std::transform(original, original + source->nvox, array.begin(), convertValue); + else + throw std::runtime_error("Only numeric arrays can be created"); + + return array; + } +} + +inline void finaliseNiftiImage (SEXP xptr) +{ + NiftiImage *object = (NiftiImage *) R_ExternalPtrAddr(xptr); + object->setPersistence(false); + delete object; + R_ClearExternalPtr(xptr); +} + +inline void addAttributes (Rcpp::RObject &object, nifti_image *source, const bool realDim = true) +{ + const int nDims = source->dim[0]; + Rcpp::IntegerVector dim(source->dim+1, source->dim+1+nDims); + + if (realDim) + object.attr("dim") = dim; + else + object.attr("imagedim") = dim; + + Rcpp::DoubleVector pixdim(source->pixdim+1, source->pixdim+1+nDims); + object.attr("pixdim") = pixdim; + + if (source->xyz_units == NIFTI_UNITS_UNKNOWN && source->time_units == NIFTI_UNITS_UNKNOWN) + object.attr("pixunits") = "Unknown"; + else + { + Rcpp::CharacterVector pixunits(2); + pixunits[0] = nifti_units_string(source->xyz_units); + pixunits[1] = nifti_units_string(source->time_units); + object.attr("pixunits") = pixunits; + } + + NiftiImage *wrappedSource = new NiftiImage(source, true); + wrappedSource->setPersistence(true); + Rcpp::XPtr xptr(wrappedSource); + R_RegisterCFinalizerEx(SEXP(xptr), &finaliseNiftiImage, FALSE); + object.attr(".nifti_image_ptr") = xptr; +} + +inline Rcpp::RObject NiftiImage::toArray () const +{ + Rcpp::RObject array; + + if (this->isNull()) + return array; + + switch (image->datatype) + { + case DT_UINT8: + array = imageDataToArray(image); + break; + + case DT_INT16: + array = imageDataToArray(image); + break; + + case DT_INT32: + array = imageDataToArray(image); + break; + + case DT_FLOAT32: + array = imageDataToArray(image); + break; + + case DT_FLOAT64: + array = imageDataToArray(image); + break; + + case DT_INT8: + array = imageDataToArray(image); + break; + + case DT_UINT16: + array = imageDataToArray(image); + break; + + case DT_UINT32: + array = imageDataToArray(image); + break; + + case DT_INT64: + array = imageDataToArray(image); + break; + + case DT_UINT64: + array = imageDataToArray(image); + break; + + default: + throw std::runtime_error("Unsupported data type (" + std::string(nifti_datatype_string(image->datatype)) + ")"); + } + + addAttributes(array, image); + const Rcpp::IntegerVector dim = array.attr("dim"); + array.attr("class") = Rcpp::CharacterVector::create("niftiImage"); + return array; +} + +inline Rcpp::RObject NiftiImage::toPointer (const std::string label) const +{ + if (this->isNull()) + return Rcpp::RObject(); + else + { + Rcpp::RObject string = Rcpp::wrap(label); + addAttributes(string, image, false); + string.attr("class") = Rcpp::CharacterVector::create("internalImage", "niftiImage"); + return string; + } +} + +inline Rcpp::RObject NiftiImage::toArrayOrPointer (const bool internal, const std::string label) const +{ + return (internal ? toPointer(label) : toArray()); +} + +inline Rcpp::RObject NiftiImage::headerToList () const +{ + if (this->image == NULL) + return Rcpp::RObject(); + + nifti_1_header header = nifti_convert_nim2nhdr(this->image); + Rcpp::List result; + + result["sizeof_hdr"] = header.sizeof_hdr; + + result["dim_info"] = int(header.dim_info); + result["dim"] = std::vector(header.dim, header.dim+8); + + result["intent_p1"] = header.intent_p1; + result["intent_p2"] = header.intent_p2; + result["intent_p3"] = header.intent_p3; + result["intent_code"] = header.intent_code; + + result["datatype"] = header.datatype; + result["bitpix"] = header.bitpix; + + result["slice_start"] = header.slice_start; + result["pixdim"] = std::vector(header.pixdim, header.pixdim+8); + result["vox_offset"] = header.vox_offset; + result["scl_slope"] = header.scl_slope; + result["scl_inter"] = header.scl_inter; + result["slice_end"] = header.slice_end; + result["slice_code"] = int(header.slice_code); + result["xyzt_units"] = int(header.xyzt_units); + result["cal_max"] = header.cal_max; + result["cal_min"] = header.cal_min; + result["slice_duration"] = header.slice_duration; + result["toffset"] = header.toffset; + result["descrip"] = std::string(header.descrip, 80); + result["aux_file"] = std::string(header.aux_file, 24); + + result["qform_code"] = header.qform_code; + result["sform_code"] = header.sform_code; + result["quatern_b"] = header.quatern_b; + result["quatern_c"] = header.quatern_c; + result["quatern_d"] = header.quatern_d; + result["qoffset_x"] = header.qoffset_x; + result["qoffset_y"] = header.qoffset_y; + result["qoffset_z"] = header.qoffset_z; + result["srow_x"] = std::vector(header.srow_x, header.srow_x+4); + result["srow_y"] = std::vector(header.srow_y, header.srow_y+4); + result["srow_z"] = std::vector(header.srow_z, header.srow_z+4); + + result["intent_name"] = std::string(header.intent_name, 16); + result["magic"] = std::string(header.magic, 4); + + result.attr("class") = Rcpp::CharacterVector::create("niftiHeader"); + + return result; +} + +#endif diff --git a/inst/include/lib/print.h b/inst/include/lib/print.h new file mode 100644 index 0000000..c3fa99b --- /dev/null +++ b/inst/include/lib/print.h @@ -0,0 +1,15 @@ +#ifndef _PRINT_H_ +#define _PRINT_H_ + +#define R_USE_C99_IN_CXX + +#include + +#define Rc_printf Rprintf +#define Rc_fprintf_stdout(...) Rprintf(__VA_ARGS__) +#define Rc_fprintf_stderr(...) REprintf(__VA_ARGS__) +#define Rc_fputs_stdout(str) Rprintf(str) +#define Rc_fputs_stderr(str) REprintf(str) +#define Rc_fputc_stderr(ch) REprintf("%c", ch) + +#endif diff --git a/inst/include/niftilib/nifti1.h b/inst/include/niftilib/nifti1.h new file mode 100644 index 0000000..80066fb --- /dev/null +++ b/inst/include/niftilib/nifti1.h @@ -0,0 +1,1490 @@ +/** \file nifti1.h + \brief Official definition of the nifti1 header. Written by Bob Cox, SSCC, NIMH. + + HISTORY: + + 29 Nov 2007 [rickr] + - added DT_RGBA32 and NIFTI_TYPE_RGBA32 + - added NIFTI_INTENT codes: + TIME_SERIES, NODE_INDEX, RGB_VECTOR, RGBA_VECTOR, SHAPE + */ + +#ifndef _NIFTI_HEADER_ +#define _NIFTI_HEADER_ + +/***************************************************************************** + ** This file defines the "NIFTI-1" header format. ** + ** It is derived from 2 meetings at the NIH (31 Mar 2003 and ** + ** 02 Sep 2003) of the Data Format Working Group (DFWG), ** + ** chartered by the NIfTI (Neuroimaging Informatics Technology ** + ** Initiative) at the National Institutes of Health (NIH). ** + **--------------------------------------------------------------** + ** Neither the National Institutes of Health (NIH), the DFWG, ** + ** nor any of the members or employees of these institutions ** + ** imply any warranty of usefulness of this material for any ** + ** purpose, and do not assume any liability for damages, ** + ** incidental or otherwise, caused by any use of this document. ** + ** If these conditions are not acceptable, do not use this! ** + **--------------------------------------------------------------** + ** Author: Robert W Cox (NIMH, Bethesda) ** + ** Advisors: John Ashburner (FIL, London), ** + ** Stephen Smith (FMRIB, Oxford), ** + ** Mark Jenkinson (FMRIB, Oxford) ** +******************************************************************************/ + +/*---------------------------------------------------------------------------*/ +/* Note that the ANALYZE 7.5 file header (dbh.h) is + (c) Copyright 1986-1995 + Biomedical Imaging Resource + Mayo Foundation + Incorporation of components of dbh.h are by permission of the + Mayo Foundation. + + Changes from the ANALYZE 7.5 file header in this file are released to the + public domain, including the functional comments and any amusing asides. +-----------------------------------------------------------------------------*/ + +/*---------------------------------------------------------------------------*/ +/*! INTRODUCTION TO NIFTI-1: + ------------------------ + The twin (and somewhat conflicting) goals of this modified ANALYZE 7.5 + format are: + (a) To add information to the header that will be useful for functional + neuroimaging data analysis and display. These additions include: + - More basic data types. + - Two affine transformations to specify voxel coordinates. + - "Intent" codes and parameters to describe the meaning of the data. + - Affine scaling of the stored data values to their "true" values. + - Optional storage of the header and image data in one file (.nii). + (b) To maintain compatibility with non-NIFTI-aware ANALYZE 7.5 compatible + software (i.e., such a program should be able to do something useful + with a NIFTI-1 dataset -- at least, with one stored in a traditional + .img/.hdr file pair). + + Most of the unused fields in the ANALYZE 7.5 header have been taken, + and some of the lesser-used fields have been co-opted for other purposes. + Notably, most of the data_history substructure has been co-opted for + other purposes, since the ANALYZE 7.5 format describes this substructure + as "not required". + + NIFTI-1 FLAG (MAGIC STRINGS): + ---------------------------- + To flag such a struct as being conformant to the NIFTI-1 spec, the last 4 + bytes of the header must be either the C String "ni1" or "n+1"; + in hexadecimal, the 4 bytes + 6E 69 31 00 or 6E 2B 31 00 + (in any future version of this format, the '1' will be upgraded to '2', + etc.). Normally, such a "magic number" or flag goes at the start of the + file, but trying to avoid clobbering widely-used ANALYZE 7.5 fields led to + putting this marker last. However, recall that "the last shall be first" + (Matthew 20:16). + + If a NIFTI-aware program reads a header file that is NOT marked with a + NIFTI magic string, then it should treat the header as an ANALYZE 7.5 + structure. + + NIFTI-1 FILE STORAGE: + -------------------- + "ni1" means that the image data is stored in the ".img" file corresponding + to the header file (starting at file offset 0). + + "n+1" means that the image data is stored in the same file as the header + information. We recommend that the combined header+data filename suffix + be ".nii". When the dataset is stored in one file, the first byte of image + data is stored at byte location (int)vox_offset in this combined file. + The minimum allowed value of vox_offset is 352; for compatibility with + some software, vox_offset should be an integral multiple of 16. + + GRACE UNDER FIRE: + ---------------- + Most NIFTI-aware programs will only be able to handle a subset of the full + range of datasets possible with this format. All NIFTI-aware programs + should take care to check if an input dataset conforms to the program's + needs and expectations (e.g., check datatype, intent_code, etc.). If the + input dataset can't be handled by the program, the program should fail + gracefully (e.g., print a useful warning; not crash). + + SAMPLE CODES: + ------------ + The associated files nifti1_io.h and nifti1_io.c provide a sample + implementation in C of a set of functions to read, write, and manipulate + NIFTI-1 files. The file nifti1_test.c is a sample program that uses + the nifti1_io.c functions. +-----------------------------------------------------------------------------*/ + +/*---------------------------------------------------------------------------*/ +/* HEADER STRUCT DECLARATION: + ------------------------- + In the comments below for each field, only NIFTI-1 specific requirements + or changes from the ANALYZE 7.5 format are described. For convenience, + the 348 byte header is described as a single struct, rather than as the + ANALYZE 7.5 group of 3 substructs. + + Further comments about the interpretation of various elements of this + header are after the data type definition itself. Fields that are + marked as ++UNUSED++ have no particular interpretation in this standard. + (Also see the UNUSED FIELDS comment section, far below.) + + The presumption below is that the various C types have particular sizes: + sizeof(int) = sizeof(float) = 4 ; sizeof(short) = 2 +-----------------------------------------------------------------------------*/ + +/*=================*/ +#ifdef __cplusplus +extern "C" { +#endif +/*=================*/ + +/*! \struct nifti_1_header + \brief Data structure defining the fields in the nifti1 header. + This binary header should be found at the beginning of a valid + NIFTI-1 header file. + */ + /*************************/ /************************/ +struct nifti_1_header { /* NIFTI-1 usage */ /* ANALYZE 7.5 field(s) */ + /*************************/ /************************/ + + /*--- was header_key substruct ---*/ + int sizeof_hdr; /*!< MUST be 348 */ /* int sizeof_hdr; */ + char data_type[10]; /*!< ++UNUSED++ */ /* char data_type[10]; */ + char db_name[18]; /*!< ++UNUSED++ */ /* char db_name[18]; */ + int extents; /*!< ++UNUSED++ */ /* int extents; */ + short session_error; /*!< ++UNUSED++ */ /* short session_error; */ + char regular; /*!< ++UNUSED++ */ /* char regular; */ + char dim_info; /*!< MRI slice ordering. */ /* char hkey_un0; */ + + /*--- was image_dimension substruct ---*/ + short dim[8]; /*!< Data array dimensions.*/ /* short dim[8]; */ + float intent_p1 ; /*!< 1st intent parameter. */ /* short unused8; */ + /* short unused9; */ + float intent_p2 ; /*!< 2nd intent parameter. */ /* short unused10; */ + /* short unused11; */ + float intent_p3 ; /*!< 3rd intent parameter. */ /* short unused12; */ + /* short unused13; */ + short intent_code ; /*!< NIFTI_INTENT_* code. */ /* short unused14; */ + short datatype; /*!< Defines data type! */ /* short datatype; */ + short bitpix; /*!< Number bits/voxel. */ /* short bitpix; */ + short slice_start; /*!< First slice index. */ /* short dim_un0; */ + float pixdim[8]; /*!< Grid spacings. */ /* float pixdim[8]; */ + float vox_offset; /*!< Offset into .nii file */ /* float vox_offset; */ + float scl_slope ; /*!< Data scaling: slope. */ /* float funused1; */ + float scl_inter ; /*!< Data scaling: offset. */ /* float funused2; */ + short slice_end; /*!< Last slice index. */ /* float funused3; */ + char slice_code ; /*!< Slice timing order. */ + char xyzt_units ; /*!< Units of pixdim[1..4] */ + float cal_max; /*!< Max display intensity */ /* float cal_max; */ + float cal_min; /*!< Min display intensity */ /* float cal_min; */ + float slice_duration;/*!< Time for 1 slice. */ /* float compressed; */ + float toffset; /*!< Time axis shift. */ /* float verified; */ + int glmax; /*!< ++UNUSED++ */ /* int glmax; */ + int glmin; /*!< ++UNUSED++ */ /* int glmin; */ + + /*--- was data_history substruct ---*/ + char descrip[80]; /*!< any text you like. */ /* char descrip[80]; */ + char aux_file[24]; /*!< auxiliary filename. */ /* char aux_file[24]; */ + + short qform_code ; /*!< NIFTI_XFORM_* code. */ /*-- all ANALYZE 7.5 ---*/ + short sform_code ; /*!< NIFTI_XFORM_* code. */ /* fields below here */ + /* are replaced */ + float quatern_b ; /*!< Quaternion b param. */ + float quatern_c ; /*!< Quaternion c param. */ + float quatern_d ; /*!< Quaternion d param. */ + float qoffset_x ; /*!< Quaternion x shift. */ + float qoffset_y ; /*!< Quaternion y shift. */ + float qoffset_z ; /*!< Quaternion z shift. */ + + float srow_x[4] ; /*!< 1st row affine transform. */ + float srow_y[4] ; /*!< 2nd row affine transform. */ + float srow_z[4] ; /*!< 3rd row affine transform. */ + + char intent_name[16];/*!< 'name' or meaning of data. */ + + char magic[4] ; /*!< MUST be "ni1\0" or "n+1\0". */ + +} ; /**** 348 bytes total ****/ + +typedef struct nifti_1_header nifti_1_header ; + +/*---------------------------------------------------------------------------*/ +/* HEADER EXTENSIONS: + ----------------- + After the end of the 348 byte header (e.g., after the magic field), + the next 4 bytes are a char array field named "extension". By default, + all 4 bytes of this array should be set to zero. In a .nii file, these + 4 bytes will always be present, since the earliest start point for + the image data is byte #352. In a separate .hdr file, these bytes may + or may not be present. If not present (i.e., if the length of the .hdr + file is 348 bytes), then a NIfTI-1 compliant program should use the + default value of extension={0,0,0,0}. The first byte (extension[0]) + is the only value of this array that is specified at present. The other + 3 bytes are reserved for future use. + + If extension[0] is nonzero, it indicates that extended header information + is present in the bytes following the extension array. In a .nii file, + this extended header data is before the image data (and vox_offset + must be set correctly to allow for this). In a .hdr file, this extended + data follows extension and proceeds (potentially) to the end of the file. + + The format of extended header data is weakly specified. Each extension + must be an integer multiple of 16 bytes long. The first 8 bytes of each + extension comprise 2 integers: + int esize , ecode ; + These values may need to be byte-swapped, as indicated by dim[0] for + the rest of the header. + * esize is the number of bytes that form the extended header data + + esize must be a positive integral multiple of 16 + + this length includes the 8 bytes of esize and ecode themselves + * ecode is a non-negative integer that indicates the format of the + extended header data that follows + + different ecode values are assigned to different developer groups + + at present, the "registered" values for code are + = 0 = unknown private format (not recommended!) + = 2 = DICOM format (i.e., attribute tags and values) + = 4 = AFNI group (i.e., ASCII XML-ish elements) + In the interests of interoperability (a primary rationale for NIfTI), + groups developing software that uses this extension mechanism are + encouraged to document and publicize the format of their extensions. + To this end, the NIfTI DFWG will assign even numbered codes upon request + to groups submitting at least rudimentary documentation for the format + of their extension; at present, the contact is mailto:rwcox@nih.gov. + The assigned codes and documentation will be posted on the NIfTI + website. All odd values of ecode (and 0) will remain unassigned; + at least, until the even ones are used up, when we get to 2,147,483,646. + + Note that the other contents of the extended header data section are + totally unspecified by the NIfTI-1 standard. In particular, if binary + data is stored in such a section, its byte order is not necessarily + the same as that given by examining dim[0]; it is incumbent on the + programs dealing with such data to determine the byte order of binary + extended header data. + + Multiple extended header sections are allowed, each starting with an + esize,ecode value pair. The first esize value, as described above, + is at bytes #352-355 in the .hdr or .nii file (files start at byte #0). + If this value is positive, then the second (esize2) will be found + starting at byte #352+esize1 , the third (esize3) at byte #352+esize1+esize2, + et cetera. Of course, in a .nii file, the value of vox_offset must + be compatible with these extensions. If a malformed file indicates + that an extended header data section would run past vox_offset, then + the entire extended header section should be ignored. In a .hdr file, + if an extended header data section would run past the end-of-file, + that extended header data should also be ignored. + + With the above scheme, a program can successively examine the esize + and ecode values, and skip over each extended header section if the + program doesn't know how to interpret the data within. Of course, any + program can simply ignore all extended header sections simply by jumping + straight to the image data using vox_offset. +-----------------------------------------------------------------------------*/ + +/*! \struct nifti1_extender + \brief This structure represents a 4-byte string that should follow the + binary nifti_1_header data in a NIFTI-1 header file. If the char + values are {1,0,0,0}, the file is expected to contain extensions, + values of {0,0,0,0} imply the file does not contain extensions. + Other sequences of values are not currently defined. + */ +struct nifti1_extender { char extension[4] ; } ; +typedef struct nifti1_extender nifti1_extender ; + +/*! \struct nifti1_extension + \brief Data structure defining the fields of a header extension. + */ +struct nifti1_extension { + int esize ; /*!< size of extension, in bytes (must be multiple of 16) */ + int ecode ; /*!< extension code, one of the NIFTI_ECODE_ values */ + char * edata ; /*!< raw data, with no byte swapping (length is esize-8) */ +} ; +typedef struct nifti1_extension nifti1_extension ; + +/*---------------------------------------------------------------------------*/ +/* DATA DIMENSIONALITY (as in ANALYZE 7.5): + --------------------------------------- + dim[0] = number of dimensions; + - if dim[0] is outside range 1..7, then the header information + needs to be byte swapped appropriately + - ANALYZE supports dim[0] up to 7, but NIFTI-1 reserves + dimensions 1,2,3 for space (x,y,z), 4 for time (t), and + 5,6,7 for anything else needed. + + dim[i] = length of dimension #i, for i=1..dim[0] (must be positive) + - also see the discussion of intent_code, far below + + pixdim[i] = voxel width along dimension #i, i=1..dim[0] (positive) + - cf. ORIENTATION section below for use of pixdim[0] + - the units of pixdim can be specified with the xyzt_units + field (also described far below). + + Number of bits per voxel value is in bitpix, which MUST correspond with + the datatype field. The total number of bytes in the image data is + dim[1] * ... * dim[dim[0]] * bitpix / 8 + + In NIFTI-1 files, dimensions 1,2,3 are for space, dimension 4 is for time, + and dimension 5 is for storing multiple values at each spatiotemporal + voxel. Some examples: + - A typical whole-brain FMRI experiment's time series: + - dim[0] = 4 + - dim[1] = 64 pixdim[1] = 3.75 xyzt_units = NIFTI_UNITS_MM + - dim[2] = 64 pixdim[2] = 3.75 | NIFTI_UNITS_SEC + - dim[3] = 20 pixdim[3] = 5.0 + - dim[4] = 120 pixdim[4] = 2.0 + - A typical T1-weighted anatomical volume: + - dim[0] = 3 + - dim[1] = 256 pixdim[1] = 1.0 xyzt_units = NIFTI_UNITS_MM + - dim[2] = 256 pixdim[2] = 1.0 + - dim[3] = 128 pixdim[3] = 1.1 + - A single slice EPI time series: + - dim[0] = 4 + - dim[1] = 64 pixdim[1] = 3.75 xyzt_units = NIFTI_UNITS_MM + - dim[2] = 64 pixdim[2] = 3.75 | NIFTI_UNITS_SEC + - dim[3] = 1 pixdim[3] = 5.0 + - dim[4] = 1200 pixdim[4] = 0.2 + - A 3-vector stored at each point in a 3D volume: + - dim[0] = 5 + - dim[1] = 256 pixdim[1] = 1.0 xyzt_units = NIFTI_UNITS_MM + - dim[2] = 256 pixdim[2] = 1.0 + - dim[3] = 128 pixdim[3] = 1.1 + - dim[4] = 1 pixdim[4] = 0.0 + - dim[5] = 3 intent_code = NIFTI_INTENT_VECTOR + - A single time series with a 3x3 matrix at each point: + - dim[0] = 5 + - dim[1] = 1 xyzt_units = NIFTI_UNITS_SEC + - dim[2] = 1 + - dim[3] = 1 + - dim[4] = 1200 pixdim[4] = 0.2 + - dim[5] = 9 intent_code = NIFTI_INTENT_GENMATRIX + - intent_p1 = intent_p2 = 3.0 (indicates matrix dimensions) +-----------------------------------------------------------------------------*/ + +/*---------------------------------------------------------------------------*/ +/* DATA STORAGE: + ------------ + If the magic field is "n+1", then the voxel data is stored in the + same file as the header. In this case, the voxel data starts at offset + (int)vox_offset into the header file. Thus, vox_offset=352.0 means that + the data starts immediately after the NIFTI-1 header. If vox_offset is + greater than 352, the NIFTI-1 format does not say much about the + contents of the dataset file between the end of the header and the + start of the data. + + FILES: + ----- + If the magic field is "ni1", then the voxel data is stored in the + associated ".img" file, starting at offset 0 (i.e., vox_offset is not + used in this case, and should be set to 0.0). + + When storing NIFTI-1 datasets in pairs of files, it is customary to name + the files in the pattern "name.hdr" and "name.img", as in ANALYZE 7.5. + When storing in a single file ("n+1"), the file name should be in + the form "name.nii" (the ".nft" and ".nif" suffixes are already taken; + cf. http://www.icdatamaster.com/n.html ). + + BYTE ORDERING: + ------------- + The byte order of the data arrays is presumed to be the same as the byte + order of the header (which is determined by examining dim[0]). + + Floating point types are presumed to be stored in IEEE-754 format. +-----------------------------------------------------------------------------*/ + +/*---------------------------------------------------------------------------*/ +/* DETAILS ABOUT vox_offset: + ------------------------ + In a .nii file, the vox_offset field value is interpreted as the start + location of the image data bytes in that file. In a .hdr/.img file pair, + the vox_offset field value is the start location of the image data + bytes in the .img file. + * If vox_offset is less than 352 in a .nii file, it is equivalent + to 352 (i.e., image data never starts before byte #352 in a .nii file). + * The default value for vox_offset in a .nii file is 352. + * In a .hdr file, the default value for vox_offset is 0. + * vox_offset should be an integer multiple of 16; otherwise, some + programs may not work properly (e.g., SPM). This is to allow + memory-mapped input to be properly byte-aligned. + Note that since vox_offset is an IEEE-754 32 bit float (for compatibility + with the ANALYZE-7.5 format), it effectively has a 24 bit mantissa. All + integers from 0 to 2^24 can be represented exactly in this format, but not + all larger integers are exactly storable as IEEE-754 32 bit floats. However, + unless you plan to have vox_offset be potentially larger than 16 MB, this + should not be an issue. (Actually, any integral multiple of 16 up to 2^27 + can be represented exactly in this format, which allows for up to 128 MB + of random information before the image data. If that isn't enough, then + perhaps this format isn't right for you.) + + In a .img file (i.e., image data stored separately from the NIfTI-1 + header), data bytes between #0 and #vox_offset-1 (inclusive) are completely + undefined and unregulated by the NIfTI-1 standard. One potential use of + having vox_offset > 0 in the .hdr/.img file pair storage method is to make + the .img file be a copy of (or link to) a pre-existing image file in some + other format, such as DICOM; then vox_offset would be set to the offset of + the image data in this file. (It may not be possible to follow the + "multiple-of-16 rule" with an arbitrary external file; using the NIfTI-1 + format in such a case may lead to a file that is incompatible with software + that relies on vox_offset being a multiple of 16.) + + In a .nii file, data bytes between #348 and #vox_offset-1 (inclusive) may + be used to store user-defined extra information; similarly, in a .hdr file, + any data bytes after byte #347 are available for user-defined extra + information. The (very weak) regulation of this extra header data is + described elsewhere. +-----------------------------------------------------------------------------*/ + +/*---------------------------------------------------------------------------*/ +/* DATA SCALING: + ------------ + If the scl_slope field is nonzero, then each voxel value in the dataset + should be scaled as + y = scl_slope * x + scl_inter + where x = voxel value stored + y = "true" voxel value + Normally, we would expect this scaling to be used to store "true" floating + values in a smaller integer datatype, but that is not required. That is, + it is legal to use scaling even if the datatype is a float type (crazy, + perhaps, but legal). + - However, the scaling is to be ignored if datatype is DT_RGB24. + - If datatype is a complex type, then the scaling is to be + applied to both the real and imaginary parts. + + The cal_min and cal_max fields (if nonzero) are used for mapping (possibly + scaled) dataset values to display colors: + - Minimum display intensity (black) corresponds to dataset value cal_min. + - Maximum display intensity (white) corresponds to dataset value cal_max. + - Dataset values below cal_min should display as black also, and values + above cal_max as white. + - Colors "black" and "white", of course, may refer to any scalar display + scheme (e.g., a color lookup table specified via aux_file). + - cal_min and cal_max only make sense when applied to scalar-valued + datasets (i.e., dim[0] < 5 or dim[5] = 1). +-----------------------------------------------------------------------------*/ + +/*---------------------------------------------------------------------------*/ +/* TYPE OF DATA (acceptable values for datatype field): + --------------------------------------------------- + Values of datatype smaller than 256 are ANALYZE 7.5 compatible. + Larger values are NIFTI-1 additions. These are all multiples of 256, so + that no bits below position 8 are set in datatype. But there is no need + to use only powers-of-2, as the original ANALYZE 7.5 datatype codes do. + + The additional codes are intended to include a complete list of basic + scalar types, including signed and unsigned integers from 8 to 64 bits, + floats from 32 to 128 bits, and complex (float pairs) from 64 to 256 bits. + + Note that most programs will support only a few of these datatypes! + A NIFTI-1 program should fail gracefully (e.g., print a warning message) + when it encounters a dataset with a type it doesn't like. +-----------------------------------------------------------------------------*/ + +#undef DT_UNKNOWN /* defined in dirent.h on some Unix systems */ + +/*! \defgroup NIFTI1_DATATYPES + \brief nifti1 datatype codes + @{ + */ + /*--- the original ANALYZE 7.5 type codes ---*/ +#define DT_NONE 0 +#define DT_UNKNOWN 0 /* what it says, dude */ +#define DT_BINARY 1 /* binary (1 bit/voxel) */ +#define DT_UNSIGNED_CHAR 2 /* unsigned char (8 bits/voxel) */ +#define DT_SIGNED_SHORT 4 /* signed short (16 bits/voxel) */ +#define DT_SIGNED_INT 8 /* signed int (32 bits/voxel) */ +#define DT_FLOAT 16 /* float (32 bits/voxel) */ +#define DT_COMPLEX 32 /* complex (64 bits/voxel) */ +#define DT_DOUBLE 64 /* double (64 bits/voxel) */ +#define DT_RGB 128 /* RGB triple (24 bits/voxel) */ +#define DT_ALL 255 /* not very useful (?) */ + + /*----- another set of names for the same ---*/ +#define DT_UINT8 2 +#define DT_INT16 4 +#define DT_INT32 8 +#define DT_FLOAT32 16 +#define DT_COMPLEX64 32 +#define DT_FLOAT64 64 +#define DT_RGB24 128 + + /*------------------- new codes for NIFTI ---*/ +#define DT_INT8 256 /* signed char (8 bits) */ +#define DT_UINT16 512 /* unsigned short (16 bits) */ +#define DT_UINT32 768 /* unsigned int (32 bits) */ +#define DT_INT64 1024 /* long long (64 bits) */ +#define DT_UINT64 1280 /* unsigned long long (64 bits) */ +#define DT_FLOAT128 1536 /* long double (128 bits) */ +#define DT_COMPLEX128 1792 /* double pair (128 bits) */ +#define DT_COMPLEX256 2048 /* long double pair (256 bits) */ +#define DT_RGBA32 2304 /* 4 byte RGBA (32 bits/voxel) */ +/* @} */ + + + /*------- aliases for all the above codes ---*/ + +/*! \defgroup NIFTI1_DATATYPE_ALIASES + \brief aliases for the nifti1 datatype codes + @{ + */ + /*! unsigned char. */ +#define NIFTI_TYPE_UINT8 2 + /*! signed short. */ +#define NIFTI_TYPE_INT16 4 + /*! signed int. */ +#define NIFTI_TYPE_INT32 8 + /*! 32 bit float. */ +#define NIFTI_TYPE_FLOAT32 16 + /*! 64 bit complex = 2 32 bit floats. */ +#define NIFTI_TYPE_COMPLEX64 32 + /*! 64 bit float = double. */ +#define NIFTI_TYPE_FLOAT64 64 + /*! 3 8 bit bytes. */ +#define NIFTI_TYPE_RGB24 128 + /*! signed char. */ +#define NIFTI_TYPE_INT8 256 + /*! unsigned short. */ +#define NIFTI_TYPE_UINT16 512 + /*! unsigned int. */ +#define NIFTI_TYPE_UINT32 768 + /*! signed long long. */ +#define NIFTI_TYPE_INT64 1024 + /*! unsigned long long. */ +#define NIFTI_TYPE_UINT64 1280 + /*! 128 bit float = long double. */ +#define NIFTI_TYPE_FLOAT128 1536 + /*! 128 bit complex = 2 64 bit floats. */ +#define NIFTI_TYPE_COMPLEX128 1792 + /*! 256 bit complex = 2 128 bit floats */ +#define NIFTI_TYPE_COMPLEX256 2048 + /*! 4 8 bit bytes. */ +#define NIFTI_TYPE_RGBA32 2304 +/* @} */ + + /*-------- sample typedefs for complicated types ---*/ +#if 0 +typedef struct { float r,i; } complex_float ; +typedef struct { double r,i; } complex_double ; +typedef struct { long double r,i; } complex_longdouble ; +typedef struct { unsigned char r,g,b; } rgb_byte ; +#endif + +/*---------------------------------------------------------------------------*/ +/* INTERPRETATION OF VOXEL DATA: + ---------------------------- + The intent_code field can be used to indicate that the voxel data has + some particular meaning. In particular, a large number of codes is + given to indicate that the the voxel data should be interpreted as + being drawn from a given probability distribution. + + VECTOR-VALUED DATASETS: + ---------------------- + The 5th dimension of the dataset, if present (i.e., dim[0]=5 and + dim[5] > 1), contains multiple values (e.g., a vector) to be stored + at each spatiotemporal location. For example, the header values + - dim[0] = 5 + - dim[1] = 64 + - dim[2] = 64 + - dim[3] = 20 + - dim[4] = 1 (indicates no time axis) + - dim[5] = 3 + - datatype = DT_FLOAT + - intent_code = NIFTI_INTENT_VECTOR + mean that this dataset should be interpreted as a 3D volume (64x64x20), + with a 3-vector of floats defined at each point in the 3D grid. + + A program reading a dataset with a 5th dimension may want to reformat + the image data to store each voxels' set of values together in a struct + or array. This programming detail, however, is beyond the scope of the + NIFTI-1 file specification! Uses of dimensions 6 and 7 are also not + specified here. + + STATISTICAL PARAMETRIC DATASETS (i.e., SPMs): + -------------------------------------------- + Values of intent_code from NIFTI_FIRST_STATCODE to NIFTI_LAST_STATCODE + (inclusive) indicate that the numbers in the dataset should be interpreted + as being drawn from a given distribution. Most such distributions have + auxiliary parameters (e.g., NIFTI_INTENT_TTEST has 1 DOF parameter). + + If the dataset DOES NOT have a 5th dimension, then the auxiliary parameters + are the same for each voxel, and are given in header fields intent_p1, + intent_p2, and intent_p3. + + If the dataset DOES have a 5th dimension, then the auxiliary parameters + are different for each voxel. For example, the header values + - dim[0] = 5 + - dim[1] = 128 + - dim[2] = 128 + - dim[3] = 1 (indicates a single slice) + - dim[4] = 1 (indicates no time axis) + - dim[5] = 2 + - datatype = DT_FLOAT + - intent_code = NIFTI_INTENT_TTEST + mean that this is a 2D dataset (128x128) of t-statistics, with the + t-statistic being in the first "plane" of data and the degrees-of-freedom + parameter being in the second "plane" of data. + + If the dataset 5th dimension is used to store the voxel-wise statistical + parameters, then dim[5] must be 1 plus the number of parameters required + by that distribution (e.g., intent_code=NIFTI_INTENT_TTEST implies dim[5] + must be 2, as in the example just above). + + Note: intent_code values 2..10 are compatible with AFNI 1.5x (which is + why there is no code with value=1, which is obsolescent in AFNI). + + OTHER INTENTIONS: + ---------------- + The purpose of the intent_* fields is to help interpret the values + stored in the dataset. Some non-statistical values for intent_code + and conventions are provided for storing other complex data types. + + The intent_name field provides space for a 15 character (plus 0 byte) + 'name' string for the type of data stored. Examples: + - intent_code = NIFTI_INTENT_ESTIMATE; intent_name = "T1"; + could be used to signify that the voxel values are estimates of the + NMR parameter T1. + - intent_code = NIFTI_INTENT_TTEST; intent_name = "House"; + could be used to signify that the voxel values are t-statistics + for the significance of 'activation' response to a House stimulus. + - intent_code = NIFTI_INTENT_DISPVECT; intent_name = "ToMNI152"; + could be used to signify that the voxel values are a displacement + vector that transforms each voxel (x,y,z) location to the + corresponding location in the MNI152 standard brain. + - intent_code = NIFTI_INTENT_SYMMATRIX; intent_name = "DTI"; + could be used to signify that the voxel values comprise a diffusion + tensor image. + + If no data name is implied or needed, intent_name[0] should be set to 0. +-----------------------------------------------------------------------------*/ + + /*! default: no intention is indicated in the header. */ + +#define NIFTI_INTENT_NONE 0 + + /*-------- These codes are for probability distributions ---------------*/ + /* Most distributions have a number of parameters, + below denoted by p1, p2, and p3, and stored in + - intent_p1, intent_p2, intent_p3 if dataset doesn't have 5th dimension + - image data array if dataset does have 5th dimension + + Functions to compute with many of the distributions below can be found + in the CDF library from U Texas. + + Formulas for and discussions of these distributions can be found in the + following books: + + [U] Univariate Discrete Distributions, + NL Johnson, S Kotz, AW Kemp. + + [C1] Continuous Univariate Distributions, vol. 1, + NL Johnson, S Kotz, N Balakrishnan. + + [C2] Continuous Univariate Distributions, vol. 2, + NL Johnson, S Kotz, N Balakrishnan. */ + /*----------------------------------------------------------------------*/ + + /*! [C2, chap 32] Correlation coefficient R (1 param): + p1 = degrees of freedom + R/sqrt(1-R*R) is t-distributed with p1 DOF. */ + +/*! \defgroup NIFTI1_INTENT_CODES + \brief nifti1 intent codes, to describe intended meaning of dataset contents + @{ + */ +#define NIFTI_INTENT_CORREL 2 + + /*! [C2, chap 28] Student t statistic (1 param): p1 = DOF. */ + +#define NIFTI_INTENT_TTEST 3 + + /*! [C2, chap 27] Fisher F statistic (2 params): + p1 = numerator DOF, p2 = denominator DOF. */ + +#define NIFTI_INTENT_FTEST 4 + + /*! [C1, chap 13] Standard normal (0 params): Density = N(0,1). */ + +#define NIFTI_INTENT_ZSCORE 5 + + /*! [C1, chap 18] Chi-squared (1 param): p1 = DOF. + Density(x) proportional to exp(-x/2) * x^(p1/2-1). */ + +#define NIFTI_INTENT_CHISQ 6 + + /*! [C2, chap 25] Beta distribution (2 params): p1=a, p2=b. + Density(x) proportional to x^(a-1) * (1-x)^(b-1). */ + +#define NIFTI_INTENT_BETA 7 + + /*! [U, chap 3] Binomial distribution (2 params): + p1 = number of trials, p2 = probability per trial. + Prob(x) = (p1 choose x) * p2^x * (1-p2)^(p1-x), for x=0,1,...,p1. */ + +#define NIFTI_INTENT_BINOM 8 + + /*! [C1, chap 17] Gamma distribution (2 params): + p1 = shape, p2 = scale. + Density(x) proportional to x^(p1-1) * exp(-p2*x). */ + +#define NIFTI_INTENT_GAMMA 9 + + /*! [U, chap 4] Poisson distribution (1 param): p1 = mean. + Prob(x) = exp(-p1) * p1^x / x! , for x=0,1,2,.... */ + +#define NIFTI_INTENT_POISSON 10 + + /*! [C1, chap 13] Normal distribution (2 params): + p1 = mean, p2 = standard deviation. */ + +#define NIFTI_INTENT_NORMAL 11 + + /*! [C2, chap 30] Noncentral F statistic (3 params): + p1 = numerator DOF, p2 = denominator DOF, + p3 = numerator noncentrality parameter. */ + +#define NIFTI_INTENT_FTEST_NONC 12 + + /*! [C2, chap 29] Noncentral chi-squared statistic (2 params): + p1 = DOF, p2 = noncentrality parameter. */ + +#define NIFTI_INTENT_CHISQ_NONC 13 + + /*! [C2, chap 23] Logistic distribution (2 params): + p1 = location, p2 = scale. + Density(x) proportional to sech^2((x-p1)/(2*p2)). */ + +#define NIFTI_INTENT_LOGISTIC 14 + + /*! [C2, chap 24] Laplace distribution (2 params): + p1 = location, p2 = scale. + Density(x) proportional to exp(-abs(x-p1)/p2). */ + +#define NIFTI_INTENT_LAPLACE 15 + + /*! [C2, chap 26] Uniform distribution: p1 = lower end, p2 = upper end. */ + +#define NIFTI_INTENT_UNIFORM 16 + + /*! [C2, chap 31] Noncentral t statistic (2 params): + p1 = DOF, p2 = noncentrality parameter. */ + +#define NIFTI_INTENT_TTEST_NONC 17 + + /*! [C1, chap 21] Weibull distribution (3 params): + p1 = location, p2 = scale, p3 = power. + Density(x) proportional to + ((x-p1)/p2)^(p3-1) * exp(-((x-p1)/p2)^p3) for x > p1. */ + +#define NIFTI_INTENT_WEIBULL 18 + + /*! [C1, chap 18] Chi distribution (1 param): p1 = DOF. + Density(x) proportional to x^(p1-1) * exp(-x^2/2) for x > 0. + p1 = 1 = 'half normal' distribution + p1 = 2 = Rayleigh distribution + p1 = 3 = Maxwell-Boltzmann distribution. */ + +#define NIFTI_INTENT_CHI 19 + + /*! [C1, chap 15] Inverse Gaussian (2 params): + p1 = mu, p2 = lambda + Density(x) proportional to + exp(-p2*(x-p1)^2/(2*p1^2*x)) / x^3 for x > 0. */ + +#define NIFTI_INTENT_INVGAUSS 20 + + /*! [C2, chap 22] Extreme value type I (2 params): + p1 = location, p2 = scale + cdf(x) = exp(-exp(-(x-p1)/p2)). */ + +#define NIFTI_INTENT_EXTVAL 21 + + /*! Data is a 'p-value' (no params). */ + +#define NIFTI_INTENT_PVAL 22 + + /*! Data is ln(p-value) (no params). + To be safe, a program should compute p = exp(-abs(this_value)). + The nifti_stats.c library returns this_value + as positive, so that this_value = -log(p). */ + + +#define NIFTI_INTENT_LOGPVAL 23 + + /*! Data is log10(p-value) (no params). + To be safe, a program should compute p = pow(10.,-abs(this_value)). + The nifti_stats.c library returns this_value + as positive, so that this_value = -log10(p). */ + +#define NIFTI_INTENT_LOG10PVAL 24 + + /*! Smallest intent_code that indicates a statistic. */ + +#define NIFTI_FIRST_STATCODE 2 + + /*! Largest intent_code that indicates a statistic. */ + +#define NIFTI_LAST_STATCODE 24 + + /*---------- these values for intent_code aren't for statistics ----------*/ + + /*! To signify that the value at each voxel is an estimate + of some parameter, set intent_code = NIFTI_INTENT_ESTIMATE. + The name of the parameter may be stored in intent_name. */ + +#define NIFTI_INTENT_ESTIMATE 1001 + + /*! To signify that the value at each voxel is an index into + some set of labels, set intent_code = NIFTI_INTENT_LABEL. + The filename with the labels may stored in aux_file. */ + +#define NIFTI_INTENT_LABEL 1002 + + /*! To signify that the value at each voxel is an index into the + NeuroNames labels set, set intent_code = NIFTI_INTENT_NEURONAME. */ + +#define NIFTI_INTENT_NEURONAME 1003 + + /*! To store an M x N matrix at each voxel: + - dataset must have a 5th dimension (dim[0]=5 and dim[5]>1) + - intent_code must be NIFTI_INTENT_GENMATRIX + - dim[5] must be M*N + - intent_p1 must be M (in float format) + - intent_p2 must be N (ditto) + - the matrix values A[i][[j] are stored in row-order: + - A[0][0] A[0][1] ... A[0][N-1] + - A[1][0] A[1][1] ... A[1][N-1] + - etc., until + - A[M-1][0] A[M-1][1] ... A[M-1][N-1] */ + +#define NIFTI_INTENT_GENMATRIX 1004 + + /*! To store an NxN symmetric matrix at each voxel: + - dataset must have a 5th dimension + - intent_code must be NIFTI_INTENT_SYMMATRIX + - dim[5] must be N*(N+1)/2 + - intent_p1 must be N (in float format) + - the matrix values A[i][[j] are stored in row-order: + - A[0][0] + - A[1][0] A[1][1] + - A[2][0] A[2][1] A[2][2] + - etc.: row-by-row */ + +#define NIFTI_INTENT_SYMMATRIX 1005 + + /*! To signify that the vector value at each voxel is to be taken + as a displacement field or vector: + - dataset must have a 5th dimension + - intent_code must be NIFTI_INTENT_DISPVECT + - dim[5] must be the dimensionality of the displacment + vector (e.g., 3 for spatial displacement, 2 for in-plane) */ + +#define NIFTI_INTENT_DISPVECT 1006 /* specifically for displacements */ +#define NIFTI_INTENT_VECTOR 1007 /* for any other type of vector */ + + /*! To signify that the vector value at each voxel is really a + spatial coordinate (e.g., the vertices or nodes of a surface mesh): + - dataset must have a 5th dimension + - intent_code must be NIFTI_INTENT_POINTSET + - dim[0] = 5 + - dim[1] = number of points + - dim[2] = dim[3] = dim[4] = 1 + - dim[5] must be the dimensionality of space (e.g., 3 => 3D space). + - intent_name may describe the object these points come from + (e.g., "pial", "gray/white" , "EEG", "MEG"). */ + +#define NIFTI_INTENT_POINTSET 1008 + + /*! To signify that the vector value at each voxel is really a triple + of indexes (e.g., forming a triangle) from a pointset dataset: + - dataset must have a 5th dimension + - intent_code must be NIFTI_INTENT_TRIANGLE + - dim[0] = 5 + - dim[1] = number of triangles + - dim[2] = dim[3] = dim[4] = 1 + - dim[5] = 3 + - datatype should be an integer type (preferably DT_INT32) + - the data values are indexes (0,1,...) into a pointset dataset. */ + +#define NIFTI_INTENT_TRIANGLE 1009 + + /*! To signify that the vector value at each voxel is a quaternion: + - dataset must have a 5th dimension + - intent_code must be NIFTI_INTENT_QUATERNION + - dim[0] = 5 + - dim[5] = 4 + - datatype should be a floating point type */ + +#define NIFTI_INTENT_QUATERNION 1010 + + /*! Dimensionless value - no params - although, as in _ESTIMATE + the name of the parameter may be stored in intent_name. */ + +#define NIFTI_INTENT_DIMLESS 1011 + + /*---------- these values apply to GIFTI datasets ----------*/ + + /*! To signify that the value at each location is from a time series. */ + +#define NIFTI_INTENT_TIME_SERIES 2001 + + /*! To signify that the value at each location is a node index, from + a complete surface dataset. */ + +#define NIFTI_INTENT_NODE_INDEX 2002 + + /*! To signify that the vector value at each location is an RGB triplet, + of whatever type. + - dataset must have a 5th dimension + - dim[0] = 5 + - dim[1] = number of nodes + - dim[2] = dim[3] = dim[4] = 1 + - dim[5] = 3 + */ + +#define NIFTI_INTENT_RGB_VECTOR 2003 + + /*! To signify that the vector value at each location is a 4 valued RGBA + vector, of whatever type. + - dataset must have a 5th dimension + - dim[0] = 5 + - dim[1] = number of nodes + - dim[2] = dim[3] = dim[4] = 1 + - dim[5] = 4 + */ + +#define NIFTI_INTENT_RGBA_VECTOR 2004 + + /*! To signify that the value at each location is a shape value, such + as the curvature. */ + +#define NIFTI_INTENT_SHAPE 2005 + +/* @} */ + +/*---------------------------------------------------------------------------*/ +/* 3D IMAGE (VOLUME) ORIENTATION AND LOCATION IN SPACE: + --------------------------------------------------- + There are 3 different methods by which continuous coordinates can + attached to voxels. The discussion below emphasizes 3D volumes, and + the continuous coordinates are referred to as (x,y,z). The voxel + index coordinates (i.e., the array indexes) are referred to as (i,j,k), + with valid ranges: + i = 0 .. dim[1]-1 + j = 0 .. dim[2]-1 (if dim[0] >= 2) + k = 0 .. dim[3]-1 (if dim[0] >= 3) + The (x,y,z) coordinates refer to the CENTER of a voxel. In methods + 2 and 3, the (x,y,z) axes refer to a subject-based coordinate system, + with + +x = Right +y = Anterior +z = Superior. + This is a right-handed coordinate system. However, the exact direction + these axes point with respect to the subject depends on qform_code + (Method 2) and sform_code (Method 3). + + N.B.: The i index varies most rapidly, j index next, k index slowest. + Thus, voxel (i,j,k) is stored starting at location + (i + j*dim[1] + k*dim[1]*dim[2]) * (bitpix/8) + into the dataset array. + + N.B.: The ANALYZE 7.5 coordinate system is + +x = Left +y = Anterior +z = Superior + which is a left-handed coordinate system. This backwardness is + too difficult to tolerate, so this NIFTI-1 standard specifies the + coordinate order which is most common in functional neuroimaging. + + N.B.: The 3 methods below all give the locations of the voxel centers + in the (x,y,z) coordinate system. In many cases, programs will wish + to display image data on some other grid. In such a case, the program + will need to convert its desired (x,y,z) values into (i,j,k) values + in order to extract (or interpolate) the image data. This operation + would be done with the inverse transformation to those described below. + + N.B.: Method 2 uses a factor 'qfac' which is either -1 or 1; qfac is + stored in the otherwise unused pixdim[0]. If pixdim[0]=0.0 (which + should not occur), we take qfac=1. Of course, pixdim[0] is only used + when reading a NIFTI-1 header, not when reading an ANALYZE 7.5 header. + + N.B.: The units of (x,y,z) can be specified using the xyzt_units field. + + METHOD 1 (the "old" way, used only when qform_code = 0): + ------------------------------------------------------- + The coordinate mapping from (i,j,k) to (x,y,z) is the ANALYZE + 7.5 way. This is a simple scaling relationship: + + x = pixdim[1] * i + y = pixdim[2] * j + z = pixdim[3] * k + + No particular spatial orientation is attached to these (x,y,z) + coordinates. (NIFTI-1 does not have the ANALYZE 7.5 orient field, + which is not general and is often not set properly.) This method + is not recommended, and is present mainly for compatibility with + ANALYZE 7.5 files. + + METHOD 2 (used when qform_code > 0, which should be the "normal" case): + --------------------------------------------------------------------- + The (x,y,z) coordinates are given by the pixdim[] scales, a rotation + matrix, and a shift. This method is intended to represent + "scanner-anatomical" coordinates, which are often embedded in the + image header (e.g., DICOM fields (0020,0032), (0020,0037), (0028,0030), + and (0018,0050)), and represent the nominal orientation and location of + the data. This method can also be used to represent "aligned" + coordinates, which would typically result from some post-acquisition + alignment of the volume to a standard orientation (e.g., the same + subject on another day, or a rigid rotation to true anatomical + orientation from the tilted position of the subject in the scanner). + The formula for (x,y,z) in terms of header parameters and (i,j,k) is: + + [ x ] [ R11 R12 R13 ] [ pixdim[1] * i ] [ qoffset_x ] + [ y ] = [ R21 R22 R23 ] [ pixdim[2] * j ] + [ qoffset_y ] + [ z ] [ R31 R32 R33 ] [ qfac * pixdim[3] * k ] [ qoffset_z ] + + The qoffset_* shifts are in the NIFTI-1 header. Note that the center + of the (i,j,k)=(0,0,0) voxel (first value in the dataset array) is + just (x,y,z)=(qoffset_x,qoffset_y,qoffset_z). + + The rotation matrix R is calculated from the quatern_* parameters. + This calculation is described below. + + The scaling factor qfac is either 1 or -1. The rotation matrix R + defined by the quaternion parameters is "proper" (has determinant 1). + This may not fit the needs of the data; for example, if the image + grid is + i increases from Left-to-Right + j increases from Anterior-to-Posterior + k increases from Inferior-to-Superior + Then (i,j,k) is a left-handed triple. In this example, if qfac=1, + the R matrix would have to be + + [ 1 0 0 ] + [ 0 -1 0 ] which is "improper" (determinant = -1). + [ 0 0 1 ] + + If we set qfac=-1, then the R matrix would be + + [ 1 0 0 ] + [ 0 -1 0 ] which is proper. + [ 0 0 -1 ] + + This R matrix is represented by quaternion [a,b,c,d] = [0,1,0,0] + (which encodes a 180 degree rotation about the x-axis). + + METHOD 3 (used when sform_code > 0): + ----------------------------------- + The (x,y,z) coordinates are given by a general affine transformation + of the (i,j,k) indexes: + + x = srow_x[0] * i + srow_x[1] * j + srow_x[2] * k + srow_x[3] + y = srow_y[0] * i + srow_y[1] * j + srow_y[2] * k + srow_y[3] + z = srow_z[0] * i + srow_z[1] * j + srow_z[2] * k + srow_z[3] + + The srow_* vectors are in the NIFTI_1 header. Note that no use is + made of pixdim[] in this method. + + WHY 3 METHODS? + -------------- + Method 1 is provided only for backwards compatibility. The intention + is that Method 2 (qform_code > 0) represents the nominal voxel locations + as reported by the scanner, or as rotated to some fiducial orientation and + location. Method 3, if present (sform_code > 0), is to be used to give + the location of the voxels in some standard space. The sform_code + indicates which standard space is present. Both methods 2 and 3 can be + present, and be useful in different contexts (method 2 for displaying the + data on its original grid; method 3 for displaying it on a standard grid). + + In this scheme, a dataset would originally be set up so that the + Method 2 coordinates represent what the scanner reported. Later, + a registration to some standard space can be computed and inserted + in the header. Image display software can use either transform, + depending on its purposes and needs. + + In Method 2, the origin of coordinates would generally be whatever + the scanner origin is; for example, in MRI, (0,0,0) is the center + of the gradient coil. + + In Method 3, the origin of coordinates would depend on the value + of sform_code; for example, for the Talairach coordinate system, + (0,0,0) corresponds to the Anterior Commissure. + + QUATERNION REPRESENTATION OF ROTATION MATRIX (METHOD 2) + ------------------------------------------------------- + The orientation of the (x,y,z) axes relative to the (i,j,k) axes + in 3D space is specified using a unit quaternion [a,b,c,d], where + a*a+b*b+c*c+d*d=1. The (b,c,d) values are all that is needed, since + we require that a = sqrt(1.0-(b*b+c*c+d*d)) be nonnegative. The (b,c,d) + values are stored in the (quatern_b,quatern_c,quatern_d) fields. + + The quaternion representation is chosen for its compactness in + representing rotations. The (proper) 3x3 rotation matrix that + corresponds to [a,b,c,d] is + + [ a*a+b*b-c*c-d*d 2*b*c-2*a*d 2*b*d+2*a*c ] + R = [ 2*b*c+2*a*d a*a+c*c-b*b-d*d 2*c*d-2*a*b ] + [ 2*b*d-2*a*c 2*c*d+2*a*b a*a+d*d-c*c-b*b ] + + [ R11 R12 R13 ] + = [ R21 R22 R23 ] + [ R31 R32 R33 ] + + If (p,q,r) is a unit 3-vector, then rotation of angle h about that + direction is represented by the quaternion + + [a,b,c,d] = [cos(h/2), p*sin(h/2), q*sin(h/2), r*sin(h/2)]. + + Requiring a >= 0 is equivalent to requiring -Pi <= h <= Pi. (Note that + [-a,-b,-c,-d] represents the same rotation as [a,b,c,d]; there are 2 + quaternions that can be used to represent a given rotation matrix R.) + To rotate a 3-vector (x,y,z) using quaternions, we compute the + quaternion product + + [0,x',y',z'] = [a,b,c,d] * [0,x,y,z] * [a,-b,-c,-d] + + which is equivalent to the matrix-vector multiply + + [ x' ] [ x ] + [ y' ] = R [ y ] (equivalence depends on a*a+b*b+c*c+d*d=1) + [ z' ] [ z ] + + Multiplication of 2 quaternions is defined by the following: + + [a,b,c,d] = a*1 + b*I + c*J + d*K + where + I*I = J*J = K*K = -1 (I,J,K are square roots of -1) + I*J = K J*K = I K*I = J + J*I = -K K*J = -I I*K = -J (not commutative!) + For example + [a,b,0,0] * [0,0,0,1] = [0,0,-b,a] + since this expands to + (a+b*I)*(K) = (a*K+b*I*K) = (a*K-b*J). + + The above formula shows how to go from quaternion (b,c,d) to + rotation matrix and direction cosines. Conversely, given R, + we can compute the fields for the NIFTI-1 header by + + a = 0.5 * sqrt(1+R11+R22+R33) (not stored) + b = 0.25 * (R32-R23) / a => quatern_b + c = 0.25 * (R13-R31) / a => quatern_c + d = 0.25 * (R21-R12) / a => quatern_d + + If a=0 (a 180 degree rotation), alternative formulas are needed. + See the nifti1_io.c function mat44_to_quatern() for an implementation + of the various cases in converting R to [a,b,c,d]. + + Note that R-transpose (= R-inverse) would lead to the quaternion + [a,-b,-c,-d]. + + The choice to specify the qoffset_x (etc.) values in the final + coordinate system is partly to make it easy to convert DICOM images to + this format. The DICOM attribute "Image Position (Patient)" (0020,0032) + stores the (Xd,Yd,Zd) coordinates of the center of the first voxel. + Here, (Xd,Yd,Zd) refer to DICOM coordinates, and Xd=-x, Yd=-y, Zd=z, + where (x,y,z) refers to the NIFTI coordinate system discussed above. + (i.e., DICOM +Xd is Left, +Yd is Posterior, +Zd is Superior, + whereas +x is Right, +y is Anterior , +z is Superior. ) + Thus, if the (0020,0032) DICOM attribute is extracted into (px,py,pz), then + qoffset_x = -px qoffset_y = -py qoffset_z = pz + is a reasonable setting when qform_code=NIFTI_XFORM_SCANNER_ANAT. + + That is, DICOM's coordinate system is 180 degrees rotated about the z-axis + from the neuroscience/NIFTI coordinate system. To transform between DICOM + and NIFTI, you just have to negate the x- and y-coordinates. + + The DICOM attribute (0020,0037) "Image Orientation (Patient)" gives the + orientation of the x- and y-axes of the image data in terms of 2 3-vectors. + The first vector is a unit vector along the x-axis, and the second is + along the y-axis. If the (0020,0037) attribute is extracted into the + value (xa,xb,xc,ya,yb,yc), then the first two columns of the R matrix + would be + [ -xa -ya ] + [ -xb -yb ] + [ xc yc ] + The negations are because DICOM's x- and y-axes are reversed relative + to NIFTI's. The third column of the R matrix gives the direction of + displacement (relative to the subject) along the slice-wise direction. + This orientation is not encoded in the DICOM standard in a simple way; + DICOM is mostly concerned with 2D images. The third column of R will be + either the cross-product of the first 2 columns or its negative. It is + possible to infer the sign of the 3rd column by examining the coordinates + in DICOM attribute (0020,0032) "Image Position (Patient)" for successive + slices. However, this method occasionally fails for reasons that I + (RW Cox) do not understand. +-----------------------------------------------------------------------------*/ + + /* [qs]form_code value: */ /* x,y,z coordinate system refers to: */ + /*-----------------------*/ /*---------------------------------------*/ + +/*! \defgroup NIFTI1_XFORM_CODES + \brief nifti1 xform codes to describe the "standard" coordinate system + @{ + */ + /*! Arbitrary coordinates (Method 1). */ + +#define NIFTI_XFORM_UNKNOWN 0 + + /*! Scanner-based anatomical coordinates */ + +#define NIFTI_XFORM_SCANNER_ANAT 1 + + /*! Coordinates aligned to another file's, + or to anatomical "truth". */ + +#define NIFTI_XFORM_ALIGNED_ANAT 2 + + /*! Coordinates aligned to Talairach- + Tournoux Atlas; (0,0,0)=AC, etc. */ + +#define NIFTI_XFORM_TALAIRACH 3 + + /*! MNI 152 normalized coordinates. */ + +#define NIFTI_XFORM_MNI_152 4 +/* @} */ + +/*---------------------------------------------------------------------------*/ +/* UNITS OF SPATIAL AND TEMPORAL DIMENSIONS: + ---------------------------------------- + The codes below can be used in xyzt_units to indicate the units of pixdim. + As noted earlier, dimensions 1,2,3 are for x,y,z; dimension 4 is for + time (t). + - If dim[4]=1 or dim[0] < 4, there is no time axis. + - A single time series (no space) would be specified with + - dim[0] = 4 (for scalar data) or dim[0] = 5 (for vector data) + - dim[1] = dim[2] = dim[3] = 1 + - dim[4] = number of time points + - pixdim[4] = time step + - xyzt_units indicates units of pixdim[4] + - dim[5] = number of values stored at each time point + + Bits 0..2 of xyzt_units specify the units of pixdim[1..3] + (e.g., spatial units are values 1..7). + Bits 3..5 of xyzt_units specify the units of pixdim[4] + (e.g., temporal units are multiples of 8). + + This compression of 2 distinct concepts into 1 byte is due to the + limited space available in the 348 byte ANALYZE 7.5 header. The + macros XYZT_TO_SPACE and XYZT_TO_TIME can be used to mask off the + undesired bits from the xyzt_units fields, leaving "pure" space + and time codes. Inversely, the macro SPACE_TIME_TO_XYZT can be + used to assemble a space code (0,1,2,...,7) with a time code + (0,8,16,32,...,56) into the combined value for xyzt_units. + + Note that codes are provided to indicate the "time" axis units are + actually frequency in Hertz (_HZ), in part-per-million (_PPM) + or in radians-per-second (_RADS). + + The toffset field can be used to indicate a nonzero start point for + the time axis. That is, time point #m is at t=toffset+m*pixdim[4] + for m=0..dim[4]-1. +-----------------------------------------------------------------------------*/ + +/*! \defgroup NIFTI1_UNITS + \brief nifti1 units codes to describe the unit of measurement for + each dimension of the dataset + @{ + */ + /*! NIFTI code for unspecified units. */ +#define NIFTI_UNITS_UNKNOWN 0 + + /** Space codes are multiples of 1. **/ + /*! NIFTI code for meters. */ +#define NIFTI_UNITS_METER 1 + /*! NIFTI code for millimeters. */ +#define NIFTI_UNITS_MM 2 + /*! NIFTI code for micrometers. */ +#define NIFTI_UNITS_MICRON 3 + + /** Time codes are multiples of 8. **/ + /*! NIFTI code for seconds. */ +#define NIFTI_UNITS_SEC 8 + /*! NIFTI code for milliseconds. */ +#define NIFTI_UNITS_MSEC 16 + /*! NIFTI code for microseconds. */ +#define NIFTI_UNITS_USEC 24 + + /*** These units are for spectral data: ***/ + /*! NIFTI code for Hertz. */ +#define NIFTI_UNITS_HZ 32 + /*! NIFTI code for ppm. */ +#define NIFTI_UNITS_PPM 40 + /*! NIFTI code for radians per second. */ +#define NIFTI_UNITS_RADS 48 +/* @} */ + +#undef XYZT_TO_SPACE +#undef XYZT_TO_TIME +#define XYZT_TO_SPACE(xyzt) ( (xyzt) & 0x07 ) +#define XYZT_TO_TIME(xyzt) ( (xyzt) & 0x38 ) + +#undef SPACE_TIME_TO_XYZT +#define SPACE_TIME_TO_XYZT(ss,tt) ( (((char)(ss)) & 0x07) \ + | (((char)(tt)) & 0x38) ) + +/*---------------------------------------------------------------------------*/ +/* MRI-SPECIFIC SPATIAL AND TEMPORAL INFORMATION: + --------------------------------------------- + A few fields are provided to store some extra information + that is sometimes important when storing the image data + from an FMRI time series experiment. (After processing such + data into statistical images, these fields are not likely + to be useful.) + + { freq_dim } = These fields encode which spatial dimension (1,2, or 3) + { phase_dim } = corresponds to which acquisition dimension for MRI data. + { slice_dim } = + Examples: + Rectangular scan multi-slice EPI: + freq_dim = 1 phase_dim = 2 slice_dim = 3 (or some permutation) + Spiral scan multi-slice EPI: + freq_dim = phase_dim = 0 slice_dim = 3 + since the concepts of frequency- and phase-encoding directions + don't apply to spiral scan + + slice_duration = If this is positive, AND if slice_dim is nonzero, + indicates the amount of time used to acquire 1 slice. + slice_duration*dim[slice_dim] can be less than pixdim[4] + with a clustered acquisition method, for example. + + slice_code = If this is nonzero, AND if slice_dim is nonzero, AND + if slice_duration is positive, indicates the timing + pattern of the slice acquisition. The following codes + are defined: + NIFTI_SLICE_SEQ_INC == sequential increasing + NIFTI_SLICE_SEQ_DEC == sequential decreasing + NIFTI_SLICE_ALT_INC == alternating increasing + NIFTI_SLICE_ALT_DEC == alternating decreasing + NIFTI_SLICE_ALT_INC2 == alternating increasing #2 + NIFTI_SLICE_ALT_DEC2 == alternating decreasing #2 + { slice_start } = Indicates the start and end of the slice acquisition + { slice_end } = pattern, when slice_code is nonzero. These values + are present to allow for the possible addition of + "padded" slices at either end of the volume, which + don't fit into the slice timing pattern. If there + are no padding slices, then slice_start=0 and + slice_end=dim[slice_dim]-1 are the correct values. + For these values to be meaningful, slice_start must + be non-negative and slice_end must be greater than + slice_start. Otherwise, they should be ignored. + + The following table indicates the slice timing pattern, relative to + time=0 for the first slice acquired, for some sample cases. Here, + dim[slice_dim]=7 (there are 7 slices, labeled 0..6), slice_duration=0.1, + and slice_start=1, slice_end=5 (1 padded slice on each end). + + slice + index SEQ_INC SEQ_DEC ALT_INC ALT_DEC ALT_INC2 ALT_DEC2 + 6 : n/a n/a n/a n/a n/a n/a n/a = not applicable + 5 : 0.4 0.0 0.2 0.0 0.4 0.2 (slice time offset + 4 : 0.3 0.1 0.4 0.3 0.1 0.0 doesn't apply to + 3 : 0.2 0.2 0.1 0.1 0.3 0.3 slices outside + 2 : 0.1 0.3 0.3 0.4 0.0 0.1 the range + 1 : 0.0 0.4 0.0 0.2 0.2 0.4 slice_start .. + 0 : n/a n/a n/a n/a n/a n/a slice_end) + + The SEQ slice_codes are sequential ordering (uncommon but not unknown), + either increasing in slice number or decreasing (INC or DEC), as + illustrated above. + + The ALT slice codes are alternating ordering. The 'standard' way for + these to operate (without the '2' on the end) is for the slice timing + to start at the edge of the slice_start .. slice_end group (at slice_start + for INC and at slice_end for DEC). For the 'ALT_*2' slice_codes, the + slice timing instead starts at the first slice in from the edge (at + slice_start+1 for INC2 and at slice_end-1 for DEC2). This latter + acquisition scheme is found on some Siemens scanners. + + The fields freq_dim, phase_dim, slice_dim are all squished into the single + byte field dim_info (2 bits each, since the values for each field are + limited to the range 0..3). This unpleasantness is due to lack of space + in the 348 byte allowance. + + The macros DIM_INFO_TO_FREQ_DIM, DIM_INFO_TO_PHASE_DIM, and + DIM_INFO_TO_SLICE_DIM can be used to extract these values from the + dim_info byte. + + The macro FPS_INTO_DIM_INFO can be used to put these 3 values + into the dim_info byte. +-----------------------------------------------------------------------------*/ + +#undef DIM_INFO_TO_FREQ_DIM +#undef DIM_INFO_TO_PHASE_DIM +#undef DIM_INFO_TO_SLICE_DIM + +#define DIM_INFO_TO_FREQ_DIM(di) ( ((di) ) & 0x03 ) +#define DIM_INFO_TO_PHASE_DIM(di) ( ((di) >> 2) & 0x03 ) +#define DIM_INFO_TO_SLICE_DIM(di) ( ((di) >> 4) & 0x03 ) + +#undef FPS_INTO_DIM_INFO +#define FPS_INTO_DIM_INFO(fd,pd,sd) ( ( ( ((char)(fd)) & 0x03) ) | \ + ( ( ((char)(pd)) & 0x03) << 2 ) | \ + ( ( ((char)(sd)) & 0x03) << 4 ) ) + +/*! \defgroup NIFTI1_SLICE_ORDER + \brief nifti1 slice order codes, describing the acquisition order + of the slices + @{ + */ +#define NIFTI_SLICE_UNKNOWN 0 +#define NIFTI_SLICE_SEQ_INC 1 +#define NIFTI_SLICE_SEQ_DEC 2 +#define NIFTI_SLICE_ALT_INC 3 +#define NIFTI_SLICE_ALT_DEC 4 +#define NIFTI_SLICE_ALT_INC2 5 /* 05 May 2005: RWCox */ +#define NIFTI_SLICE_ALT_DEC2 6 /* 05 May 2005: RWCox */ +/* @} */ + +/*---------------------------------------------------------------------------*/ +/* UNUSED FIELDS: + ------------- + Some of the ANALYZE 7.5 fields marked as ++UNUSED++ may need to be set + to particular values for compatibility with other programs. The issue + of interoperability of ANALYZE 7.5 files is a murky one -- not all + programs require exactly the same set of fields. (Unobscuring this + murkiness is a principal motivation behind NIFTI-1.) + + Some of the fields that may need to be set for other (non-NIFTI aware) + software to be happy are: + + extents dbh.h says this should be 16384 + regular dbh.h says this should be the character 'r' + glmin, } dbh.h says these values should be the min and max voxel + glmax } values for the entire dataset + + It is best to initialize ALL fields in the NIFTI-1 header to 0 + (e.g., with calloc()), then fill in what is needed. +-----------------------------------------------------------------------------*/ + +/*---------------------------------------------------------------------------*/ +/* MISCELLANEOUS C MACROS +-----------------------------------------------------------------------------*/ + +/*.................*/ +/*! Given a nifti_1_header struct, check if it has a good magic number. + Returns NIFTI version number (1..9) if magic is good, 0 if it is not. */ + +#define NIFTI_VERSION(h) \ + ( ( (h).magic[0]=='n' && (h).magic[3]=='\0' && \ + ( (h).magic[1]=='i' || (h).magic[1]=='+' ) && \ + ( (h).magic[2]>='1' && (h).magic[2]<='9' ) ) \ + ? (h).magic[2]-'0' : 0 ) + +/*.................*/ +/*! Check if a nifti_1_header struct says if the data is stored in the + same file or in a separate file. Returns 1 if the data is in the same + file as the header, 0 if it is not. */ + +#define NIFTI_ONEFILE(h) ( (h).magic[1] == '+' ) + +/*.................*/ +/*! Check if a nifti_1_header struct needs to be byte swapped. + Returns 1 if it needs to be swapped, 0 if it does not. */ + +#define NIFTI_NEEDS_SWAP(h) ( (h).dim[0] < 0 || (h).dim[0] > 7 ) + +/*.................*/ +/*! Check if a nifti_1_header struct contains a 5th (vector) dimension. + Returns size of 5th dimension if > 1, returns 0 otherwise. */ + +#define NIFTI_5TH_DIM(h) ( ((h).dim[0]>4 && (h).dim[5]>1) ? (h).dim[5] : 0 ) + +/*****************************************************************************/ + +/*=================*/ +#ifdef __cplusplus +} +#endif +/*=================*/ + +#endif /* _NIFTI_HEADER_ */ diff --git a/inst/include/niftilib/nifti1_io.h b/inst/include/niftilib/nifti1_io.h new file mode 100644 index 0000000..ebb22b7 --- /dev/null +++ b/inst/include/niftilib/nifti1_io.h @@ -0,0 +1,556 @@ +/** \file nifti1_io.h + \brief Data structures for using nifti1_io API. + - Written by Bob Cox, SSCC NIMH + - Revisions by Rick Reynolds, SSCC NIMH + */ +#ifndef _NIFTI_IO_HEADER_ +#define _NIFTI_IO_HEADER_ + +#include +#include +#include +#include +#include + +#ifndef DONT_INCLUDE_ANALYZE_STRUCT +#define DONT_INCLUDE_ANALYZE_STRUCT /*** not needed herein ***/ +#endif +#include "niftilib/nifti1.h" /*** NIFTI-1 header specification ***/ + +#include "lib/print.h" +#include + +/*=================*/ +#ifdef __cplusplus +extern "C" { +#endif +/*=================*/ + +/*****===================================================================*****/ +/***** File nifti1_io.h == Declarations for nifti1_io.c *****/ +/*****...................................................................*****/ +/***** This code is released to the public domain. *****/ +/*****...................................................................*****/ +/***** Author: Robert W Cox, SSCC/DIRP/NIMH/NIH/DHHS/USA/EARTH *****/ +/***** Date: August 2003 *****/ +/*****...................................................................*****/ +/***** Neither the National Institutes of Health (NIH), nor any of its *****/ +/***** employees imply any warranty of usefulness of this software for *****/ +/***** any purpose, and do not assume any liability for damages, *****/ +/***** incidental or otherwise, caused by any use of this document. *****/ +/*****===================================================================*****/ + +/* + Modified by: Mark Jenkinson (FMRIB Centre, University of Oxford, UK) + Date: July/August 2004 + + Mainly adding low-level IO and changing things to allow gzipped files + to be read and written + Full backwards compatability should have been maintained + + Modified by: Rick Reynolds (SSCC/DIRP/NIMH, National Institutes of Health) + Date: December 2004 + + Modified and added many routines for I/O. +*/ + +/********************** Some sample data structures **************************/ + +typedef struct { /** 4x4 matrix struct **/ + float m[4][4] ; +} mat44 ; + +typedef struct { /** 3x3 matrix struct **/ + float m[3][3] ; +} mat33 ; + +/*...........................................................................*/ + +/*! \enum analyze_75_orient_code + * \brief Old-style analyze75 orientation + * codes. + */ +typedef enum _analyze75_orient_code { + a75_transverse_unflipped = 0, + a75_coronal_unflipped = 1, + a75_sagittal_unflipped = 2, + a75_transverse_flipped = 3, + a75_coronal_flipped = 4, + a75_sagittal_flipped = 5, + a75_orient_unknown = 6 +} analyze_75_orient_code; + +/*! \struct nifti_image + \brief High level data structure for open nifti datasets in the + nifti1_io API. Note that this structure is not part of the + nifti1 format definition; it is used to implement one API + for reading/writing formats in the nifti1 format. + */ +typedef struct { /*!< Image storage struct **/ + + int ndim ; /*!< last dimension greater than 1 (1..7) */ + int nx ; /*!< dimensions of grid array */ + int ny ; /*!< dimensions of grid array */ + int nz ; /*!< dimensions of grid array */ + int nt ; /*!< dimensions of grid array */ + int nu ; /*!< dimensions of grid array */ + int nv ; /*!< dimensions of grid array */ + int nw ; /*!< dimensions of grid array */ + int dim[8] ; /*!< dim[0]=ndim, dim[1]=nx, etc. */ + size_t nvox ; /*!< number of voxels = nx*ny*nz*...*nw */ + int nbyper ; /*!< bytes per voxel, matches datatype */ + int datatype ; /*!< type of data in voxels: DT_* code */ + + float dx ; /*!< grid spacings */ + float dy ; /*!< grid spacings */ + float dz ; /*!< grid spacings */ + float dt ; /*!< grid spacings */ + float du ; /*!< grid spacings */ + float dv ; /*!< grid spacings */ + float dw ; /*!< grid spacings */ + float pixdim[8] ; /*!< pixdim[1]=dx, etc. */ + + float scl_slope ; /*!< scaling parameter - slope */ + float scl_inter ; /*!< scaling parameter - intercept */ + + float cal_min ; /*!< calibration parameter, minimum */ + float cal_max ; /*!< calibration parameter, maximum */ + + int qform_code ; /*!< codes for (x,y,z) space meaning */ + int sform_code ; /*!< codes for (x,y,z) space meaning */ + + int freq_dim ; /*!< indexes (1,2,3, or 0) for MRI */ + int phase_dim ; /*!< directions in dim[]/pixdim[] */ + int slice_dim ; /*!< directions in dim[]/pixdim[] */ + + int slice_code ; /*!< code for slice timing pattern */ + int slice_start ; /*!< index for start of slices */ + int slice_end ; /*!< index for end of slices */ + float slice_duration ; /*!< time between individual slices */ + + /*! quaternion transform parameters + [when writing a dataset, these are used for qform, NOT qto_xyz] */ + float quatern_b , quatern_c , quatern_d , + qoffset_x , qoffset_y , qoffset_z , + qfac ; + + mat44 qto_xyz ; /*!< qform: transform (i,j,k) to (x,y,z) */ + mat44 qto_ijk ; /*!< qform: transform (x,y,z) to (i,j,k) */ + + mat44 sto_xyz ; /*!< sform: transform (i,j,k) to (x,y,z) */ + mat44 sto_ijk ; /*!< sform: transform (x,y,z) to (i,j,k) */ + + float toffset ; /*!< time coordinate offset */ + + int xyz_units ; /*!< dx,dy,dz units: NIFTI_UNITS_* code */ + int time_units ; /*!< dt units: NIFTI_UNITS_* code */ + + int nifti_type ; /*!< 0==ANALYZE, 1==NIFTI-1 (1 file), + 2==NIFTI-1 (2 files), + 3==NIFTI-ASCII (1 file) */ + int intent_code ; /*!< statistic type (or something) */ + float intent_p1 ; /*!< intent parameters */ + float intent_p2 ; /*!< intent parameters */ + float intent_p3 ; /*!< intent parameters */ + char intent_name[16] ; /*!< optional description of intent data */ + + char descrip[80] ; /*!< optional text to describe dataset */ + char aux_file[24] ; /*!< auxiliary filename */ + + char *fname ; /*!< header filename (.hdr or .nii) */ + char *iname ; /*!< image filename (.img or .nii) */ + int iname_offset ; /*!< offset into iname where data starts */ + int swapsize ; /*!< swap unit in image data (might be 0) */ + int byteorder ; /*!< byte order on disk (MSB_ or LSB_FIRST) */ + void *data ; /*!< pointer to data: nbyper*nvox bytes */ + + int num_ext ; /*!< number of extensions in ext_list */ + nifti1_extension * ext_list ; /*!< array of extension structs (with data) */ + analyze_75_orient_code analyze75_orient; /*!< for old analyze files, orient */ + +} nifti_image ; + + + +/* struct for return from nifti_image_read_bricks() */ +typedef struct { + int nbricks; /* the number of allocated pointers in 'bricks' */ + size_t bsize; /* the length of each data block, in bytes */ + void ** bricks; /* array of pointers to data blocks */ +} nifti_brick_list; + + +/*****************************************************************************/ +/*------------------ NIfTI version of ANALYZE 7.5 structure -----------------*/ + +/* (based on fsliolib/dbh.h, but updated for version 7.5) */ + +typedef struct { + /* header info fields - describes the header overlap with NIfTI */ + /* ------------------ */ + int sizeof_hdr; /* 0 + 4 same */ + char data_type[10]; /* 4 + 10 same */ + char db_name[18]; /* 14 + 18 same */ + int extents; /* 32 + 4 same */ + short int session_error; /* 36 + 2 same */ + char regular; /* 38 + 1 same */ + char hkey_un0; /* 39 + 1 40 bytes */ + + /* image dimension fields - describes image sizes */ + short int dim[8]; /* 0 + 16 same */ + short int unused8; /* 16 + 2 intent_p1... */ + short int unused9; /* 18 + 2 ... */ + short int unused10; /* 20 + 2 intent_p2... */ + short int unused11; /* 22 + 2 ... */ + short int unused12; /* 24 + 2 intent_p3... */ + short int unused13; /* 26 + 2 ... */ + short int unused14; /* 28 + 2 intent_code */ + short int datatype; /* 30 + 2 same */ + short int bitpix; /* 32 + 2 same */ + short int dim_un0; /* 34 + 2 slice_start */ + float pixdim[8]; /* 36 + 32 same */ + + float vox_offset; /* 68 + 4 same */ + float funused1; /* 72 + 4 scl_slope */ + float funused2; /* 76 + 4 scl_inter */ + float funused3; /* 80 + 4 slice_end, */ + /* slice_code, */ + /* xyzt_units */ + float cal_max; /* 84 + 4 same */ + float cal_min; /* 88 + 4 same */ + float compressed; /* 92 + 4 slice_duration */ + float verified; /* 96 + 4 toffset */ + int glmax,glmin; /* 100 + 8 108 bytes */ + + /* data history fields - optional */ + char descrip[80]; /* 0 + 80 same */ + char aux_file[24]; /* 80 + 24 same */ + char orient; /* 104 + 1 NO GOOD OVERLAP */ + char originator[10]; /* 105 + 10 FROM HERE DOWN... */ + char generated[10]; /* 115 + 10 */ + char scannum[10]; /* 125 + 10 */ + char patient_id[10]; /* 135 + 10 */ + char exp_date[10]; /* 145 + 10 */ + char exp_time[10]; /* 155 + 10 */ + char hist_un0[3]; /* 165 + 3 */ + int views; /* 168 + 4 */ + int vols_added; /* 172 + 4 */ + int start_field; /* 176 + 4 */ + int field_skip; /* 180 + 4 */ + int omax, omin; /* 184 + 8 */ + int smax, smin; /* 192 + 8 200 bytes */ +} nifti_analyze75; /* total: 348 bytes */ + + +/*****************************************************************************/ +/*--------------- Prototypes of functions defined in this file --------------*/ + +char const * nifti_datatype_string ( int dt ) ; +char const *nifti_units_string ( int uu ) ; +char const *nifti_intent_string ( int ii ) ; +char const *nifti_xform_string ( int xx ) ; +char const *nifti_slice_string ( int ss ) ; +char const *nifti_orientation_string( int ii ) ; + +int nifti_is_inttype( int dt ) ; + +mat44 nifti_mat44_inverse( mat44 R ) ; + +mat33 nifti_mat33_inverse( mat33 R ) ; +mat33 nifti_mat33_polar ( mat33 A ) ; +float nifti_mat33_rownorm( mat33 A ) ; +float nifti_mat33_colnorm( mat33 A ) ; +float nifti_mat33_determ ( mat33 R ) ; +mat33 nifti_mat33_mul ( mat33 A , mat33 B ) ; + +void nifti_swap_2bytes ( size_t n , void *ar ) ; +void nifti_swap_4bytes ( size_t n , void *ar ) ; +void nifti_swap_8bytes ( size_t n , void *ar ) ; +void nifti_swap_16bytes( size_t n , void *ar ) ; +void nifti_swap_Nbytes ( size_t n , int siz , void *ar ) ; + +int nifti_datatype_is_valid (int dtype, int for_nifti); +int nifti_datatype_from_string(const char * name); +const char * nifti_datatype_to_string (int dtype); + +int nifti_get_filesize( const char *pathname ) ; +void swap_nifti_header ( struct nifti_1_header *h , int is_nifti ) ; +void old_swap_nifti_header( struct nifti_1_header *h , int is_nifti ); +int nifti_swap_as_analyze( nifti_analyze75 *h ); + + +/* main read/write routines */ + +nifti_image *nifti_image_read_bricks(const char *hname , int nbricks, + const int *blist, nifti_brick_list * NBL); +int nifti_image_load_bricks(nifti_image *nim , int nbricks, + const int *blist, nifti_brick_list * NBL); +void nifti_free_NBL( nifti_brick_list * NBL ); + +nifti_image *nifti_image_read ( const char *hname , int read_data ) ; +int nifti_image_load ( nifti_image *nim ) ; +void nifti_image_unload ( nifti_image *nim ) ; +void nifti_image_free ( nifti_image *nim ) ; + +int nifti_read_collapsed_image( nifti_image * nim, const int dims [8], + void ** data ); + +int nifti_read_subregion_image( nifti_image * nim, + int *start_index, int *region_size, + void ** data ); + +void nifti_image_write ( nifti_image * nim ) ; +void nifti_image_write_bricks(nifti_image * nim, + const nifti_brick_list * NBL); +void nifti_image_infodump( const nifti_image * nim ) ; + +void nifti_disp_lib_hist( void ) ; /* to display library history */ +void nifti_disp_lib_version( void ) ; /* to display library version */ +int nifti_disp_matrix_orient( const char * mesg, mat44 mat ); +int nifti_disp_type_list( int which ); + + +char * nifti_image_to_ascii ( const nifti_image * nim ) ; +nifti_image *nifti_image_from_ascii( const char * str, int * bytes_read ) ; + +size_t nifti_get_volsize(const nifti_image *nim) ; + +/* basic file operations */ +int nifti_set_filenames(nifti_image * nim, const char * prefix, int check, + int set_byte_order); +char * nifti_makehdrname (const char * prefix, int nifti_type, int check, + int comp); +char * nifti_makeimgname (const char * prefix, int nifti_type, int check, + int comp); +int is_nifti_file (const char *hname); +char * nifti_find_file_extension(const char * name); +int nifti_is_complete_filename(const char* fname); +int nifti_validfilename(const char* fname); + +int disp_nifti_1_header(const char * info, const nifti_1_header * hp ) ; +void nifti_set_debug_level( int level ) ; +void nifti_set_skip_blank_ext( int skip ) ; +void nifti_set_allow_upper_fext( int allow ) ; + +int valid_nifti_brick_list(nifti_image * nim , int nbricks, + const int * blist, int disp_error); + +/* znzFile operations */ +znzFile nifti_image_open(const char * hname, char * opts, nifti_image ** nim); +znzFile nifti_image_write_hdr_img(nifti_image *nim, int write_data, + const char* opts); +znzFile nifti_image_write_hdr_img2( nifti_image *nim , int write_opts , + const char* opts, znzFile imgfile, const nifti_brick_list * NBL); +size_t nifti_read_buffer(znzFile fp, void* datatptr, size_t ntot, + nifti_image *nim); +int nifti_write_all_data(znzFile fp, nifti_image * nim, + const nifti_brick_list * NBL); +size_t nifti_write_buffer(znzFile fp, const void * buffer, size_t numbytes); +nifti_image *nifti_read_ascii_image(znzFile fp, char *fname, int flen, + int read_data); +znzFile nifti_write_ascii_image(nifti_image *nim, const nifti_brick_list * NBL, + const char * opts, int write_data, int leave_open); + + +void nifti_datatype_sizes( int datatype , int *nbyper, int *swapsize ) ; + +void nifti_mat44_to_quatern( mat44 R , + float *qb, float *qc, float *qd, + float *qx, float *qy, float *qz, + float *dx, float *dy, float *dz, float *qfac ) ; + +mat44 nifti_quatern_to_mat44( float qb, float qc, float qd, + float qx, float qy, float qz, + float dx, float dy, float dz, float qfac ); + +mat44 nifti_make_orthog_mat44( float r11, float r12, float r13 , + float r21, float r22, float r23 , + float r31, float r32, float r33 ) ; + +int nifti_short_order(void) ; /* CPU byte order */ + + +/* Orientation codes that might be returned from nifti_mat44_to_orientation().*/ + +#define NIFTI_L2R 1 /* Left to Right */ +#define NIFTI_R2L 2 /* Right to Left */ +#define NIFTI_P2A 3 /* Posterior to Anterior */ +#define NIFTI_A2P 4 /* Anterior to Posterior */ +#define NIFTI_I2S 5 /* Inferior to Superior */ +#define NIFTI_S2I 6 /* Superior to Inferior */ + +void nifti_mat44_to_orientation( mat44 R , int *icod, int *jcod, int *kcod ) ; + +/*--------------------- Low level IO routines ------------------------------*/ + +char * nifti_findhdrname (const char* fname); +char * nifti_findimgname (const char* fname , int nifti_type); +int nifti_is_gzfile (const char* fname); + +char * nifti_makebasename(const char* fname); + + +/* other routines */ +struct nifti_1_header nifti_convert_nim2nhdr(const nifti_image* nim); +nifti_1_header * nifti_make_new_header(const int arg_dims[], int arg_dtype); +nifti_1_header * nifti_read_header(const char *hname, int *swapped, int check); +nifti_image * nifti_copy_nim_info(const nifti_image * src); +nifti_image * nifti_make_new_nim(const int dims[], int datatype, + int data_fill); +nifti_image * nifti_simple_init_nim(void); +nifti_image * nifti_convert_nhdr2nim(struct nifti_1_header nhdr, + const char * fname); + +int nifti_hdr_looks_good (const nifti_1_header * hdr); +int nifti_is_valid_datatype (int dtype); +int nifti_is_valid_ecode (int ecode); +int nifti_nim_is_valid (nifti_image * nim, int complain); +int nifti_nim_has_valid_dims (nifti_image * nim, int complain); +int is_valid_nifti_type (int nifti_type); +int nifti_test_datatype_sizes (int verb); +int nifti_type_and_names_match (nifti_image * nim, int show_warn); +int nifti_update_dims_from_array(nifti_image * nim); +void nifti_set_iname_offset (nifti_image *nim); +int nifti_set_type_from_names (nifti_image * nim); +int nifti_add_extension(nifti_image * nim, const char * data, int len, + int ecode ); +int nifti_compiled_with_zlib (void); +int nifti_copy_extensions (nifti_image *nim_dest,const nifti_image *nim_src); +int nifti_free_extensions (nifti_image *nim); +int * nifti_get_intlist (int nvals , const char *str); +char * nifti_strdup (const char *str); +int valid_nifti_extensions(const nifti_image *nim); + + +/*-------------------- Some C convenience macros ----------------------------*/ + +/* NIfTI-1.1 extension codes: + see http://nifti.nimh.nih.gov/nifti-1/documentation/faq#Q21 */ + +#define NIFTI_ECODE_IGNORE 0 /* changed from UNKNOWN, 29 June 2005 */ + +#define NIFTI_ECODE_DICOM 2 /* intended for raw DICOM attributes */ + +#define NIFTI_ECODE_AFNI 4 /* Robert W Cox: rwcox@nih.gov + http://afni.nimh.nih.gov/afni */ + +#define NIFTI_ECODE_COMMENT 6 /* plain ASCII text only */ + +#define NIFTI_ECODE_XCEDE 8 /* David B Keator: dbkeator@uci.edu + http://www.nbirn.net/Resources + /Users/Applications/ + /xcede/index.htm */ + +#define NIFTI_ECODE_JIMDIMINFO 10 /* Mark A Horsfield: + mah5@leicester.ac.uk + http://someplace/something */ + +#define NIFTI_ECODE_WORKFLOW_FWDS 12 /* Kate Fissell: fissell@pitt.edu + http://kraepelin.wpic.pitt.edu + /~fissell/NIFTI_ECODE_WORKFLOW_FWDS + /NIFTI_ECODE_WORKFLOW_FWDS.html */ + +#define NIFTI_ECODE_FREESURFER 14 /* http://surfer.nmr.mgh.harvard.edu */ + +#define NIFTI_ECODE_PYPICKLE 16 /* embedded Python objects + http://niftilib.sourceforge.net + /pynifti */ + + /* LONI MiND codes: http://www.loni.ucla.edu/twiki/bin/view/Main/MiND */ +#define NIFTI_ECODE_MIND_IDENT 18 /* Vishal Patel: vishal.patel@ucla.edu*/ +#define NIFTI_ECODE_B_VALUE 20 +#define NIFTI_ECODE_SPHERICAL_DIRECTION 22 +#define NIFTI_ECODE_DT_COMPONENT 24 +#define NIFTI_ECODE_SHC_DEGREEORDER 26 /* end LONI MiND codes */ + +#define NIFTI_ECODE_VOXBO 28 /* Dan Kimberg: www.voxbo.org */ + +#define NIFTI_ECODE_CARET 30 /* John Harwell: john@brainvis.wustl.edu + http://brainvis.wustl.edu/wiki + /index.php/Caret:Documentation + :CaretNiftiExtension */ + +#define NIFTI_ECODE_CIFTI 32 /* CIFTI-2_Main_FINAL_1March2014.pdf */ + +#define NIFTI_ECODE_VARIABLE_FRAME_TIMING 34 + +/* 36 is currently unassigned, waiting on NIFTI_ECODE_AGILENT_PROCPAR */ + +#define NIFTI_ECODE_EVAL 38 /* Munster University Hospital */ + +/* http://www.mathworks.com/matlabcentral/fileexchange/42997-dicom-to-nifti-converter */ +#define NIFTI_ECODE_MATLAB 40 /* MATLAB extension */ + + +#define NIFTI_MAX_ECODE 40 /******* maximum extension code *******/ + +/* nifti_type file codes */ +#define NIFTI_FTYPE_ANALYZE 0 +#define NIFTI_FTYPE_NIFTI1_1 1 +#define NIFTI_FTYPE_NIFTI1_2 2 +#define NIFTI_FTYPE_ASCII 3 +#define NIFTI_MAX_FTYPE 3 /* this should match the maximum code */ + +/*------------------------------------------------------------------------*/ +/*-- the rest of these apply only to nifti1_io.c, check for _NIFTI1_IO_C_ */ +/* Feb 9, 2005 [rickr] */ +#ifdef _NIFTI1_IO_C_ + +typedef struct { + int debug; /*!< debug level for status reports */ + int skip_blank_ext; /*!< skip extender if no extensions */ + int allow_upper_fext; /*!< allow uppercase file extensions */ +} nifti_global_options; + +typedef struct { + int type; /* should match the NIFTI_TYPE_ #define */ + int nbyper; /* bytes per value, matches nifti_image */ + int swapsize; /* bytes per swap piece, matches nifti_image */ + char const * const name; /* text string to match #define */ +} nifti_type_ele; + +#undef LNI_FERR /* local nifti file error, to be compact and repetative */ +#define LNI_FERR(func,msg,file) \ + Rc_fprintf_stderr("** ERROR (%s): %s '%s'\n",func,msg,file) + +#undef swap_2 +#undef swap_4 +#define swap_2(s) nifti_swap_2bytes(1,&(s)) /* s: 2-byte short; swap in place */ +#define swap_4(v) nifti_swap_4bytes(1,&(v)) /* v: 4-byte value; swap in place */ + + /***** isfinite() is a C99 macro, which is + present in many C implementations already *****/ + +#undef IS_GOOD_FLOAT +#undef FIXED_FLOAT + +#ifdef isfinite /* use isfinite() to check floats/doubles for goodness */ +# define IS_GOOD_FLOAT(x) isfinite(x) /* check if x is a "good" float */ +# define FIXED_FLOAT(x) (isfinite(x) ? (x) : 0) /* fixed if bad */ +#else +# define IS_GOOD_FLOAT(x) 1 /* don't check it */ +# define FIXED_FLOAT(x) (x) /* don't fix it */ +#endif + +#undef ASSIF /* assign v to *p, if possible */ +#define ASSIF(p,v) if( (p)!=NULL ) *(p) = (v) + +#undef MSB_FIRST +#undef LSB_FIRST +#undef REVERSE_ORDER +#define LSB_FIRST 1 +#define MSB_FIRST 2 +#define REVERSE_ORDER(x) (3-(x)) /* convert MSB_FIRST <--> LSB_FIRST */ + +#define LNI_MAX_NIA_EXT_LEN 100000 /* consider a longer extension invalid */ + +#endif /* _NIFTI1_IO_C_ section */ +/*------------------------------------------------------------------------*/ + +/*=================*/ +#ifdef __cplusplus +} +#endif +/*=================*/ + +#endif /* _NIFTI_IO_HEADER_ */ diff --git a/inst/include/zlib/zconf.h b/inst/include/zlib/zconf.h new file mode 100644 index 0000000..996fff2 --- /dev/null +++ b/inst/include/zlib/zconf.h @@ -0,0 +1,511 @@ +/* zconf.h -- configuration of the zlib compression library + * Copyright (C) 1995-2013 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#ifndef ZCONF_H +#define ZCONF_H + +/* + * If you *really* need a unique prefix for all types and library functions, + * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. + * Even better than compiling with -DZ_PREFIX would be to use configure to set + * this permanently in zconf.h using "./configure --zprefix". + */ +#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ +# define Z_PREFIX_SET + +/* all linked symbols */ +# define _dist_code z__dist_code +# define _length_code z__length_code +# define _tr_align z__tr_align +# define _tr_flush_bits z__tr_flush_bits +# define _tr_flush_block z__tr_flush_block +# define _tr_init z__tr_init +# define _tr_stored_block z__tr_stored_block +# define _tr_tally z__tr_tally +# define adler32 z_adler32 +# define adler32_combine z_adler32_combine +# define adler32_combine64 z_adler32_combine64 +# ifndef Z_SOLO +# define compress z_compress +# define compress2 z_compress2 +# define compressBound z_compressBound +# endif +# define crc32 z_crc32 +# define crc32_combine z_crc32_combine +# define crc32_combine64 z_crc32_combine64 +# define deflate z_deflate +# define deflateBound z_deflateBound +# define deflateCopy z_deflateCopy +# define deflateEnd z_deflateEnd +# define deflateInit2_ z_deflateInit2_ +# define deflateInit_ z_deflateInit_ +# define deflateParams z_deflateParams +# define deflatePending z_deflatePending +# define deflatePrime z_deflatePrime +# define deflateReset z_deflateReset +# define deflateResetKeep z_deflateResetKeep +# define deflateSetDictionary z_deflateSetDictionary +# define deflateSetHeader z_deflateSetHeader +# define deflateTune z_deflateTune +# define deflate_copyright z_deflate_copyright +# define get_crc_table z_get_crc_table +# ifndef Z_SOLO +# define gz_error z_gz_error +# define gz_intmax z_gz_intmax +# define gz_strwinerror z_gz_strwinerror +# define gzbuffer z_gzbuffer +# define gzclearerr z_gzclearerr +# define gzclose z_gzclose +# define gzclose_r z_gzclose_r +# define gzclose_w z_gzclose_w +# define gzdirect z_gzdirect +# define gzdopen z_gzdopen +# define gzeof z_gzeof +# define gzerror z_gzerror +# define gzflush z_gzflush +# define gzgetc z_gzgetc +# define gzgetc_ z_gzgetc_ +# define gzgets z_gzgets +# define gzoffset z_gzoffset +# define gzoffset64 z_gzoffset64 +# define gzopen z_gzopen +# define gzopen64 z_gzopen64 +# ifdef _WIN32 +# define gzopen_w z_gzopen_w +# endif +# define gzprintf z_gzprintf +# define gzvprintf z_gzvprintf +# define gzputc z_gzputc +# define gzputs z_gzputs +# define gzread z_gzread +# define gzrewind z_gzrewind +# define gzseek z_gzseek +# define gzseek64 z_gzseek64 +# define gzsetparams z_gzsetparams +# define gztell z_gztell +# define gztell64 z_gztell64 +# define gzungetc z_gzungetc +# define gzwrite z_gzwrite +# endif +# define inflate z_inflate +# define inflateBack z_inflateBack +# define inflateBackEnd z_inflateBackEnd +# define inflateBackInit_ z_inflateBackInit_ +# define inflateCopy z_inflateCopy +# define inflateEnd z_inflateEnd +# define inflateGetHeader z_inflateGetHeader +# define inflateInit2_ z_inflateInit2_ +# define inflateInit_ z_inflateInit_ +# define inflateMark z_inflateMark +# define inflatePrime z_inflatePrime +# define inflateReset z_inflateReset +# define inflateReset2 z_inflateReset2 +# define inflateSetDictionary z_inflateSetDictionary +# define inflateGetDictionary z_inflateGetDictionary +# define inflateSync z_inflateSync +# define inflateSyncPoint z_inflateSyncPoint +# define inflateUndermine z_inflateUndermine +# define inflateResetKeep z_inflateResetKeep +# define inflate_copyright z_inflate_copyright +# define inflate_fast z_inflate_fast +# define inflate_table z_inflate_table +# ifndef Z_SOLO +# define uncompress z_uncompress +# endif +# define zError z_zError +# ifndef Z_SOLO +# define zcalloc z_zcalloc +# define zcfree z_zcfree +# endif +# define zlibCompileFlags z_zlibCompileFlags +# define zlibVersion z_zlibVersion + +/* all zlib typedefs in zlib.h and zconf.h */ +# define Byte z_Byte +# define Bytef z_Bytef +# define alloc_func z_alloc_func +# define charf z_charf +# define free_func z_free_func +# ifndef Z_SOLO +# define gzFile z_gzFile +# endif +# define gz_header z_gz_header +# define gz_headerp z_gz_headerp +# define in_func z_in_func +# define intf z_intf +# define out_func z_out_func +# define uInt z_uInt +# define uIntf z_uIntf +# define uLong z_uLong +# define uLongf z_uLongf +# define voidp z_voidp +# define voidpc z_voidpc +# define voidpf z_voidpf + +/* all zlib structs in zlib.h and zconf.h */ +# define gz_header_s z_gz_header_s +# define internal_state z_internal_state + +#endif + +#if defined(__MSDOS__) && !defined(MSDOS) +# define MSDOS +#endif +#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) +# define OS2 +#endif +#if defined(_WINDOWS) && !defined(WINDOWS) +# define WINDOWS +#endif +#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) +# ifndef WIN32 +# define WIN32 +# endif +#endif +#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) +# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) +# ifndef SYS16BIT +# define SYS16BIT +# endif +# endif +#endif + +/* + * Compile with -DMAXSEG_64K if the alloc function cannot allocate more + * than 64k bytes at a time (needed on systems with 16-bit int). + */ +#ifdef SYS16BIT +# define MAXSEG_64K +#endif +#ifdef MSDOS +# define UNALIGNED_OK +#endif + +#ifdef __STDC_VERSION__ +# ifndef STDC +# define STDC +# endif +# if __STDC_VERSION__ >= 199901L +# ifndef STDC99 +# define STDC99 +# endif +# endif +#endif +#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) +# define STDC +#endif +#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) +# define STDC +#endif +#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) +# define STDC +#endif +#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) +# define STDC +#endif + +#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ +# define STDC +#endif + +#ifndef STDC +# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ +# define const /* note: need a more gentle solution here */ +# endif +#endif + +#if defined(ZLIB_CONST) && !defined(z_const) +# define z_const const +#else +# define z_const +#endif + +/* Some Mac compilers merge all .h files incorrectly: */ +#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) +# define NO_DUMMY_DECL +#endif + +/* Maximum value for memLevel in deflateInit2 */ +#ifndef MAX_MEM_LEVEL +# ifdef MAXSEG_64K +# define MAX_MEM_LEVEL 8 +# else +# define MAX_MEM_LEVEL 9 +# endif +#endif + +/* Maximum value for windowBits in deflateInit2 and inflateInit2. + * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files + * created by gzip. (Files created by minigzip can still be extracted by + * gzip.) + */ +#ifndef MAX_WBITS +# define MAX_WBITS 15 /* 32K LZ77 window */ +#endif + +/* The memory requirements for deflate are (in bytes): + (1 << (windowBits+2)) + (1 << (memLevel+9)) + that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) + plus a few kilobytes for small objects. For example, if you want to reduce + the default memory requirements from 256K to 128K, compile with + make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" + Of course this will generally degrade compression (there's no free lunch). + + The memory requirements for inflate are (in bytes) 1 << windowBits + that is, 32K for windowBits=15 (default value) plus a few kilobytes + for small objects. +*/ + + /* Type declarations */ + +#ifndef OF /* function prototypes */ +# ifdef STDC +# define OF(args) args +# else +# define OF(args) () +# endif +#endif + +#ifndef Z_ARG /* function prototypes for stdarg */ +# if defined(STDC) || defined(Z_HAVE_STDARG_H) +# define Z_ARG(args) args +# else +# define Z_ARG(args) () +# endif +#endif + +/* The following definitions for FAR are needed only for MSDOS mixed + * model programming (small or medium model with some far allocations). + * This was tested only with MSC; for other MSDOS compilers you may have + * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, + * just define FAR to be empty. + */ +#ifdef SYS16BIT +# if defined(M_I86SM) || defined(M_I86MM) + /* MSC small or medium model */ +# define SMALL_MEDIUM +# ifdef _MSC_VER +# define FAR _far +# else +# define FAR far +# endif +# endif +# if (defined(__SMALL__) || defined(__MEDIUM__)) + /* Turbo C small or medium model */ +# define SMALL_MEDIUM +# ifdef __BORLANDC__ +# define FAR _far +# else +# define FAR far +# endif +# endif +#endif + +#if defined(WINDOWS) || defined(WIN32) + /* If building or using zlib as a DLL, define ZLIB_DLL. + * This is not mandatory, but it offers a little performance increase. + */ +# ifdef ZLIB_DLL +# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) +# ifdef ZLIB_INTERNAL +# define ZEXTERN extern __declspec(dllexport) +# else +# define ZEXTERN extern __declspec(dllimport) +# endif +# endif +# endif /* ZLIB_DLL */ + /* If building or using zlib with the WINAPI/WINAPIV calling convention, + * define ZLIB_WINAPI. + * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. + */ +# ifdef ZLIB_WINAPI +# ifdef FAR +# undef FAR +# endif +# include + /* No need for _export, use ZLIB.DEF instead. */ + /* For complete Windows compatibility, use WINAPI, not __stdcall. */ +# define ZEXPORT WINAPI +# ifdef WIN32 +# define ZEXPORTVA WINAPIV +# else +# define ZEXPORTVA FAR CDECL +# endif +# endif +#endif + +#if defined (__BEOS__) +# ifdef ZLIB_DLL +# ifdef ZLIB_INTERNAL +# define ZEXPORT __declspec(dllexport) +# define ZEXPORTVA __declspec(dllexport) +# else +# define ZEXPORT __declspec(dllimport) +# define ZEXPORTVA __declspec(dllimport) +# endif +# endif +#endif + +#ifndef ZEXTERN +# define ZEXTERN extern +#endif +#ifndef ZEXPORT +# define ZEXPORT +#endif +#ifndef ZEXPORTVA +# define ZEXPORTVA +#endif + +#ifndef FAR +# define FAR +#endif + +#if !defined(__MACTYPES__) +typedef unsigned char Byte; /* 8 bits */ +#endif +typedef unsigned int uInt; /* 16 bits or more */ +typedef unsigned long uLong; /* 32 bits or more */ + +#ifdef SMALL_MEDIUM + /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ +# define Bytef Byte FAR +#else + typedef Byte FAR Bytef; +#endif +typedef char FAR charf; +typedef int FAR intf; +typedef uInt FAR uIntf; +typedef uLong FAR uLongf; + +#ifdef STDC + typedef void const *voidpc; + typedef void FAR *voidpf; + typedef void *voidp; +#else + typedef Byte const *voidpc; + typedef Byte FAR *voidpf; + typedef Byte *voidp; +#endif + +#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC) +# include +# if (UINT_MAX == 0xffffffffUL) +# define Z_U4 unsigned +# elif (ULONG_MAX == 0xffffffffUL) +# define Z_U4 unsigned long +# elif (USHRT_MAX == 0xffffffffUL) +# define Z_U4 unsigned short +# endif +#endif + +#ifdef Z_U4 + typedef Z_U4 z_crc_t; +#else + typedef unsigned long z_crc_t; +#endif + +#if 1 /* was set to #if 1 by ./configure */ +# define Z_HAVE_UNISTD_H +#endif + +#if 1 /* was set to #if 1 by ./configure */ +# define Z_HAVE_STDARG_H +#endif + +#ifdef STDC +# ifndef Z_SOLO +# include /* for off_t */ +# endif +#endif + +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifndef Z_SOLO +# include /* for va_list */ +# endif +#endif + +#ifdef _WIN32 +# ifndef Z_SOLO +# include /* for wchar_t */ +# endif +#endif + +/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and + * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even + * though the former does not conform to the LFS document), but considering + * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as + * equivalently requesting no 64-bit operations + */ +#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1 +# undef _LARGEFILE64_SOURCE +#endif + +#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H) +# define Z_HAVE_UNISTD_H +#endif +#ifndef Z_SOLO +# if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) +# include /* for SEEK_*, off_t, and _LFS64_LARGEFILE */ +# ifdef VMS +# include /* for off_t */ +# endif +# ifndef z_off_t +# define z_off_t off_t +# endif +# endif +#endif + +#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0 +# define Z_LFS64 +#endif + +#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64) +# define Z_LARGE64 +#endif + +#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64) +# define Z_WANT64 +#endif + +#if !defined(SEEK_SET) && !defined(Z_SOLO) +# define SEEK_SET 0 /* Seek from beginning of file. */ +# define SEEK_CUR 1 /* Seek from current position. */ +# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ +#endif + +#ifndef z_off_t +# define z_off_t long +#endif + +#if !defined(_WIN32) && defined(Z_LARGE64) +# define z_off64_t off64_t +#else +# if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO) +# define z_off64_t __int64 +# else +# define z_off64_t z_off_t +# endif +#endif + +/* MVS linker does not support external names larger than 8 bytes */ +#if defined(__MVS__) + #pragma map(deflateInit_,"DEIN") + #pragma map(deflateInit2_,"DEIN2") + #pragma map(deflateEnd,"DEEND") + #pragma map(deflateBound,"DEBND") + #pragma map(inflateInit_,"ININ") + #pragma map(inflateInit2_,"ININ2") + #pragma map(inflateEnd,"INEND") + #pragma map(inflateSync,"INSY") + #pragma map(inflateSetDictionary,"INSEDI") + #pragma map(compressBound,"CMBND") + #pragma map(inflate_table,"INTABL") + #pragma map(inflate_fast,"INFA") + #pragma map(inflate_copyright,"INCOPY") +#endif + +#endif /* ZCONF_H */ diff --git a/inst/include/zlib/zlib.h b/inst/include/zlib/zlib.h new file mode 100644 index 0000000..25c7307 --- /dev/null +++ b/inst/include/zlib/zlib.h @@ -0,0 +1,1768 @@ +/* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.2.8, April 28th, 2013 + + Copyright (C) 1995-2013 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + + + The data format used by the zlib library is described by RFCs (Request for + Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950 + (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format). +*/ + +#ifndef ZLIB_H +#define ZLIB_H + +#include "zlib/zconf.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ZLIB_VERSION "1.2.8" +#define ZLIB_VERNUM 0x1280 +#define ZLIB_VER_MAJOR 1 +#define ZLIB_VER_MINOR 2 +#define ZLIB_VER_REVISION 8 +#define ZLIB_VER_SUBREVISION 0 + +/* + The 'zlib' compression library provides in-memory compression and + decompression functions, including integrity checks of the uncompressed data. + This version of the library supports only one compression method (deflation) + but other algorithms will be added later and will have the same stream + interface. + + Compression can be done in a single step if the buffers are large enough, + or can be done by repeated calls of the compression function. In the latter + case, the application must provide more input and/or consume the output + (providing more output space) before each call. + + The compressed data format used by default by the in-memory functions is + the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped + around a deflate stream, which is itself documented in RFC 1951. + + The library also supports reading and writing files in gzip (.gz) format + with an interface similar to that of stdio using the functions that start + with "gz". The gzip format is different from the zlib format. gzip is a + gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. + + This library can optionally read and write gzip streams in memory as well. + + The zlib format was designed to be compact and fast for use in memory + and on communications channels. The gzip format was designed for single- + file compression on file systems, has a larger header than zlib to maintain + directory information, and uses a different, slower check method than zlib. + + The library does not install any signal handler. The decoder checks + the consistency of the compressed data, so the library should never crash + even in case of corrupted input. +*/ + +typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); +typedef void (*free_func) OF((voidpf opaque, voidpf address)); + +struct internal_state; + +typedef struct z_stream_s { + z_const Bytef *next_in; /* next input byte */ + uInt avail_in; /* number of bytes available at next_in */ + uLong total_in; /* total number of input bytes read so far */ + + Bytef *next_out; /* next output byte should be put there */ + uInt avail_out; /* remaining free space at next_out */ + uLong total_out; /* total number of bytes output so far */ + + z_const char *msg; /* last error message, NULL if no error */ + struct internal_state FAR *state; /* not visible by applications */ + + alloc_func zalloc; /* used to allocate the internal state */ + free_func zfree; /* used to free the internal state */ + voidpf opaque; /* private data object passed to zalloc and zfree */ + + int data_type; /* best guess about the data type: binary or text */ + uLong adler; /* adler32 value of the uncompressed data */ + uLong reserved; /* reserved for future use */ +} z_stream; + +typedef z_stream FAR *z_streamp; + +/* + gzip header information passed to and from zlib routines. See RFC 1952 + for more details on the meanings of these fields. +*/ +typedef struct gz_header_s { + int text; /* true if compressed data believed to be text */ + uLong time; /* modification time */ + int xflags; /* extra flags (not used when writing a gzip file) */ + int os; /* operating system */ + Bytef *extra; /* pointer to extra field or Z_NULL if none */ + uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ + uInt extra_max; /* space at extra (only when reading header) */ + Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ + uInt name_max; /* space at name (only when reading header) */ + Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ + uInt comm_max; /* space at comment (only when reading header) */ + int hcrc; /* true if there was or will be a header crc */ + int done; /* true when done reading gzip header (not used + when writing a gzip file) */ +} gz_header; + +typedef gz_header FAR *gz_headerp; + +/* + The application must update next_in and avail_in when avail_in has dropped + to zero. It must update next_out and avail_out when avail_out has dropped + to zero. The application must initialize zalloc, zfree and opaque before + calling the init function. All other fields are set by the compression + library and must not be updated by the application. + + The opaque value provided by the application will be passed as the first + parameter for calls of zalloc and zfree. This can be useful for custom + memory management. The compression library attaches no meaning to the + opaque value. + + zalloc must return Z_NULL if there is not enough memory for the object. + If zlib is used in a multi-threaded application, zalloc and zfree must be + thread safe. + + On 16-bit systems, the functions zalloc and zfree must be able to allocate + exactly 65536 bytes, but will not be required to allocate more than this if + the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers + returned by zalloc for objects of exactly 65536 bytes *must* have their + offset normalized to zero. The default allocation function provided by this + library ensures this (see zutil.c). To reduce memory requirements and avoid + any allocation of 64K objects, at the expense of compression ratio, compile + the library with -DMAX_WBITS=14 (see zconf.h). + + The fields total_in and total_out can be used for statistics or progress + reports. After compression, total_in holds the total size of the + uncompressed data and may be saved for use in the decompressor (particularly + if the decompressor wants to decompress everything in a single step). +*/ + + /* constants */ + +#define Z_NO_FLUSH 0 +#define Z_PARTIAL_FLUSH 1 +#define Z_SYNC_FLUSH 2 +#define Z_FULL_FLUSH 3 +#define Z_FINISH 4 +#define Z_BLOCK 5 +#define Z_TREES 6 +/* Allowed flush values; see deflate() and inflate() below for details */ + +#define Z_OK 0 +#define Z_STREAM_END 1 +#define Z_NEED_DICT 2 +#define Z_ERRNO (-1) +#define Z_STREAM_ERROR (-2) +#define Z_DATA_ERROR (-3) +#define Z_MEM_ERROR (-4) +#define Z_BUF_ERROR (-5) +#define Z_VERSION_ERROR (-6) +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + +#define Z_NO_COMPRESSION 0 +#define Z_BEST_SPEED 1 +#define Z_BEST_COMPRESSION 9 +#define Z_DEFAULT_COMPRESSION (-1) +/* compression levels */ + +#define Z_FILTERED 1 +#define Z_HUFFMAN_ONLY 2 +#define Z_RLE 3 +#define Z_FIXED 4 +#define Z_DEFAULT_STRATEGY 0 +/* compression strategy; see deflateInit2() below for details */ + +#define Z_BINARY 0 +#define Z_TEXT 1 +#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ +#define Z_UNKNOWN 2 +/* Possible values of the data_type field (though see inflate()) */ + +#define Z_DEFLATED 8 +/* The deflate compression method (the only one supported in this version) */ + +#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ + +#define zlib_version zlibVersion() +/* for compatibility with versions < 1.0.2 */ + + + /* basic functions */ + +ZEXTERN const char * ZEXPORT zlibVersion OF((void)); +/* The application can compare zlibVersion and ZLIB_VERSION for consistency. + If the first character differs, the library code actually used is not + compatible with the zlib.h header file used by the application. This check + is automatically made by deflateInit and inflateInit. + */ + +/* +ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); + + Initializes the internal stream state for compression. The fields + zalloc, zfree and opaque must be initialized before by the caller. If + zalloc and zfree are set to Z_NULL, deflateInit updates them to use default + allocation functions. + + The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: + 1 gives best speed, 9 gives best compression, 0 gives no compression at all + (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION + requests a default compromise between speed and compression (currently + equivalent to level 6). + + deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if level is not a valid compression level, or + Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible + with the version assumed by the caller (ZLIB_VERSION). msg is set to null + if there is no error message. deflateInit does not perform any compression: + this will be done by deflate(). +*/ + + +ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); +/* + deflate compresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. deflate performs one or both of the + following actions: + + - Compress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in and avail_in are updated and + processing will resume at this point for the next call of deflate(). + + - Provide more output starting at next_out and update next_out and avail_out + accordingly. This action is forced if the parameter flush is non zero. + Forcing flush frequently degrades the compression ratio, so this parameter + should be set only when necessary (in interactive applications). Some + output may be provided even if flush is not set. + + Before the call of deflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating avail_in or avail_out accordingly; avail_out should + never be zero before the call. The application can consume the compressed + output when it wants, for example when the output buffer is full (avail_out + == 0), or after each call of deflate(). If deflate returns Z_OK and with + zero avail_out, it must be called again after making room in the output + buffer because there might be more output pending. + + Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to + decide how much data to accumulate before producing output, in order to + maximize compression. + + If the parameter flush is set to Z_SYNC_FLUSH, all pending output is + flushed to the output buffer and the output is aligned on a byte boundary, so + that the decompressor can get all input data available so far. (In + particular avail_in is zero after the call if enough output space has been + provided before the call.) Flushing may degrade compression for some + compression algorithms and so it should be used only when necessary. This + completes the current deflate block and follows it with an empty stored block + that is three bits plus filler bits to the next byte, followed by four bytes + (00 00 ff ff). + + If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the + output buffer, but the output is not aligned to a byte boundary. All of the + input data so far will be available to the decompressor, as for Z_SYNC_FLUSH. + This completes the current deflate block and follows it with an empty fixed + codes block that is 10 bits long. This assures that enough bytes are output + in order for the decompressor to finish the block before the empty fixed code + block. + + If flush is set to Z_BLOCK, a deflate block is completed and emitted, as + for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to + seven bits of the current block are held to be written as the next byte after + the next deflate block is completed. In this case, the decompressor may not + be provided enough bits at this point in order to complete decompression of + the data provided so far to the compressor. It may need to wait for the next + block to be emitted. This is for advanced applications that need to control + the emission of deflate blocks. + + If flush is set to Z_FULL_FLUSH, all output is flushed as with + Z_SYNC_FLUSH, and the compression state is reset so that decompression can + restart from this point if previous compressed data has been damaged or if + random access is desired. Using Z_FULL_FLUSH too often can seriously degrade + compression. + + If deflate returns with avail_out == 0, this function must be called again + with the same value of the flush parameter and more output space (updated + avail_out), until the flush is complete (deflate returns with non-zero + avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that + avail_out is greater than six to avoid repeated flush markers due to + avail_out == 0 on return. + + If the parameter flush is set to Z_FINISH, pending input is processed, + pending output is flushed and deflate returns with Z_STREAM_END if there was + enough output space; if deflate returns with Z_OK, this function must be + called again with Z_FINISH and more output space (updated avail_out) but no + more input data, until it returns with Z_STREAM_END or an error. After + deflate has returned Z_STREAM_END, the only possible operations on the stream + are deflateReset or deflateEnd. + + Z_FINISH can be used immediately after deflateInit if all the compression + is to be done in a single step. In this case, avail_out must be at least the + value returned by deflateBound (see below). Then deflate is guaranteed to + return Z_STREAM_END. If not enough output space is provided, deflate will + not return Z_STREAM_END, and it must be called again as described above. + + deflate() sets strm->adler to the adler32 checksum of all input read + so far (that is, total_in bytes). + + deflate() may update strm->data_type if it can make a good guess about + the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered + binary. This field is only for information purposes and does not affect the + compression algorithm in any manner. + + deflate() returns Z_OK if some progress has been made (more input + processed or more output produced), Z_STREAM_END if all input has been + consumed and all output has been produced (only when flush is set to + Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example + if next_in or next_out was Z_NULL), Z_BUF_ERROR if no progress is possible + (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not + fatal, and deflate() can be called again with more input and more output + space to continue compressing. +*/ + + +ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the + stream state was inconsistent, Z_DATA_ERROR if the stream was freed + prematurely (some input or output was discarded). In the error case, msg + may be set but then points to a static string (which must not be + deallocated). +*/ + + +/* +ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); + + Initializes the internal stream state for decompression. The fields + next_in, avail_in, zalloc, zfree and opaque must be initialized before by + the caller. If next_in is not Z_NULL and avail_in is large enough (the + exact value depends on the compression method), inflateInit determines the + compression method from the zlib header and allocates all data structures + accordingly; otherwise the allocation will be deferred to the first call of + inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to + use default allocation functions. + + inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit does not perform any decompression + apart from possibly reading the zlib header if present: actual decompression + will be done by inflate(). (So next_in and avail_in may be modified, but + next_out and avail_out are unused and unchanged.) The current implementation + of inflateInit() does not process any header information -- that is deferred + until inflate() is called. +*/ + + +ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); +/* + inflate decompresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. inflate performs one or both of the + following actions: + + - Decompress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in is updated and processing will + resume at this point for the next call of inflate(). + + - Provide more output starting at next_out and update next_out and avail_out + accordingly. inflate() provides as much output as possible, until there is + no more input data or no more space in the output buffer (see below about + the flush parameter). + + Before the call of inflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating the next_* and avail_* values accordingly. The + application can consume the uncompressed output when it wants, for example + when the output buffer is full (avail_out == 0), or after each call of + inflate(). If inflate returns Z_OK and with zero avail_out, it must be + called again after making room in the output buffer because there might be + more output pending. + + The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, + Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much + output as possible to the output buffer. Z_BLOCK requests that inflate() + stop if and when it gets to the next deflate block boundary. When decoding + the zlib or gzip format, this will cause inflate() to return immediately + after the header and before the first block. When doing a raw inflate, + inflate() will go ahead and process the first block, and will return when it + gets to the end of that block, or when it runs out of data. + + The Z_BLOCK option assists in appending to or combining deflate streams. + Also to assist in this, on return inflate() will set strm->data_type to the + number of unused bits in the last byte taken from strm->next_in, plus 64 if + inflate() is currently decoding the last block in the deflate stream, plus + 128 if inflate() returned immediately after decoding an end-of-block code or + decoding the complete header up to just before the first byte of the deflate + stream. The end-of-block will not be indicated until all of the uncompressed + data from that block has been written to strm->next_out. The number of + unused bits may in general be greater than seven, except when bit 7 of + data_type is set, in which case the number of unused bits will be less than + eight. data_type is set as noted here every time inflate() returns for all + flush options, and so can be used to determine the amount of currently + consumed input in bits. + + The Z_TREES option behaves as Z_BLOCK does, but it also returns when the + end of each deflate block header is reached, before any actual data in that + block is decoded. This allows the caller to determine the length of the + deflate block header for later use in random access within a deflate block. + 256 is added to the value of strm->data_type when inflate() returns + immediately after reaching the end of the deflate block header. + + inflate() should normally be called until it returns Z_STREAM_END or an + error. However if all decompression is to be performed in a single step (a + single call of inflate), the parameter flush should be set to Z_FINISH. In + this case all pending input is processed and all pending output is flushed; + avail_out must be large enough to hold all of the uncompressed data for the + operation to complete. (The size of the uncompressed data may have been + saved by the compressor for this purpose.) The use of Z_FINISH is not + required to perform an inflation in one step. However it may be used to + inform inflate that a faster approach can be used for the single inflate() + call. Z_FINISH also informs inflate to not maintain a sliding window if the + stream completes, which reduces inflate's memory footprint. If the stream + does not complete, either because not all of the stream is provided or not + enough output space is provided, then a sliding window will be allocated and + inflate() can be called again to continue the operation as if Z_NO_FLUSH had + been used. + + In this implementation, inflate() always flushes as much output as + possible to the output buffer, and always uses the faster approach on the + first call. So the effects of the flush parameter in this implementation are + on the return value of inflate() as noted below, when inflate() returns early + when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of + memory for a sliding window when Z_FINISH is used. + + If a preset dictionary is needed after this call (see inflateSetDictionary + below), inflate sets strm->adler to the Adler-32 checksum of the dictionary + chosen by the compressor and returns Z_NEED_DICT; otherwise it sets + strm->adler to the Adler-32 checksum of all output produced so far (that is, + total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described + below. At the end of the stream, inflate() checks that its computed adler32 + checksum is equal to that saved by the compressor and returns Z_STREAM_END + only if the checksum is correct. + + inflate() can decompress and check either zlib-wrapped or gzip-wrapped + deflate data. The header type is detected automatically, if requested when + initializing with inflateInit2(). Any information contained in the gzip + header is not retained, so applications that need that information should + instead use raw inflate, see inflateInit2() below, or inflateBack() and + perform their own processing of the gzip header and trailer. When processing + gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output + producted so far. The CRC-32 is checked against the gzip trailer. + + inflate() returns Z_OK if some progress has been made (more input processed + or more output produced), Z_STREAM_END if the end of the compressed data has + been reached and all uncompressed output has been produced, Z_NEED_DICT if a + preset dictionary is needed at this point, Z_DATA_ERROR if the input data was + corrupted (input stream not conforming to the zlib format or incorrect check + value), Z_STREAM_ERROR if the stream structure was inconsistent (for example + next_in or next_out was Z_NULL), Z_MEM_ERROR if there was not enough memory, + Z_BUF_ERROR if no progress is possible or if there was not enough room in the + output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and + inflate() can be called again with more input and more output space to + continue decompressing. If Z_DATA_ERROR is returned, the application may + then call inflateSync() to look for a good compression block if a partial + recovery of the data is desired. +*/ + + +ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state + was inconsistent. In the error case, msg may be set but then points to a + static string (which must not be deallocated). +*/ + + + /* Advanced functions */ + +/* + The following functions are needed only in some special applications. +*/ + +/* +ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, + int level, + int method, + int windowBits, + int memLevel, + int strategy)); + + This is another version of deflateInit with more compression options. The + fields next_in, zalloc, zfree and opaque must be initialized before by the + caller. + + The method parameter is the compression method. It must be Z_DEFLATED in + this version of the library. + + The windowBits parameter is the base two logarithm of the window size + (the size of the history buffer). It should be in the range 8..15 for this + version of the library. Larger values of this parameter result in better + compression at the expense of memory usage. The default value is 15 if + deflateInit is used instead. + + windowBits can also be -8..-15 for raw deflate. In this case, -windowBits + determines the window size. deflate() will then generate raw deflate data + with no zlib header or trailer, and will not compute an adler32 check value. + + windowBits can also be greater than 15 for optional gzip encoding. Add + 16 to windowBits to write a simple gzip header and trailer around the + compressed data instead of a zlib wrapper. The gzip header will have no + file name, no extra data, no comment, no modification time (set to zero), no + header crc, and the operating system will be set to 255 (unknown). If a + gzip stream is being written, strm->adler is a crc32 instead of an adler32. + + The memLevel parameter specifies how much memory should be allocated + for the internal compression state. memLevel=1 uses minimum memory but is + slow and reduces compression ratio; memLevel=9 uses maximum memory for + optimal speed. The default value is 8. See zconf.h for total memory usage + as a function of windowBits and memLevel. + + The strategy parameter is used to tune the compression algorithm. Use the + value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a + filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no + string match), or Z_RLE to limit match distances to one (run-length + encoding). Filtered data consists mostly of small values with a somewhat + random distribution. In this case, the compression algorithm is tuned to + compress them better. The effect of Z_FILTERED is to force more Huffman + coding and less string matching; it is somewhat intermediate between + Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as + fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The + strategy parameter only affects the compression ratio but not the + correctness of the compressed output even if it is not set appropriately. + Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler + decoder for special applications. + + deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid + method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is + incompatible with the version assumed by the caller (ZLIB_VERSION). msg is + set to null if there is no error message. deflateInit2 does not perform any + compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the compression dictionary from the given byte sequence + without producing any compressed output. When using the zlib format, this + function must be called immediately after deflateInit, deflateInit2 or + deflateReset, and before any call of deflate. When doing raw deflate, this + function must be called either before any call of deflate, or immediately + after the completion of a deflate block, i.e. after all input has been + consumed and all output has been delivered when using any of the flush + options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH. The + compressor and decompressor must use exactly the same dictionary (see + inflateSetDictionary). + + The dictionary should consist of strings (byte sequences) that are likely + to be encountered later in the data to be compressed, with the most commonly + used strings preferably put towards the end of the dictionary. Using a + dictionary is most useful when the data to be compressed is short and can be + predicted with good accuracy; the data can then be compressed better than + with the default empty dictionary. + + Depending on the size of the compression data structures selected by + deflateInit or deflateInit2, a part of the dictionary may in effect be + discarded, for example if the dictionary is larger than the window size + provided in deflateInit or deflateInit2. Thus the strings most likely to be + useful should be put at the end of the dictionary, not at the front. In + addition, the current implementation of deflate will use at most the window + size minus 262 bytes of the provided dictionary. + + Upon return of this function, strm->adler is set to the adler32 value + of the dictionary; the decompressor may later use this value to determine + which dictionary has been used by the compressor. (The adler32 value + applies to the whole dictionary even if only a subset of the dictionary is + actually used by the compressor.) If a raw deflate was requested, then the + adler32 value is not computed and strm->adler is not set. + + deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent (for example if deflate has already been called for this stream + or if not at a block boundary for raw deflate). deflateSetDictionary does + not perform any compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when several compression strategies will be + tried, for example when there are several ways of pre-processing the input + data with a filter. The streams that will be discarded should then be freed + by calling deflateEnd. Note that deflateCopy duplicates the internal + compression state which can be quite large, so this strategy is slow and can + consume lots of memory. + + deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); +/* + This function is equivalent to deflateEnd followed by deflateInit, + but does not free and reallocate all the internal compression state. The + stream will keep the same compression level and any other attributes that + may have been set by deflateInit2. + + deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + +ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, + int level, + int strategy)); +/* + Dynamically update the compression level and compression strategy. The + interpretation of level and strategy is as in deflateInit2. This can be + used to switch between compression and straight copy of the input data, or + to switch to a different kind of input data requiring a different strategy. + If the compression level is changed, the input available so far is + compressed with the old level (and may be flushed); the new level will take + effect only at the next call of deflate(). + + Before the call of deflateParams, the stream state must be set as for + a call of deflate(), since the currently available input may have to be + compressed and flushed. In particular, strm->avail_out must be non-zero. + + deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source + stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR if + strm->avail_out was zero. +*/ + +ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, + int good_length, + int max_lazy, + int nice_length, + int max_chain)); +/* + Fine tune deflate's internal compression parameters. This should only be + used by someone who understands the algorithm used by zlib's deflate for + searching for the best matching string, and even then only by the most + fanatic optimizer trying to squeeze out the last compressed bit for their + specific input data. Read the deflate.c source code for the meaning of the + max_lazy, good_length, nice_length, and max_chain parameters. + + deflateTune() can be called after deflateInit() or deflateInit2(), and + returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. + */ + +ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, + uLong sourceLen)); +/* + deflateBound() returns an upper bound on the compressed size after + deflation of sourceLen bytes. It must be called after deflateInit() or + deflateInit2(), and after deflateSetHeader(), if used. This would be used + to allocate an output buffer for deflation in a single pass, and so would be + called before deflate(). If that first deflate() call is provided the + sourceLen input bytes, an output buffer allocated to the size returned by + deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed + to return Z_STREAM_END. Note that it is possible for the compressed size to + be larger than the value returned by deflateBound() if flush options other + than Z_FINISH or Z_NO_FLUSH are used. +*/ + +ZEXTERN int ZEXPORT deflatePending OF((z_streamp strm, + unsigned *pending, + int *bits)); +/* + deflatePending() returns the number of bytes and bits of output that have + been generated, but not yet provided in the available output. The bytes not + provided would be due to the available output space having being consumed. + The number of bits of output not provided are between 0 and 7, where they + await more bits to join them in order to fill out a full byte. If pending + or bits are Z_NULL, then those values are not set. + + deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. + */ + +ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + deflatePrime() inserts bits in the deflate output stream. The intent + is that this function is used to start off the deflate output with the bits + leftover from a previous deflate stream when appending to it. As such, this + function can only be used for raw deflate, and must be used before the first + deflate() call after a deflateInit2() or deflateReset(). bits must be less + than or equal to 16, and that many of the least significant bits of value + will be inserted in the output. + + deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough + room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the + source stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, + gz_headerp head)); +/* + deflateSetHeader() provides gzip header information for when a gzip + stream is requested by deflateInit2(). deflateSetHeader() may be called + after deflateInit2() or deflateReset() and before the first call of + deflate(). The text, time, os, extra field, name, and comment information + in the provided gz_header structure are written to the gzip header (xflag is + ignored -- the extra flags are set according to the compression level). The + caller must assure that, if not Z_NULL, name and comment are terminated with + a zero byte, and that if extra is not Z_NULL, that extra_len bytes are + available there. If hcrc is true, a gzip header crc is included. Note that + the current versions of the command-line version of gzip (up through version + 1.3.x) do not support header crc's, and will report that it is a "multi-part + gzip file" and give up. + + If deflateSetHeader is not used, the default gzip header has text false, + the time set to zero, and os set to 255, with no extra, name, or comment + fields. The gzip header is returned to the default state by deflateReset(). + + deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, + int windowBits)); + + This is another version of inflateInit with an extra parameter. The + fields next_in, avail_in, zalloc, zfree and opaque must be initialized + before by the caller. + + The windowBits parameter is the base two logarithm of the maximum window + size (the size of the history buffer). It should be in the range 8..15 for + this version of the library. The default value is 15 if inflateInit is used + instead. windowBits must be greater than or equal to the windowBits value + provided to deflateInit2() while compressing, or it must be equal to 15 if + deflateInit2() was not used. If a compressed stream with a larger window + size is given as input, inflate() will return with the error code + Z_DATA_ERROR instead of trying to allocate a larger window. + + windowBits can also be zero to request that inflate use the window size in + the zlib header of the compressed stream. + + windowBits can also be -8..-15 for raw inflate. In this case, -windowBits + determines the window size. inflate() will then process raw deflate data, + not looking for a zlib or gzip header, not generating a check value, and not + looking for any check values for comparison at the end of the stream. This + is for use with other formats that use the deflate compressed data format + such as zip. Those formats provide their own check values. If a custom + format is developed using the raw deflate format for compressed data, it is + recommended that a check value such as an adler32 or a crc32 be applied to + the uncompressed data as is done in the zlib, gzip, and zip formats. For + most applications, the zlib format should be used as is. Note that comments + above on the use in deflateInit2() applies to the magnitude of windowBits. + + windowBits can also be greater than 15 for optional gzip decoding. Add + 32 to windowBits to enable zlib and gzip decoding with automatic header + detection, or add 16 to decode only the gzip format (the zlib format will + return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a + crc32 instead of an adler32. + + inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit2 does not perform any decompression + apart from possibly reading the zlib header if present: actual decompression + will be done by inflate(). (So next_in and avail_in may be modified, but + next_out and avail_out are unused and unchanged.) The current implementation + of inflateInit2() does not process any header information -- that is + deferred until inflate() is called. +*/ + +ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the decompression dictionary from the given uncompressed byte + sequence. This function must be called immediately after a call of inflate, + if that call returned Z_NEED_DICT. The dictionary chosen by the compressor + can be determined from the adler32 value returned by that call of inflate. + The compressor and decompressor must use exactly the same dictionary (see + deflateSetDictionary). For raw inflate, this function can be called at any + time to set the dictionary. If the provided dictionary is smaller than the + window and there is already data in the window, then the provided dictionary + will amend what's there. The application must insure that the dictionary + that was used for compression is provided. + + inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the + expected one (incorrect adler32 value). inflateSetDictionary does not + perform any decompression: this will be done by subsequent calls of + inflate(). +*/ + +ZEXTERN int ZEXPORT inflateGetDictionary OF((z_streamp strm, + Bytef *dictionary, + uInt *dictLength)); +/* + Returns the sliding dictionary being maintained by inflate. dictLength is + set to the number of bytes in the dictionary, and that many bytes are copied + to dictionary. dictionary must have enough space, where 32768 bytes is + always enough. If inflateGetDictionary() is called with dictionary equal to + Z_NULL, then only the dictionary length is returned, and nothing is copied. + Similary, if dictLength is Z_NULL, then it is not set. + + inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the + stream state is inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); +/* + Skips invalid compressed data until a possible full flush point (see above + for the description of deflate with Z_FULL_FLUSH) can be found, or until all + available input is skipped. No output is provided. + + inflateSync searches for a 00 00 FF FF pattern in the compressed data. + All full flush points have this pattern, but not all occurrences of this + pattern are full flush points. + + inflateSync returns Z_OK if a possible full flush point has been found, + Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point + has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. + In the success case, the application may save the current current value of + total_in which indicates where valid compressed data was found. In the + error case, the application may repeatedly call inflateSync, providing more + input each time, until success or end of the input data. +*/ + +ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when randomly accessing a large stream. The + first pass through the stream can periodically record the inflate state, + allowing restarting inflate at those points when randomly accessing the + stream. + + inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); +/* + This function is equivalent to inflateEnd followed by inflateInit, + but does not free and reallocate all the internal decompression state. The + stream will keep attributes that may have been set by inflateInit2. + + inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + +ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm, + int windowBits)); +/* + This function is the same as inflateReset, but it also permits changing + the wrap and window size requests. The windowBits parameter is interpreted + the same as it is for inflateInit2. + + inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL), or if + the windowBits parameter is invalid. +*/ + +ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + This function inserts bits in the inflate input stream. The intent is + that this function is used to start inflating at a bit position in the + middle of a byte. The provided bits will be used before any bytes are used + from next_in. This function should only be used with raw inflate, and + should be used before the first inflate() call after inflateInit2() or + inflateReset(). bits must be less than or equal to 16, and that many of the + least significant bits of value will be inserted in the input. + + If bits is negative, then the input stream bit buffer is emptied. Then + inflatePrime() can be called again to put bits in the buffer. This is used + to clear out bits leftover after feeding inflate a block description prior + to feeding inflate codes. + + inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm)); +/* + This function returns two values, one in the lower 16 bits of the return + value, and the other in the remaining upper bits, obtained by shifting the + return value down 16 bits. If the upper value is -1 and the lower value is + zero, then inflate() is currently decoding information outside of a block. + If the upper value is -1 and the lower value is non-zero, then inflate is in + the middle of a stored block, with the lower value equaling the number of + bytes from the input remaining to copy. If the upper value is not -1, then + it is the number of bits back from the current bit position in the input of + the code (literal or length/distance pair) currently being processed. In + that case the lower value is the number of bytes already emitted for that + code. + + A code is being processed if inflate is waiting for more input to complete + decoding of the code, or if it has completed decoding but is waiting for + more output space to write the literal or match data. + + inflateMark() is used to mark locations in the input data for random + access, which may be at bit positions, and to note those cases where the + output of a code may span boundaries of random access blocks. The current + location in the input stream can be determined from avail_in and data_type + as noted in the description for the Z_BLOCK flush parameter for inflate. + + inflateMark returns the value noted above or -1 << 16 if the provided + source stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, + gz_headerp head)); +/* + inflateGetHeader() requests that gzip header information be stored in the + provided gz_header structure. inflateGetHeader() may be called after + inflateInit2() or inflateReset(), and before the first call of inflate(). + As inflate() processes the gzip stream, head->done is zero until the header + is completed, at which time head->done is set to one. If a zlib stream is + being decoded, then head->done is set to -1 to indicate that there will be + no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be + used to force inflate() to return immediately after header processing is + complete and before any actual data is decompressed. + + The text, time, xflags, and os fields are filled in with the gzip header + contents. hcrc is set to true if there is a header CRC. (The header CRC + was valid if done is set to one.) If extra is not Z_NULL, then extra_max + contains the maximum number of bytes to write to extra. Once done is true, + extra_len contains the actual extra field length, and extra contains the + extra field, or that field truncated if extra_max is less than extra_len. + If name is not Z_NULL, then up to name_max characters are written there, + terminated with a zero unless the length is greater than name_max. If + comment is not Z_NULL, then up to comm_max characters are written there, + terminated with a zero unless the length is greater than comm_max. When any + of extra, name, or comment are not Z_NULL and the respective field is not + present in the header, then that field is set to Z_NULL to signal its + absence. This allows the use of deflateSetHeader() with the returned + structure to duplicate the header. However if those fields are set to + allocated memory, then the application will need to save those pointers + elsewhere so that they can be eventually freed. + + If inflateGetHeader is not used, then the header information is simply + discarded. The header is always checked for validity, including the header + CRC if present. inflateReset() will reset the process to discard the header + information. The application would need to call inflateGetHeader() again to + retrieve the header from the next gzip stream. + + inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, + unsigned char FAR *window)); + + Initialize the internal stream state for decompression using inflateBack() + calls. The fields zalloc, zfree and opaque in strm must be initialized + before the call. If zalloc and zfree are Z_NULL, then the default library- + derived memory allocation routines are used. windowBits is the base two + logarithm of the window size, in the range 8..15. window is a caller + supplied buffer of that size. Except for special applications where it is + assured that deflate was used with small window sizes, windowBits must be 15 + and a 32K byte window must be supplied to be able to decompress general + deflate streams. + + See inflateBack() for the usage of these routines. + + inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of + the parameters are invalid, Z_MEM_ERROR if the internal state could not be + allocated, or Z_VERSION_ERROR if the version of the library does not match + the version of the header file. +*/ + +typedef unsigned (*in_func) OF((void FAR *, + z_const unsigned char FAR * FAR *)); +typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); + +ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, + in_func in, void FAR *in_desc, + out_func out, void FAR *out_desc)); +/* + inflateBack() does a raw inflate with a single call using a call-back + interface for input and output. This is potentially more efficient than + inflate() for file i/o applications, in that it avoids copying between the + output and the sliding window by simply making the window itself the output + buffer. inflate() can be faster on modern CPUs when used with large + buffers. inflateBack() trusts the application to not change the output + buffer passed by the output function, at least until inflateBack() returns. + + inflateBackInit() must be called first to allocate the internal state + and to initialize the state with the user-provided window buffer. + inflateBack() may then be used multiple times to inflate a complete, raw + deflate stream with each call. inflateBackEnd() is then called to free the + allocated state. + + A raw deflate stream is one with no zlib or gzip header or trailer. + This routine would normally be used in a utility that reads zip or gzip + files and writes out uncompressed files. The utility would decode the + header and process the trailer on its own, hence this routine expects only + the raw deflate stream to decompress. This is different from the normal + behavior of inflate(), which expects either a zlib or gzip header and + trailer around the deflate stream. + + inflateBack() uses two subroutines supplied by the caller that are then + called by inflateBack() for input and output. inflateBack() calls those + routines until it reads a complete deflate stream and writes out all of the + uncompressed data, or until it encounters an error. The function's + parameters and return types are defined above in the in_func and out_func + typedefs. inflateBack() will call in(in_desc, &buf) which should return the + number of bytes of provided input, and a pointer to that input in buf. If + there is no input available, in() must return zero--buf is ignored in that + case--and inflateBack() will return a buffer error. inflateBack() will call + out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() + should return zero on success, or non-zero on failure. If out() returns + non-zero, inflateBack() will return with an error. Neither in() nor out() + are permitted to change the contents of the window provided to + inflateBackInit(), which is also the buffer that out() uses to write from. + The length written by out() will be at most the window size. Any non-zero + amount of input may be provided by in(). + + For convenience, inflateBack() can be provided input on the first call by + setting strm->next_in and strm->avail_in. If that input is exhausted, then + in() will be called. Therefore strm->next_in must be initialized before + calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called + immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in + must also be initialized, and then if strm->avail_in is not zero, input will + initially be taken from strm->next_in[0 .. strm->avail_in - 1]. + + The in_desc and out_desc parameters of inflateBack() is passed as the + first parameter of in() and out() respectively when they are called. These + descriptors can be optionally used to pass any information that the caller- + supplied in() and out() functions need to do their job. + + On return, inflateBack() will set strm->next_in and strm->avail_in to + pass back any unused input that was provided by the last in() call. The + return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR + if in() or out() returned an error, Z_DATA_ERROR if there was a format error + in the deflate stream (in which case strm->msg is set to indicate the nature + of the error), or Z_STREAM_ERROR if the stream was not properly initialized. + In the case of Z_BUF_ERROR, an input or output error can be distinguished + using strm->next_in which will be Z_NULL only if in() returned an error. If + strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning + non-zero. (in() will always be called before out(), so strm->next_in is + assured to be defined if out() returns non-zero.) Note that inflateBack() + cannot return Z_OK. +*/ + +ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); +/* + All memory allocated by inflateBackInit() is freed. + + inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream + state was inconsistent. +*/ + +ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); +/* Return flags indicating compile-time options. + + Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: + 1.0: size of uInt + 3.2: size of uLong + 5.4: size of voidpf (pointer) + 7.6: size of z_off_t + + Compiler, assembler, and debug options: + 8: DEBUG + 9: ASMV or ASMINF -- use ASM code + 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention + 11: 0 (reserved) + + One-time table building (smaller code, but not thread-safe if true): + 12: BUILDFIXED -- build static block decoding tables when needed + 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed + 14,15: 0 (reserved) + + Library content (indicates missing functionality): + 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking + deflate code when not needed) + 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect + and decode gzip streams (to avoid linking crc code) + 18-19: 0 (reserved) + + Operation variations (changes in library functionality): + 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate + 21: FASTEST -- deflate algorithm with only one, lowest compression level + 22,23: 0 (reserved) + + The sprintf variant used by gzprintf (zero is best): + 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format + 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! + 26: 0 = returns value, 1 = void -- 1 means inferred string length returned + + Remainder: + 27-31: 0 (reserved) + */ + +#ifndef Z_SOLO + + /* utility functions */ + +/* + The following utility functions are implemented on top of the basic + stream-oriented functions. To simplify the interface, some default options + are assumed (compression level and memory usage, standard memory allocation + functions). The source code of these utility functions can be modified if + you need special options. +*/ + +ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Compresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size + of the destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed buffer. + + compress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer. +*/ + +ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen, + int level)); +/* + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed buffer. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ + +ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); +/* + compressBound() returns an upper bound on the compressed size after + compress() or compress2() on sourceLen bytes. It would be used before a + compress() or compress2() call to allocate the destination buffer. +*/ + +ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size + of the destination buffer, which must be large enough to hold the entire + uncompressed data. (The size of the uncompressed data must have been saved + previously by the compressor and transmitted to the decompressor by some + mechanism outside the scope of this compression library.) Upon exit, destLen + is the actual size of the uncompressed buffer. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. In + the case where there is not enough room, uncompress() will fill the output + buffer with the uncompressed data up to that point. +*/ + + /* gzip file access functions */ + +/* + This library supports reading and writing files in gzip (.gz) format with + an interface similar to that of stdio, using the functions that start with + "gz". The gzip format is different from the zlib format. gzip is a gzip + wrapper, documented in RFC 1952, wrapped around a deflate stream. +*/ + +typedef struct gzFile_s *gzFile; /* semi-opaque gzip file descriptor */ + +/* +ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); + + Opens a gzip (.gz) file for reading or writing. The mode parameter is as + in fopen ("rb" or "wb") but can also include a compression level ("wb9") or + a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only + compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F' + for fixed code compression as in "wb9F". (See the description of + deflateInit2 for more information about the strategy parameter.) 'T' will + request transparent writing or appending with no compression and not using + the gzip format. + + "a" can be used instead of "w" to request that the gzip stream that will + be written be appended to the file. "+" will result in an error, since + reading and writing to the same gzip file is not supported. The addition of + "x" when writing will create the file exclusively, which fails if the file + already exists. On systems that support it, the addition of "e" when + reading or writing will set the flag to close the file on an execve() call. + + These functions, as well as gzip, will read and decode a sequence of gzip + streams in a file. The append function of gzopen() can be used to create + such a file. (Also see gzflush() for another way to do this.) When + appending, gzopen does not test whether the file begins with a gzip stream, + nor does it look for the end of the gzip streams to begin appending. gzopen + will simply append a gzip stream to the existing file. + + gzopen can be used to read a file which is not in gzip format; in this + case gzread will directly read from the file without decompression. When + reading, this will be detected automatically by looking for the magic two- + byte gzip header. + + gzopen returns NULL if the file could not be opened, if there was + insufficient memory to allocate the gzFile state, or if an invalid mode was + specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). + errno can be checked to determine if the reason gzopen failed was that the + file could not be opened. +*/ + +ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); +/* + gzdopen associates a gzFile with the file descriptor fd. File descriptors + are obtained from calls like open, dup, creat, pipe or fileno (if the file + has been previously opened with fopen). The mode parameter is as in gzopen. + + The next call of gzclose on the returned gzFile will also close the file + descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor + fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, + mode);. The duplicated descriptor should be saved to avoid a leak, since + gzdopen does not close fd if it fails. If you are using fileno() to get the + file descriptor from a FILE *, then you will have to use dup() to avoid + double-close()ing the file descriptor. Both gzclose() and fclose() will + close the associated file descriptor, so they need to have different file + descriptors. + + gzdopen returns NULL if there was insufficient memory to allocate the + gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not + provided, or '+' was provided), or if fd is -1. The file descriptor is not + used until the next gz* read, write, seek, or close operation, so gzdopen + will not detect if fd is invalid (unless fd is -1). +*/ + +ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size)); +/* + Set the internal buffer size used by this library's functions. The + default buffer size is 8192 bytes. This function must be called after + gzopen() or gzdopen(), and before any other calls that read or write the + file. The buffer memory allocation is always deferred to the first read or + write. Two buffers are allocated, either both of the specified size when + writing, or one of the specified size and the other twice that size when + reading. A larger buffer size of, for example, 64K or 128K bytes will + noticeably increase the speed of decompression (reading). + + The new buffer size also affects the maximum length for gzprintf(). + + gzbuffer() returns 0 on success, or -1 on failure, such as being called + too late. +*/ + +ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); +/* + Dynamically update the compression level or strategy. See the description + of deflateInit2 for the meaning of these parameters. + + gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not + opened for writing. +*/ + +ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); +/* + Reads the given number of uncompressed bytes from the compressed file. If + the input file is not in gzip format, gzread copies the given number of + bytes into the buffer directly from the file. + + After reaching the end of a gzip stream in the input, gzread will continue + to read, looking for another gzip stream. Any number of gzip streams may be + concatenated in the input file, and will all be decompressed by gzread(). + If something other than a gzip stream is encountered after a gzip stream, + that remaining trailing garbage is ignored (and no error is returned). + + gzread can be used to read a gzip file that is being concurrently written. + Upon reaching the end of the input, gzread will return with the available + data. If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then + gzclearerr can be used to clear the end of file indicator in order to permit + gzread to be tried again. Z_OK indicates that a gzip stream was completed + on the last gzread. Z_BUF_ERROR indicates that the input file ended in the + middle of a gzip stream. Note that gzread does not return -1 in the event + of an incomplete gzip stream. This error is deferred until gzclose(), which + will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip + stream. Alternatively, gzerror can be used before gzclose to detect this + case. + + gzread returns the number of uncompressed bytes actually read, less than + len for end of file, or -1 for error. +*/ + +ZEXTERN int ZEXPORT gzwrite OF((gzFile file, + voidpc buf, unsigned len)); +/* + Writes the given number of uncompressed bytes into the compressed file. + gzwrite returns the number of uncompressed bytes written or 0 in case of + error. +*/ + +ZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...)); +/* + Converts, formats, and writes the arguments to the compressed file under + control of the format string, as in fprintf. gzprintf returns the number of + uncompressed bytes actually written, or 0 in case of error. The number of + uncompressed bytes written is limited to 8191, or one less than the buffer + size given to gzbuffer(). The caller should assure that this limit is not + exceeded. If it is exceeded, then gzprintf() will return an error (0) with + nothing written. In this case, there may also be a buffer overflow with + unpredictable consequences, which is possible only if zlib was compiled with + the insecure functions sprintf() or vsprintf() because the secure snprintf() + or vsnprintf() functions were not available. This can be determined using + zlibCompileFlags(). +*/ + +ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); +/* + Writes the given null-terminated string to the compressed file, excluding + the terminating null character. + + gzputs returns the number of characters written, or -1 in case of error. +*/ + +ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); +/* + Reads bytes from the compressed file until len-1 characters are read, or a + newline character is read and transferred to buf, or an end-of-file + condition is encountered. If any characters are read or if len == 1, the + string is terminated with a null character. If no characters are read due + to an end-of-file or len < 1, then the buffer is left untouched. + + gzgets returns buf which is a null-terminated string, or it returns NULL + for end-of-file or in case of error. If there was an error, the contents at + buf are indeterminate. +*/ + +ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); +/* + Writes c, converted to an unsigned char, into the compressed file. gzputc + returns the value that was written, or -1 in case of error. +*/ + +ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); +/* + Reads one byte from the compressed file. gzgetc returns this byte or -1 + in case of end of file or error. This is implemented as a macro for speed. + As such, it does not do all of the checking the other functions do. I.e. + it does not check to see if file is NULL, nor whether the structure file + points to has been clobbered or not. +*/ + +ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); +/* + Push one character back onto the stream to be read as the first character + on the next read. At least one character of push-back is allowed. + gzungetc() returns the character pushed, or -1 on failure. gzungetc() will + fail if c is -1, and may fail if a character has been pushed but not read + yet. If gzungetc is used immediately after gzopen or gzdopen, at least the + output buffer size of pushed characters is allowed. (See gzbuffer above.) + The pushed character will be discarded if the stream is repositioned with + gzseek() or gzrewind(). +*/ + +ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); +/* + Flushes all pending output into the compressed file. The parameter flush + is as in the deflate() function. The return value is the zlib error number + (see function gzerror below). gzflush is only permitted when writing. + + If the flush parameter is Z_FINISH, the remaining data is written and the + gzip stream is completed in the output. If gzwrite() is called again, a new + gzip stream will be started in the output. gzread() is able to read such + concatented gzip streams. + + gzflush should be called only when strictly necessary because it will + degrade compression if called too often. +*/ + +/* +ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, + z_off_t offset, int whence)); + + Sets the starting position for the next gzread or gzwrite on the given + compressed file. The offset represents a number of bytes in the + uncompressed data stream. The whence parameter is defined as in lseek(2); + the value SEEK_END is not supported. + + If the file is opened for reading, this function is emulated but can be + extremely slow. If the file is opened for writing, only forward seeks are + supported; gzseek then compresses a sequence of zeroes up to the new + starting position. + + gzseek returns the resulting offset location as measured in bytes from + the beginning of the uncompressed stream, or -1 in case of error, in + particular if the file is opened for writing and the new starting position + would be before the current position. +*/ + +ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); +/* + Rewinds the given file. This function is supported only for reading. + + gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) +*/ + +/* +ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); + + Returns the starting position for the next gzread or gzwrite on the given + compressed file. This position represents a number of bytes in the + uncompressed data stream, and is zero when starting, even if appending or + reading a gzip stream from the middle of a file using gzdopen(). + + gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) +*/ + +/* +ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file)); + + Returns the current offset in the file being read or written. This offset + includes the count of bytes that precede the gzip stream, for example when + appending or when using gzdopen() for reading. When reading, the offset + does not include as yet unused buffered input. This information can be used + for a progress indicator. On error, gzoffset() returns -1. +*/ + +ZEXTERN int ZEXPORT gzeof OF((gzFile file)); +/* + Returns true (1) if the end-of-file indicator has been set while reading, + false (0) otherwise. Note that the end-of-file indicator is set only if the + read tried to go past the end of the input, but came up short. Therefore, + just like feof(), gzeof() may return false even if there is no more data to + read, in the event that the last read request was for the exact number of + bytes remaining in the input file. This will happen if the input file size + is an exact multiple of the buffer size. + + If gzeof() returns true, then the read functions will return no more data, + unless the end-of-file indicator is reset by gzclearerr() and the input file + has grown since the previous end of file was detected. +*/ + +ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); +/* + Returns true (1) if file is being copied directly while reading, or false + (0) if file is a gzip stream being decompressed. + + If the input file is empty, gzdirect() will return true, since the input + does not contain a gzip stream. + + If gzdirect() is used immediately after gzopen() or gzdopen() it will + cause buffers to be allocated to allow reading the file to determine if it + is a gzip file. Therefore if gzbuffer() is used, it should be called before + gzdirect(). + + When writing, gzdirect() returns true (1) if transparent writing was + requested ("wT" for the gzopen() mode), or false (0) otherwise. (Note: + gzdirect() is not needed when writing. Transparent writing must be + explicitly requested, so the application already knows the answer. When + linking statically, using gzdirect() will include all of the zlib code for + gzip file reading and decompression, which may not be desired.) +*/ + +ZEXTERN int ZEXPORT gzclose OF((gzFile file)); +/* + Flushes all pending output if necessary, closes the compressed file and + deallocates the (de)compression state. Note that once file is closed, you + cannot call gzerror with file, since its structures have been deallocated. + gzclose must not be called more than once on the same file, just as free + must not be called more than once on the same allocation. + + gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a + file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the + last read ended in the middle of a gzip stream, or Z_OK on success. +*/ + +ZEXTERN int ZEXPORT gzclose_r OF((gzFile file)); +ZEXTERN int ZEXPORT gzclose_w OF((gzFile file)); +/* + Same as gzclose(), but gzclose_r() is only for use when reading, and + gzclose_w() is only for use when writing or appending. The advantage to + using these instead of gzclose() is that they avoid linking in zlib + compression or decompression code that is not used when only reading or only + writing respectively. If gzclose() is used, then both compression and + decompression code will be included the application when linking to a static + zlib library. +*/ + +ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); +/* + Returns the error message for the last error which occurred on the given + compressed file. errnum is set to zlib error number. If an error occurred + in the file system and not in the compression library, errnum is set to + Z_ERRNO and the application may consult errno to get the exact error code. + + The application must not modify the returned string. Future calls to + this function may invalidate the previously returned string. If file is + closed, then the string previously returned by gzerror will no longer be + available. + + gzerror() should be used to distinguish errors from end-of-file for those + functions above that do not distinguish those cases in their return values. +*/ + +ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); +/* + Clears the error and end-of-file flags for file. This is analogous to the + clearerr() function in stdio. This is useful for continuing to read a gzip + file that is being written concurrently. +*/ + +#endif /* !Z_SOLO */ + + /* checksum functions */ + +/* + These functions are not related to compression but are exported + anyway because they might be useful in applications using the compression + library. +*/ + +ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); +/* + Update a running Adler-32 checksum with the bytes buf[0..len-1] and + return the updated checksum. If buf is Z_NULL, this function returns the + required initial value for the checksum. + + An Adler-32 checksum is almost as reliable as a CRC32 but can be computed + much faster. + + Usage example: + + uLong adler = adler32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + adler = adler32(adler, buffer, length); + } + if (adler != original_adler) error(); +*/ + +/* +ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, + z_off_t len2)); + + Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 + and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for + each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of + seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. Note + that the z_off_t type (like off_t) is a signed integer. If len2 is + negative, the result has no meaning or utility. +*/ + +ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); +/* + Update a running CRC-32 with the bytes buf[0..len-1] and return the + updated CRC-32. If buf is Z_NULL, this function returns the required + initial value for the crc. Pre- and post-conditioning (one's complement) is + performed within this function so it shouldn't be done by the application. + + Usage example: + + uLong crc = crc32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + crc = crc32(crc, buffer, length); + } + if (crc != original_crc) error(); +*/ + +/* +ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); + + Combine two CRC-32 check values into one. For two sequences of bytes, + seq1 and seq2 with lengths len1 and len2, CRC-32 check values were + calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 + check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and + len2. +*/ + + + /* various hacks, don't look :) */ + +/* deflateInit and inflateInit are macros to allow checking the zlib version + * and the compiler's view of z_stream: + */ +ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, + int windowBits, int memLevel, + int strategy, const char *version, + int stream_size)); +ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, + unsigned char FAR *window, + const char *version, + int stream_size)); +#define deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) +#define inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) +#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) +#define inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ + (int)sizeof(z_stream)) +#define inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, (int)sizeof(z_stream)) + +#ifndef Z_SOLO + +/* gzgetc() macro and its supporting function and exposed data structure. Note + * that the real internal state is much larger than the exposed structure. + * This abbreviated structure exposes just enough for the gzgetc() macro. The + * user should not mess with these exposed elements, since their names or + * behavior could change in the future, perhaps even capriciously. They can + * only be used by the gzgetc() macro. You have been warned. + */ +struct gzFile_s { + unsigned have; + unsigned char *next; + z_off64_t pos; +}; +ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ +#ifdef Z_PREFIX_SET +# undef z_gzgetc +# define z_gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : gzgetc(g)) +#else +# define gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : gzgetc(g)) +#endif + +/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or + * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if + * both are true, the application gets the *64 functions, and the regular + * functions are changed to 64 bits) -- in case these are set on systems + * without large file support, _LFS64_LARGEFILE must also be true + */ +#ifdef Z_LARGE64 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); + ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t)); +#endif + +#if !defined(ZLIB_INTERNAL) && defined(Z_WANT64) +# ifdef Z_PREFIX_SET +# define z_gzopen z_gzopen64 +# define z_gzseek z_gzseek64 +# define z_gztell z_gztell64 +# define z_gzoffset z_gzoffset64 +# define z_adler32_combine z_adler32_combine64 +# define z_crc32_combine z_crc32_combine64 +# else +# define gzopen gzopen64 +# define gzseek gzseek64 +# define gztell gztell64 +# define gzoffset gzoffset64 +# define adler32_combine adler32_combine64 +# define crc32_combine crc32_combine64 +# endif +# ifndef Z_LARGE64 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int)); + ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); +# endif +#else + ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *)); + ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int)); + ZEXTERN z_off_t ZEXPORT gztell OF((gzFile)); + ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); +#endif + +#else /* Z_SOLO */ + + ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); + +#endif /* !Z_SOLO */ + +/* hack for buggy compilers */ +#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) + struct internal_state {int dummy;}; +#endif + +/* undocumented functions */ +ZEXTERN const char * ZEXPORT zError OF((int)); +ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp)); +ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table OF((void)); +ZEXTERN int ZEXPORT inflateUndermine OF((z_streamp, int)); +ZEXTERN int ZEXPORT inflateResetKeep OF((z_streamp)); +ZEXTERN int ZEXPORT deflateResetKeep OF((z_streamp)); +#if defined(_WIN32) && !defined(Z_SOLO) +ZEXTERN gzFile ZEXPORT gzopen_w OF((const wchar_t *path, + const char *mode)); +#endif +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifndef Z_SOLO +ZEXTERN int ZEXPORTVA gzvprintf Z_ARG((gzFile file, + const char *format, + va_list va)); +# endif +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* ZLIB_H */ diff --git a/inst/include/znzlib/znzlib.h b/inst/include/znzlib/znzlib.h new file mode 100644 index 0000000..f563f93 --- /dev/null +++ b/inst/include/znzlib/znzlib.h @@ -0,0 +1,122 @@ +#ifndef _ZNZLIB_H_ +#define _ZNZLIB_H_ + +/* +znzlib.h (zipped or non-zipped library) + +***** This code is released to the public domain. ***** + +***** Author: Mark Jenkinson, FMRIB Centre, University of Oxford ***** +***** Date: September 2004 ***** + +***** Neither the FMRIB Centre, the University of Oxford, nor any of ***** +***** its employees imply any warranty of usefulness of this software ***** +***** for any purpose, and do not assume any liability for damages, ***** +***** incidental or otherwise, caused by any use of this document. ***** + +*/ + +/* + +This library provides an interface to both compressed (gzip/zlib) and +uncompressed (normal) file IO. The functions are written to have the +same interface as the standard file IO functions. + +To use this library instead of normal file IO, the following changes +are required: + - replace all instances of FILE* with znzFile + - change the name of all function calls, replacing the initial character + f with the znz (e.g. fseek becomes znzseek) + - add a third parameter to all calls to znzopen (previously fopen) + that specifies whether to use compression (1) or not (0) + - use znz_isnull rather than any (pointer == NULL) comparisons in the code + +NB: seeks for writable files with compression are quite restricted + +*/ + + +/*=================*/ +#ifdef __cplusplus +extern "C" { +#endif +/*=================*/ + +#include +#include +#include +#include + +/* include optional check for HAVE_FDOPEN here, from deleted config.h: + + uncomment the following line if fdopen() exists for your compiler and + compiler options +*/ +/* #define HAVE_FDOPEN */ + + +#ifdef HAVE_ZLIB +#if defined(ITKZLIB) && !defined(ITK_USE_SYSTEM_ZLIB) +#include "itk_zlib.h" +#else +#include "zlib/zlib.h" +#endif +#endif + +struct znzptr { + int withz; + FILE* nzfptr; +#ifdef HAVE_ZLIB + gzFile zfptr; +#endif +} ; + +/* the type for all file pointers */ +typedef struct znzptr * znzFile; + + +/* int znz_isnull(znzFile f); */ +/* int znzclose(znzFile f); */ +#define znz_isnull(f) ((f) == NULL) +#define znzclose(f) Xznzclose(&(f)) + +/* Note extra argument (use_compression) where + use_compression==0 is no compression + use_compression!=0 uses zlib (gzip) compression +*/ + +znzFile znzopen(const char *path, const char *mode, int use_compression); + +znzFile znzdopen(int fd, const char *mode, int use_compression); + +int Xznzclose(znzFile * file); + +size_t znzread(void* buf, size_t size, size_t nmemb, znzFile file); + +size_t znzwrite(const void* buf, size_t size, size_t nmemb, znzFile file); + +long znzseek(znzFile file, long offset, int whence); + +int znzrewind(znzFile stream); + +long znztell(znzFile file); + +int znzputs(const char *str, znzFile file); + +char * znzgets(char* str, int size, znzFile file); + +int znzputc(int c, znzFile file); + +int znzgetc(znzFile file); + +#if !defined(WIN32) +int znzprintf(znzFile stream, const char *format, ...); +#endif + +/*=================*/ +#ifdef __cplusplus +} +#endif +/*=================*/ + +#endif diff --git a/man/dumpNifti.Rd b/man/dumpNifti.Rd new file mode 100644 index 0000000..4a9c549 --- /dev/null +++ b/man/dumpNifti.Rd @@ -0,0 +1,34 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/nifti.R +\name{dumpNifti} +\alias{dumpNifti} +\alias{print.niftiHeader} +\title{Dump the contents of an internal NIfTI-1 object} +\usage{ +dumpNifti(image) + +\method{print}{niftiHeader}(x, ...) +} +\arguments{ +\item{image}{An image, in any acceptable form (see +\code{\link{retrieveNifti}}).} + +\item{x}{A \code{"niftiHeader"} object.} + +\item{...}{Ignored.} +} +\value{ +For \code{dumpNifti}, a list of class \code{"niftiHeader"}, with + named components corresponding to the elements in a raw NIfTI-1 file. +} +\description{ +This function extracts the contents of an internal NIfTI-1 object into an R +list. No processing is done to the elements. +} +\author{ +Jon Clayden +} +\references{ +The NIfTI-1 standard (\url{http://nifti.nimh.nih.gov/nifti-1}). +} + diff --git a/man/internalImage.Rd b/man/internalImage.Rd new file mode 100644 index 0000000..4585b30 --- /dev/null +++ b/man/internalImage.Rd @@ -0,0 +1,34 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/image.R +\name{dim.internalImage} +\alias{as.array.internalImage} +\alias{dim.internalImage} +\alias{dim<-.internalImage} +\alias{internalImage} +\title{Internal images} +\usage{ +\method{dim}{internalImage}(x) + +\method{dim}{internalImage}(x) <- value + +\method{as.array}{internalImage}(x, ...) +} +\arguments{ +\item{x}{An \code{"internalImage"} object.} + +\item{value}{Not used. Changing the dimensions of an internal image is +invalid, and will produce an error.} + +\item{...}{Additional parameters to methods. Currently unused.} +} +\description{ +An internal image is a simple R object with a few attributes including a +pointer to an internal C structure, which contains the full image data. They +are used in the package for efficiency, but can be converted to a normal +R array using the \code{as.array} method. Attributes of these objects should +not be changed. +} +\author{ +Jon Clayden +} + diff --git a/man/ndim.Rd b/man/ndim.Rd new file mode 100644 index 0000000..aa91c0c --- /dev/null +++ b/man/ndim.Rd @@ -0,0 +1,22 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/image.R +\name{ndim} +\alias{ndim} +\title{Number of dimensions} +\usage{ +ndim(object) +} +\arguments{ +\item{object}{An R object.} +} +\value{ +The dimensionality of the object. Objects without a \code{dim} + attribute will produce zero. +} +\description{ +This function is shorthand for \code{length(dim(object))}. +} +\author{ +Jon Clayden +} + diff --git a/man/pixdim.Rd b/man/pixdim.Rd new file mode 100644 index 0000000..af5d700 --- /dev/null +++ b/man/pixdim.Rd @@ -0,0 +1,52 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/image.R +\name{pixdim} +\alias{pixdim} +\alias{pixdim.default} +\alias{pixdim<-} +\alias{pixdim<-.default} +\alias{pixunits} +\alias{pixunits.default} +\alias{pixunits<-} +\alias{pixunits<-.default} +\title{Pixel dimensions and units} +\usage{ +pixdim(object) + +\method{pixdim}{default}(object) + +pixdim(object) <- value + +\method{pixdim}{default}(object) <- value + +pixunits(object) + +\method{pixunits}{default}(object) + +pixunits(object) <- value + +\method{pixunits}{default}(object) <- value +} +\arguments{ +\item{object}{An R object, generally an image.} + +\item{value}{Numeric vector of pixel dimensions along each axis, or +character vector of abbreviated units. For dimensions, a scalar +\code{value} will be recycled if necessary.} +} +\value{ +\code{pixdim} returns a numeric vector of pixel dimensions. + \code{pixunits} returns a character vector of length up to two, giving the + spatial and temporal unit names. +} +\description{ +By default, these generic functions return or replace the \code{"pixdim"} +and \code{"pixunits"} attributes of their arguments. These represent the +physical step size between pixel or voxel centre points, and the spatial and +temporal units that they are given in. The former defaults to 1 in each +dimension, if there is no attribute. +} +\author{ +Jon Clayden +} + diff --git a/man/readNifti.Rd b/man/readNifti.Rd new file mode 100644 index 0000000..04ec850 --- /dev/null +++ b/man/readNifti.Rd @@ -0,0 +1,45 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/nifti.R +\name{readNifti} +\alias{readNifti} +\title{Read a NIfTI-1 format file} +\usage{ +readNifti(file, internal = FALSE) +} +\arguments{ +\item{file}{A character vector of file names.} + +\item{internal}{Logical value. If \code{FALSE} (the default), an array +of class \code{"niftiImage"}, containing the image pixel or voxel values, +will be returned. If \code{TRUE}, the return value will be an object of +class \code{"internalImage"}, which contains only minimal metadata about +the image. Either way, the return value has an attribute which points to a +C data structure containing the full image.} +} +\value{ +An array or internal image, with class \code{"niftiImage"}, and + possibly also \code{"internalImage"}. +} +\description{ +This function reads one or more NIfTI-1 files into R, using the standard +NIfTI-1 C library. +} +\note{ +If the \code{internal} argument is \code{FALSE} (the default), the + data type of the image pointer will be set to match one of R's native + numeric data types, i.e., 32-bit signed integer or 64-bit double-precision + floating-point. In these circumstances the data type reported by the + \code{\link{dumpNifti}} function will therefore not, in general, match + the storage type used in the file. See also the \code{datatype} argument + to \code{\link{writeNifti}}. +} +\author{ +Jon Clayden +} +\references{ +The NIfTI-1 standard (\url{http://nifti.nimh.nih.gov/nifti-1}). +} +\seealso{ +\code{\link{writeNifti}} +} + diff --git a/man/retrieveNifti.Rd b/man/retrieveNifti.Rd new file mode 100644 index 0000000..ee5bb6c --- /dev/null +++ b/man/retrieveNifti.Rd @@ -0,0 +1,34 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/nifti.R +\name{retrieveNifti} +\alias{retrieveNifti} +\title{Obtain an internal NIfTI representation of an object} +\usage{ +retrieveNifti(object) +} +\arguments{ +\item{object}{Any suitable object (see Details).} +} +\value{ +An internal image. +} +\description{ +This function converts filenames, arrays and other image classes into an +object of class \code{"internalImage"}. +} +\details{ +If the \code{object} has an internal NIfTI pointer, that will be retrieved +directly. Otherwise, if it is a string, it will be taken to be a filename. +If it looks like a \code{"nifti"} object (from package \code{oro.nifti}), +or an \code{"MriImage"} object (from package \code{tractor.base}), a +conversion will be attempted. A list will be assumed to be of the form +produced by \code{\link{dumpNifti}}. Finally, a numeric array or matrix +will be converted using default image parameters. +} +\author{ +Jon Clayden +} +\seealso{ +\code{\link{readNifti}}, \code{\link{updateNifti}} +} + diff --git a/man/updateNifti.Rd b/man/updateNifti.Rd new file mode 100644 index 0000000..1e26726 --- /dev/null +++ b/man/updateNifti.Rd @@ -0,0 +1,29 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/nifti.R +\name{updateNifti} +\alias{updateNifti} +\title{Update an internal NIfTI-1 object using a template} +\usage{ +updateNifti(image, template = NULL) +} +\arguments{ +\item{image}{A numeric array.} + +\item{template}{An image, in any acceptable form (see +\code{\link{retrieveNifti}}), or a named list of NIfTI-1 properties like +that produced by \code{\link{dumpNifti}}. The default of \code{NULL} will +have no effect.} +} +\value{ +A copy of the original \code{image}, with its internal image + attribute set or updated appropriately. +} +\description{ +This function adds or updates the internal NIfTI-1 object for an array, +using metadata from the template. The dimensions and, if available, pixel +dimensions, from the \code{image} will replace those from the template. +} +\author{ +Jon Clayden +} + diff --git a/man/voxelToWorld.Rd b/man/voxelToWorld.Rd new file mode 100644 index 0000000..96a8c95 --- /dev/null +++ b/man/voxelToWorld.Rd @@ -0,0 +1,43 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/xform.R +\name{voxelToWorld} +\alias{voxelToWorld} +\alias{worldToVoxel} +\title{Transform points between voxel and ``world'' coordinates} +\usage{ +voxelToWorld(points, image, simple = FALSE, ...) + +worldToVoxel(points, image, simple = FALSE, ...) +} +\arguments{ +\item{points}{A vector giving the coordinates of a point, or a matrix with +one point per row.} + +\item{image}{The image in whose space the points are given.} + +\item{simple}{A logical value: if \code{TRUE} then the transformation is +performed simply by rescaling the points according to the voxel dimensions +recorded in the \code{image}. Otherwise the full xform matrix is used.} + +\item{...}{Additional arguments to \code{\link{xform}}.} +} +\value{ +A vector or matrix of transformed points. +} +\description{ +These functions are used to transform points from dimensionless pixel or +voxel coordinates to ``real-world'' coordinates, typically in millimetres, +and back. Actual pixel units can be obtained using the +\code{\link{pixunits}} function. +} +\note{ +Voxel coordinates are assumed by these functions to use R's indexing + convention, beginning from 1. +} +\author{ +Jon Clayden +} +\seealso{ +\code{\link{xform}}, \code{\link{pixdim}}, \code{\link{pixunits}} +} + diff --git a/man/writeNifti.Rd b/man/writeNifti.Rd new file mode 100644 index 0000000..7f7a3fd --- /dev/null +++ b/man/writeNifti.Rd @@ -0,0 +1,37 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/nifti.R +\name{writeNifti} +\alias{writeNifti} +\title{Write a NIfTI-1 format file} +\usage{ +writeNifti(image, file, template = NULL, datatype = "auto") +} +\arguments{ +\item{image}{An image, in any acceptable form (see +\code{\link{retrieveNifti}}).} + +\item{file}{A character string containing a file name.} + +\item{template}{An optional template object to derive NIfTI-1 properties +from. Passed to \code{\link{updateNifti}} if \code{image} is an array.} + +\item{datatype}{The NIfTI datatype to use when writing the data out. The +default, \code{"auto"} uses the R type or, for internal images, the +original datatype. Other possibilities are \code{"float"}, \code{"int16"}, +etc., which may be preferred to reduce file size. However, no checks are +done to ensure that the coercion maintains precision.} +} +\description{ +This function writes an image to NIfTI-1 format, using the standard NIfTI-1 +C library. +} +\author{ +Jon Clayden +} +\references{ +The NIfTI-1 standard (\url{http://nifti.nimh.nih.gov/nifti-1}). +} +\seealso{ +\code{\link{readNifti}}, \code{\link{updateNifti}} +} + diff --git a/man/xform.Rd b/man/xform.Rd new file mode 100644 index 0000000..89e3580 --- /dev/null +++ b/man/xform.Rd @@ -0,0 +1,50 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/xform.R +\name{xform} +\alias{qform<-} +\alias{sform<-} +\alias{xform} +\title{Obtain or replace the ``xform'' transforms for an image} +\usage{ +xform(image, useQuaternionFirst = TRUE) + +qform(x) <- value + +sform(x) <- value +} +\arguments{ +\item{image, x}{An image, in any acceptable form (see +\code{\link{retrieveNifti}}).} + +\item{useQuaternionFirst}{A single logical value. If \code{TRUE}, the +``qform'' matrix will be used first, if it is defined; otherwise the +``sform'' matrix will take priority.} + +\item{value}{A new 4x4 qform or sform matrix. If the matrix has a +\code{"code"} attribute, the appropriate qform or sform code is also set.} +} +\value{ +A affine matrix corresponding to the ``qform'' or ``sform'' + information in the image header. This is a plain matrix, which does not + have the \code{"affine"} class or \code{source} and \code{target} + attributes. +} +\description{ +These functions convert the ``qform'' or ``sform'' information in a NIfTI +header to or from a corresponding affine matrix. These two ``xform'' +mechanisms are defined by the NIfTI standard, and may both be in use in a +particular image header. +} +\note{ +The qform and sform replacement functions are for advanced users only. + Modifying the transforms without knowing what you're doing is usually + unwise, as you can make the image object inconsistent. +} +\author{ +Jon Clayden +} +\references{ +The NIfTI-1 standard (\url{http://nifti.nimh.nih.gov/nifti-1}) + is the definitive reference on ``xform'' conventions. +} + diff --git a/src/Makevars b/src/Makevars new file mode 100644 index 0000000..0fa7d0f --- /dev/null +++ b/src/Makevars @@ -0,0 +1,7 @@ +PKG_CPPFLAGS = -DNDEBUG -DHAVE_ZLIB -I../inst/include -Izlib + +OBJECTS_ZLIB = zlib/adler32.o zlib/compress.o zlib/crc32.o zlib/deflate.o zlib/gzclose.o zlib/gzlib.o zlib/gzread.o zlib/gzwrite.o zlib/infback.o zlib/inffast.o zlib/inflate.o zlib/inftrees.o zlib/trees.o zlib/uncompr.o zlib/zutil.o + +OBJECTS_NIFTI = znzlib/znzlib.o niftilib/nifti1_io.o + +OBJECTS = main.o init.o $(OBJECTS_ZLIB) $(OBJECTS_NIFTI) diff --git a/src/init.cpp b/src/init.cpp new file mode 100644 index 0000000..eb2e937 --- /dev/null +++ b/src/init.cpp @@ -0,0 +1,37 @@ +#include +#include + +#include "niftilib/nifti1_io.h" + +extern "C" { + +void R_init_RNifti (DllInfo *info) +{ + R_RegisterCCallable("RNifti", "nii_make_new_header", (DL_FUNC) &nifti_make_new_header); + R_RegisterCCallable("RNifti", "nii_make_new_nim", (DL_FUNC) &nifti_make_new_nim); + R_RegisterCCallable("RNifti", "nii_convert_nhdr2nim", (DL_FUNC) &nifti_convert_nhdr2nim); + R_RegisterCCallable("RNifti", "nii_convert_nim2nhdr", (DL_FUNC) &nifti_convert_nim2nhdr); + R_RegisterCCallable("RNifti", "nii_copy_nim_info", (DL_FUNC) &nifti_copy_nim_info); + R_RegisterCCallable("RNifti", "nii_copy_extensions", (DL_FUNC) &nifti_copy_extensions); + R_RegisterCCallable("RNifti", "nii_image_free", (DL_FUNC) &nifti_image_free); + + R_RegisterCCallable("RNifti", "nii_datatype_sizes", (DL_FUNC) &nifti_datatype_sizes); + R_RegisterCCallable("RNifti", "nii_datatype_string", (DL_FUNC) &nifti_datatype_string); + R_RegisterCCallable("RNifti", "nii_units_string", (DL_FUNC) &nifti_units_string); + R_RegisterCCallable("RNifti", "nii_get_volsize", (DL_FUNC) &nifti_get_volsize); + R_RegisterCCallable("RNifti", "nii_update_dims_from_array", (DL_FUNC) &nifti_update_dims_from_array); + + R_RegisterCCallable("RNifti", "nii_set_filenames", (DL_FUNC) &nifti_set_filenames); + R_RegisterCCallable("RNifti", "nii_image_read", (DL_FUNC) &nifti_image_read); + R_RegisterCCallable("RNifti", "nii_image_write", (DL_FUNC) &nifti_image_write); + + R_RegisterCCallable("RNifti", "nii_mat33_determ", (DL_FUNC) &nifti_mat33_determ); + R_RegisterCCallable("RNifti", "nii_mat33_inverse", (DL_FUNC) &nifti_mat33_inverse); + R_RegisterCCallable("RNifti", "nii_mat33_mul", (DL_FUNC) &nifti_mat33_mul); + R_RegisterCCallable("RNifti", "nii_mat33_polar", (DL_FUNC) &nifti_mat33_polar); + R_RegisterCCallable("RNifti", "nii_mat44_inverse", (DL_FUNC) &nifti_mat44_inverse); + R_RegisterCCallable("RNifti", "nii_mat44_to_quatern", (DL_FUNC) &nifti_mat44_to_quatern); + R_RegisterCCallable("RNifti", "nii_quatern_to_mat44", (DL_FUNC) &nifti_quatern_to_mat44); +} + +} diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..737dc0a --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,134 @@ +#include + +#include "lib/NiftiImage.h" + +using namespace Rcpp; + +typedef std::vector float_vector; + +RcppExport SEXP readNifti (SEXP _object, SEXP _internal) +{ +BEGIN_RCPP + NiftiImage image(_object); + return image.toArrayOrPointer(as(_internal), "NIfTI image"); +END_RCPP +} + +RcppExport SEXP writeNifti (SEXP _image, SEXP _file, SEXP _datatype) +{ +BEGIN_RCPP + NiftiImage image(_image); + image.toFile(as(_file), as(_datatype)); + return R_NilValue; +END_RCPP +} + +RcppExport SEXP updateNifti (SEXP _image, SEXP _reference) +{ +BEGIN_RCPP + const NiftiImage reference(_reference); + RObject image(_image); + + if (!reference.isNull()) + { + NiftiImage updatedImage = reference; + updatedImage.update(image); + return updatedImage.toArray(); + } + else + return image; +END_RCPP +} + +RcppExport SEXP dumpNifti (SEXP _image) +{ +BEGIN_RCPP + const NiftiImage image(_image, false); + return image.headerToList(); +END_RCPP +} + +RcppExport SEXP getXform (SEXP _image, SEXP _preferQuaternion) +{ +BEGIN_RCPP + const NiftiImage image(_image, false); + const bool preferQuaternion = as(_preferQuaternion); + + mat44 xform = image.xform(preferQuaternion); + NumericMatrix matrix(4,4); + for (int i=0; i<4; i++) + { + for (int j=0; j<4; j++) + matrix(i,j) = static_cast(xform.m[i][j]); + } + + return matrix; +END_RCPP +} + +RcppExport SEXP setXform (SEXP _image, SEXP _matrix, SEXP _isQform) +{ +BEGIN_RCPP + NiftiImage image(_image); + NumericMatrix matrix(_matrix); + + if (matrix.cols() != 4 || matrix.rows() != 4) + throw std::runtime_error("Specified affine matrix does not have dimensions of 4x4"); + mat44 xform; + for (int i=0; i<4; i++) + { + for (int j=0; j<4; j++) + xform.m[i][j] = static_cast(matrix(i,j)); + } + + int code = -1; + if (!Rf_isNull(matrix.attr("code"))) + code = as(matrix.attr("code")); + + if (!image.isNull()) + { + if (as(_isQform)) + { + image->qto_xyz = xform; + image->qto_ijk = nifti_mat44_inverse(image->qto_xyz); + nifti_mat44_to_quatern(image->qto_xyz, &image->quatern_b, &image->quatern_c, &image->quatern_d, &image->qoffset_x, &image->qoffset_y, &image->qoffset_z, NULL, NULL, NULL, &image->qfac); + + if (code >= 0) + image->qform_code = code; + } + else + { + image->sto_xyz = xform; + image->sto_ijk = nifti_mat44_inverse(image->sto_xyz); + + if (code >= 0) + image->sform_code = code; + } + } + + if (image.isPersistent()) + return _image; + else + return image.toArray(); +END_RCPP +} + +RcppExport SEXP rescaleImage (SEXP _image, SEXP _scales) +{ +BEGIN_RCPP + const float_vector scales = as(_scales); + const NiftiImage image(_image); + + NiftiImage newImage(nifti_copy_nim_info(image)); + newImage.rescale(scales); + return newImage.toPointer("NIfTI image"); +END_RCPP +} + +RcppExport SEXP pointerToArray (SEXP _image) +{ +BEGIN_RCPP + NiftiImage image(_image); + return image.toArray(); +END_RCPP +} diff --git a/src/niftilib/nifti1_io.c b/src/niftilib/nifti1_io.c new file mode 100644 index 0000000..4cb746b --- /dev/null +++ b/src/niftilib/nifti1_io.c @@ -0,0 +1,7523 @@ +#define _NIFTI1_IO_C_ + +#include "niftilib/nifti1_io.h" /* typedefs, prototypes, macros, etc. */ + +/*****===================================================================*****/ +/***** Sample functions to deal with NIFTI-1 and ANALYZE files *****/ +/*****...................................................................*****/ +/***** This code is released to the public domain. *****/ +/*****...................................................................*****/ +/***** Author: Robert W Cox, SSCC/DIRP/NIMH/NIH/DHHS/USA/EARTH *****/ +/***** Date: August 2003 *****/ +/*****...................................................................*****/ +/***** Neither the National Institutes of Health (NIH), nor any of its *****/ +/***** employees imply any warranty of usefulness of this software for *****/ +/***** any purpose, and do not assume any liability for damages, *****/ +/***** incidental or otherwise, caused by any use of this document. *****/ +/*****===================================================================*****/ + +/** \file nifti1_io.c + \brief main collection of nifti1 i/o routines + - written by Bob Cox, SSCC NIMH + - revised by Mark Jenkinson, FMRIB + - revised by Rick Reynolds, SSCC, NIMH + - revised by Kate Fissell, University of Pittsburgh + + The library history can be viewed via "nifti_tool -nifti_hist". +
The library version can be viewed via "nifti_tool -nifti_ver". + */ + +/*! global history and version strings, for printing */ +static char const * const gni_history[] = +{ + "----------------------------------------------------------------------\n" + "history (of nifti library changes):\n" + "\n", + "0.0 August, 2003 [rwcox]\n" + " (Robert W Cox of the National Institutes of Health, SSCC/DIRP/NIMH)\n" + " - initial version\n" + "\n", + "0.1 July/August, 2004 [Mark Jenkinson]\n" + " (FMRIB Centre, University of Oxford, UK)\n" + " - Mainly adding low-level IO and changing things to allow gzipped\n" + " files to be read and written\n" + " - Full backwards compatability should have been maintained\n" + "\n", + "0.2 16 Nov 2004 [rickr]\n" + " (Rick Reynolds of the National Institutes of Health, SSCC/DIRP/NIMH)\n" + " - included Mark's changes in the AFNI distribution (including znzlib/)\n" + " (HAVE_ZLIB is commented out for the standard distribution)\n" + " - modified nifti_validfilename() and nifti_makebasename()\n" + " - added nifti_find_file_extension()\n" + "\n", + "0.3 3 Dec 2004 [rickr]\n" + " - note: header extensions are not yet checked for\n" + " - added formatted history as global string, for printing\n" + " - added nifti_disp_lib_hist(), to display the nifti library history\n" + " - added nifti_disp_lib_version(), to display the nifti library history\n", + " - re-wrote nifti_findhdrname()\n" + " o used nifti_find_file_extension()\n" + " o changed order of file tests (default is .nii, depends on input)\n" + " o free hdrname on failure\n" + " - made similar changes to nifti_findimgname()\n" + " - check for NULL return from nifti_findhdrname() calls\n", + " - removed most of ERREX() macros\n" + " - modified nifti_image_read()\n" + " o added debug info and error checking (on gni_debug > 0, only)\n" + " o fail if workingname is NULL\n" + " o check for failure to open header file\n" + " o free workingname on failure\n" + " o check for failure of nifti_image_load()\n" + " o check for failure of nifti_convert_nhdr2nim()\n", + " - changed nifti_image_load() to int, and check nifti_read_buffer return\n" + " - changed nifti_read_buffer() to fail on short read, and to count float\n" + " fixes (to print on debug)\n" + " - changed nifti_image_infodump to print to stderr\n" + " - updated function header comments, or moved comments above header\n" + " - removed const keyword\n" + " - added LNI_FERR() macro for error reporting on input files\n" + "\n", + "0.4 10 Dec 2004 [rickr] - added header extensions\n" + " - in nifti1_io.h:\n" + " o added num_ext and ext_list to the definition of nifti_image\n" + " o made many functions static (more to follow)\n" + " o added LNI_MAX_NIA_EXT_LEN, for max nifti_type 3 extension length\n", + " - added __DATE__ to version output in nifti_disp_lib_version()\n" + " - added nifti_disp_matrix_orient() to print orientation information\n" + " - added '.nia' as a valid file extension in nifti_find_file_extension()\n" + " - added much more debug output\n" + " - in nifti_image_read(), in the case of an ASCII header, check for\n" + " extensions after the end of the header\n", + " - added nifti_read_extensions() function\n" + " - added nifti_read_next_extension() function\n" + " - added nifti_add_exten_to_list() function\n" + " - added nifti_check_extension() function\n" + " - added nifti_write_extensions() function\n" + " - added nifti_extension_size() function\n" + " - in nifti_set_iname_offest():\n" + " o adjust offset by the extension size and the extender size\n", + " o fixed the 'ceiling modulo 16' computation\n" + " - in nifti_image_write_hdr_img2(): \n" + " o added extension writing\n" + " o check for NULL return from nifti_findimgname()\n" + " - include number of extensions in nifti_image_to_ascii() output\n" + " - in nifti_image_from_ascii():\n" + " o return bytes_read as a parameter, computed from the final spos\n" + " o extract num_ext from ASCII header\n" + "\n", + "0.5 14 Dec 2004 [rickr] - added sub-brick reading functions\n" + " - added nifti_brick_list type to nifti1_io.h, along with new prototypes\n" + " - added main nifti_image_read_bricks() function, with description\n" + " - added nifti_image_load_bricks() - library function (requires nim)\n" + " - added valid_nifti_brick_list() - library function\n" + " - added free_NBL() - library function\n", + " - added update_nifti_image_for_brick_list() for dimension update\n" + " - added nifti_load_NBL_bricks(), nifti_alloc_NBL_mem(),\n" + " nifti_copynsort() and force_positive() (static functions)\n" + " - in nifti_image_read(), check for failed load only if read_data is set\n" + " - broke most of nifti_image_load() into nifti_image_load_prep()\n" + "\n", + "0.6 15 Dec 2004 [rickr] - added sub-brick writing functionality\n" + " - in nifti1_io.h, removed znzlib directory from include - all nifti\n" + " library files are now under the nifti directory\n" + " - nifti_read_extensions(): print no offset warning for nifti_type 3\n" + " - nifti_write_all_data():\n" + " o pass nifti_brick_list * NBL, for optional writing\n" + " o if NBL, write each sub-brick, sequentially\n", + " - nifti_set_iname_offset(): case 1 must have sizeof() cast to int\n" + " - pass NBL to nifti_image_write_hdr_img2(), and allow NBL or data\n" + " - added nifti_image_write_bricks() wrapper for ...write_hdr_img2()\n" + " - included compression abilities\n" + "\n", + "0.7 16 Dec 2004 [rickr] - minor changes to extension reading\n" + "\n", + "0.8 21 Dec 2004 [rickr] - restrict extension reading, and minor changes\n" + " - in nifti_image_read(), compute bytes for extensions (see remaining)\n" + " - in nifti_read_extensions(), pass 'remain' as space for extensions,\n" + " pass it to nifti_read_next_ext(), and update for each one read \n" + " - in nifti_check_extension(), require (size <= remain)\n", + " - in update_nifti_image_brick_list(), update nvox\n" + " - in nifti_image_load_bricks(), make explicit check for nbricks <= 0\n" + " - in int_force_positive(), check for (!list)\n" + " - in swap_nifti_header(), swap sizeof_hdr, and reorder to struct order\n" + " - change get_filesize functions to signed ( < 0 is no file or error )\n", + " - in nifti_validfilename(), lose redundant (len < 0) check\n" + " - make print_hex_vals() static\n" + " - in disp_nifti_1_header, restrict string field widths\n" + "\n", + "0.9 23 Dec 2004 [rickr] - minor changes\n" + " - broke ASCII header reading out of nifti_image_read(), into new\n" + " functions has_ascii_header() and read_ascii_image()\n", + " - check image_read failure and znzseek failure\n" + " - altered some debug output\n" + " - nifti_write_all_data() now returns an int\n" + "\n", + "0.10 29 Dec 2004 [rickr]\n" + " - renamed nifti_valid_extension() to nifti_check_extension()\n" + " - added functions nifti_makehdrname() and nifti_makeimgname()\n" + " - added function valid_nifti_extensions()\n" + " - in nifti_write_extensions(), check for validity before writing\n", + " - rewrote nifti_image_write_hdr_img2():\n" + " o set write_data and leave_open flags from write_opts\n" + " o add debug print statements\n" + " o use nifti_write_ascii_image() for the ascii case\n" + " o rewrote the logic of all cases to be easier to follow\n", + " - broke out code as nifti_write_ascii_image() function\n" + " - added debug to top-level write functions, and free the znzFile\n" + " - removed unused internal function nifti_image_open()\n" + "\n", + "0.11 30 Dec 2004 [rickr] - small mods\n" + " - moved static function prototypes from header to C file\n" + " - free extensions in nifti_image_free()\n" + "\n", + "1.0 07 Jan 2005 [rickr] - INITIAL RELEASE VERSION\n" + " - added function nifti_set_filenames()\n" + " - added function nifti_read_header()\n" + " - added static function nhdr_looks_good()\n" + " - added static function need_nhdr_swap()\n" + " - exported nifti_add_exten_to_list symbol\n", + " - fixed #bytes written in nifti_write_extensions()\n" + " - only modify offset if it is too small (nifti_set_iname_offset)\n" + " - added nifti_type 3 to nifti_makehdrname and nifti_makeimgname\n" + " - added function nifti_set_filenames()\n" + "\n", + "1.1 07 Jan 2005 [rickr]\n" + " - in nifti_read_header(), swap if needed\n" + "\n", + "1.2 07 Feb 2005 [kate fissell c/o rickr] \n" + " - nifti1.h: added doxygen comments for main struct and #define groups\n" + " - nifti1_io.h: added doxygen comments for file and nifti_image struct\n" + " - nifti1_io.h: added doxygen comments for file and some functions\n" + " - nifti1_io.c: changed nifti_copy_nim_info to use memcpy\n" + "\n", + "1.3 09 Feb 2005 [rickr]\n" + " - nifti1.h: added doxygen comments for extension structs\n" + " - nifti1_io.h: put most #defines in #ifdef _NIFTI1_IO_C_ block\n" + " - added a doxygen-style description to every exported function\n" + " - added doxygen-style comments within some functions\n" + " - re-exported many znzFile functions that I had made static\n" + " - re-added nifti_image_open (sorry, Mark)\n" + " - every exported function now has 'nifti' in the name (19 functions)\n", + " - made sure every alloc() has a failure test\n" + " - added nifti_copy_extensions function, for use in nifti_copy_nim_info\n" + " - nifti_is_gzfile: added initial strlen test\n" + " - nifti_set_filenames: added set_byte_order parameter option\n" + " (it seems appropriate to set the BO when new files are associated)\n" + " - disp_nifti_1_header: prints to stdout (a.o.t. stderr), with fflush\n" + "\n", + "1.4 23 Feb 2005 [rickr] - sourceforge merge\n" + " - merged into the nifti_io CVS directory structure at sourceforge.net\n" + " - merged in 4 changes by Mark, and re-added his const keywords\n" + " - cast some pointers to (void *) for -pedantic compile option\n" + " - added nifti_free_extensions()\n" + "\n", + "1.5 02 Mar 2005 [rickr] - started nifti global options\n" + " - gni_debug is now g_opts.debug\n" + " - added validity check parameter to nifti_read_header\n" + " - need_nhdr_swap no longer does test swaps on the stack\n" + "\n", + "1.6 05 April 2005 [rickr] - validation and collapsed_image_read\n" + " - added nifti_read_collapsed_image(), an interface for reading partial\n" + " datasets, specifying a subset of array indices\n" + " - for read_collapsed_image, added static functions: rci_read_data(),\n" + " rci_alloc_mem(), and make_pivot_list()\n", + " - added nifti_nim_is_valid() to check for consistency (more to do)\n" + " - added nifti_nim_has_valid_dims() to do many dimensions tests\n" + "\n", + "1.7 08 April 2005 [rickr]\n" + " - added nifti_update_dims_from_array() - to update dimensions\n" + " - modified nifti_makehdrname() and nifti_makeimgname():\n" + " if prefix has a valid extension, use it (else make one up)\n" + " - added nifti_get_intlist - for making an array of ints\n" + " - fixed init of NBL->bsize in nifti_alloc_NBL_mem() {thanks, Bob}\n" + "\n", + "1.8 14 April 2005 [rickr]\n" + " - added nifti_set_type_from_names(), for nifti_set_filenames()\n" + " (only updates type if number of files does not match it)\n" + " - added is_valid_nifti_type(), just to be sure\n" + " - updated description of nifti_read_collapsed_image() for *data change\n" + " (if *data is already set, assume memory exists for results)\n" + " - modified rci_alloc_mem() to allocate only if *data is NULL\n" + "\n", + "1.9 19 April 2005 [rickr]\n" + " - added extension codes NIFTI_ECODE_COMMENT and NIFTI_ECODE_XCEDE\n" + " - added nifti_type codes NIFTI_MAX_ECODE and NIFTI_MAX_FTYPE\n" + " - added nifti_add_extension() {exported}\n" + " - added nifti_fill_extension() as a static function\n" + " - added nifti_is_valid_ecode() {exported}\n", + " - nifti_type values are now NIFTI_FTYPE_* file codes\n" + " - in nifti_read_extensions(), decrement 'remain' by extender size, 4\n" + " - in nifti_set_iname_offset(), case 1, update if offset differs\n" + " - only output '-d writing nifti file' if debug > 1\n" + "\n", + "1.10 10 May 2005 [rickr]\n" + " - files are read using ZLIB only if they end in '.gz'\n" + "\n", + "1.11 12 August 2005 [kate fissell]\n" + " - Kate's 0.2 release packaging, for sourceforge\n" + "\n", + "1.12 17 August 2005 [rickr] - comment (doxygen) updates\n" + " - updated comments for most functions (2 updates from Cinly Ooi)\n" + " - added nifti_type_and_names_match()\n" + "\n", + "1.12a 24 August 2005 [rickr] - remove all tabs from Clibs/*/*.[ch]\n", + "1.12b 25 August 2005 [rickr] - changes by Hans Johnson\n", + "1.13 25 August 2005 [rickr]\n", + " - finished changes by Hans for Insight\n" + " - added const in all appropraite parameter locations (30-40)\n" + " (any pointer referencing data that will not change)\n" + " - shortened all string constants below 509 character limit\n" + "1.14 28 October 2005 [HJohnson]\n", + " - use nifti_set_filenames() in nifti_convert_nhdr2nim()\n" + "1.15 02 November 2005 [rickr]\n", + " - added skip_blank_ext to nifti_global_options\n" + " - added nifti_set_skip_blank_ext(), to set option\n" + " - if skip_blank_ext and no extensions, do not read/write extender\n" + "1.16 18 November 2005 [rickr]\n", + " - removed any test or access of dim[i], i>dim[0]\n" + " - do not set pixdim for collapsed dims to 1.0, leave them as they are\n" + " - added magic and dim[i] tests in nifti_hdr_looks_good()\n" + " - added 2 size_t casts\n" + "1.17 22 November 2005 [rickr]\n", + " - in hdr->nim, for i > dim[0], pass 0 or 1, else set to 1\n" + "1.18 02 March 2006 [rickr]\n", + " - in nifti_alloc_NBL_mem(), fixed nt=0 case from 1.17 change\n" + "1.19 23 May 2006 [HJohnson,rickr]\n", + " - nifti_write_ascii_image(): free(hstr)\n" + " - nifti_copy_extensions(): clear num_ext and ext_list\n" + "1.20 27 Jun 2006 [rickr]\n", + " - nifti_findhdrname(): fixed assign of efirst to match stated logic\n" + " (problem found by Atle Bjørnerud)\n" + "1.21 05 Sep 2006 [rickr] update for nifticlib-0.4 release\n", + " - was reminded to actually add nifti_set_skip_blank_ext()\n" + " - init g_opts.skip_blank_ext to 0\n" + "1.22 01 Jun 2007 nifticlib-0.5 release\n", + "1.23 05 Jun 2007 nifti_add_exten_to_list: revert on failure, free old list\n" + "1.24 07 Jun 2007 nifti_copy_extensions: use esize-8 for data size\n" + "1.25 12 Jun 2007 [rickr] EMPTY_IMAGE creation\n", + " - added nifti_make_new_header() - to create from dims/dtype\n" + " - added nifti_make_new_nim() - to create from dims/dtype/fill\n" + " - added nifti_is_valid_datatype(), and more debug info\n", + "1.26 27 Jul 2007 [rickr] handle single volumes > 2^31 bytes (but < 2^32)\n", + "1.27 28 Jul 2007 [rickr] nim->nvox, NBL-bsize are now type size_t\n" + "1.28 30 Jul 2007 [rickr] size_t updates\n", + "1.29 08 Aug 2007 [rickr] for list, valid_nifti_brick_list requires 3 dims\n" + "1.30 08 Nov 2007 [Yaroslav/rickr]\n" + " - fix ARM struct alignment problem in byte-swapping routines\n", + "1.31 29 Nov 2007 [rickr] for nifticlib-1.0.0\n" + " - added nifti_datatype_to/from_string routines\n" + " - added DT_RGBA32/NIFTI_TYPE_RGBA32 datatype macros (2304)\n" + " - added NIFTI_ECODE_FREESURFER (14)\n", + "1.32 08 Dec 2007 [rickr]\n" + " - nifti_hdr_looks_good() allows ANALYZE headers (req. by V. Luccio)\n" + " - added nifti_datatype_is_valid()\n", + "1.33 05 Feb 2008 [hansj,rickr] - block nia.gz use\n" + "1.34 13 Jun 2008 [rickr] - added nifti_compiled_with_zlib()\n" + "1.35 03 Aug 2008 [rickr]\n", + " - deal with swapping, so that CPU type does not affect output\n" + " (motivated by C Burns)\n" + " - added nifti_analyze75 structure and nifti_swap_as_analyze()\n" + " - previous swap_nifti_header is saved as old_swap_nifti_header\n" + " - also swap UNUSED fields in nifti_1_header struct\n", + "1.36 07 Oct 2008 [rickr]\n", + " - added nifti_NBL_matches_nim() check for write_bricks()\n" + "1.37 10 Mar 2009 [rickr]\n", + " - H Johnson cast updates (06 Feb)\n" + " - added NIFTI_ECODE_PYPICKLE for PyNIfTI (06 Feb)\n" + " - added NIFTI_ECODEs 18-28 for the LONI MiND group\n" + "1.38 28 Apr 2009 [rickr]\n", + " - uppercase extensions are now valid (requested by M. Coursolle)\n" + " - nifti_set_allow_upper_fext controls this option (req by C. Ooi)\n" + "1.39 23 Jun 2009 [rickr]: added 4 checks of alloc() returns\n", + "1.40 16 Mar 2010 [rickr]: added NIFTI_ECODE_VOXBO for D. Kimberg\n", + "1.41 28 Apr 2010 [rickr]: added NIFTI_ECODE_CARET for J. Harwell\n", + "1.42 06 Jul 2010 [rickr]: trouble with large (gz) files\n", + " - noted/investigated by M Hanke and Y Halchenko\n" + " - fixed znzread/write, noting example by M Adler\n" + " - changed nifti_swap_* routines/calls to take size_t (6)\n" + "1.43 07 Jul 2010 [rickr]: fixed znzR/W to again return nmembers\n", + "1.44 19 Jul 2013 [rickr]: ITK compatibility updates from H Johnson\n", + "----------------------------------------------------------------------\n" +}; +static const char gni_version[] = "nifti library version 1.44 (19 July, 2013)"; + +/*! global nifti options structure - init with defaults */ +static nifti_global_options g_opts = { + 1, /* debug level */ + 0, /* skip_blank_ext - skip extender if no extensions */ + 1 /* allow_upper_fext - allow uppercase file extensions */ +}; + +/*! global nifti types structure list (per type, ordered oldest to newest) */ +static const nifti_type_ele nifti_type_list[] = { + /* type nbyper swapsize name */ + { 0, 0, 0, "DT_UNKNOWN" }, + { 0, 0, 0, "DT_NONE" }, + { 1, 0, 0, "DT_BINARY" }, /* not usable */ + { 2, 1, 0, "DT_UNSIGNED_CHAR" }, + { 2, 1, 0, "DT_UINT8" }, + { 2, 1, 0, "NIFTI_TYPE_UINT8" }, + { 4, 2, 2, "DT_SIGNED_SHORT" }, + { 4, 2, 2, "DT_INT16" }, + { 4, 2, 2, "NIFTI_TYPE_INT16" }, + { 8, 4, 4, "DT_SIGNED_INT" }, + { 8, 4, 4, "DT_INT32" }, + { 8, 4, 4, "NIFTI_TYPE_INT32" }, + { 16, 4, 4, "DT_FLOAT" }, + { 16, 4, 4, "DT_FLOAT32" }, + { 16, 4, 4, "NIFTI_TYPE_FLOAT32" }, + { 32, 8, 4, "DT_COMPLEX" }, + { 32, 8, 4, "DT_COMPLEX64" }, + { 32, 8, 4, "NIFTI_TYPE_COMPLEX64" }, + { 64, 8, 8, "DT_DOUBLE" }, + { 64, 8, 8, "DT_FLOAT64" }, + { 64, 8, 8, "NIFTI_TYPE_FLOAT64" }, + { 128, 3, 0, "DT_RGB" }, + { 128, 3, 0, "DT_RGB24" }, + { 128, 3, 0, "NIFTI_TYPE_RGB24" }, + { 255, 0, 0, "DT_ALL" }, + { 256, 1, 0, "DT_INT8" }, + { 256, 1, 0, "NIFTI_TYPE_INT8" }, + { 512, 2, 2, "DT_UINT16" }, + { 512, 2, 2, "NIFTI_TYPE_UINT16" }, + { 768, 4, 4, "DT_UINT32" }, + { 768, 4, 4, "NIFTI_TYPE_UINT32" }, + { 1024, 8, 8, "DT_INT64" }, + { 1024, 8, 8, "NIFTI_TYPE_INT64" }, + { 1280, 8, 8, "DT_UINT64" }, + { 1280, 8, 8, "NIFTI_TYPE_UINT64" }, + { 1536, 16, 16, "DT_FLOAT128" }, + { 1536, 16, 16, "NIFTI_TYPE_FLOAT128" }, + { 1792, 16, 8, "DT_COMPLEX128" }, + { 1792, 16, 8, "NIFTI_TYPE_COMPLEX128" }, + { 2048, 32, 16, "DT_COMPLEX256" }, + { 2048, 32, 16, "NIFTI_TYPE_COMPLEX256" }, + { 2304, 4, 0, "DT_RGBA32" }, + { 2304, 4, 0, "NIFTI_TYPE_RGBA32" }, +}; + +/*---------------------------------------------------------------------------*/ +/* prototypes for internal functions - not part of exported library */ + +/* extension routines */ +static int nifti_read_extensions( nifti_image *nim, znzFile fp, int remain ); +static int nifti_read_next_extension( nifti1_extension * nex, nifti_image *nim, int remain, znzFile fp ); +static int nifti_check_extension(nifti_image *nim, int size,int code, int rem); +static void update_nifti_image_for_brick_list(nifti_image * nim , int nbricks); +static int nifti_add_exten_to_list(nifti1_extension * new_ext, + nifti1_extension ** list, int new_length); +static int nifti_fill_extension(nifti1_extension * ext, const char * data, + int len, int ecode); + +/* NBL routines */ +static int nifti_load_NBL_bricks(nifti_image * nim , int * slist, int * sindex, nifti_brick_list * NBL, znzFile fp ); +static int nifti_alloc_NBL_mem( nifti_image * nim, int nbricks, + nifti_brick_list * nbl); +static int nifti_copynsort(int nbricks, const int *blist, int **slist, + int **sindex); +static int nifti_NBL_matches_nim(const nifti_image *nim, + const nifti_brick_list *NBL); + +/* for nifti_read_collapsed_image: */ +static int rci_read_data(nifti_image *nim, int *pivots, int *prods, int nprods, + const int dims[], char *data, znzFile fp, size_t base_offset); +static int rci_alloc_mem(void ** data, int prods[8], int nprods, int nbyper ); +static int make_pivot_list(nifti_image * nim, const int dims[], int pivots[], + int prods[], int * nprods ); + +/* misc */ +static int compare_strlist (const char * str, char ** strlist, int len); +static int fileext_compare (const char * test_ext, const char * known_ext); +static int fileext_n_compare (const char * test_ext, + const char * known_ext, size_t maxlen); +static int is_mixedcase (const char * str); +static int is_uppercase (const char * str); +static int make_lowercase (char * str); +static int make_uppercase (char * str); +static int need_nhdr_swap (short dim0, int hdrsize); +static int print_hex_vals (const char * data, int nbytes, FILE * fp); +static int unescape_string (char *str); /* string utility functions */ +static char *escapize_string (const char *str); + +/* internal I/O routines */ +static znzFile nifti_image_load_prep( nifti_image *nim ); +static int has_ascii_header(znzFile fp); +/*---------------------------------------------------------------------------*/ + + +/* for calling from some main program */ + +/*----------------------------------------------------------------------*/ +/*! display the nifti library module history (via stdout) +*//*--------------------------------------------------------------------*/ +void nifti_disp_lib_hist( void ) +{ + int c, len = sizeof(gni_history)/sizeof(char *); + for( c = 0; c < len; c++ ) + Rc_fputs_stdout(gni_history[c]); +} + +/*----------------------------------------------------------------------*/ +/*! display the nifti library version (via stdout) +*//*--------------------------------------------------------------------*/ +void nifti_disp_lib_version( void ) +{ + Rc_printf("%s, compiled %s\n", gni_version, __DATE__); +} + + +/*----------------------------------------------------------------------*/ +/*! nifti_image_read_bricks - read nifti data as array of bricks + * + * 13 Dec 2004 [rickr] + * + * \param hname - filename of dataset to read (must be valid) + * \param nbricks - number of sub-bricks to read + * (if blist is valid, nbricks must be > 0) + * \param blist - list of sub-bricks to read + * (can be NULL; if NULL, read complete dataset) + * \param NBL - pointer to empty nifti_brick_list struct + * (must be a valid pointer) + * + * \return + *
nim - same as nifti_image_read, but + * nim->nt = NBL->nbricks (or nt*nu*nv*nw) + * nim->nu,nv,nw = 1 + * nim->data = NULL + *
NBL - filled with data volumes + * + * By default, this function will read the nifti dataset and break the data + * into a list of nt*nu*nv*nw sub-bricks, each having size nx*ny*nz elements. + * That is to say, instead of reading the entire dataset as a single array, + * break it up into sub-bricks (volumes), each of size nx*ny*nz elements. + * + * Note: in the returned nifti_image, nu, nv and nw will always be 1. The + * intention of this function is to collapse the dataset into a single + * array of volumes (of length nbricks or nt*nu*nv*nw). + * + * If 'blist' is valid, it is taken to be a list of sub-bricks, of length + * 'nbricks'. The data will still be separated into sub-bricks of size + * nx*ny*nz elements, but now 'nbricks' sub-bricks will be returned, of the + * caller's choosing via 'blist'. + * + * E.g. consider a dataset with 12 sub-bricks (numbered 0..11), and the + * following code: + * + *
+ * { nifti_brick_list   NB_orig, NB_select;
+ *   nifti_image      * nim_orig, * nim_select;
+ *   int                blist[5] = { 7, 0, 5, 5, 9 };
+ *
+ *   nim_orig   = nifti_image_read_bricks("myfile.nii", 0, NULL,  &NB_orig);
+ *   nim_select = nifti_image_read_bricks("myfile.nii", 5, blist, &NB_select);
+ * }
+ * 
+ * + * Here, nim_orig gets the entire dataset, where NB_orig.nbricks = 12. But + * nim_select has NB_select.nbricks = 5. + * + * Note that the first case is not quite the same as just calling the + * nifti_image_read function, as here the data is separated into sub-bricks. + * + * Note that valid blist elements are in [0..nt*nu*nv*nw-1], + * or written [ 0 .. (dim[4]*dim[5]*dim[6]*dim[7] - 1) ]. + * + * Note that, as is the case with all of the reading functions, the + * data will be allocated, read in, and properly byte-swapped, if + * necessary. + * + * \sa nifti_image_load_bricks, nifti_free_NBL, valid_nifti_brick_list, + nifti_image_read +*//*----------------------------------------------------------------------*/ +nifti_image *nifti_image_read_bricks(const char * hname, int nbricks, + const int * blist, nifti_brick_list * NBL) +{ + nifti_image * nim; + + if( !hname || !NBL ){ + Rc_fprintf_stderr("** nifti_image_read_bricks: bad params (%p,%p)\n", + hname, (void *)NBL); + return NULL; + } + + if( blist && nbricks <= 0 ){ + Rc_fprintf_stderr("** nifti_image_read_bricks: bad nbricks, %d\n", nbricks); + return NULL; + } + + nim = nifti_image_read(hname, 0); /* read header, but not data */ + + if( !nim ) return NULL; /* errors were already printed */ + + /* if we fail, free image and return */ + if( nifti_image_load_bricks(nim, nbricks, blist, NBL) <= 0 ){ + nifti_image_free(nim); + return NULL; + } + + if( blist ) update_nifti_image_for_brick_list(nim, nbricks); + + return nim; +} + + +/*---------------------------------------------------------------------- + * update_nifti_image_for_brick_list - update nifti_image + * + * When loading a specific brick list, the distinction between + * nt, nu, nv and nw is lost. So put everything in t, and set + * dim[0] = 4. + *----------------------------------------------------------------------*/ +static void update_nifti_image_for_brick_list( nifti_image * nim , int nbricks ) +{ + int ndim; + + if( g_opts.debug > 2 ){ + Rc_fprintf_stderr("+d updating image dimensions for %d bricks in list\n", + nbricks); + Rc_fprintf_stderr(" ndim = %d\n",nim->ndim); + Rc_fprintf_stderr(" nx,ny,nz,nt,nu,nv,nw: (%d,%d,%d,%d,%d,%d,%d)\n", + nim->nx, nim->ny, nim->nz, nim->nt, nim->nu, nim->nv, nim->nw); + } + + nim->nt = nbricks; + nim->nu = nim->nv = nim->nw = 1; + nim->dim[4] = nbricks; + nim->dim[5] = nim->dim[6] = nim->dim[7] = 1; + + /* compute nvox */ + /* do not rely on dimensions above dim[0] 16 Nov 2005 [rickr] */ + for( nim->nvox = 1, ndim = 1; ndim <= nim->dim[0]; ndim++ ) + nim->nvox *= nim->dim[ndim]; + + /* update the dimensions to 4 or lower */ + for( ndim = 4; (ndim > 1) && (nim->dim[ndim] <= 1); ndim-- ) + ; + + if( g_opts.debug > 2 ){ + Rc_fprintf_stderr("+d ndim = %d -> %d\n",nim->ndim, ndim); + Rc_fprintf_stderr(" --> (%d,%d,%d,%d,%d,%d,%d)\n", + nim->nx, nim->ny, nim->nz, nim->nt, nim->nu, nim->nv, nim->nw); + } + + nim->dim[0] = nim->ndim = ndim; +} + + +/*----------------------------------------------------------------------*/ +/*! nifti_update_dims_from_array - update nx, ny, ... from nim->dim[] + + Fix all the dimension information, based on a new nim->dim[]. + + Note: we assume that dim[0] will not increase. + + Check for updates to pixdim[], dx,..., nx,..., nvox, ndim, dim[0]. +*//*--------------------------------------------------------------------*/ +int nifti_update_dims_from_array( nifti_image * nim ) +{ + int c, ndim; + + if( !nim ){ + Rc_fprintf_stderr("** update_dims: missing nim\n"); + return 1; + } + + if( g_opts.debug > 2 ){ + Rc_fprintf_stderr("+d updating image dimensions given nim->dim:"); + for( c = 0; c < 8; c++ ) Rc_fprintf_stderr(" %d", nim->dim[c]); + Rc_fputc_stderr('\n'); + } + + /* verify dim[0] first */ + if(nim->dim[0] < 1 || nim->dim[0] > 7){ + Rc_fprintf_stderr("** invalid dim[0], dim[] = "); + for( c = 0; c < 8; c++ ) Rc_fprintf_stderr(" %d", nim->dim[c]); + Rc_fputc_stderr('\n'); + return 1; + } + + /* set nx, ny ..., dx, dy, ..., one by one */ + + /* less than 1, set to 1, else copy */ + if(nim->dim[1] < 1) nim->nx = nim->dim[1] = 1; + else nim->nx = nim->dim[1]; + nim->dx = nim->pixdim[1]; + + /* if undefined, or less than 1, set to 1 */ + if(nim->dim[0] < 2 || (nim->dim[0] >= 2 && nim->dim[2] < 1)) + nim->ny = nim->dim[2] = 1; + else + nim->ny = nim->dim[2]; + /* copy delta values, in any case */ + nim->dy = nim->pixdim[2]; + + if(nim->dim[0] < 3 || (nim->dim[0] >= 3 && nim->dim[3] < 1)) + nim->nz = nim->dim[3] = 1; + else /* just copy vals from arrays */ + nim->nz = nim->dim[3]; + nim->dz = nim->pixdim[3]; + + if(nim->dim[0] < 4 || (nim->dim[0] >= 4 && nim->dim[4] < 1)) + nim->nt = nim->dim[4] = 1; + else /* just copy vals from arrays */ + nim->nt = nim->dim[4]; + nim->dt = nim->pixdim[4]; + + if(nim->dim[0] < 5 || (nim->dim[0] >= 5 && nim->dim[5] < 1)) + nim->nu = nim->dim[5] = 1; + else /* just copy vals from arrays */ + nim->nu = nim->dim[5]; + nim->du = nim->pixdim[5]; + + if(nim->dim[0] < 6 || (nim->dim[0] >= 6 && nim->dim[6] < 1)) + nim->nv = nim->dim[6] = 1; + else /* just copy vals from arrays */ + nim->nv = nim->dim[6]; + nim->dv = nim->pixdim[6]; + + if(nim->dim[0] < 7 || (nim->dim[0] >= 7 && nim->dim[7] < 1)) + nim->nw = nim->dim[7] = 1; + else /* just copy vals from arrays */ + nim->nw = nim->dim[7]; + nim->dw = nim->pixdim[7]; + + for( c = 1, nim->nvox = 1; c <= nim->dim[0]; c++ ) + nim->nvox *= nim->dim[c]; + + /* compute ndim, assuming it can be no larger than the old one */ + for( ndim = nim->dim[0]; (ndim > 1) && (nim->dim[ndim] <= 1); ndim-- ) + ; + + if( g_opts.debug > 2 ){ + Rc_fprintf_stderr("+d ndim = %d -> %d\n",nim->ndim, ndim); + Rc_fprintf_stderr(" --> (%d,%d,%d,%d,%d,%d,%d)\n", + nim->nx, nim->ny, nim->nz, nim->nt, nim->nu, nim->nv, nim->nw); + } + + nim->dim[0] = nim->ndim = ndim; + + return 0; +} + + +/*----------------------------------------------------------------------*/ +/*! Load the image data from disk into an already-prepared image struct. + * + * \param nim - initialized nifti_image, without data + * \param nbricks - the length of blist (must be 0 if blist is NULL) + * \param blist - an array of xyz volume indices to read (can be NULL) + * \param NBL - pointer to struct where resulting data will be stored + * + * If blist is NULL, read all sub-bricks. + * + * \return the number of loaded bricks (NBL->nbricks), + * 0 on failure, < 0 on error + * + * NOTE: it is likely that another function will copy the data pointers + * out of NBL, in which case the only pointer the calling function + * will want to free is NBL->bricks (not each NBL->bricks[i]). +*//*--------------------------------------------------------------------*/ +int nifti_image_load_bricks( nifti_image * nim , int nbricks, + const int * blist, nifti_brick_list * NBL ) +{ + int * slist = NULL, * sindex = NULL, rv; + znzFile fp; + + /* we can have blist == NULL */ + if( !nim || !NBL ){ + Rc_fprintf_stderr("** nifti_image_load_bricks, bad params (%p,%p)\n", + (void *)nim, (void *)NBL); + return -1; + } + + if( blist && nbricks <= 0 ){ + if( g_opts.debug > 1 ) + Rc_fprintf_stderr("-d load_bricks: received blist with nbricks = %d," + "ignoring blist\n", nbricks); + blist = NULL; /* pretend nothing was passed */ + } + + if( blist && ! valid_nifti_brick_list(nim, nbricks, blist, g_opts.debug>0) ) + return -1; + + /* for efficiency, let's read the file in order */ + if( blist && nifti_copynsort( nbricks, blist, &slist, &sindex ) != 0 ) + return -1; + + /* open the file and position the FILE pointer */ + fp = nifti_image_load_prep( nim ); + if( !fp ){ + if( g_opts.debug > 0 ) + Rc_fprintf_stderr("** nifti_image_load_bricks, failed load_prep\n"); + if( blist ){ free(slist); free(sindex); } + return -1; + } + + /* this will flag to allocate defaults */ + if( !blist ) nbricks = 0; + if( nifti_alloc_NBL_mem( nim, nbricks, NBL ) != 0 ){ + if( blist ){ free(slist); free(sindex); } + znzclose(fp); + return -1; + } + + rv = nifti_load_NBL_bricks(nim, slist, sindex, NBL, fp); + + if( rv != 0 ){ + nifti_free_NBL( NBL ); /* failure! */ + NBL->nbricks = 0; /* repetative, but clear */ + } + + if( slist ){ free(slist); free(sindex); } + + znzclose(fp); + + return NBL->nbricks; +} + + +/*----------------------------------------------------------------------*/ +/*! nifti_free_NBL - free all pointers and clear structure + * + * note: this does not presume to free the structure pointer +*//*--------------------------------------------------------------------*/ +void nifti_free_NBL( nifti_brick_list * NBL ) +{ + int c; + + if( NBL->bricks ){ + for( c = 0; c < NBL->nbricks; c++ ) + if( NBL->bricks[c] ) free(NBL->bricks[c]); + free(NBL->bricks); + NBL->bricks = NULL; + } + + NBL->bsize = NBL->nbricks = 0; +} + + +/*---------------------------------------------------------------------- + * nifti_load_NBL_bricks - read the file data into the NBL struct + * + * return 0 on success, -1 on failure + *----------------------------------------------------------------------*/ +static int nifti_load_NBL_bricks( nifti_image * nim , int * slist, int * sindex, + nifti_brick_list * NBL, znzFile fp ) +{ + size_t oposn, fposn; /* orig and current file positions */ + size_t rv; + long test; + int c; + int prev, isrc, idest; /* previous and current sub-brick, and new index */ + + test = znztell(fp); /* store current file position */ + if( test < 0 ){ + Rc_fprintf_stderr("** load bricks: ztell failed??\n"); + return -1; + } + fposn = oposn = test; + + /* first, handle the default case, no passed blist */ + if( !slist ){ + for( c = 0; c < NBL->nbricks; c++ ) { + rv = nifti_read_buffer(fp, NBL->bricks[c], NBL->bsize, nim); + if( rv != NBL->bsize ){ + Rc_fprintf_stderr("** load bricks: cannot read brick %d from '%s'\n", + c, nim->iname ? nim->iname : nim->fname); + return -1; + } + } + if( g_opts.debug > 1 ) + Rc_fprintf_stderr("+d read %d default %u-byte bricks from file %s\n", + NBL->nbricks, (unsigned int)NBL->bsize, + nim->iname ? nim->iname:nim->fname ); + return 0; + } + + if( !sindex ){ + Rc_fprintf_stderr("** load_NBL_bricks: missing index list\n"); + return -1; + } + + prev = -1; /* use prev for previous sub-brick */ + for( c = 0; c < NBL->nbricks; c++ ){ + isrc = slist[c]; /* this is original brick index (c is new one) */ + idest = sindex[c]; /* this is the destination index for this data */ + + /* if this sub-brick is not the previous, we must read from disk */ + if( isrc != prev ){ + + /* if we are not looking at the correct sub-brick, scan forward */ + if( fposn != (oposn + isrc*NBL->bsize) ){ + fposn = oposn + isrc*NBL->bsize; + if( znzseek(fp, (long)fposn, SEEK_SET) < 0 ){ + Rc_fprintf_stderr("** failed to locate brick %d in file '%s'\n", + isrc, nim->iname ? nim->iname : nim->fname); + return -1; + } + } + + /* only 10,000 lines later and we're actually reading something! */ + rv = nifti_read_buffer(fp, NBL->bricks[idest], NBL->bsize, nim); + if( rv != NBL->bsize ){ + Rc_fprintf_stderr("** failed to read brick %d from file '%s'\n", + isrc, nim->iname ? nim->iname : nim->fname); + if( g_opts.debug > 1 ) + Rc_fprintf_stderr(" (read %u of %u bytes)\n", + (unsigned int)rv, (unsigned int)NBL->bsize); + return -1; + } + fposn += NBL->bsize; + } else { + /* we have already read this sub-brick, just copy the previous one */ + /* note that this works because they are sorted */ + memcpy(NBL->bricks[idest], NBL->bricks[sindex[c-1]], NBL->bsize); + } + + prev = isrc; /* in any case, note the now previous sub-brick */ + } + + return 0; +} + + +/*---------------------------------------------------------------------- + * nifti_alloc_NBL_mem - allocate memory for bricks + * + * return 0 on success, -1 on failure + *----------------------------------------------------------------------*/ +static int nifti_alloc_NBL_mem(nifti_image * nim, int nbricks, + nifti_brick_list * nbl) +{ + int c; + + /* if nbricks is not specified, use the default */ + if( nbricks > 0 ) nbl->nbricks = nbricks; + else { /* I missed this one with the 1.17 change 02 Mar 2006 [rickr] */ + nbl->nbricks = 1; + for( c = 4; c <= nim->ndim; c++ ) + nbl->nbricks *= nim->dim[c]; + } + + nbl->bsize = (size_t)nim->nx * nim->ny * nim->nz * nim->nbyper;/* bytes */ + nbl->bricks = (void **)malloc(nbl->nbricks * sizeof(void *)); + + if( ! nbl->bricks ){ + Rc_fprintf_stderr("** NANM: failed to alloc %d void ptrs\n",nbricks); + return -1; + } + + for( c = 0; c < nbl->nbricks; c++ ){ + nbl->bricks[c] = (void *)malloc(nbl->bsize); + if( ! nbl->bricks[c] ){ + Rc_fprintf_stderr("** NANM: failed to alloc %u bytes for brick %d\n", + (unsigned int)nbl->bsize, c); + /* so free and clear everything before returning */ + while( c > 0 ){ + c--; + free(nbl->bricks[c]); + } + free(nbl->bricks); + nbl->bricks = NULL; + nbl->bsize = nbl->nbricks = 0; + return -1; + } + } + + if( g_opts.debug > 2 ) + Rc_fprintf_stderr("+d NANM: alloc'd %d bricks of %u bytes for NBL\n", + nbl->nbricks, (unsigned int)nbl->bsize); + + return 0; +} + + +/*---------------------------------------------------------------------- + * nifti_copynsort - copy int list, and sort with indices + * + * 1. duplicate the incoming list + * 2. create an sindex list, and init with 0..nbricks-1 + * 3. do a slow insertion sort on the small slist, along with sindex list + * 4. check results, just to be positive + * + * So slist is sorted, and sindex hold original positions. + * + * return 0 on success, -1 on failure + *----------------------------------------------------------------------*/ +static int nifti_copynsort(int nbricks, const int * blist, int ** slist, + int ** sindex) +{ + int * stmp, * itmp; /* for ease of typing/reading */ + int c1, c2, spos, tmp; + + *slist = (int *)malloc(nbricks * sizeof(int)); + *sindex = (int *)malloc(nbricks * sizeof(int)); + + if( !*slist || !*sindex ){ + Rc_fprintf_stderr("** NCS: failed to alloc %d ints for sorting\n",nbricks); + if(*slist) free(*slist); /* maybe one succeeded */ + if(*sindex) free(*sindex); + return -1; + } + + /* init the lists */ + memcpy(*slist, blist, nbricks*sizeof(int)); + for( c1 = 0; c1 < nbricks; c1++ ) (*sindex)[c1] = c1; + + /* now actually sort slist */ + stmp = *slist; + itmp = *sindex; + for( c1 = 0; c1 < nbricks-1; c1++ ) { + /* find smallest value, init to current */ + spos = c1; + for( c2 = c1+1; c2 < nbricks; c2++ ) + if( stmp[c2] < stmp[spos] ) spos = c2; + if( spos != c1 ) /* swap: fine, don't maintain sub-order, see if I care */ + { + tmp = stmp[c1]; /* first swap the sorting values */ + stmp[c1] = stmp[spos]; + stmp[spos] = tmp; + + tmp = itmp[c1]; /* then swap the index values */ + itmp[c1] = itmp[spos]; + itmp[spos] = tmp; + } + } + + if( g_opts.debug > 2 ){ + Rc_fprintf_stderr("+d sorted indexing list:\n"); + Rc_fprintf_stderr(" orig : "); + for( c1 = 0; c1 < nbricks; c1++ ) Rc_fprintf_stderr(" %d",blist[c1]); + Rc_fprintf_stderr("\n new : "); + for( c1 = 0; c1 < nbricks; c1++ ) Rc_fprintf_stderr(" %d",stmp[c1]); + Rc_fprintf_stderr("\n indices: "); + for( c1 = 0; c1 < nbricks; c1++ ) Rc_fprintf_stderr(" %d",itmp[c1]); + Rc_fputc_stderr('\n'); + } + + /* check the sort (why not? I've got time...) */ + for( c1 = 0; c1 < nbricks-1; c1++ ){ + if( (stmp[c1] > stmp[c1+1]) || (blist[itmp[c1]] != stmp[c1]) ){ + Rc_fprintf_stderr("** sorting screw-up, way to go, rick!\n"); + free(stmp); free(itmp); *slist = NULL; *sindex = NULL; + return -1; + } + } + + if( g_opts.debug > 2 ) Rc_fprintf_stderr("-d sorting is okay\n"); + + return 0; +} + + +/*----------------------------------------------------------------------*/ +/*! valid_nifti_brick_list - check sub-brick list for image + * + * This function verifies that nbricks and blist are appropriate + * for use with this nim, based on the dimensions. + * + * \param nim nifti_image to check against + * \param nbricks number of brick indices in blist + * \param blist list of brick indices to check in nim + * \param disp_error if this flag is set, report errors to user + * + * \return 1 if valid, 0 if not +*//*--------------------------------------------------------------------*/ +int valid_nifti_brick_list(nifti_image * nim , int nbricks, + const int * blist, int disp_error) +{ + int c, nsubs; + + if( !nim ){ + if( disp_error || g_opts.debug > 0 ) + Rc_fprintf_stderr("** valid_nifti_brick_list: missing nifti image\n"); + return 0; + } + + if( nbricks <= 0 || !blist ){ + if( disp_error || g_opts.debug > 1 ) + Rc_fprintf_stderr("** valid_nifti_brick_list: no brick list to check\n"); + return 0; + } + + if( nim->dim[0] < 3 ){ + if( disp_error || g_opts.debug > 1 ) + Rc_fprintf_stderr("** cannot read explict brick list from %d-D dataset\n", + nim->dim[0]); + return 0; + } + + /* nsubs sub-brick is nt*nu*nv*nw */ + for( c = 4, nsubs = 1; c <= nim->dim[0]; c++ ) + nsubs *= nim->dim[c]; + + if( nsubs <= 0 ){ + Rc_fprintf_stderr("** VNBL warning: bad dim list (%d,%d,%d,%d)\n", + nim->dim[4], nim->dim[5], nim->dim[6], nim->dim[7]); + return 0; + } + + for( c = 0; c < nbricks; c++ ) + if( (blist[c] < 0) || (blist[c] >= nsubs) ){ + if( disp_error || g_opts.debug > 1 ) + Rc_fprintf_stderr("** volume index %d (#%d) is out of range [0,%d]\n", + blist[c], c, nsubs-1); + return 0; + } + + return 1; /* all is well */ +} + +/*----------------------------------------------------------------------*/ +/* verify that NBL struct is a valid data source for the image + * + * return 1 if so, 0 otherwise +*//*--------------------------------------------------------------------*/ +static int nifti_NBL_matches_nim(const nifti_image *nim, + const nifti_brick_list *NBL) +{ + size_t volbytes = 0; /* bytes per volume */ + int ind, errs = 0, nvols = 0; + + + if( !nim || !NBL ) { + if( g_opts.debug > 0 ) + Rc_fprintf_stderr("** nifti_NBL_matches_nim: NULL pointer(s)\n"); + return 0; + } + + /* for nim, compute volbytes and nvols */ + if( nim->ndim > 0 ) { + /* first 3 indices are over a single volume */ + volbytes = (size_t)nim->nbyper; + for( ind = 1; ind <= nim->ndim && ind < 4; ind++ ) + volbytes *= (size_t)nim->dim[ind]; + + for( ind = 4, nvols = 1; ind <= nim->ndim; ind++ ) + nvols *= nim->dim[ind]; + } + + if( volbytes != NBL->bsize ) { + if( g_opts.debug > 1 ) + Rc_fprintf_stderr("** NBL/nim mismatch, volbytes = %u, %u\n", + (unsigned)NBL->bsize, (unsigned)volbytes); + errs++; + } + + if( nvols != NBL->nbricks ) { + if( g_opts.debug > 1 ) + Rc_fprintf_stderr("** NBL/nim mismatch, nvols = %d, %d\n", + NBL->nbricks, nvols); + errs++; + } + + if( errs ) return 0; + else if ( g_opts.debug > 2 ) + Rc_fprintf_stderr("-- nim/NBL agree: nvols = %d, nbytes = %u\n", + nvols, (unsigned)volbytes); + + return 1; +} + +/* end of new nifti_image_read_bricks() functionality */ + +/*----------------------------------------------------------------------*/ +/*! display the orientation from the quaternian fields + * + * \param mesg if non-NULL, display this message first + * \param mat the matrix to convert to "nearest" orientation + * + * \return -1 if results cannot be determined, 0 if okay +*//*--------------------------------------------------------------------*/ +int nifti_disp_matrix_orient( const char * mesg, mat44 mat ) +{ + int i, j, k; + + if ( mesg ) Rc_fputs_stderr( mesg ); /* use stdout? */ + + nifti_mat44_to_orientation( mat, &i,&j,&k ); + if ( i <= 0 || j <= 0 || k <= 0 ) return -1; + + /* so we have good codes */ + Rc_fprintf_stderr(" i orientation = '%s'\n" + " j orientation = '%s'\n" + " k orientation = '%s'\n", + nifti_orientation_string(i), + nifti_orientation_string(j), + nifti_orientation_string(k) ); + return 0; +} + + +/*----------------------------------------------------------------------*/ +/*! duplicate the given string (alloc length+1) + * + * \return allocated pointer (or NULL on failure) +*//*--------------------------------------------------------------------*/ +char *nifti_strdup(const char *str) +{ + char *dup; + + if( !str ) return NULL; /* allow calls passing NULL */ + + dup = (char *)malloc(strlen(str) + 1); + + /* check for failure */ + if( dup ) strcpy(dup, str); + else Rc_fprintf_stderr("** nifti_strdup: failed to alloc %u bytes\n", + (unsigned int)strlen(str)+1); + + return dup; +} + + +/*---------------------------------------------------------------------------*/ +/*! Return a pointer to a string holding the name of a NIFTI datatype. + + \param dt NIfTI-1 datatype + + \return pointer to static string holding the datatype name + + \warning Do not free() or modify this string! + It points to static storage. + + \sa NIFTI1_DATATYPES group in nifti1.h +*//*-------------------------------------------------------------------------*/ +char const * nifti_datatype_string( int dt ) +{ + switch( dt ){ + case DT_UNKNOWN: return "UNKNOWN" ; + case DT_BINARY: return "BINARY" ; + case DT_INT8: return "INT8" ; + case DT_UINT8: return "UINT8" ; + case DT_INT16: return "INT16" ; + case DT_UINT16: return "UINT16" ; + case DT_INT32: return "INT32" ; + case DT_UINT32: return "UINT32" ; + case DT_INT64: return "INT64" ; + case DT_UINT64: return "UINT64" ; + case DT_FLOAT32: return "FLOAT32" ; + case DT_FLOAT64: return "FLOAT64" ; + case DT_FLOAT128: return "FLOAT128" ; + case DT_COMPLEX64: return "COMPLEX64" ; + case DT_COMPLEX128: return "COMPLEX128" ; + case DT_COMPLEX256: return "COMPLEX256" ; + case DT_RGB24: return "RGB24" ; + case DT_RGBA32: return "RGBA32" ; + } + return "**ILLEGAL**" ; +} + +/*----------------------------------------------------------------------*/ +/*! Determine if the datatype code dt is an integer type (1=YES, 0=NO). + + \return whether the given NIfTI-1 datatype code is valid + + \sa NIFTI1_DATATYPES group in nifti1.h +*//*--------------------------------------------------------------------*/ +int nifti_is_inttype( int dt ) +{ + switch( dt ){ + case DT_UNKNOWN: return 0 ; + case DT_BINARY: return 0 ; + case DT_INT8: return 1 ; + case DT_UINT8: return 1 ; + case DT_INT16: return 1 ; + case DT_UINT16: return 1 ; + case DT_INT32: return 1 ; + case DT_UINT32: return 1 ; + case DT_INT64: return 1 ; + case DT_UINT64: return 1 ; + case DT_FLOAT32: return 0 ; + case DT_FLOAT64: return 0 ; + case DT_FLOAT128: return 0 ; + case DT_COMPLEX64: return 0 ; + case DT_COMPLEX128: return 0 ; + case DT_COMPLEX256: return 0 ; + case DT_RGB24: return 1 ; + case DT_RGBA32: return 1 ; + } + return 0 ; +} + +/*---------------------------------------------------------------------------*/ +/*! Return a pointer to a string holding the name of a NIFTI units type. + + \param uu NIfTI-1 unit code + + \return pointer to static string for the given unit type + + \warning Do not free() or modify this string! + It points to static storage. + + \sa NIFTI1_UNITS group in nifti1.h +*//*-------------------------------------------------------------------------*/ +char const *nifti_units_string( int uu ) +{ + switch( uu ){ + case NIFTI_UNITS_METER: return "m" ; + case NIFTI_UNITS_MM: return "mm" ; + case NIFTI_UNITS_MICRON: return "um" ; + case NIFTI_UNITS_SEC: return "s" ; + case NIFTI_UNITS_MSEC: return "ms" ; + case NIFTI_UNITS_USEC: return "us" ; + case NIFTI_UNITS_HZ: return "Hz" ; + case NIFTI_UNITS_PPM: return "ppm" ; + case NIFTI_UNITS_RADS: return "rad/s" ; + } + return "Unknown" ; +} + +/*---------------------------------------------------------------------------*/ +/*! Return a pointer to a string holding the name of a NIFTI transform type. + + \param xx NIfTI-1 xform code + + \return pointer to static string describing xform code + + \warning Do not free() or modify this string! + It points to static storage. + + \sa NIFTI1_XFORM_CODES group in nifti1.h +*//*-------------------------------------------------------------------------*/ +char const *nifti_xform_string( int xx ) +{ + switch( xx ){ + case NIFTI_XFORM_SCANNER_ANAT: return "Scanner Anat" ; + case NIFTI_XFORM_ALIGNED_ANAT: return "Aligned Anat" ; + case NIFTI_XFORM_TALAIRACH: return "Talairach" ; + case NIFTI_XFORM_MNI_152: return "MNI_152" ; + } + return "Unknown" ; +} + +/*---------------------------------------------------------------------------*/ +/*! Return a pointer to a string holding the name of a NIFTI intent type. + + \param ii NIfTI-1 intent code + + \return pointer to static string describing code + + \warning Do not free() or modify this string! + It points to static storage. + + \sa NIFTI1_INTENT_CODES group in nifti1.h +*//*-------------------------------------------------------------------------*/ +char const *nifti_intent_string( int ii ) +{ + switch( ii ){ + case NIFTI_INTENT_CORREL: return "Correlation statistic" ; + case NIFTI_INTENT_TTEST: return "T-statistic" ; + case NIFTI_INTENT_FTEST: return "F-statistic" ; + case NIFTI_INTENT_ZSCORE: return "Z-score" ; + case NIFTI_INTENT_CHISQ: return "Chi-squared distribution" ; + case NIFTI_INTENT_BETA: return "Beta distribution" ; + case NIFTI_INTENT_BINOM: return "Binomial distribution" ; + case NIFTI_INTENT_GAMMA: return "Gamma distribution" ; + case NIFTI_INTENT_POISSON: return "Poisson distribution" ; + case NIFTI_INTENT_NORMAL: return "Normal distribution" ; + case NIFTI_INTENT_FTEST_NONC: return "F-statistic noncentral" ; + case NIFTI_INTENT_CHISQ_NONC: return "Chi-squared noncentral" ; + case NIFTI_INTENT_LOGISTIC: return "Logistic distribution" ; + case NIFTI_INTENT_LAPLACE: return "Laplace distribution" ; + case NIFTI_INTENT_UNIFORM: return "Uniform distribition" ; + case NIFTI_INTENT_TTEST_NONC: return "T-statistic noncentral" ; + case NIFTI_INTENT_WEIBULL: return "Weibull distribution" ; + case NIFTI_INTENT_CHI: return "Chi distribution" ; + case NIFTI_INTENT_INVGAUSS: return "Inverse Gaussian distribution" ; + case NIFTI_INTENT_EXTVAL: return "Extreme Value distribution" ; + case NIFTI_INTENT_PVAL: return "P-value" ; + + case NIFTI_INTENT_LOGPVAL: return "Log P-value" ; + case NIFTI_INTENT_LOG10PVAL: return "Log10 P-value" ; + + case NIFTI_INTENT_ESTIMATE: return "Estimate" ; + case NIFTI_INTENT_LABEL: return "Label index" ; + case NIFTI_INTENT_NEURONAME: return "NeuroNames index" ; + case NIFTI_INTENT_GENMATRIX: return "General matrix" ; + case NIFTI_INTENT_SYMMATRIX: return "Symmetric matrix" ; + case NIFTI_INTENT_DISPVECT: return "Displacement vector" ; + case NIFTI_INTENT_VECTOR: return "Vector" ; + case NIFTI_INTENT_POINTSET: return "Pointset" ; + case NIFTI_INTENT_TRIANGLE: return "Triangle" ; + case NIFTI_INTENT_QUATERNION: return "Quaternion" ; + + case NIFTI_INTENT_DIMLESS: return "Dimensionless number" ; + } + return "Unknown" ; +} + +/*---------------------------------------------------------------------------*/ +/*! Return a pointer to a string holding the name of a NIFTI slice_code. + + \param ss NIfTI-1 slice order code + + \return pointer to static string describing code + + \warning Do not free() or modify this string! + It points to static storage. + + \sa NIFTI1_SLICE_ORDER group in nifti1.h +*//*-------------------------------------------------------------------------*/ +char const *nifti_slice_string( int ss ) +{ + switch( ss ){ + case NIFTI_SLICE_SEQ_INC: return "sequential_increasing" ; + case NIFTI_SLICE_SEQ_DEC: return "sequential_decreasing" ; + case NIFTI_SLICE_ALT_INC: return "alternating_increasing" ; + case NIFTI_SLICE_ALT_DEC: return "alternating_decreasing" ; + case NIFTI_SLICE_ALT_INC2: return "alternating_increasing_2" ; + case NIFTI_SLICE_ALT_DEC2: return "alternating_decreasing_2" ; + } + return "Unknown" ; +} + +/*---------------------------------------------------------------------------*/ +/*! Return a pointer to a string holding the name of a NIFTI orientation. + + \param ii orientation code + + \return pointer to static string holding the orientation information + + \warning Do not free() or modify the return string! + It points to static storage. + + \sa NIFTI_L2R in nifti1_io.h +*//*-------------------------------------------------------------------------*/ +char const *nifti_orientation_string( int ii ) +{ + switch( ii ){ + case NIFTI_L2R: return "Left-to-Right" ; + case NIFTI_R2L: return "Right-to-Left" ; + case NIFTI_P2A: return "Posterior-to-Anterior" ; + case NIFTI_A2P: return "Anterior-to-Posterior" ; + case NIFTI_I2S: return "Inferior-to-Superior" ; + case NIFTI_S2I: return "Superior-to-Inferior" ; + } + return "Unknown" ; +} + +/*--------------------------------------------------------------------------*/ +/*! Given a datatype code, set number of bytes per voxel and the swapsize. + + \param datatype nifti1 datatype code + \param nbyper pointer to return value: number of bytes per voxel + \param swapsize pointer to return value: size of swap blocks + + \return appropriate values at nbyper and swapsize + + The swapsize is set to 0 if this datatype doesn't ever need swapping. + + \sa NIFTI1_DATATYPES in nifti1.h +*//*------------------------------------------------------------------------*/ +void nifti_datatype_sizes( int datatype , int *nbyper, int *swapsize ) +{ + int nb=0, ss=0 ; + switch( datatype ){ + case DT_INT8: + case DT_UINT8: nb = 1 ; ss = 0 ; break ; + + case DT_INT16: + case DT_UINT16: nb = 2 ; ss = 2 ; break ; + + case DT_RGB24: nb = 3 ; ss = 0 ; break ; + case DT_RGBA32: nb = 4 ; ss = 0 ; break ; + + case DT_INT32: + case DT_UINT32: + case DT_FLOAT32: nb = 4 ; ss = 4 ; break ; + + case DT_COMPLEX64: nb = 8 ; ss = 4 ; break ; + + case DT_FLOAT64: + case DT_INT64: + case DT_UINT64: nb = 8 ; ss = 8 ; break ; + + case DT_FLOAT128: nb = 16 ; ss = 16 ; break ; + + case DT_COMPLEX128: nb = 16 ; ss = 8 ; break ; + + case DT_COMPLEX256: nb = 32 ; ss = 16 ; break ; + } + + ASSIF(nbyper,nb) ; ASSIF(swapsize,ss) ; return ; +} + +/*---------------------------------------------------------------------------*/ +/*! Given the quaternion parameters (etc.), compute a transformation matrix. + + See comments in nifti1.h for details. + - qb,qc,qd = quaternion parameters + - qx,qy,qz = offset parameters + - dx,dy,dz = grid stepsizes (non-negative inputs are set to 1.0) + - qfac = sign of dz step (< 0 is negative; >= 0 is positive) + +
+   If qx=qy=qz=0, dx=dy=dz=1, then the output is a rotation matrix.
+   For qfac >= 0, the rotation is proper.
+   For qfac <  0, the rotation is improper.
+   
+ + \see "QUATERNION REPRESENTATION OF ROTATION MATRIX" in nifti1.h + \see nifti_mat44_to_quatern, nifti_make_orthog_mat44, + nifti_mat44_to_orientation + +*//*-------------------------------------------------------------------------*/ +mat44 nifti_quatern_to_mat44( float qb, float qc, float qd, + float qx, float qy, float qz, + float dx, float dy, float dz, float qfac ) +{ + mat44 R ; + double a,b=qb,c=qc,d=qd , xd,yd,zd ; + + /* last row is always [ 0 0 0 1 ] */ + + R.m[3][0]=R.m[3][1]=R.m[3][2] = 0.0f ; R.m[3][3]= 1.0f ; + + /* compute a parameter from b,c,d */ + + a = 1.0l - (b*b + c*c + d*d) ; + if( a < 1.e-7l ){ /* special case */ + a = 1.0l / sqrt(b*b+c*c+d*d) ; + b *= a ; c *= a ; d *= a ; /* normalize (b,c,d) vector */ + a = 0.0l ; /* a = 0 ==> 180 degree rotation */ + } else{ + a = sqrt(a) ; /* angle = 2*arccos(a) */ + } + + /* load rotation matrix, including scaling factors for voxel sizes */ + + xd = (dx > 0.0) ? dx : 1.0l ; /* make sure are positive */ + yd = (dy > 0.0) ? dy : 1.0l ; + zd = (dz > 0.0) ? dz : 1.0l ; + + if( qfac < 0.0 ) zd = -zd ; /* left handedness? */ + + R.m[0][0] = (float)( (a*a+b*b-c*c-d*d) * xd) ; + R.m[0][1] = 2.0l * (b*c-a*d ) * yd ; + R.m[0][2] = 2.0l * (b*d+a*c ) * zd ; + R.m[1][0] = 2.0l * (b*c+a*d ) * xd ; + R.m[1][1] = (float)( (a*a+c*c-b*b-d*d) * yd) ; + R.m[1][2] = 2.0l * (c*d-a*b ) * zd ; + R.m[2][0] = 2.0l * (b*d-a*c ) * xd ; + R.m[2][1] = 2.0l * (c*d+a*b ) * yd ; + R.m[2][2] = (float)( (a*a+d*d-c*c-b*b) * zd) ; + + /* load offsets */ + + R.m[0][3] = qx ; R.m[1][3] = qy ; R.m[2][3] = qz ; + + return R ; +} + +/*---------------------------------------------------------------------------*/ +/*! Given the 3x4 upper corner of the matrix R, compute the quaternion + parameters that fit it. + + - Any NULL pointer on input won't get assigned (e.g., if you don't want + dx,dy,dz, just pass NULL in for those pointers). + - If the 3 input matrix columns are NOT orthogonal, they will be + orthogonalized prior to calculating the parameters, using + the polar decomposition to find the orthogonal matrix closest + to the column-normalized input matrix. + - However, if the 3 input matrix columns are NOT orthogonal, then + the matrix produced by nifti_quatern_to_mat44 WILL have orthogonal + columns, so it won't be the same as the matrix input here. + This "feature" is because the NIFTI 'qform' transform is + deliberately not fully general -- it is intended to model a volume + with perpendicular axes. + - If the 3 input matrix columns are not even linearly independent, + you'll just have to take your luck, won't you? + + \see "QUATERNION REPRESENTATION OF ROTATION MATRIX" in nifti1.h + + \see nifti_quatern_to_mat44, nifti_make_orthog_mat44, + nifti_mat44_to_orientation +*//*-------------------------------------------------------------------------*/ +void nifti_mat44_to_quatern( mat44 R , + float *qb, float *qc, float *qd, + float *qx, float *qy, float *qz, + float *dx, float *dy, float *dz, float *qfac ) +{ + double r11,r12,r13 , r21,r22,r23 , r31,r32,r33 ; + double xd,yd,zd , a,b,c,d ; + mat33 P,Q ; + + /* offset outputs are read write out of input matrix */ + + ASSIF(qx,R.m[0][3]) ; ASSIF(qy,R.m[1][3]) ; ASSIF(qz,R.m[2][3]) ; + + /* load 3x3 matrix into local variables */ + + r11 = R.m[0][0] ; r12 = R.m[0][1] ; r13 = R.m[0][2] ; + r21 = R.m[1][0] ; r22 = R.m[1][1] ; r23 = R.m[1][2] ; + r31 = R.m[2][0] ; r32 = R.m[2][1] ; r33 = R.m[2][2] ; + + /* compute lengths of each column; these determine grid spacings */ + + xd = sqrt( r11*r11 + r21*r21 + r31*r31 ) ; + yd = sqrt( r12*r12 + r22*r22 + r32*r32 ) ; + zd = sqrt( r13*r13 + r23*r23 + r33*r33 ) ; + + /* if a column length is zero, patch the trouble */ + + if( xd == 0.0l ){ r11 = 1.0l ; r21 = r31 = 0.0l ; xd = 1.0l ; } + if( yd == 0.0l ){ r22 = 1.0l ; r12 = r32 = 0.0l ; yd = 1.0l ; } + if( zd == 0.0l ){ r33 = 1.0l ; r13 = r23 = 0.0l ; zd = 1.0l ; } + + /* assign the output lengths */ + + ASSIF(dx,(float)xd) ; ASSIF(dy,(float)yd) ; ASSIF(dz,(float)zd) ; + + /* normalize the columns */ + + r11 /= xd ; r21 /= xd ; r31 /= xd ; + r12 /= yd ; r22 /= yd ; r32 /= yd ; + r13 /= zd ; r23 /= zd ; r33 /= zd ; + + /* At this point, the matrix has normal columns, but we have to allow + for the fact that the hideous user may not have given us a matrix + with orthogonal columns. + + So, now find the orthogonal matrix closest to the current matrix. + + One reason for using the polar decomposition to get this + orthogonal matrix, rather than just directly orthogonalizing + the columns, is so that inputting the inverse matrix to R + will result in the inverse orthogonal matrix at this point. + If we just orthogonalized the columns, this wouldn't necessarily hold. */ + + Q.m[0][0] = (float)r11 ; Q.m[0][1] = (float)r12 ; Q.m[0][2] = (float)r13 ; /* load Q */ + Q.m[1][0] = (float)r21 ; Q.m[1][1] = (float)r22 ; Q.m[1][2] = (float)r23 ; + Q.m[2][0] = (float)r31 ; Q.m[2][1] = (float)r32 ; Q.m[2][2] = (float)r33 ; + + P = nifti_mat33_polar(Q) ; /* P is orthog matrix closest to Q */ + + r11 = P.m[0][0] ; r12 = P.m[0][1] ; r13 = P.m[0][2] ; /* unload */ + r21 = P.m[1][0] ; r22 = P.m[1][1] ; r23 = P.m[1][2] ; + r31 = P.m[2][0] ; r32 = P.m[2][1] ; r33 = P.m[2][2] ; + + /* [ r11 r12 r13 ] */ + /* at this point, the matrix [ r21 r22 r23 ] is orthogonal */ + /* [ r31 r32 r33 ] */ + + /* compute the determinant to determine if it is proper */ + + zd = r11*r22*r33-r11*r32*r23-r21*r12*r33 + +r21*r32*r13+r31*r12*r23-r31*r22*r13 ; /* should be -1 or 1 */ + + if( zd > 0 ){ /* proper */ + ASSIF(qfac,1.0f) ; + } else { /* improper ==> flip 3rd column */ + ASSIF(qfac,-1.0f) ; + r13 = -r13 ; r23 = -r23 ; r33 = -r33 ; + } + + /* now, compute quaternion parameters */ + + a = r11 + r22 + r33 + 1.0l ; + + if( a > 0.5l ){ /* simplest case */ + a = 0.5l * sqrt(a) ; + b = 0.25l * (r32-r23) / a ; + c = 0.25l * (r13-r31) / a ; + d = 0.25l * (r21-r12) / a ; + } else { /* trickier case */ + xd = 1.0 + r11 - (r22+r33) ; /* 4*b*b */ + yd = 1.0 + r22 - (r11+r33) ; /* 4*c*c */ + zd = 1.0 + r33 - (r11+r22) ; /* 4*d*d */ + if( xd > 1.0 ){ + b = 0.5l * sqrt(xd) ; + c = 0.25l* (r12+r21) / b ; + d = 0.25l* (r13+r31) / b ; + a = 0.25l* (r32-r23) / b ; + } else if( yd > 1.0 ){ + c = 0.5l * sqrt(yd) ; + b = 0.25l* (r12+r21) / c ; + d = 0.25l* (r23+r32) / c ; + a = 0.25l* (r13-r31) / c ; + } else { + d = 0.5l * sqrt(zd) ; + b = 0.25l* (r13+r31) / d ; + c = 0.25l* (r23+r32) / d ; + a = 0.25l* (r21-r12) / d ; + } + if( a < 0.0l ){ b=-b ; c=-c ; d=-d; a=-a; } + } + + ASSIF(qb,(float)b) ; ASSIF(qc,(float)c) ; ASSIF(qd,(float)d) ; + return ; +} + +/*---------------------------------------------------------------------------*/ +/*! Compute the inverse of a bordered 4x4 matrix. + +
+   - Some numerical code fragments were generated by Maple 8.
+   - If a singular matrix is input, the output matrix will be all zero.
+   - You can check for this by examining the [3][3] element, which will
+     be 1.0 for the normal case and 0.0 for the bad case.
+
+     The input matrix should have the form:
+        [ r11 r12 r13 v1 ]
+        [ r21 r22 r23 v2 ]
+        [ r31 r32 r33 v3 ]
+        [  0   0   0   1 ]
+     
+*//*-------------------------------------------------------------------------*/ +mat44 nifti_mat44_inverse( mat44 R ) +{ + double r11,r12,r13,r21,r22,r23,r31,r32,r33,v1,v2,v3 , deti ; + mat44 Q ; + /* INPUT MATRIX IS: */ + r11 = R.m[0][0]; r12 = R.m[0][1]; r13 = R.m[0][2]; /* [ r11 r12 r13 v1 ] */ + r21 = R.m[1][0]; r22 = R.m[1][1]; r23 = R.m[1][2]; /* [ r21 r22 r23 v2 ] */ + r31 = R.m[2][0]; r32 = R.m[2][1]; r33 = R.m[2][2]; /* [ r31 r32 r33 v3 ] */ + v1 = R.m[0][3]; v2 = R.m[1][3]; v3 = R.m[2][3]; /* [ 0 0 0 1 ] */ + + deti = r11*r22*r33-r11*r32*r23-r21*r12*r33 + +r21*r32*r13+r31*r12*r23-r31*r22*r13 ; + + if( deti != 0.0l ) deti = 1.0l / deti ; + + Q.m[0][0] = (float)( deti*( r22*r33-r32*r23) ) ; + Q.m[0][1] = (float)( deti*(-r12*r33+r32*r13) ) ; + Q.m[0][2] = (float)( deti*( r12*r23-r22*r13) ) ; + Q.m[0][3] = (float)( deti*(-r12*r23*v3+r12*v2*r33+r22*r13*v3 + -r22*v1*r33-r32*r13*v2+r32*v1*r23) ) ; + + Q.m[1][0] = (float)( deti*(-r21*r33+r31*r23) ) ; + Q.m[1][1] = (float)( deti*( r11*r33-r31*r13) ) ; + Q.m[1][2] = (float)( deti*(-r11*r23+r21*r13) ) ; + Q.m[1][3] = (float)( deti*( r11*r23*v3-r11*v2*r33-r21*r13*v3 + +r21*v1*r33+r31*r13*v2-r31*v1*r23) ) ; + + Q.m[2][0] = (float)( deti*( r21*r32-r31*r22) ) ; + Q.m[2][1] = (float)( deti*(-r11*r32+r31*r12) ) ; + Q.m[2][2] = (float)( deti*( r11*r22-r21*r12) ) ; + Q.m[2][3] = (float)( deti*(-r11*r22*v3+r11*r32*v2+r21*r12*v3 + -r21*r32*v1-r31*r12*v2+r31*r22*v1) ) ; + + Q.m[3][0] = Q.m[3][1] = Q.m[3][2] = 0.0l ; + Q.m[3][3] = (deti == 0.0l) ? 0.0l : 1.0l ; /* failure flag if deti == 0 */ + + return Q ; +} + +/*---------------------------------------------------------------------------*/ +/*! Input 9 floats and make an orthgonal mat44 out of them. + + Each row is normalized, then nifti_mat33_polar() is used to orthogonalize + them. If row #3 (r31,r32,r33) is input as zero, then it will be taken to + be the cross product of rows #1 and #2. + + This function can be used to create a rotation matrix for transforming + an oblique volume to anatomical coordinates. For this application: + - row #1 (r11,r12,r13) is the direction vector along the image i-axis + - row #2 (r21,r22,r23) is the direction vector along the image j-axis + - row #3 (r31,r32,r33) is the direction vector along the slice direction + (if available; otherwise enter it as 0's) + + The first 2 rows can be taken from the DICOM attribute (0020,0037) + "Image Orientation (Patient)". + + After forming the rotation matrix, the complete affine transformation from + (i,j,k) grid indexes to (x,y,z) spatial coordinates can be computed by + multiplying each column by the appropriate grid spacing: + - column #1 (R.m[0][0],R.m[1][0],R.m[2][0]) by delta-x + - column #2 (R.m[0][1],R.m[1][1],R.m[2][1]) by delta-y + - column #3 (R.m[0][2],R.m[1][2],R.m[2][2]) by delta-z + + and by then placing the center (x,y,z) coordinates of voxel (0,0,0) into + the column #4 (R.m[0][3],R.m[1][3],R.m[2][3]). + + \sa nifti_quatern_to_mat44, nifti_mat44_to_quatern, + nifti_mat44_to_orientation +*//*-------------------------------------------------------------------------*/ +mat44 nifti_make_orthog_mat44( float r11, float r12, float r13 , + float r21, float r22, float r23 , + float r31, float r32, float r33 ) +{ + mat44 R ; + mat33 Q , P ; + double val ; + + R.m[3][0] = R.m[3][1] = R.m[3][2] = 0.0l ; R.m[3][3] = 1.0l ; + + Q.m[0][0] = r11 ; Q.m[0][1] = r12 ; Q.m[0][2] = r13 ; /* load Q */ + Q.m[1][0] = r21 ; Q.m[1][1] = r22 ; Q.m[1][2] = r23 ; + Q.m[2][0] = r31 ; Q.m[2][1] = r32 ; Q.m[2][2] = r33 ; + + /* normalize row 1 */ + + val = Q.m[0][0]*Q.m[0][0] + Q.m[0][1]*Q.m[0][1] + Q.m[0][2]*Q.m[0][2] ; + if( val > 0.0l ){ + val = 1.0l / sqrt(val) ; + Q.m[0][0] *= (float)val ; Q.m[0][1] *= (float)val ; Q.m[0][2] *= (float)val ; + } else { + Q.m[0][0] = 1.0l ; Q.m[0][1] = 0.0l ; Q.m[0][2] = 0.0l ; + } + + /* normalize row 2 */ + + val = Q.m[1][0]*Q.m[1][0] + Q.m[1][1]*Q.m[1][1] + Q.m[1][2]*Q.m[1][2] ; + if( val > 0.0l ){ + val = 1.0l / sqrt(val) ; + Q.m[1][0] *= (float)val ; Q.m[1][1] *= (float)val ; Q.m[1][2] *= (float)val ; + } else { + Q.m[1][0] = 0.0l ; Q.m[1][1] = 1.0l ; Q.m[1][2] = 0.0l ; + } + + /* normalize row 3 */ + + val = Q.m[2][0]*Q.m[2][0] + Q.m[2][1]*Q.m[2][1] + Q.m[2][2]*Q.m[2][2] ; + if( val > 0.0l ){ + val = 1.0l / sqrt(val) ; + Q.m[2][0] *= (float)val ; Q.m[2][1] *= (float)val ; Q.m[2][2] *= (float)val ; + } else { + Q.m[2][0] = Q.m[0][1]*Q.m[1][2] - Q.m[0][2]*Q.m[1][1] ; /* cross */ + Q.m[2][1] = Q.m[0][2]*Q.m[1][0] - Q.m[0][0]*Q.m[1][2] ; /* product */ + Q.m[2][2] = Q.m[0][0]*Q.m[1][1] - Q.m[0][1]*Q.m[1][0] ; + } + + P = nifti_mat33_polar(Q) ; /* P is orthog matrix closest to Q */ + + R.m[0][0] = P.m[0][0] ; R.m[0][1] = P.m[0][1] ; R.m[0][2] = P.m[0][2] ; + R.m[1][0] = P.m[1][0] ; R.m[1][1] = P.m[1][1] ; R.m[1][2] = P.m[1][2] ; + R.m[2][0] = P.m[2][0] ; R.m[2][1] = P.m[2][1] ; R.m[2][2] = P.m[2][2] ; + + R.m[0][3] = R.m[1][3] = R.m[2][3] = 0.0f ; return R ; +} + +/*----------------------------------------------------------------------*/ +/*! compute the inverse of a 3x3 matrix +*//*--------------------------------------------------------------------*/ +mat33 nifti_mat33_inverse( mat33 R ) /* inverse of 3x3 matrix */ +{ + double r11,r12,r13,r21,r22,r23,r31,r32,r33 , deti ; + mat33 Q ; + /* INPUT MATRIX: */ + r11 = R.m[0][0]; r12 = R.m[0][1]; r13 = R.m[0][2]; /* [ r11 r12 r13 ] */ + r21 = R.m[1][0]; r22 = R.m[1][1]; r23 = R.m[1][2]; /* [ r21 r22 r23 ] */ + r31 = R.m[2][0]; r32 = R.m[2][1]; r33 = R.m[2][2]; /* [ r31 r32 r33 ] */ + + deti = r11*r22*r33-r11*r32*r23-r21*r12*r33 + +r21*r32*r13+r31*r12*r23-r31*r22*r13 ; + + if( deti != 0.0l ) deti = 1.0l / deti ; + + Q.m[0][0] = (float)( deti*( r22*r33-r32*r23) ) ; + Q.m[0][1] = (float)( deti*(-r12*r33+r32*r13) ) ; + Q.m[0][2] = (float)( deti*( r12*r23-r22*r13) ) ; + + Q.m[1][0] = (float)( deti*(-r21*r33+r31*r23) ) ; + Q.m[1][1] = (float)( deti*( r11*r33-r31*r13) ) ; + Q.m[1][2] = (float)( deti*(-r11*r23+r21*r13) ) ; + + Q.m[2][0] = (float)( deti*( r21*r32-r31*r22) ) ; + Q.m[2][1] = (float)( deti*(-r11*r32+r31*r12) ) ; + Q.m[2][2] = (float)( deti*( r11*r22-r21*r12) ) ; + + return Q ; +} + +/*----------------------------------------------------------------------*/ +/*! compute the determinant of a 3x3 matrix +*//*--------------------------------------------------------------------*/ +float nifti_mat33_determ( mat33 R ) /* determinant of 3x3 matrix */ +{ + double r11,r12,r13,r21,r22,r23,r31,r32,r33 ; + /* INPUT MATRIX: */ + r11 = R.m[0][0]; r12 = R.m[0][1]; r13 = R.m[0][2]; /* [ r11 r12 r13 ] */ + r21 = R.m[1][0]; r22 = R.m[1][1]; r23 = R.m[1][2]; /* [ r21 r22 r23 ] */ + r31 = R.m[2][0]; r32 = R.m[2][1]; r33 = R.m[2][2]; /* [ r31 r32 r33 ] */ + + return (float)(r11*r22*r33-r11*r32*r23-r21*r12*r33 + +r21*r32*r13+r31*r12*r23-r31*r22*r13) ; +} + +/*----------------------------------------------------------------------*/ +/*! compute the max row norm of a 3x3 matrix +*//*--------------------------------------------------------------------*/ +float nifti_mat33_rownorm( mat33 A ) /* max row norm of 3x3 matrix */ +{ + float r1,r2,r3 ; + + r1 = (float)( fabs(A.m[0][0])+fabs(A.m[0][1])+fabs(A.m[0][2]) ) ; + r2 = (float)( fabs(A.m[1][0])+fabs(A.m[1][1])+fabs(A.m[1][2]) ) ; + r3 = (float)( fabs(A.m[2][0])+fabs(A.m[2][1])+fabs(A.m[2][2]) ) ; + if( r1 < r2 ) r1 = r2 ; + if( r1 < r3 ) r1 = r3 ; + return r1 ; +} + +/*----------------------------------------------------------------------*/ +/*! compute the max column norm of a 3x3 matrix +*//*--------------------------------------------------------------------*/ +float nifti_mat33_colnorm( mat33 A ) /* max column norm of 3x3 matrix */ +{ + float r1,r2,r3 ; + + r1 = (float)( fabs(A.m[0][0])+fabs(A.m[1][0])+fabs(A.m[2][0]) ) ; + r2 = (float)( fabs(A.m[0][1])+fabs(A.m[1][1])+fabs(A.m[2][1]) ) ; + r3 = (float)( fabs(A.m[0][2])+fabs(A.m[1][2])+fabs(A.m[2][2]) ) ; + if( r1 < r2 ) r1 = r2 ; + if( r1 < r3 ) r1 = r3 ; + return r1 ; +} + +/*----------------------------------------------------------------------*/ +/*! multiply 2 3x3 matrices +*//*--------------------------------------------------------------------*/ +mat33 nifti_mat33_mul( mat33 A , mat33 B ) /* multiply 2 3x3 matrices */ +{ + mat33 C ; int i,j ; + for( i=0 ; i < 3 ; i++ ) + for( j=0 ; j < 3 ; j++ ) + C.m[i][j] = A.m[i][0] * B.m[0][j] + + A.m[i][1] * B.m[1][j] + + A.m[i][2] * B.m[2][j] ; + return C ; +} + +/*---------------------------------------------------------------------------*/ +/*! polar decomposition of a 3x3 matrix + + This finds the closest orthogonal matrix to input A + (in both the Frobenius and L2 norms). + + Algorithm is that from NJ Higham, SIAM J Sci Stat Comput, 7:1160-1174. +*//*-------------------------------------------------------------------------*/ +mat33 nifti_mat33_polar( mat33 A ) +{ + mat33 X , Y , Z ; + float alp,bet,gam,gmi , dif=1.0f ; + int k=0 ; + + X = A ; + + /* force matrix to be nonsingular */ + + gam = nifti_mat33_determ(X) ; + while( gam == 0.0 ){ /* perturb matrix */ + gam = (float)( 0.00001 * ( 0.001 + nifti_mat33_rownorm(X) ) ) ; + X.m[0][0] += gam ; X.m[1][1] += gam ; X.m[2][2] += gam ; + gam = nifti_mat33_determ(X) ; + } + + while(1){ + Y = nifti_mat33_inverse(X) ; + if( dif > 0.3 ){ /* far from convergence */ + alp = (float)( sqrt( nifti_mat33_rownorm(X) * nifti_mat33_colnorm(X) ) ) ; + bet = (float)( sqrt( nifti_mat33_rownorm(Y) * nifti_mat33_colnorm(Y) ) ) ; + gam = (float)( sqrt( bet / alp ) ) ; + gmi = (float)( 1.0 / gam ) ; + } else { + gam = gmi = 1.0f ; /* close to convergence */ + } + Z.m[0][0] = (float)( 0.5 * ( gam*X.m[0][0] + gmi*Y.m[0][0] ) ) ; + Z.m[0][1] = (float)( 0.5 * ( gam*X.m[0][1] + gmi*Y.m[1][0] ) ) ; + Z.m[0][2] = (float)( 0.5 * ( gam*X.m[0][2] + gmi*Y.m[2][0] ) ) ; + Z.m[1][0] = (float)( 0.5 * ( gam*X.m[1][0] + gmi*Y.m[0][1] ) ) ; + Z.m[1][1] = (float)( 0.5 * ( gam*X.m[1][1] + gmi*Y.m[1][1] ) ) ; + Z.m[1][2] = (float)( 0.5 * ( gam*X.m[1][2] + gmi*Y.m[2][1] ) ) ; + Z.m[2][0] = (float)( 0.5 * ( gam*X.m[2][0] + gmi*Y.m[0][2] ) ) ; + Z.m[2][1] = (float)( 0.5 * ( gam*X.m[2][1] + gmi*Y.m[1][2] ) ) ; + Z.m[2][2] = (float)( 0.5 * ( gam*X.m[2][2] + gmi*Y.m[2][2] ) ) ; + + dif = (float)( fabs(Z.m[0][0]-X.m[0][0])+fabs(Z.m[0][1]-X.m[0][1]) + +fabs(Z.m[0][2]-X.m[0][2])+fabs(Z.m[1][0]-X.m[1][0]) + +fabs(Z.m[1][1]-X.m[1][1])+fabs(Z.m[1][2]-X.m[1][2]) + +fabs(Z.m[2][0]-X.m[2][0])+fabs(Z.m[2][1]-X.m[2][1]) + +fabs(Z.m[2][2]-X.m[2][2]) ); + + k = k+1 ; + if( k > 100 || dif < 3.e-6 ) break ; /* convergence or exhaustion */ + X = Z ; + } + + return Z ; +} + +/*---------------------------------------------------------------------------*/ +/*! compute the (closest) orientation from a 4x4 ijk->xyz tranformation matrix + +
+   Input:  4x4 matrix that transforms (i,j,k) indexes to (x,y,z) coordinates,
+           where +x=Right, +y=Anterior, +z=Superior.
+           (Only the upper-left 3x3 corner of R is used herein.)
+   Output: 3 orientation codes that correspond to the closest "standard"
+           anatomical orientation of the (i,j,k) axes.
+   Method: Find which permutation of (x,y,z) has the smallest angle to the
+           (i,j,k) axes directions, which are the columns of the R matrix.
+   Errors: The codes returned will be zero.
+
+   For example, an axial volume might get return values of
+     *icod = NIFTI_R2L   (i axis is mostly Right to Left)
+     *jcod = NIFTI_P2A   (j axis is mostly Posterior to Anterior)
+     *kcod = NIFTI_I2S   (k axis is mostly Inferior to Superior)
+   
+ + \see "QUATERNION REPRESENTATION OF ROTATION MATRIX" in nifti1.h + + \see nifti_quatern_to_mat44, nifti_mat44_to_quatern, + nifti_make_orthog_mat44 +*//*-------------------------------------------------------------------------*/ +void nifti_mat44_to_orientation( mat44 R , int *icod, int *jcod, int *kcod ) +{ + float xi,xj,xk , yi,yj,yk , zi,zj,zk , val,detQ,detP ; + mat33 P , Q , M ; + int i,j,k=0,p,q,r , ibest,jbest,kbest,pbest,qbest,rbest ; + float vbest ; + + if( icod == NULL || jcod == NULL || kcod == NULL ) return ; /* bad */ + + *icod = *jcod = *kcod = 0 ; /* error returns, if sh*t happens */ + + /* load column vectors for each (i,j,k) direction from matrix */ + + /*-- i axis --*/ /*-- j axis --*/ /*-- k axis --*/ + + xi = R.m[0][0] ; xj = R.m[0][1] ; xk = R.m[0][2] ; + yi = R.m[1][0] ; yj = R.m[1][1] ; yk = R.m[1][2] ; + zi = R.m[2][0] ; zj = R.m[2][1] ; zk = R.m[2][2] ; + + /* normalize column vectors to get unit vectors along each ijk-axis */ + + /* normalize i axis */ + + val = (float)sqrt( xi*xi + yi*yi + zi*zi ) ; + if( val == 0.0 ) return ; /* stupid input */ + xi /= val ; yi /= val ; zi /= val ; + + /* normalize j axis */ + + val = (float)sqrt( xj*xj + yj*yj + zj*zj ) ; + if( val == 0.0 ) return ; /* stupid input */ + xj /= val ; yj /= val ; zj /= val ; + + /* orthogonalize j axis to i axis, if needed */ + + val = xi*xj + yi*yj + zi*zj ; /* dot product between i and j */ + if( fabs(val) > 1.e-4 ){ + xj -= val*xi ; yj -= val*yi ; zj -= val*zi ; + val = (float)sqrt( xj*xj + yj*yj + zj*zj ) ; /* must renormalize */ + if( val == 0.0 ) return ; /* j was parallel to i? */ + xj /= val ; yj /= val ; zj /= val ; + } + + /* normalize k axis; if it is zero, make it the cross product i x j */ + + val = (float)sqrt( xk*xk + yk*yk + zk*zk ) ; + if( val == 0.0 ){ xk = yi*zj-zi*yj; yk = zi*xj-zj*xi ; zk=xi*yj-yi*xj ; } + else { xk /= val ; yk /= val ; zk /= val ; } + + /* orthogonalize k to i */ + + val = xi*xk + yi*yk + zi*zk ; /* dot product between i and k */ + if( fabs(val) > 1.e-4 ){ + xk -= val*xi ; yk -= val*yi ; zk -= val*zi ; + val = (float)sqrt( xk*xk + yk*yk + zk*zk ) ; + if( val == 0.0 ) return ; /* bad */ + xk /= val ; yk /= val ; zk /= val ; + } + + /* orthogonalize k to j */ + + val = xj*xk + yj*yk + zj*zk ; /* dot product between j and k */ + if( fabs(val) > 1.e-4 ){ + xk -= val*xj ; yk -= val*yj ; zk -= val*zj ; + val = (float)sqrt( xk*xk + yk*yk + zk*zk ) ; + if( val == 0.0 ) return ; /* bad */ + xk /= val ; yk /= val ; zk /= val ; + } + + Q.m[0][0] = xi ; Q.m[0][1] = xj ; Q.m[0][2] = xk ; + Q.m[1][0] = yi ; Q.m[1][1] = yj ; Q.m[1][2] = yk ; + Q.m[2][0] = zi ; Q.m[2][1] = zj ; Q.m[2][2] = zk ; + + /* at this point, Q is the rotation matrix from the (i,j,k) to (x,y,z) axes */ + + detQ = nifti_mat33_determ( Q ) ; + if( detQ == 0.0 ) return ; /* shouldn't happen unless user is a DUFIS */ + + /* Build and test all possible +1/-1 coordinate permutation matrices P; + then find the P such that the rotation matrix M=PQ is closest to the + identity, in the sense of M having the smallest total rotation angle. */ + + /* Despite the formidable looking 6 nested loops, there are + only 3*3*3*2*2*2 = 216 passes, which will run very quickly. */ + + vbest = -666.0f ; ibest=pbest=qbest=rbest=1 ; jbest=2 ; kbest=3 ; + for( i=1 ; i <= 3 ; i++ ){ /* i = column number to use for row #1 */ + for( j=1 ; j <= 3 ; j++ ){ /* j = column number to use for row #2 */ + if( i == j ) continue ; + for( k=1 ; k <= 3 ; k++ ){ /* k = column number to use for row #3 */ + if( i == k || j == k ) continue ; + P.m[0][0] = P.m[0][1] = P.m[0][2] = + P.m[1][0] = P.m[1][1] = P.m[1][2] = + P.m[2][0] = P.m[2][1] = P.m[2][2] = 0.0f ; + for( p=-1 ; p <= 1 ; p+=2 ){ /* p,q,r are -1 or +1 */ + for( q=-1 ; q <= 1 ; q+=2 ){ /* and go into rows #1,2,3 */ + for( r=-1 ; r <= 1 ; r+=2 ){ + P.m[0][i-1] = p ; P.m[1][j-1] = q ; P.m[2][k-1] = r ; + detP = nifti_mat33_determ(P) ; /* sign of permutation */ + if( detP * detQ <= 0.0 ) continue ; /* doesn't match sign of Q */ + M = nifti_mat33_mul(P,Q) ; + + /* angle of M rotation = 2.0*acos(0.5*sqrt(1.0+trace(M))) */ + /* we want largest trace(M) == smallest angle == M nearest to I */ + + val = M.m[0][0] + M.m[1][1] + M.m[2][2] ; /* trace */ + if( val > vbest ){ + vbest = val ; + ibest = i ; jbest = j ; kbest = k ; + pbest = p ; qbest = q ; rbest = r ; + } + }}}}}} + + /* At this point ibest is 1 or 2 or 3; pbest is -1 or +1; etc. + + The matrix P that corresponds is the best permutation approximation + to Q-inverse; that is, P (approximately) takes (x,y,z) coordinates + to the (i,j,k) axes. + + For example, the first row of P (which contains pbest in column ibest) + determines the way the i axis points relative to the anatomical + (x,y,z) axes. If ibest is 2, then the i axis is along the y axis, + which is direction P2A (if pbest > 0) or A2P (if pbest < 0). + + So, using ibest and pbest, we can assign the output code for + the i axis. Mutatis mutandis for the j and k axes, of course. */ + + switch( ibest*pbest ){ + case 1: i = NIFTI_L2R ; break ; + case -1: i = NIFTI_R2L ; break ; + case 2: i = NIFTI_P2A ; break ; + case -2: i = NIFTI_A2P ; break ; + case 3: i = NIFTI_I2S ; break ; + case -3: i = NIFTI_S2I ; break ; + } + + switch( jbest*qbest ){ + case 1: j = NIFTI_L2R ; break ; + case -1: j = NIFTI_R2L ; break ; + case 2: j = NIFTI_P2A ; break ; + case -2: j = NIFTI_A2P ; break ; + case 3: j = NIFTI_I2S ; break ; + case -3: j = NIFTI_S2I ; break ; + } + + switch( kbest*rbest ){ + case 1: k = NIFTI_L2R ; break ; + case -1: k = NIFTI_R2L ; break ; + case 2: k = NIFTI_P2A ; break ; + case -2: k = NIFTI_A2P ; break ; + case 3: k = NIFTI_I2S ; break ; + case -3: k = NIFTI_S2I ; break ; + } + + *icod = i ; *jcod = j ; *kcod = k ; return ; +} + +/*---------------------------------------------------------------------------*/ +/* Routines to swap byte arrays in various ways: + - 2 at a time: ab -> ba [short] + - 4 at a time: abcd -> dcba [int, float] + - 8 at a time: abcdDCBA -> ABCDdcba [long long, double] + - 16 at a time: abcdefghHGFEDCBA -> ABCDEFGHhgfedcba [long double] +-----------------------------------------------------------------------------*/ + +/*----------------------------------------------------------------------*/ +/*! swap each byte pair from the given list of n pairs + * + * Due to alignment of structures at some architectures (e.g. on ARM), + * stick to char varaibles. + * Fixes http://bugs.debian.org/446893 Yaroslav + * +*//*--------------------------------------------------------------------*/ +void nifti_swap_2bytes( size_t n , void *ar ) /* 2 bytes at a time */ +{ + register size_t ii ; + unsigned char * cp1 = (unsigned char *)ar, * cp2 ; + unsigned char tval; + + for( ii=0 ; ii < n ; ii++ ){ + cp2 = cp1 + 1; + tval = *cp1; *cp1 = *cp2; *cp2 = tval; + cp1 += 2; + } + return ; +} + +/*----------------------------------------------------------------------*/ +/*! swap 4 bytes at a time from the given list of n sets of 4 bytes +*//*--------------------------------------------------------------------*/ +void nifti_swap_4bytes( size_t n , void *ar ) /* 4 bytes at a time */ +{ + register size_t ii ; + unsigned char * cp0 = (unsigned char *)ar, * cp1, * cp2 ; + register unsigned char tval ; + + for( ii=0 ; ii < n ; ii++ ){ + cp1 = cp0; cp2 = cp0+3; + tval = *cp1; *cp1 = *cp2; *cp2 = tval; + cp1++; cp2--; + tval = *cp1; *cp1 = *cp2; *cp2 = tval; + cp0 += 4; + } + return ; +} + +/*----------------------------------------------------------------------*/ +/*! swap 8 bytes at a time from the given list of n sets of 8 bytes + * + * perhaps use this style for the general Nbytes, as Yaroslav suggests +*//*--------------------------------------------------------------------*/ +void nifti_swap_8bytes( size_t n , void *ar ) /* 8 bytes at a time */ +{ + register size_t ii ; + unsigned char * cp0 = (unsigned char *)ar, * cp1, * cp2 ; + register unsigned char tval ; + + for( ii=0 ; ii < n ; ii++ ){ + cp1 = cp0; cp2 = cp0+7; + while ( cp2 > cp1 ) /* unroll? */ + { + tval = *cp1 ; *cp1 = *cp2 ; *cp2 = tval ; + cp1++; cp2--; + } + cp0 += 8; + } + return ; +} + +/*----------------------------------------------------------------------*/ +/*! swap 16 bytes at a time from the given list of n sets of 16 bytes +*//*--------------------------------------------------------------------*/ +void nifti_swap_16bytes( size_t n , void *ar ) /* 16 bytes at a time */ +{ + register size_t ii ; + unsigned char * cp0 = (unsigned char *)ar, * cp1, * cp2 ; + register unsigned char tval ; + + for( ii=0 ; ii < n ; ii++ ){ + cp1 = cp0; cp2 = cp0+15; + while ( cp2 > cp1 ) + { + tval = *cp1 ; *cp1 = *cp2 ; *cp2 = tval ; + cp1++; cp2--; + } + cp0 += 16; + } + return ; +} + +#if 0 /* not important: save for version update 6 Jul 2010 [rickr] */ + +/*----------------------------------------------------------------------*/ +/*! generic: swap siz bytes at a time from the given list of n sets +*//*--------------------------------------------------------------------*/ +void nifti_swap_bytes( size_t n , int siz , void *ar ) +{ + register size_t ii ; + unsigned char * cp0 = (unsigned char *)ar, * cp1, * cp2 ; + register unsigned char tval ; + + for( ii=0 ; ii < n ; ii++ ){ + cp1 = cp0; cp2 = cp0+(siz-1); + while ( cp2 > cp1 ) + { + tval = *cp1 ; *cp1 = *cp2 ; *cp2 = tval ; + cp1++; cp2--; + } + cp0 += siz; + } + return ; +} +#endif + +/*---------------------------------------------------------------------------*/ + +/*----------------------------------------------------------------------*/ +/*! based on siz, call the appropriate nifti_swap_Nbytes() function +*//*--------------------------------------------------------------------*/ +void nifti_swap_Nbytes( size_t n , int siz , void *ar ) /* subsuming case */ +{ + switch( siz ){ + case 2: nifti_swap_2bytes ( n , ar ) ; break ; + case 4: nifti_swap_4bytes ( n , ar ) ; break ; + case 8: nifti_swap_8bytes ( n , ar ) ; break ; + case 16: nifti_swap_16bytes( n , ar ) ; break ; + default: /* nifti_swap_bytes ( n , siz, ar ) ; */ + Rc_fprintf_stderr("** NIfTI: cannot swap in %d byte blocks\n", siz); + break ; + } + return ; +} + + +/*-------------------------------------------------------------------------*/ +/*! Byte swap NIFTI-1 file header in various places and ways. + + If is_nifti, swap all (even UNUSED) fields of NIfTI header. + Else, swap as a nifti_analyze75 struct. +*//*---------------------------------------------------------------------- */ +void swap_nifti_header( struct nifti_1_header *h , int is_nifti ) +{ + + /* if ANALYZE, swap as such and return */ + if( ! is_nifti ) { + nifti_swap_as_analyze((nifti_analyze75 *)h); + return; + } + + /* otherwise, swap all NIFTI fields */ + + nifti_swap_4bytes(1, &h->sizeof_hdr); + nifti_swap_4bytes(1, &h->extents); + nifti_swap_2bytes(1, &h->session_error); + + nifti_swap_2bytes(8, h->dim); + nifti_swap_4bytes(1, &h->intent_p1); + nifti_swap_4bytes(1, &h->intent_p2); + nifti_swap_4bytes(1, &h->intent_p3); + + nifti_swap_2bytes(1, &h->intent_code); + nifti_swap_2bytes(1, &h->datatype); + nifti_swap_2bytes(1, &h->bitpix); + nifti_swap_2bytes(1, &h->slice_start); + + nifti_swap_4bytes(8, h->pixdim); + + nifti_swap_4bytes(1, &h->vox_offset); + nifti_swap_4bytes(1, &h->scl_slope); + nifti_swap_4bytes(1, &h->scl_inter); + nifti_swap_2bytes(1, &h->slice_end); + + nifti_swap_4bytes(1, &h->cal_max); + nifti_swap_4bytes(1, &h->cal_min); + nifti_swap_4bytes(1, &h->slice_duration); + nifti_swap_4bytes(1, &h->toffset); + nifti_swap_4bytes(1, &h->glmax); + nifti_swap_4bytes(1, &h->glmin); + + nifti_swap_2bytes(1, &h->qform_code); + nifti_swap_2bytes(1, &h->sform_code); + + nifti_swap_4bytes(1, &h->quatern_b); + nifti_swap_4bytes(1, &h->quatern_c); + nifti_swap_4bytes(1, &h->quatern_d); + nifti_swap_4bytes(1, &h->qoffset_x); + nifti_swap_4bytes(1, &h->qoffset_y); + nifti_swap_4bytes(1, &h->qoffset_z); + + nifti_swap_4bytes(4, h->srow_x); + nifti_swap_4bytes(4, h->srow_y); + nifti_swap_4bytes(4, h->srow_z); + + return ; +} + +/*-------------------------------------------------------------------------*/ +/*! Byte swap as an ANALYZE 7.5 header + * + * return non-zero on failure +*//*---------------------------------------------------------------------- */ +int nifti_swap_as_analyze( nifti_analyze75 * h ) +{ + if( !h ) return 1; + + nifti_swap_4bytes(1, &h->sizeof_hdr); + nifti_swap_4bytes(1, &h->extents); + nifti_swap_2bytes(1, &h->session_error); + + nifti_swap_2bytes(8, h->dim); + nifti_swap_2bytes(1, &h->unused8); + nifti_swap_2bytes(1, &h->unused9); + nifti_swap_2bytes(1, &h->unused10); + nifti_swap_2bytes(1, &h->unused11); + nifti_swap_2bytes(1, &h->unused12); + nifti_swap_2bytes(1, &h->unused13); + nifti_swap_2bytes(1, &h->unused14); + + nifti_swap_2bytes(1, &h->datatype); + nifti_swap_2bytes(1, &h->bitpix); + nifti_swap_2bytes(1, &h->dim_un0); + + nifti_swap_4bytes(8, h->pixdim); + + nifti_swap_4bytes(1, &h->vox_offset); + nifti_swap_4bytes(1, &h->funused1); + nifti_swap_4bytes(1, &h->funused2); + nifti_swap_4bytes(1, &h->funused3); + + nifti_swap_4bytes(1, &h->cal_max); + nifti_swap_4bytes(1, &h->cal_min); + nifti_swap_4bytes(1, &h->compressed); + nifti_swap_4bytes(1, &h->verified); + + nifti_swap_4bytes(1, &h->glmax); + nifti_swap_4bytes(1, &h->glmin); + + nifti_swap_4bytes(1, &h->views); + nifti_swap_4bytes(1, &h->vols_added); + nifti_swap_4bytes(1, &h->start_field); + nifti_swap_4bytes(1, &h->field_skip); + + nifti_swap_4bytes(1, &h->omax); + nifti_swap_4bytes(1, &h->omin); + nifti_swap_4bytes(1, &h->smax); + nifti_swap_4bytes(1, &h->smin); + + return 0; +} + +/*-------------------------------------------------------------------------*/ +/*! OLD VERSION of swap_nifti_header (left for undo/compare operations) + + Byte swap NIFTI-1 file header in various places and ways. + + If is_nifti is nonzero, will also swap the NIFTI-specific + components of the header; otherwise, only the components + common to NIFTI and ANALYZE will be swapped. +*//*---------------------------------------------------------------------- */ +void old_swap_nifti_header( struct nifti_1_header *h , int is_nifti ) +{ + /* this stuff is always present, for ANALYZE and NIFTI */ + + swap_4(h->sizeof_hdr) ; + nifti_swap_2bytes( 8 , h->dim ) ; + nifti_swap_4bytes( 8 , h->pixdim ) ; + + swap_2(h->datatype) ; + swap_2(h->bitpix) ; + + swap_4(h->vox_offset); swap_4(h->cal_max); swap_4(h->cal_min); + + /* this stuff is NIFTI specific */ + + if( is_nifti ){ + swap_4(h->intent_p1); swap_4(h->intent_p2); swap_4(h->intent_p3); + swap_2(h->intent_code); + + swap_2(h->slice_start); swap_2(h->slice_end); + swap_4(h->scl_slope); swap_4(h->scl_inter); + swap_4(h->slice_duration); swap_4(h->toffset); + + swap_2(h->qform_code); swap_2(h->sform_code); + swap_4(h->quatern_b); swap_4(h->quatern_c); swap_4(h->quatern_d); + swap_4(h->qoffset_x); swap_4(h->qoffset_y); swap_4(h->qoffset_z); + nifti_swap_4bytes(4,h->srow_x); + nifti_swap_4bytes(4,h->srow_y); + nifti_swap_4bytes(4,h->srow_z); + } + return ; +} + + +#define USE_STAT +#ifdef USE_STAT +/*---------------------------------------------------------------------------*/ +/* Return the file length (0 if file not found or has no contents). + This is a Unix-specific function, since it uses stat(). +-----------------------------------------------------------------------------*/ +#include +#include + +/*---------------------------------------------------------------------------*/ +/*! return the size of a file, in bytes + + \return size of file on success, -1 on error or no file + + changed to return int, -1 means no file or error 20 Dec 2004 [rickr] +*//*-------------------------------------------------------------------------*/ +int nifti_get_filesize( const char *pathname ) +{ + struct stat buf ; int ii ; + + if( pathname == NULL || *pathname == '\0' ) return -1 ; + ii = stat( pathname , &buf ); if( ii != 0 ) return -1 ; + return (unsigned int)buf.st_size ; +} + +#else /*---------- non-Unix version of the above, less efficient -----------*/ + +int nifti_get_filesize( const char *pathname ) +{ + znzFile fp ; int len ; + + if( pathname == NULL || *pathname == '\0' ) return -1 ; + fp = znzopen(pathname,"rb",0); if( znz_isnull(fp) ) return -1 ; + znzseek(fp,0L,SEEK_END) ; len = znztell(fp) ; + znzclose(fp) ; return len ; +} + +#endif /* USE_STAT */ + + +/*----------------------------------------------------------------------*/ +/*! return the total volume size, in bytes + + This is computed as nvox * nbyper. +*//*--------------------------------------------------------------------*/ +size_t nifti_get_volsize(const nifti_image *nim) +{ + return (size_t)(nim->nbyper) * (size_t)(nim->nvox) ; /* total bytes */ +} + + +/*--------------------------------------------------------------------------*/ +/* Support functions for filenames in read and write + - allows for gzipped files +*/ + + +/*----------------------------------------------------------------------*/ +/*! simple check for file existence + + \return 1 on existence, 0 otherwise +*//*--------------------------------------------------------------------*/ +int nifti_fileexists(const char* fname) +{ + znzFile fp; + fp = znzopen( fname , "rb" , 1 ) ; + if( !znz_isnull(fp) ) { znzclose(fp); return 1; } + return 0; /* fp is NULL */ +} + +/*----------------------------------------------------------------------*/ +/*! return whether the filename is valid + + Note: uppercase extensions are now valid. 27 Apr 2009 [rickr] + + The name is considered valid if the file basename has length greater than + zero, AND one of the valid nifti extensions is provided. + fname input | return | + =============================== + "myimage" | 0 | + "myimage.tif" | 0 | + "myimage.tif.gz" | 0 | + "myimage.nii" | 1 | + ".nii" | 0 | + ".myhiddenimage" | 0 | + ".myhiddenimage.nii" | 1 | +*//*--------------------------------------------------------------------*/ +int nifti_is_complete_filename(const char* fname) +{ + const char * ext; + + /* check input file(s) for sanity */ + if( fname == NULL || *fname == '\0' ){ + if ( g_opts.debug > 1 ) + Rc_fprintf_stderr("-- empty filename in nifti_validfilename()\n"); + return 0; + } + + ext = nifti_find_file_extension(fname); + if ( ext == NULL ) { /*Invalid extension given */ + if ( g_opts.debug > 0 ) + Rc_fprintf_stderr("-- no nifti valid extension for filename '%s'\n", fname); + return 0; + } + + if ( ext && ext == fname ) { /* then no filename prefix */ + if ( g_opts.debug > 0 ) + Rc_fprintf_stderr("-- no prefix for filename '%s'\n", fname); + return 0; + } + return 1; +} + +/*----------------------------------------------------------------------*/ +/*! return whether the filename is valid + + Allow uppercase extensions as valid. 27 Apr 2009 [rickr] + Any .gz extension case must match the base extension case. + + The name is considered valid if its length is positive, excluding + any nifti filename extension. + fname input | return | result of nifti_makebasename + ==================================================================== + "myimage" | 1 | "myimage" + "myimage.tif" | 1 | "myimage.tif" + "myimage.tif.gz" | 1 | "myimage.tif" + "myimage.nii" | 1 | "myimage" + ".nii" | 0 | + ".myhiddenimage" | 1 | ".myhiddenimage" + ".myhiddenimage.nii | 1 | ".myhiddenimage" +*//*--------------------------------------------------------------------*/ +int nifti_validfilename(const char* fname) +{ + const char * ext; + + /* check input file(s) for sanity */ + if( fname == NULL || *fname == '\0' ){ + if ( g_opts.debug > 1 ) + Rc_fprintf_stderr("-- empty filename in nifti_validfilename()\n"); + return 0; + } + + ext = nifti_find_file_extension(fname); + + if ( ext && ext == fname ) { /* then no filename prefix */ + if ( g_opts.debug > 0 ) + Rc_fprintf_stderr("-- no prefix for filename '%s'\n", fname); + return 0; + } + + return 1; +} + +/*----------------------------------------------------------------------*/ +/*! check the end of the filename for a valid nifti extension + + Valid extensions are currently .nii, .hdr, .img, .nia, + or any of them followed by .gz. Note that '.' is part of + the extension. + + Uppercase extensions are also valid, but not mixed case. + + \return a pointer to the extension substring within the original + function input parameter name, or NULL if not found. + \caution Note that if the input parameter is is immutabale + (i.e. a const char *) then this function performs an + implicit casting away of the mutability constraint and + the return parameter will appear as a mutable + even though it is part of the immuttable string. +*//*--------------------------------------------------------------------*/ +char * nifti_find_file_extension( const char * name ) +{ + const char * ext; + char extcopy[8]; + int len; + char extnii[8] = ".nii"; /* modifiable, for possible uppercase */ + char exthdr[8] = ".hdr"; /* (leave space for .gz) */ + char extimg[8] = ".img"; + char extnia[8] = ".nia"; + char extgz[4] = ".gz"; + char * elist[4] = { NULL, NULL, NULL, NULL}; + + /* stupid compiler... */ + elist[0] = extnii; elist[1] = exthdr; elist[2] = extimg; elist[3] = extnia; + + if ( ! name ) return NULL; + + len = (int)strlen(name); + if ( len < 4 ) return NULL; + + ext = name + len - 4; + + /* make manipulation copy, and possibly convert to lowercase */ + strcpy(extcopy, ext); + if( g_opts.allow_upper_fext ) make_lowercase(extcopy); + + /* if it look like a basic extension, fail or return it */ + if( compare_strlist(extcopy, elist, 4) >= 0 ) { + if( is_mixedcase(ext) ) { + Rc_fprintf_stderr("** mixed case extension '%s' is not valid\n", ext); + return NULL; + } + else return (char *)ext; /* Cast away the constness of the input parameter */ + } + +#ifdef HAVE_ZLIB + if ( len < 7 ) return NULL; + + ext = name + len - 7; + + /* make manipulation copy, and possibly convert to lowercase */ + strcpy(extcopy, ext); + if( g_opts.allow_upper_fext ) make_lowercase(extcopy); + + /* go after .gz extensions using the modifiable strings */ + strcat(elist[0], extgz); strcat(elist[1], extgz); strcat(elist[2], extgz); + + if( compare_strlist(extcopy, elist, 3) >= 0 ) { + if( is_mixedcase(ext) ) { + Rc_fprintf_stderr("** mixed case extension '%s' is not valid\n", ext); + return NULL; + } + else return (char *)ext; /* Cast away the constness of the input parameter */ + } + +#endif + + if( g_opts.debug > 1 ) + Rc_fprintf_stderr("** find_file_ext: failed for name '%s'\n", name); + + return NULL; +} + +/*----------------------------------------------------------------------*/ +/*! return whether the filename ends in ".gz" +*//*--------------------------------------------------------------------*/ +int nifti_is_gzfile(const char* fname) +{ + /* return true if the filename ends with .gz */ + if (fname == NULL) { return 0; } +#ifdef HAVE_ZLIB + { /* just so len doesn't generate compile warning */ + int len; + len = (int)strlen(fname); + if (len < 3) return 0; /* so we don't search before the name */ + if (fileext_compare(fname + strlen(fname) - 3,".gz")==0) { return 1; } + } +#endif + return 0; +} + +/*----------------------------------------------------------------------*/ +/*! return whether the given library was compiled with HAVE_ZLIB set +*//*--------------------------------------------------------------------*/ +int nifti_compiled_with_zlib(void) +{ +#ifdef HAVE_ZLIB + return 1; +#else + return 0; +#endif +} + +/*----------------------------------------------------------------------*/ +/*! duplicate the filename, while clearing any extension + + This allocates memory for basename which should eventually be freed. +*//*--------------------------------------------------------------------*/ +char * nifti_makebasename(const char* fname) +{ + char *basename; + const char *ext; + + basename=nifti_strdup(fname); + + ext = nifti_find_file_extension(basename); + if ( ext ) + { + basename[strlen(basename)-strlen(ext)] = '\0'; /* clear out extension */ + } + + return basename; /* in either case */ +} + +/*----------------------------------------------------------------------*/ +/*! set nifti's global debug level, for status reporting + + - 0 : quiet, nothing is printed to the terminal, but errors + - 1 : normal execution (the default) + - 2, 3 : more details +*//*--------------------------------------------------------------------*/ +void nifti_set_debug_level( int level ) +{ + g_opts.debug = level; +} + +/*----------------------------------------------------------------------*/ +/*! set nifti's global skip_blank_ext flag 5 Sep 2006 [rickr] + + explicitly set to 0 or 1 +*//*--------------------------------------------------------------------*/ +void nifti_set_skip_blank_ext( int skip ) +{ + g_opts.skip_blank_ext = skip ? 1 : 0; +} + +/*----------------------------------------------------------------------*/ +/*! set nifti's global allow_upper_fext flag 28 Apr 2009 [rickr] + + explicitly set to 0 or 1 +*//*--------------------------------------------------------------------*/ +void nifti_set_allow_upper_fext( int allow ) +{ + g_opts.allow_upper_fext = allow ? 1 : 0; +} + +/*----------------------------------------------------------------------*/ +/*! check current directory for existing header file + + \return filename of header on success and NULL if no appropriate file + could be found + + If fname has an uppercase extension, check for uppercase files. + + NB: it allocates memory for hdrname which should be freed + when no longer required +*//*-------------------------------------------------------------------*/ +char * nifti_findhdrname(const char* fname) +{ + char *basename, *hdrname; + const char *ext; + char elist[2][5] = { ".hdr", ".nii" }; + char extzip[4] = ".gz"; + int efirst = 1; /* init to .nii extension */ + int eisupper = 0; /* init to lowercase extensions */ + + /**- check input file(s) for sanity */ + if( !nifti_validfilename(fname) ) return NULL; + + basename = nifti_makebasename(fname); + if( !basename ) return NULL; /* only on string alloc failure */ + + /**- return filename if it has a valid extension and exists + (except if it is an .img file (and maybe .gz)) */ + ext = nifti_find_file_extension(fname); + + if( ext ) eisupper = is_uppercase(ext); /* do we look for uppercase? */ + + /* if the file exists and is a valid header name (not .img), return it */ + if ( ext && nifti_fileexists(fname) ) { + /* allow for uppercase extension */ + if ( fileext_n_compare(ext,".img",4) != 0 ){ + hdrname = nifti_strdup(fname); + free(basename); + return hdrname; + } else + efirst = 0; /* note for below */ + } + + /* So the requested name is a basename, contains .img, or does not exist. */ + /* In any case, use basename. */ + + /**- if .img, look for .hdr, .hdr.gz, .nii, .nii.gz, in that order */ + /**- else, look for .nii, .nii.gz, .hdr, .hdr.gz, in that order */ + + /* if we get more extension choices, this could be a loop */ + + /* note: efirst is 0 in the case of ".img" */ + + /* if the user passed an uppercase entension (.IMG), search for uppercase */ + if( eisupper ) { + make_uppercase(elist[0]); + make_uppercase(elist[1]); + make_uppercase(extzip); + } + + hdrname = (char *)calloc(sizeof(char),strlen(basename)+8); + if( !hdrname ){ + Rc_fprintf_stderr("** nifti_findhdrname: failed to alloc hdrname\n"); + free(basename); + return NULL; + } + + strcpy(hdrname,basename); + strcat(hdrname,elist[efirst]); + if (nifti_fileexists(hdrname)) { free(basename); return hdrname; } +#ifdef HAVE_ZLIB + strcat(hdrname,extzip); + if (nifti_fileexists(hdrname)) { free(basename); return hdrname; } +#endif + + /* okay, try the other possibility */ + + efirst = 1 - efirst; + + strcpy(hdrname,basename); + strcat(hdrname,elist[efirst]); + if (nifti_fileexists(hdrname)) { free(basename); return hdrname; } +#ifdef HAVE_ZLIB + strcat(hdrname,extzip); + if (nifti_fileexists(hdrname)) { free(basename); return hdrname; } +#endif + + /**- if nothing has been found, return NULL */ + free(basename); + free(hdrname); + return NULL; +} + + +/*------------------------------------------------------------------------*/ +/*! check current directory for existing image file + + \param fname filename to check for + \nifti_type nifti_type for dataset - this determines whether to + first check for ".nii" or ".img" (since both may exist) + + \return filename of data/img file on success and NULL if no appropriate + file could be found + + If fname has a valid, uppercase extension, apply all extensions as + uppercase. + + NB: it allocates memory for the image filename, which should be freed + when no longer required +*//*---------------------------------------------------------------------*/ +char * nifti_findimgname(const char* fname , int nifti_type) +{ + /* store all extensions as strings, in case we need to go uppercase */ + char *basename, *imgname, elist[2][5] = { ".nii", ".img" }; + char extzip[4] = ".gz"; + char extnia[5] = ".nia"; + const char *ext; + int first; /* first extension to use */ + + /* check input file(s) for sanity */ + if( !nifti_validfilename(fname) ) return NULL; + + basename = nifti_makebasename(fname); + imgname = (char *)calloc(sizeof(char),strlen(basename)+8); + if( !imgname ){ + Rc_fprintf_stderr("** nifti_findimgname: failed to alloc imgname\n"); + free(basename); + return NULL; + } + + /* if we are looking for uppercase, apply the fact now */ + ext = nifti_find_file_extension(fname); + if( ext && is_uppercase(ext) ) { + make_uppercase(elist[0]); + make_uppercase(elist[1]); + make_uppercase(extzip); + make_uppercase(extnia); + } + + /* only valid extension for ASCII type is .nia, handle first */ + if( nifti_type == NIFTI_FTYPE_ASCII ){ + strcpy(imgname,basename); + strcat(imgname,extnia); + if (nifti_fileexists(imgname)) { free(basename); return imgname; } + + } else { + + /**- test for .nii and .img (don't assume input type from image type) */ + /**- if nifti_type = 1, check for .nii first, else .img first */ + + /* if we get 3 or more extensions, can make a loop here... */ + + if (nifti_type == NIFTI_FTYPE_NIFTI1_1) first = 0; /* should match .nii */ + else first = 1; /* should match .img */ + + strcpy(imgname,basename); + strcat(imgname,elist[first]); + if (nifti_fileexists(imgname)) { free(basename); return imgname; } +#ifdef HAVE_ZLIB /* then also check for .gz */ + strcat(imgname,extzip); + if (nifti_fileexists(imgname)) { free(basename); return imgname; } +#endif + + /* failed to find image file with expected extension, try the other */ + + strcpy(imgname,basename); + strcat(imgname,elist[1-first]); /* can do this with only 2 choices */ + if (nifti_fileexists(imgname)) { free(basename); return imgname; } +#ifdef HAVE_ZLIB /* then also check for .gz */ + strcat(imgname,extzip); + if (nifti_fileexists(imgname)) { free(basename); return imgname; } +#endif + } + + /**- if nothing has been found, return NULL */ + free(basename); + free(imgname); + return NULL; +} + + +/*----------------------------------------------------------------------*/ +/*! creates a filename for storing the header, based on nifti_type + + \param prefix - this will be copied before the suffix is added + \param nifti_type - determines the extension, unless one is in prefix + \param check - check for existence (fail condition) + \param comp - add .gz for compressed name + + Note that if prefix provides a file suffix, nifti_type is not used. + + NB: this allocates memory which should be freed + + \sa nifti_set_filenames +*//*-------------------------------------------------------------------*/ +char * nifti_makehdrname(const char * prefix, int nifti_type, int check, + int comp) +{ + char * iname; + const char * ext; + char extnii[5] = ".nii"; /* modifiable, for possible uppercase */ + char exthdr[5] = ".hdr"; + char extimg[5] = ".img"; + char extnia[5] = ".nia"; + char extgz[5] = ".gz"; + + if( !nifti_validfilename(prefix) ) return NULL; + + /* add space for extension, optional ".gz", and null char */ + iname = (char *)calloc(sizeof(char),strlen(prefix)+8); + if( !iname ){ Rc_fprintf_stderr("** small malloc failure!\n"); return NULL; } + strcpy(iname, prefix); + + /* use any valid extension */ + if( (ext = nifti_find_file_extension(iname)) != NULL ){ + /* if uppercase, convert all extensions */ + if( is_uppercase(ext) ) { + make_uppercase(extnii); + make_uppercase(exthdr); + make_uppercase(extimg); + make_uppercase(extnia); + make_uppercase(extgz); + } + + if( strncmp(ext,extimg,4) == 0 ) + { + memcpy(&(iname[strlen(iname)-strlen(ext)]),exthdr,4); /* then convert img name to hdr */ + } + } + /* otherwise, make one up */ + else if( nifti_type == NIFTI_FTYPE_NIFTI1_1 ) strcat(iname, extnii); + else if( nifti_type == NIFTI_FTYPE_ASCII ) strcat(iname, extnia); + else strcat(iname, exthdr); + +#ifdef HAVE_ZLIB /* if compression is requested, make sure of suffix */ + if( comp && (!ext || !strstr(iname,extgz)) ) strcat(iname,extgz); +#endif + + /* check for existence failure */ + if( check && nifti_fileexists(iname) ){ + Rc_fprintf_stderr("** failure: header file '%s' already exists\n",iname); + free(iname); + return NULL; + } + + if(g_opts.debug > 2) Rc_fprintf_stderr("+d made header filename '%s'\n", iname); + + return iname; +} + + +/*----------------------------------------------------------------------*/ +/*! creates a filename for storing the image, based on nifti_type + + \param prefix - this will be copied before the suffix is added + \param nifti_type - determines the extension, unless provided by prefix + \param check - check for existence (fail condition) + \param comp - add .gz for compressed name + + Note that if prefix provides a file suffix, nifti_type is not used. + + NB: it allocates memory which should be freed + + \sa nifti_set_filenames +*//*-------------------------------------------------------------------*/ +char * nifti_makeimgname(const char * prefix, int nifti_type, int check, + int comp) +{ + char * iname; + const char * ext; + char extnii[5] = ".nii"; /* modifiable, for possible uppercase */ + char exthdr[5] = ".hdr"; + char extimg[5] = ".img"; + char extnia[5] = ".nia"; + char extgz[5] = ".gz"; + + if( !nifti_validfilename(prefix) ) return NULL; + + /* add space for extension, optional ".gz", and null char */ + iname = (char *)calloc(sizeof(char),strlen(prefix)+8); + if( !iname ){ Rc_fprintf_stderr("** small malloc failure!\n"); return NULL; } + strcpy(iname, prefix); + + /* use any valid extension */ + if( (ext = nifti_find_file_extension(iname)) != NULL ){ + /* if uppercase, convert all extensions */ + if( is_uppercase(ext) ) { + make_uppercase(extnii); + make_uppercase(exthdr); + make_uppercase(extimg); + make_uppercase(extnia); + make_uppercase(extgz); + } + + if( strncmp(ext,exthdr,4) == 0 ) + { + memcpy(&(iname[strlen(iname)-strlen(ext)]),extimg,4); /* then convert hdr name to img */ + } + } + /* otherwise, make one up */ + else if( nifti_type == NIFTI_FTYPE_NIFTI1_1 ) strcat(iname, extnii); + else if( nifti_type == NIFTI_FTYPE_ASCII ) strcat(iname, extnia); + else strcat(iname, extimg); + +#ifdef HAVE_ZLIB /* if compression is requested, make sure of suffix */ + if( comp && (!ext || !strstr(iname,extgz)) ) strcat(iname,extgz); +#endif + + /* check for existence failure */ + if( check && nifti_fileexists(iname) ){ + Rc_fprintf_stderr("** failure: image file '%s' already exists\n",iname); + free(iname); + return NULL; + } + + if( g_opts.debug > 2 ) Rc_fprintf_stderr("+d made image filename '%s'\n",iname); + + return iname; +} + + +/*----------------------------------------------------------------------*/ +/*! create and set new filenames, based on prefix and image type + + \param nim pointer to nifti_image in which to set filenames + \param prefix (required) prefix for output filenames + \param check check for previous existence of filename + (existence is an error condition) + \param set_byte_order flag to set nim->byteorder here + (this is probably a logical place to do so) + + \return 0 on successful update + + \warning this will free() any existing names and create new ones + + \sa nifti_makeimgname, nifti_makehdrname, nifti_type_and_names_match +*//*--------------------------------------------------------------------*/ +int nifti_set_filenames( nifti_image * nim, const char * prefix, int check, + int set_byte_order ) +{ + int comp = nifti_is_gzfile(prefix); + + if( !nim || !prefix ){ + Rc_fprintf_stderr("** nifti_set_filenames, bad params %p, %p\n", + (void *)nim,prefix); + return -1; + } + + if( g_opts.debug > 1 ) + Rc_fprintf_stderr("+d modifying output filenames using prefix %s\n", prefix); + + if( nim->fname ) free(nim->fname); + if( nim->iname ) free(nim->iname); + nim->fname = nifti_makehdrname(prefix, nim->nifti_type, check, comp); + nim->iname = nifti_makeimgname(prefix, nim->nifti_type, check, comp); + if( !nim->fname || !nim->iname ){ + LNI_FERR("nifti_set_filename","failed to set prefix for",prefix); + return -1; + } + + if( set_byte_order ) nim->byteorder = nifti_short_order() ; + + if( nifti_set_type_from_names(nim) < 0 ) + return -1; + + if( g_opts.debug > 2 ) + Rc_fprintf_stderr("+d have new filenames %s and %s\n",nim->fname,nim->iname); + + return 0; +} + + +/*--------------------------------------------------------------------------*/ +/*! check whether nifti_type matches fname and iname for the nifti_image + + - if type 0 or 2, expect .hdr/.img pair + - if type 1, expect .nii (and names must match) + + \param nim given nifti_image + \param show_warn if set, print a warning message for any mis-match + + \return + - 1 if the values seem to match + - 0 if there is a mis-match + - -1 if there is not sufficient information to create file(s) + + \sa NIFTI_FTYPE_* codes in nifti1_io.h + \sa nifti_set_type_from_names, is_valid_nifti_type +*//*------------------------------------------------------------------------*/ +int nifti_type_and_names_match( nifti_image * nim, int show_warn ) +{ + char func[] = "nifti_type_and_names_match"; + const char * ext_h; /* header filename extension */ + const char * ext_i; /* image filename extension */ + int errs = 0; /* error counter */ + + /* sanity checks */ + if( !nim ){ + if( show_warn ) Rc_fprintf_stderr("** %s: missing nifti_image\n", func); + return -1; + } + if( !nim->fname ){ + if( show_warn ) Rc_fprintf_stderr("** %s: missing header filename\n", func); + errs++; + } + if( !nim->iname ){ + if( show_warn ) Rc_fprintf_stderr("** %s: missing image filename\n", func); + errs++; + } + if( !is_valid_nifti_type(nim->nifti_type) ){ + if( show_warn ) + Rc_fprintf_stderr("** %s: bad nifti_type %d\n", func, nim->nifti_type); + errs++; + } + + if( errs ) return -1; /* then do not proceed */ + + /* get pointers to extensions */ + ext_h = nifti_find_file_extension( nim->fname ); + ext_i = nifti_find_file_extension( nim->iname ); + + /* check for filename extensions */ + if( !ext_h ){ + if( show_warn ) + Rc_fprintf_stderr("-d missing NIFTI extension in header filename, %s\n", + nim->fname); + errs++; + } + if( !ext_i ){ + if( show_warn ) + Rc_fprintf_stderr("-d missing NIFTI extension in image filename, %s\n", + nim->iname); + errs++; + } + + if( errs ) return 0; /* do not proceed, but this is just a mis-match */ + + /* general tests */ + if( nim->nifti_type == NIFTI_FTYPE_NIFTI1_1 ){ /* .nii */ + if( fileext_n_compare(ext_h,".nii",4) ) { + if( show_warn ) + Rc_fprintf_stderr("-d NIFTI_FTYPE 1, but no .nii extension in header filename, %s\n", + nim->fname); + errs++; + } + if( fileext_n_compare(ext_i,".nii",4) ) { + if( show_warn ) + Rc_fprintf_stderr("-d NIFTI_FTYPE 1, but no .nii extension in image filename, %s\n", + nim->iname); + errs++; + } + if( strcmp(nim->fname, nim->iname) != 0 ){ + if( show_warn ) + Rc_fprintf_stderr("-d NIFTI_FTYPE 1, but header and image filenames differ: %s, %s\n", + nim->fname, nim->iname); + errs++; + } + } + else if( (nim->nifti_type == NIFTI_FTYPE_NIFTI1_2) || /* .hdr/.img */ + (nim->nifti_type == NIFTI_FTYPE_ANALYZE) ) + { + if( fileext_n_compare(ext_h,".hdr",4) != 0 ){ + if( show_warn ) + Rc_fprintf_stderr("-d no '.hdr' extension, but NIFTI type is %d, %s\n", + nim->nifti_type, nim->fname); + errs++; + } + if( fileext_n_compare(ext_i,".img",4) != 0 ){ + if( show_warn ) + Rc_fprintf_stderr("-d no '.img' extension, but NIFTI type is %d, %s\n", + nim->nifti_type, nim->iname); + errs++; + } + } + /* ignore any other nifti_type */ + + return 1; +} + +/* like strcmp, but also check against capitalization of known_ext + * (test as local string, with max length 7) */ +static int fileext_compare(const char * test_ext, const char * known_ext) +{ + char caps[8] = ""; + size_t c,len; + /* if equal, don't need to check case (store to avoid multiple calls) */ + const int cmp = strcmp(test_ext, known_ext); + if( cmp == 0 ) return cmp; + + /* if anything odd, use default */ + if( !test_ext || !known_ext ) return cmp; + + len = strlen(known_ext); + if( len > 7 ) return cmp; + + /* if here, strings are different but need to check upper-case */ + + for(c = 0; c < len; c++ ) caps[c] = toupper((int) known_ext[c]); + caps[c] = '\0'; + + return strcmp(test_ext, caps); +} + +/* like strncmp, but also check against capitalization of known_ext + * (test as local string, with max length 7) */ +static int fileext_n_compare(const char * test_ext, + const char * known_ext, size_t maxlen) +{ + char caps[8] = ""; + size_t c,len; + /* if equal, don't need to check case (store to avoid multiple calls) */ + const int cmp = strncmp(test_ext, known_ext, maxlen); + if( cmp == 0 ) return cmp; + + /* if anything odd, use default */ + if( !test_ext || !known_ext ) return cmp; + + len = strlen(known_ext); + if( len > maxlen ) len = maxlen; /* ignore anything past maxlen */ + if( len > 7 ) return cmp; + + /* if here, strings are different but need to check upper-case */ + for(c = 0; c < len; c++ ) caps[c] = toupper((int) known_ext[c]); + caps[c] = '\0'; + + return strncmp(test_ext, caps, maxlen); +} + +/* return 1 if there are uppercase but no lowercase */ +static int is_uppercase(const char * str) +{ + size_t c; + int hasupper = 0; + + if( !str || !*str ) return 0; + + for(c = 0; c < strlen(str); c++ ) { + if( islower((int) str[c]) ) return 0; + if( !hasupper && isupper((int) str[c]) ) hasupper = 1; + } + + return hasupper; +} + +/* return 1 if there are both uppercase and lowercase characters */ +static int is_mixedcase(const char * str) +{ + size_t c; + int hasupper = 0, haslower = 0; + + if( !str || !*str ) return 0; + + for(c = 0; c < strlen(str); c++ ) { + if( !haslower && islower((int) str[c]) ) haslower = 1; + if( !hasupper && isupper((int) str[c]) ) hasupper = 1; + + if( haslower && hasupper ) return 1; + } + + return 0; +} + +/* convert any lowercase chars to uppercase */ +static int make_uppercase(char * str) +{ + size_t c; + + if( !str || !*str ) return 0; + + for(c = 0; c < strlen(str); c++ ) + if( islower((int) str[c]) ) str[c] = toupper((int) str[c]); + + return 0; +} + +/* convert any uppercase chars to lowercase */ +static int make_lowercase(char * str) +{ + size_t c; + if( !str || !*str ) return 0; + + for(c = 0; c < strlen(str); c++ ) + if( isupper((int) str[c]) ) str[c] = tolower((int) str[c]); + + return 0; +} + +/* run strcmp against of list of strings + * return index of equality, if found + * else return -1 */ +static int compare_strlist(const char * str, char ** strlist, int len) +{ + int c; + if( len <= 0 || !str || !strlist ) return -1; + for( c = 0; c < len; c++ ) + if( strlist[c] && !strcmp(str, strlist[c]) ) return c; + return -1; +} + +/*--------------------------------------------------------------------------*/ +/*! check whether the given type is on the "approved" list + + The code is valid if it is non-negative, and does not exceed + NIFTI_MAX_FTYPE. + + \return 1 if nifti_type is valid, 0 otherwise + \sa NIFTI_FTYPE_* codes in nifti1_io.h +*//*------------------------------------------------------------------------*/ +int is_valid_nifti_type( int nifti_type ) +{ + if( nifti_type >= NIFTI_FTYPE_ANALYZE && /* smallest type, 0 */ + nifti_type <= NIFTI_MAX_FTYPE ) + return 1; + return 0; +} + + +/*--------------------------------------------------------------------------*/ +/*! check whether the given type is on the "approved" list + + The type is explicitly checked against the NIFTI_TYPE_* list + in nifti1.h. + + \return 1 if dtype is valid, 0 otherwise + \sa NIFTI_TYPE_* codes in nifti1.h +*//*------------------------------------------------------------------------*/ +int nifti_is_valid_datatype( int dtype ) +{ + if( dtype == NIFTI_TYPE_UINT8 || + dtype == NIFTI_TYPE_INT16 || + dtype == NIFTI_TYPE_INT32 || + dtype == NIFTI_TYPE_FLOAT32 || + dtype == NIFTI_TYPE_COMPLEX64 || + dtype == NIFTI_TYPE_FLOAT64 || + dtype == NIFTI_TYPE_RGB24 || + dtype == NIFTI_TYPE_RGBA32 || + dtype == NIFTI_TYPE_INT8 || + dtype == NIFTI_TYPE_UINT16 || + dtype == NIFTI_TYPE_UINT32 || + dtype == NIFTI_TYPE_INT64 || + dtype == NIFTI_TYPE_UINT64 || + dtype == NIFTI_TYPE_FLOAT128 || + dtype == NIFTI_TYPE_COMPLEX128 || + dtype == NIFTI_TYPE_COMPLEX256 ) return 1; + return 0; +} + + +/*--------------------------------------------------------------------------*/ +/*! set the nifti_type field based on fname and iname + + Note that nifti_type is changed only when it does not match + the filenames. + + \return 0 on success, -1 on error + + \sa is_valid_nifti_type, nifti_type_and_names_match +*//*------------------------------------------------------------------------*/ +int nifti_set_type_from_names( nifti_image * nim ) +{ + /* error checking first */ + if( !nim ){ Rc_fprintf_stderr("** NSTFN: no nifti_image\n"); return -1; } + + if( !nim->fname || !nim->iname ){ + Rc_fprintf_stderr("** NSTFN: missing filename(s) fname @ %p, iname @ %p\n", + nim->fname, nim->iname); + return -1; + } + + if( ! nifti_validfilename ( nim->fname ) || + ! nifti_validfilename ( nim->iname ) || + ! nifti_find_file_extension( nim->fname ) || + ! nifti_find_file_extension( nim->iname ) + ) { + Rc_fprintf_stderr("** NSTFN: invalid filename(s) fname='%s', iname='%s'\n", + nim->fname, nim->iname); + return -1; + } + + if( g_opts.debug > 2 ) + Rc_fprintf_stderr("-d verify nifti_type from filenames: %d",nim->nifti_type); + + /* type should be NIFTI_FTYPE_ASCII if extension is .nia */ + if( (fileext_compare(nifti_find_file_extension(nim->fname),".nia")==0)){ + nim->nifti_type = NIFTI_FTYPE_ASCII; + } else { + /* not too picky here, do what must be done, and then verify */ + if( strcmp(nim->fname, nim->iname) == 0 ) /* one file, type 1 */ + nim->nifti_type = NIFTI_FTYPE_NIFTI1_1; + else if( nim->nifti_type == NIFTI_FTYPE_NIFTI1_1 ) /* cannot be type 1 */ + nim->nifti_type = NIFTI_FTYPE_NIFTI1_2; + } + + if( g_opts.debug > 2 ) Rc_fprintf_stderr(" -> %d\n",nim->nifti_type); + + if( g_opts.debug > 1 ) /* warn user about anything strange */ + nifti_type_and_names_match(nim, 1); + + if( is_valid_nifti_type(nim->nifti_type) ) return 0; /* success! */ + + Rc_fprintf_stderr("** NSTFN: bad nifti_type %d, for '%s' and '%s'\n", + nim->nifti_type, nim->fname, nim->iname); + + return -1; +} + + +/*--------------------------------------------------------------------------*/ +/*! Determine if this is a NIFTI-formatted file. + +
+   \return  0 if file looks like ANALYZE 7.5 [checks sizeof_hdr field == 348]
+            1 if file marked as NIFTI (header+data in 1 file)
+            2 if file marked as NIFTI (header+data in 2 files)
+           -1 if it can't tell, file doesn't exist, etc.
+   
+*//*------------------------------------------------------------------------*/ +int is_nifti_file( const char *hname ) +{ + struct nifti_1_header nhdr ; + znzFile fp ; + int ii ; + char *tmpname; + + /* bad input name? */ + + if( !nifti_validfilename(hname) ) return -1 ; + + /* open file */ + + tmpname = nifti_findhdrname(hname); + if( tmpname == NULL ){ + if( g_opts.debug > 0 ) + Rc_fprintf_stderr("** no header file found for '%s'\n",hname); + return -1; + } + fp = znzopen( tmpname , "rb" , nifti_is_gzfile(tmpname) ) ; + free(tmpname); + if (znz_isnull(fp)) return -1 ; /* bad open? */ + + /* read header, close file */ + + ii = (int)znzread( &nhdr , 1 , sizeof(nhdr) , fp ) ; + znzclose( fp ) ; + if( ii < (int) sizeof(nhdr) ) return -1 ; /* bad read? */ + + /* check for NIFTI-ness */ + + if( NIFTI_VERSION(nhdr) != 0 ){ + return ( NIFTI_ONEFILE(nhdr) ) ? 1 : 2 ; + } + + /* check for ANALYZE-ness (sizeof_hdr field == 348) */ + + ii = nhdr.sizeof_hdr ; + if( ii == (int)sizeof(nhdr) ) return 0 ; /* matches */ + + /* try byte-swapping header */ + + swap_4(ii) ; + if( ii == (int)sizeof(nhdr) ) return 0 ; /* matches */ + + return -1 ; /* not good */ +} + +static int print_hex_vals( const char * data, int nbytes, FILE * fp ) +{ + int c; + + if ( !data || nbytes < 1 || !fp ) return -1; + + fputs("0x", fp); + for ( c = 0; c < nbytes; c++ ) + fprintf(fp, " %x", data[c]); + + return 0; +} + +/*----------------------------------------------------------------------*/ +/*! display the contents of the nifti_1_header (send to stdout) + + \param info if non-NULL, print this character string + \param hp pointer to nifti_1_header +*//*--------------------------------------------------------------------*/ +int disp_nifti_1_header( const char * info, const nifti_1_header * hp ) +{ + int c; + + Rc_fputs_stdout( "-------------------------------------------------------\n" ); + if ( info ) Rc_fputs_stdout( info ); + if ( !hp ){ Rc_fputs_stdout(" ** no nifti_1_header to display!\n"); return 1; } + + Rc_fprintf_stdout(" nifti_1_header :\n" + " sizeof_hdr = %d\n" + " data_type[10] = ", hp->sizeof_hdr); + Rc_fprintf_stdout("\n" + " db_name[18] = "); + Rc_fprintf_stdout("\n" + " extents = %d\n" + " session_error = %d\n" + " regular = 0x%x\n" + " dim_info = 0x%x\n", + hp->extents, hp->session_error, hp->regular, hp->dim_info ); + Rc_fprintf_stdout(" dim[8] ="); + for ( c = 0; c < 8; c++ ) Rc_fprintf_stdout(" %d", hp->dim[c]); + Rc_fprintf_stdout("\n" + " intent_p1 = %f\n" + " intent_p2 = %f\n" + " intent_p3 = %f\n" + " intent_code = %d\n" + " datatype = %d\n" + " bitpix = %d\n" + " slice_start = %d\n" + " pixdim[8] =", + hp->intent_p1, hp->intent_p2, hp->intent_p3, hp->intent_code, + hp->datatype, hp->bitpix, hp->slice_start); + /* break pixdim over 2 lines */ + for ( c = 0; c < 4; c++ ) Rc_fprintf_stdout(" %f", hp->pixdim[c]); + Rc_fprintf_stdout("\n "); + for ( c = 4; c < 8; c++ ) Rc_fprintf_stdout(" %f", hp->pixdim[c]); + Rc_fprintf_stdout("\n" + " vox_offset = %f\n" + " scl_slope = %f\n" + " scl_inter = %f\n" + " slice_end = %d\n" + " slice_code = %d\n" + " xyzt_units = 0x%x\n" + " cal_max = %f\n" + " cal_min = %f\n" + " slice_duration = %f\n" + " toffset = %f\n" + " glmax = %d\n" + " glmin = %d\n", + hp->vox_offset, hp->scl_slope, hp->scl_inter, hp->slice_end, + hp->slice_code, hp->xyzt_units, hp->cal_max, hp->cal_min, + hp->slice_duration, hp->toffset, hp->glmax, hp->glmin); + Rc_fprintf_stdout(" descrip = '%.80s'\n" + " aux_file = '%.24s'\n" + " qform_code = %d\n" + " sform_code = %d\n" + " quatern_b = %f\n" + " quatern_c = %f\n" + " quatern_d = %f\n" + " qoffset_x = %f\n" + " qoffset_y = %f\n" + " qoffset_z = %f\n" + " srow_x[4] = %f, %f, %f, %f\n" + " srow_y[4] = %f, %f, %f, %f\n" + " srow_z[4] = %f, %f, %f, %f\n" + " intent_name = '%-.16s'\n" + " magic = '%-.4s'\n", + hp->descrip, hp->aux_file, hp->qform_code, hp->sform_code, + hp->quatern_b, hp->quatern_c, hp->quatern_d, + hp->qoffset_x, hp->qoffset_y, hp->qoffset_z, + hp->srow_x[0], hp->srow_x[1], hp->srow_x[2], hp->srow_x[3], + hp->srow_y[0], hp->srow_y[1], hp->srow_y[2], hp->srow_y[3], + hp->srow_z[0], hp->srow_z[1], hp->srow_z[2], hp->srow_z[3], + hp->intent_name, hp->magic); + Rc_fprintf_stdout( "-------------------------------------------------------\n" ); + + return 0; +} + + +#undef ERREX +#define ERREX(msg) \ + do{ Rc_fprintf_stderr("** ERROR: nifti_convert_nhdr2nim: %s\n", (msg) ) ; \ + return NULL ; } while(0) + +/*----------------------------------------------------------------------*/ +/*! convert a nifti_1_header into a nift1_image + + \return an allocated nifti_image, or NULL on failure +*//*--------------------------------------------------------------------*/ +nifti_image* nifti_convert_nhdr2nim(struct nifti_1_header nhdr, + const char * fname) +{ + int ii , doswap , ioff ; + int is_nifti , is_onefile ; + nifti_image *nim; + + nim = (nifti_image *)calloc( 1 , sizeof(nifti_image) ) ; + if( !nim ) ERREX("failed to allocate nifti image"); + + /* be explicit with pointers */ + nim->fname = NULL; + nim->iname = NULL; + nim->data = NULL; + + /**- check if we must swap bytes */ + + doswap = need_nhdr_swap(nhdr.dim[0], nhdr.sizeof_hdr); /* swap data flag */ + + if( doswap < 0 ){ + free(nim); + if( doswap == -1 ) ERREX("bad dim[0]") ; + ERREX("bad sizeof_hdr") ; /* else */ + } + + /**- determine if this is a NIFTI-1 compliant header */ + + is_nifti = NIFTI_VERSION(nhdr) ; + /* + * before swapping header, record the Analyze75 orient code + */ + if(!is_nifti) + { + /**- in analyze75, the orient code is at the same address as + * qform_code, but it's just one byte + * the qform_code will be zero, at which point you can check + * analyze75_orient if you care to. + */ + unsigned char c = *((char *)(&nhdr.qform_code)); + nim->analyze75_orient = (analyze_75_orient_code)c; + } + if( doswap ) { + if ( g_opts.debug > 3 ) disp_nifti_1_header("-d ni1 pre-swap: ", &nhdr); + swap_nifti_header( &nhdr , is_nifti ) ; + } + + if ( g_opts.debug > 2 ) disp_nifti_1_header("-d nhdr2nim : ", &nhdr); + + if( nhdr.datatype == DT_BINARY || nhdr.datatype == DT_UNKNOWN ) + { + free(nim); + ERREX("bad datatype") ; + } + + if( nhdr.dim[1] <= 0 ) + { + free(nim); + ERREX("bad dim[1]") ; + } + + /* fix bad dim[] values in the defined dimension range */ + for( ii=2 ; ii <= nhdr.dim[0] ; ii++ ) + if( nhdr.dim[ii] <= 0 ) nhdr.dim[ii] = 1 ; + + /* fix any remaining bad dim[] values, so garbage does not propagate */ + /* (only values 0 or 1 seem rational, otherwise set to arbirary 1) */ + for( ii=nhdr.dim[0]+1 ; ii <= 7 ; ii++ ) + if( nhdr.dim[ii] != 1 && nhdr.dim[ii] != 0) nhdr.dim[ii] = 1 ; + +#if 0 /* rely on dim[0], do not attempt to modify it 16 Nov 2005 [rickr] */ + + /**- get number of dimensions (ignoring dim[0] now) */ + for( ii=7 ; ii >= 2 ; ii-- ) /* loop backwards until we */ + if( nhdr.dim[ii] > 1 ) break ; /* find a dim bigger than 1 */ + ndim = ii ; +#endif + + /**- set bad grid spacings to 1.0 */ + + for( ii=1 ; ii <= nhdr.dim[0] ; ii++ ){ + if( nhdr.pixdim[ii] == 0.0 || + !IS_GOOD_FLOAT(nhdr.pixdim[ii]) ) nhdr.pixdim[ii] = 1.0f ; + } + + is_onefile = is_nifti && NIFTI_ONEFILE(nhdr) ; + + if( is_nifti ) nim->nifti_type = (is_onefile) ? NIFTI_FTYPE_NIFTI1_1 + : NIFTI_FTYPE_NIFTI1_2 ; + else nim->nifti_type = NIFTI_FTYPE_ANALYZE ; + + ii = nifti_short_order() ; + if( doswap ) nim->byteorder = REVERSE_ORDER(ii) ; + else nim->byteorder = ii ; + + + /**- set dimensions of data array */ + + nim->ndim = nim->dim[0] = nhdr.dim[0]; + nim->nx = nim->dim[1] = nhdr.dim[1]; + nim->ny = nim->dim[2] = nhdr.dim[2]; + nim->nz = nim->dim[3] = nhdr.dim[3]; + nim->nt = nim->dim[4] = nhdr.dim[4]; + nim->nu = nim->dim[5] = nhdr.dim[5]; + nim->nv = nim->dim[6] = nhdr.dim[6]; + nim->nw = nim->dim[7] = nhdr.dim[7]; + + for( ii=1, nim->nvox=1; ii <= nhdr.dim[0]; ii++ ) + nim->nvox *= nhdr.dim[ii]; + + /**- set the type of data in voxels and how many bytes per voxel */ + + nim->datatype = nhdr.datatype ; + + nifti_datatype_sizes( nim->datatype , &(nim->nbyper) , &(nim->swapsize) ) ; + if( nim->nbyper == 0 ){ free(nim); ERREX("bad datatype"); } + + /**- set the grid spacings */ + + nim->dx = nim->pixdim[1] = nhdr.pixdim[1] ; + nim->dy = nim->pixdim[2] = nhdr.pixdim[2] ; + nim->dz = nim->pixdim[3] = nhdr.pixdim[3] ; + nim->dt = nim->pixdim[4] = nhdr.pixdim[4] ; + nim->du = nim->pixdim[5] = nhdr.pixdim[5] ; + nim->dv = nim->pixdim[6] = nhdr.pixdim[6] ; + nim->dw = nim->pixdim[7] = nhdr.pixdim[7] ; + + /**- compute qto_xyz transformation from pixel indexes (i,j,k) to (x,y,z) */ + + if( !is_nifti || nhdr.qform_code <= 0 ){ + /**- if not nifti or qform_code <= 0, use grid spacing for qto_xyz */ + + nim->qto_xyz.m[0][0] = nim->dx ; /* grid spacings */ + nim->qto_xyz.m[1][1] = nim->dy ; /* along diagonal */ + nim->qto_xyz.m[2][2] = nim->dz ; + + /* off diagonal is zero */ + + nim->qto_xyz.m[0][1]=nim->qto_xyz.m[0][2]=nim->qto_xyz.m[0][3] = 0.0f; + nim->qto_xyz.m[1][0]=nim->qto_xyz.m[1][2]=nim->qto_xyz.m[1][3] = 0.0f; + nim->qto_xyz.m[2][0]=nim->qto_xyz.m[2][1]=nim->qto_xyz.m[2][3] = 0.0f; + + /* last row is always [ 0 0 0 1 ] */ + + nim->qto_xyz.m[3][0]=nim->qto_xyz.m[3][1]=nim->qto_xyz.m[3][2] = 0.0f; + nim->qto_xyz.m[3][3]= 1.0f ; + + nim->qform_code = NIFTI_XFORM_UNKNOWN ; + + if( g_opts.debug > 1 ) Rc_fprintf_stderr("-d no qform provided\n"); + } else { + /**- else NIFTI: use the quaternion-specified transformation */ + + nim->quatern_b = FIXED_FLOAT( nhdr.quatern_b ) ; + nim->quatern_c = FIXED_FLOAT( nhdr.quatern_c ) ; + nim->quatern_d = FIXED_FLOAT( nhdr.quatern_d ) ; + + nim->qoffset_x = FIXED_FLOAT(nhdr.qoffset_x) ; + nim->qoffset_y = FIXED_FLOAT(nhdr.qoffset_y) ; + nim->qoffset_z = FIXED_FLOAT(nhdr.qoffset_z) ; + + nim->qfac = (nhdr.pixdim[0] < 0.0) ? -1.0f : 1.0f ; /* left-handedness? */ + + nim->qto_xyz = nifti_quatern_to_mat44( + nim->quatern_b, nim->quatern_c, nim->quatern_d, + nim->qoffset_x, nim->qoffset_y, nim->qoffset_z, + nim->dx , nim->dy , nim->dz , + nim->qfac ) ; + + nim->qform_code = nhdr.qform_code ; + + if( g_opts.debug > 1 ) + nifti_disp_matrix_orient("-d qform orientations:\n", nim->qto_xyz); + } + + /**- load inverse transformation (x,y,z) -> (i,j,k) */ + + nim->qto_ijk = nifti_mat44_inverse( nim->qto_xyz ) ; + + /**- load sto_xyz affine transformation, if present */ + + if( !is_nifti || nhdr.sform_code <= 0 ){ + /**- if not nifti or sform_code <= 0, then no sto transformation */ + + nim->sform_code = NIFTI_XFORM_UNKNOWN ; + + if( g_opts.debug > 1 ) Rc_fprintf_stderr("-d no sform provided\n"); + + } else { + /**- else set the sto transformation from srow_*[] */ + + nim->sto_xyz.m[0][0] = nhdr.srow_x[0] ; + nim->sto_xyz.m[0][1] = nhdr.srow_x[1] ; + nim->sto_xyz.m[0][2] = nhdr.srow_x[2] ; + nim->sto_xyz.m[0][3] = nhdr.srow_x[3] ; + + nim->sto_xyz.m[1][0] = nhdr.srow_y[0] ; + nim->sto_xyz.m[1][1] = nhdr.srow_y[1] ; + nim->sto_xyz.m[1][2] = nhdr.srow_y[2] ; + nim->sto_xyz.m[1][3] = nhdr.srow_y[3] ; + + nim->sto_xyz.m[2][0] = nhdr.srow_z[0] ; + nim->sto_xyz.m[2][1] = nhdr.srow_z[1] ; + nim->sto_xyz.m[2][2] = nhdr.srow_z[2] ; + nim->sto_xyz.m[2][3] = nhdr.srow_z[3] ; + + /* last row is always [ 0 0 0 1 ] */ + + nim->sto_xyz.m[3][0]=nim->sto_xyz.m[3][1]=nim->sto_xyz.m[3][2] = 0.0f; + nim->sto_xyz.m[3][3]= 1.0f ; + + nim->sto_ijk = nifti_mat44_inverse( nim->sto_xyz ) ; + + nim->sform_code = nhdr.sform_code ; + + if( g_opts.debug > 1 ) + nifti_disp_matrix_orient("-d sform orientations:\n", nim->sto_xyz); + } + + /**- set miscellaneous NIFTI stuff */ + + if( is_nifti ){ + nim->scl_slope = FIXED_FLOAT( nhdr.scl_slope ) ; + nim->scl_inter = FIXED_FLOAT( nhdr.scl_inter ) ; + + nim->intent_code = nhdr.intent_code ; + + nim->intent_p1 = FIXED_FLOAT( nhdr.intent_p1 ) ; + nim->intent_p2 = FIXED_FLOAT( nhdr.intent_p2 ) ; + nim->intent_p3 = FIXED_FLOAT( nhdr.intent_p3 ) ; + + nim->toffset = FIXED_FLOAT( nhdr.toffset ) ; + + memcpy(nim->intent_name,nhdr.intent_name,15); nim->intent_name[15] = '\0'; + + nim->xyz_units = XYZT_TO_SPACE(nhdr.xyzt_units) ; + nim->time_units = XYZT_TO_TIME (nhdr.xyzt_units) ; + + nim->freq_dim = DIM_INFO_TO_FREQ_DIM ( nhdr.dim_info ) ; + nim->phase_dim = DIM_INFO_TO_PHASE_DIM( nhdr.dim_info ) ; + nim->slice_dim = DIM_INFO_TO_SLICE_DIM( nhdr.dim_info ) ; + + nim->slice_code = nhdr.slice_code ; + nim->slice_start = nhdr.slice_start ; + nim->slice_end = nhdr.slice_end ; + nim->slice_duration = FIXED_FLOAT(nhdr.slice_duration) ; + } + + /**- set Miscellaneous ANALYZE stuff */ + + nim->cal_min = FIXED_FLOAT(nhdr.cal_min) ; + nim->cal_max = FIXED_FLOAT(nhdr.cal_max) ; + + memcpy(nim->descrip ,nhdr.descrip ,79) ; nim->descrip [79] = '\0' ; + memcpy(nim->aux_file,nhdr.aux_file,23) ; nim->aux_file[23] = '\0' ; + + /**- set ioff from vox_offset (but at least sizeof(header)) */ + + is_onefile = is_nifti && NIFTI_ONEFILE(nhdr) ; + + if( is_onefile ){ + ioff = (int)nhdr.vox_offset ; + if( ioff < (int) sizeof(nhdr) ) ioff = (int) sizeof(nhdr) ; + } else { + ioff = (int)nhdr.vox_offset ; + } + nim->iname_offset = ioff ; + + + /**- deal with file names if set */ + if (fname!=NULL) { + nifti_set_filenames(nim,fname,0,0); + if (nim->iname==NULL) { ERREX("bad filename"); } + } else { + nim->fname = NULL; + nim->iname = NULL; + } + + /* clear extension fields */ + nim->num_ext = 0; + nim->ext_list = NULL; + + return nim; +} + +#undef ERREX +#define ERREX(msg) \ + do{ Rc_fprintf_stderr("** ERROR: nifti_image_open(%s): %s\n", \ + (hname != NULL) ? hname : "(null)" , (msg) ) ; \ + return fptr ; } while(0) + +/*************************************************************** + * nifti_image_open + ***************************************************************/ +/*! znzFile nifti_image_open( char *hname, char *opts , nifti_image **nim) + \brief Read in NIFTI-1 or ANALYZE-7.5 file (pair) header information into a nifti_image struct. + + - The image data is not read from disk (it may be read later using + nifti_image_load(), for example). + - The image data will be stored in whatever data format the + input data is; no scaling will be applied. + - DT_BINARY data is not supported. + - nifti_image_free() can be used to delete the returned struct, + when you are done with it. + + \param hname filename of dataset .hdr or .nii file + \param opts options string for opening the header file + \param nim pointer to pointer to nifti_image struct + (this routine allocates the nifti_image struct) + \return file pointer (gzippable) to the file with the image data, + ready for reading. +
NULL if something fails badly. + \sa nifti_image_load, nifti_image_free + */ +znzFile nifti_image_open(const char * hname, char * opts, nifti_image ** nim) +{ + znzFile fptr=NULL; + /* open the hdr and reading it in, but do not load the data */ + *nim = nifti_image_read(hname,0); + /* open the image file, ready for reading (compressed works for all reads) */ + if( ((*nim) == NULL) || ((*nim)->iname == NULL) || + ((*nim)->nbyper <= 0) || ((*nim)->nvox <= 0) ) + ERREX("bad header info") ; + + /* open image data file */ + fptr = znzopen( (*nim)->iname, opts, nifti_is_gzfile((*nim)->iname) ); + if( znz_isnull(fptr) ) ERREX("Can't open data file") ; + + return fptr; +} + + +/*----------------------------------------------------------------------*/ +/*! return an allocated and filled nifti_1_header struct + + Read the binary header from disk, and swap bytes if necessary. + + \return an allocated nifti_1_header struct, or NULL on failure + + \param hname name of file containing header + \param swapped if not NULL, return whether header bytes were swapped + \param check flag to check for invalid nifti_1_header + + \warning ASCII header type is not supported + + \sa nifti_image_read, nifti_image_free, nifti_image_read_bricks +*//*--------------------------------------------------------------------*/ +nifti_1_header * nifti_read_header(const char * hname, int * swapped, int check) +{ + nifti_1_header nhdr, * hptr; + znzFile fp; + int bytes, lswap; + char * hfile; + char fname[] = { "nifti_read_header" }; + + /* determine file name to use for header */ + hfile = nifti_findhdrname(hname); + if( hfile == NULL ){ + if( g_opts.debug > 0 ) + LNI_FERR(fname,"failed to find header file for", hname); + return NULL; + } else if( g_opts.debug > 1 ) + Rc_fprintf_stderr("-d %s: found header filename '%s'\n",fname,hfile); + + fp = znzopen( hfile, "rb", nifti_is_gzfile(hfile) ); + if( znz_isnull(fp) ){ + if( g_opts.debug > 0 ) LNI_FERR(fname,"failed to open header file",hfile); + free(hfile); + return NULL; + } + + free(hfile); /* done with filename */ + + if( has_ascii_header(fp) == 1 ){ + znzclose( fp ); + if( g_opts.debug > 0 ) + LNI_FERR(fname,"ASCII header type not supported",hname); + return NULL; + } + + /* read the binary header */ + bytes = (int)znzread( &nhdr, 1, sizeof(nhdr), fp ); + znzclose( fp ); /* we are done with the file now */ + + if( bytes < (int)sizeof(nhdr) ){ + if( g_opts.debug > 0 ){ + LNI_FERR(fname,"bad binary header read for file", hname); + Rc_fprintf_stderr(" - read %d of %d bytes\n",bytes, (int)sizeof(nhdr)); + } + return NULL; + } + + /* now just decide on byte swapping */ + lswap = need_nhdr_swap(nhdr.dim[0], nhdr.sizeof_hdr); /* swap data flag */ + if( check && lswap < 0 ){ + LNI_FERR(fname,"bad nifti_1_header for file", hname); + return NULL; + } else if ( lswap < 0 ) { + lswap = 0; /* if swapping does not help, don't do it */ + if(g_opts.debug > 1) Rc_fprintf_stderr("-- swap failure, none applied\n"); + } + + if( lswap ) { + if ( g_opts.debug > 3 ) disp_nifti_1_header("-d nhdr pre-swap: ", &nhdr); + swap_nifti_header( &nhdr , NIFTI_VERSION(nhdr) ) ; + } + + if ( g_opts.debug > 2 ) disp_nifti_1_header("-d nhdr post-swap: ", &nhdr); + + if ( check && ! nifti_hdr_looks_good(&nhdr) ){ + LNI_FERR(fname,"nifti_1_header looks bad for file", hname); + return NULL; + } + + /* all looks good, so allocate memory for and return the header */ + hptr = (nifti_1_header *)malloc(sizeof(nifti_1_header)); + if( ! hptr ){ + Rc_fprintf_stderr("** nifti_read_hdr: failed to alloc nifti_1_header\n"); + return NULL; + } + + if( swapped ) *swapped = lswap; /* only if they care */ + + memcpy(hptr, &nhdr, sizeof(nifti_1_header)); + + return hptr; +} + + +/*----------------------------------------------------------------------*/ +/*! decide if this nifti_1_header structure looks reasonable + + Check dim[0], dim[1], sizeof_hdr, and datatype. + Check magic string for "n+1". + Maybe more tests will follow. + + \return 1 if the header seems valid, 0 otherwise + + \sa nifti_nim_is_valid, valid_nifti_extensions +*//*--------------------------------------------------------------------*/ +int nifti_hdr_looks_good(const nifti_1_header * hdr) +{ + int is_nifti, c, errs = 0; + + /* check dim[0] and sizeof_hdr */ + if( need_nhdr_swap(hdr->dim[0], hdr->sizeof_hdr) < 0 ){ + if( g_opts.debug > 0 ) + Rc_fprintf_stderr("** bad nhdr fields: dim0, sizeof_hdr = %d, %d\n", + hdr->dim[0], hdr->sizeof_hdr); + errs++; + } + + /* check the valid dimension sizes (maybe dim[0] is bad) */ + for( c = 1; c <= hdr->dim[0] && c <= 7; c++ ) + if( hdr->dim[c] <= 0 ){ + if( g_opts.debug > 0 ) + Rc_fprintf_stderr("** bad nhdr field: dim[%d] = %d\n",c,hdr->dim[c]); + errs++; + } + + is_nifti = NIFTI_VERSION(*hdr); /* determine header type */ + + if( is_nifti ){ /* NIFTI */ + + if( ! nifti_datatype_is_valid(hdr->datatype, 1) ){ + if( g_opts.debug > 0 ) + Rc_fprintf_stderr("** bad NIFTI datatype in hdr, %d\n",hdr->datatype); + errs++; + } + + } else { /* ANALYZE 7.5 */ + + if( g_opts.debug > 1 ) /* maybe tell user it's an ANALYZE hdr */ + Rc_fprintf_stderr("-- nhdr magic field implies ANALYZE: magic = '%.4s'\n",hdr->magic); + + if( ! nifti_datatype_is_valid(hdr->datatype, 0) ){ + if( g_opts.debug > 0 ) + Rc_fprintf_stderr("** bad ANALYZE datatype in hdr, %d\n",hdr->datatype); + errs++; + } + } + + if( errs ) return 0; /* problems */ + + if( g_opts.debug > 2 ) Rc_fprintf_stderr("-d nifti header looks good\n"); + + return 1; /* looks good */ +} + + +/*---------------------------------------------------------------------- + * check whether byte swapping is needed + * + * dim[0] should be in [0,7], and sizeof_hdr should be accurate + * + * \returns > 0 : needs swap + * 0 : does not need swap + * < 0 : error condition + *----------------------------------------------------------------------*/ +static int need_nhdr_swap( short dim0, int hdrsize ) +{ + short d0 = dim0; /* so we won't have to swap them on the stack */ + int hsize = hdrsize; + + if( d0 != 0 ){ /* then use it for the check */ + if( d0 > 0 && d0 <= 7 ) return 0; + + nifti_swap_2bytes(1, &d0); /* swap? */ + if( d0 > 0 && d0 <= 7 ) return 1; + + if( g_opts.debug > 1 ){ + Rc_fprintf_stderr("** NIFTI: bad swapped d0 = %d, unswapped = ", d0); + nifti_swap_2bytes(1, &d0); /* swap? */ + Rc_fprintf_stderr("%d\n", d0); + } + + return -1; /* bad, naughty d0 */ + } + + /* dim[0] == 0 should not happen, but could, so try hdrsize */ + if( hsize == sizeof(nifti_1_header) ) return 0; + + nifti_swap_4bytes(1, &hsize); /* swap? */ + if( hsize == sizeof(nifti_1_header) ) return 1; + + if( g_opts.debug > 1 ){ + Rc_fprintf_stderr("** NIFTI: bad swapped hsize = %d, unswapped = ", hsize); + nifti_swap_4bytes(1, &hsize); /* swap? */ + Rc_fprintf_stderr("%d\n", hsize); + } + + return -2; /* bad, naughty hsize */ +} + + +/* use macro LNI_FILE_ERROR instead of ERREX() +#undef ERREX +#define ERREX(msg) \ + do{ Rc_fprintf_stderr("** ERROR: nifti_image_read(%s): %s\n", \ + (hname != NULL) ? hname : "(null)" , (msg) ) ; \ + return NULL ; } while(0) +*/ + + +/*************************************************************** + * nifti_image_read + ***************************************************************/ +/*! \brief Read a nifti header and optionally the data, creating a nifti_image. + + - The data buffer will be byteswapped if necessary. + - The data buffer will not be scaled. + - The data buffer is allocated with calloc(). + + \param hname filename of the nifti dataset + \param read_data Flag, true=read data blob, false=don't read blob. + \return A pointer to the nifti_image data structure. + + \sa nifti_image_free, nifti_free_extensions, nifti_image_read_bricks +*/ +nifti_image *nifti_image_read( const char *hname , int read_data ) +{ + struct nifti_1_header nhdr ; + nifti_image *nim ; + znzFile fp ; + int rv, ii , filesize, remaining; + char fname[] = { "nifti_image_read" }; + char *hfile=NULL; + + if( g_opts.debug > 1 ){ + Rc_fprintf_stderr("-d image_read from '%s', read_data = %d",hname,read_data); +#ifdef HAVE_ZLIB + Rc_fprintf_stderr(", HAVE_ZLIB = 1\n"); +#else + Rc_fprintf_stderr(", HAVE_ZLIB = 0\n"); +#endif + } + + /**- determine filename to use for header */ + hfile = nifti_findhdrname(hname); + if( hfile == NULL ){ + if(g_opts.debug > 0) + LNI_FERR(fname,"failed to find header file for", hname); + return NULL; /* check return */ + } else if( g_opts.debug > 1 ) + Rc_fprintf_stderr("-d %s: found header filename '%s'\n",fname,hfile); + + if( nifti_is_gzfile(hfile) ) filesize = -1; /* unknown */ + else filesize = nifti_get_filesize(hfile); + + fp = znzopen(hfile, "rb", nifti_is_gzfile(hfile)); + if( znz_isnull(fp) ){ + if( g_opts.debug > 0 ) LNI_FERR(fname,"failed to open header file",hfile); + free(hfile); + return NULL; + } + + rv = has_ascii_header( fp ); + if( rv < 0 ){ + if( g_opts.debug > 0 ) LNI_FERR(fname,"short header read",hfile); + znzclose( fp ); + free(hfile); + return NULL; + } + else if ( rv == 1 ) /* process special file type */ + return nifti_read_ascii_image( fp, hfile, filesize, read_data ); + + /* else, just process normally */ + + /**- read binary header */ + + ii = (int)znzread( &nhdr , 1 , sizeof(nhdr) , fp ) ; /* read the thing */ + + /* keep file open so we can check for exts. after nifti_convert_nhdr2nim() */ + + if( ii < (int) sizeof(nhdr) ){ + if( g_opts.debug > 0 ){ + LNI_FERR(fname,"bad binary header read for file", hfile); + Rc_fprintf_stderr(" - read %d of %d bytes\n",ii, (int)sizeof(nhdr)); + } + znzclose(fp) ; + free(hfile); + return NULL; + } + + /* create output image struct and set it up */ + + /**- convert all nhdr fields to nifti_image fields */ + nim = nifti_convert_nhdr2nim(nhdr,hfile); + + if( nim == NULL ){ + znzclose( fp ) ; /* close the file */ + if( g_opts.debug > 0 ) + LNI_FERR(fname,"cannot create nifti image from header",hfile); + free(hfile); /* had to save this for debug message */ + return NULL; + } + + if( g_opts.debug > 3 ){ + Rc_fprintf_stderr("+d nifti_image_read(), have nifti image:\n"); + if( g_opts.debug > 2 ) nifti_image_infodump(nim); + } + + /**- check for extensions (any errors here means no extensions) */ + if( NIFTI_ONEFILE(nhdr) ) remaining = nim->iname_offset - sizeof(nhdr); + else remaining = filesize - sizeof(nhdr); + + (void)nifti_read_extensions(nim, fp, remaining); + + znzclose( fp ) ; /* close the file */ + free(hfile); + + /**- read the data if desired, then bug out */ + if( read_data ){ + if( nifti_image_load( nim ) < 0 ){ + nifti_image_free(nim); /* take ball, go home. */ + return NULL; + } + } + else nim->data = NULL ; + + return nim ; +} + + +/*---------------------------------------------------------------------- + * has_ascii_header - see if the NIFTI header is an ASCII format + * + * If the file starts with the ASCII string " 1 ) + Rc_fprintf_stderr("-d %s: have ASCII NIFTI file of size %d\n",fname,slen); + + if( slen > 65530 ) slen = 65530 ; + sbuf = (char *)calloc(sizeof(char),slen+1) ; + if( !sbuf ){ + Rc_fprintf_stderr("** %s: failed to alloc %d bytes for sbuf",lfunc,65530); + free(fname); znzclose(fp); return NULL; + } + znzread( sbuf , 1 , slen , fp ) ; + nim = nifti_image_from_ascii( sbuf, &txt_size ) ; free( sbuf ) ; + if( nim == NULL ){ + LNI_FERR(lfunc,"failed nifti_image_from_ascii()",fname); + free(fname); znzclose(fp); return NULL; + } + nim->nifti_type = NIFTI_FTYPE_ASCII ; + + /* compute remaining space for extensions */ + remain = flen - txt_size - (int)nifti_get_volsize(nim); + if( remain > 4 ){ + /* read extensions (reposition file pointer, first) */ + znzseek(fp, txt_size, SEEK_SET); + (void) nifti_read_extensions(nim, fp, remain); + } + + free(fname); + znzclose( fp ) ; + + nim->iname_offset = -1 ; /* check from the end of the file */ + + if( read_data ) rv = nifti_image_load( nim ) ; + else nim->data = NULL ; + + /* check for nifti_image_load() failure, maybe bail out */ + if( read_data && rv != 0 ){ + if( g_opts.debug > 1 ) + Rc_fprintf_stderr("-d failed image_load, free nifti image struct\n"); + free(nim); + return NULL; + } + + return nim ; +} + + +/*---------------------------------------------------------------------- + * Read the extensions into the nifti_image struct 08 Dec 2004 [rickr] + * + * This function is called just after the header struct is read in, and + * it is assumed the file pointer has not moved. The value in remain + * is assumed to be accurate, reflecting the bytes of space for potential + * extensions. + * + * return the number of extensions read in, or < 0 on error + *----------------------------------------------------------------------*/ +static int nifti_read_extensions( nifti_image *nim, znzFile fp, int remain ) +{ + nifti1_extender extdr; /* defines extension existence */ + nifti1_extension extn; /* single extension to process */ + nifti1_extension * Elist; /* list of processed extensions */ + int posn, count; + + if( !nim || znz_isnull(fp) ) { + if( g_opts.debug > 0 ) + Rc_fprintf_stderr("** nifti_read_extensions: bad inputs (%p,%p)\n", + (void *)nim, (void *)fp); + return -1; + } + + posn = znztell(fp); + + if( (posn != sizeof(nifti_1_header)) && + (nim->nifti_type != NIFTI_FTYPE_ASCII) ) + Rc_fprintf_stderr("** WARNING: posn not header size (%d, %d)\n", + posn, (int)sizeof(nifti_1_header)); + + if( g_opts.debug > 2 ) + Rc_fprintf_stderr("-d nre: posn = %d, offset = %d, type = %d, remain = %d\n", + posn, nim->iname_offset, nim->nifti_type, remain); + + if( remain < 16 ){ + if( g_opts.debug > 2 ){ + if( g_opts.skip_blank_ext ) + Rc_fprintf_stderr("-d no extender in '%s' is okay, as " + "skip_blank_ext is set\n",nim->fname); + else + Rc_fprintf_stderr("-d remain=%d, no space for extensions\n",remain); + } + return 0; + } + + count = (int)znzread( extdr.extension, 1, 4, fp ); /* get extender */ + + if( count < 4 ){ + if( g_opts.debug > 1 ) + Rc_fprintf_stderr("-d file '%s' is too short for an extender\n", + nim->fname); + return 0; + } + + if( extdr.extension[0] != 1 ){ + if( g_opts.debug > 2 ) + Rc_fprintf_stderr("-d extender[0] (%d) shows no extensions for '%s'\n", + extdr.extension[0], nim->fname); + return 0; + } + + remain -= 4; + if( g_opts.debug > 2 ) + Rc_fprintf_stderr("-d found valid 4-byte extender, remain = %d\n", remain); + + /* so we expect extensions, but have no idea of how many there may be */ + + count = 0; + Elist = NULL; + while (nifti_read_next_extension(&extn, nim, remain, fp) > 0) + { + if( nifti_add_exten_to_list(&extn, &Elist, count+1) < 0 ){ + if( g_opts.debug > 0 ) + Rc_fprintf_stderr("** failed adding ext %d to list\n", count); + return -1; + } + + /* we have a new extension */ + if( g_opts.debug > 1 ){ + Rc_fprintf_stderr("+d found extension #%d, code = 0x%x, size = %d\n", + count, extn.ecode, extn.esize); + if( extn.ecode == NIFTI_ECODE_AFNI && g_opts.debug > 2 ) /* ~XML */ + Rc_fprintf_stderr(" AFNI extension: %.*s\n", + extn.esize-8,extn.edata); + else if( extn.ecode == NIFTI_ECODE_COMMENT && g_opts.debug > 2 ) + Rc_fprintf_stderr(" COMMENT extension: %.*s\n", /* TEXT */ + extn.esize-8,extn.edata); + } + remain -= extn.esize; + count++; + } + + if( g_opts.debug > 2 ) Rc_fprintf_stderr("+d found %d extension(s)\n", count); + + nim->num_ext = count; + nim->ext_list = Elist; + + return count; +} + + +/*----------------------------------------------------------------------*/ +/*! nifti_add_extension - add an extension, with a copy of the data + + Add an extension to the nim->ext_list array. + Fill this extension with a copy of the data, noting the + length and extension code. + + \param nim - nifti_image to add extension to + \param data - raw extension data + \param length - length of raw extension data + \param ecode - extension code + + \sa extension codes NIFTI_ECODE_* in nifti1_io.h + \sa nifti_free_extensions, valid_nifti_extensions, nifti_copy_extensions + + \return 0 on success, -1 on error (and free the entire list) +*//*--------------------------------------------------------------------*/ +int nifti_add_extension(nifti_image *nim, const char * data, int len, int ecode) +{ + nifti1_extension ext; + + /* error are printed in functions */ + if( nifti_fill_extension(&ext, data, len, ecode) ) return -1; + if( nifti_add_exten_to_list(&ext, &nim->ext_list, nim->num_ext+1)) return -1; + + nim->num_ext++; /* success, so increment */ + + return 0; +} + + +/*----------------------------------------------------------------------*/ +/* nifti_add_exten_to_list - add a new nifti1_extension to the list + + We will append via "malloc, copy and free", because on an error, + the list will revert to the previous one (sorry realloc(), only + quality dolphins get to become part of St@rk!st brand tunafish). + + return 0 on success, -1 on error (and free the entire list) +*//*--------------------------------------------------------------------*/ +static int nifti_add_exten_to_list( nifti1_extension * new_ext, + nifti1_extension ** list, int new_length ) +{ + nifti1_extension * tmplist; + + tmplist = *list; + *list = (nifti1_extension *)malloc(new_length * sizeof(nifti1_extension)); + + /* check for failure first */ + if( ! *list ){ + Rc_fprintf_stderr("** failed to alloc %d extension structs (%d bytes)\n", + new_length, new_length*(int)sizeof(nifti1_extension)); + if( !tmplist ) return -1; /* no old list to lose */ + + *list = tmplist; /* reset list to old one */ + return -1; + } + + /* if an old list exists, copy the pointers and free the list */ + if( tmplist ){ + memcpy(*list, tmplist, (new_length-1)*sizeof(nifti1_extension)); + free(tmplist); + } + + /* for some reason, I just don't like struct copy... */ + (*list)[new_length-1].esize = new_ext->esize; + (*list)[new_length-1].ecode = new_ext->ecode; + (*list)[new_length-1].edata = new_ext->edata; + + if( g_opts.debug > 2 ) + Rc_fprintf_stderr("+d allocated and appended extension #%d to list\n", + new_length); + + return 0; +} + + +/*----------------------------------------------------------------------*/ +/* nifti_fill_extension - given data and length, fill an extension struct + + Allocate memory for data, copy data, set the size and code. + + return 0 on success, -1 on error (and free the entire list) +*//*--------------------------------------------------------------------*/ +static int nifti_fill_extension( nifti1_extension *ext, const char * data, + int len, int ecode) +{ + int esize; + + if( !ext || !data || len < 0 ){ + Rc_fprintf_stderr("** fill_ext: bad params (%p,%p,%d)\n", + (void *)ext, data, len); + return -1; + } else if( ! nifti_is_valid_ecode(ecode) ){ + Rc_fprintf_stderr("** warning: writing unknown ecode %d\n", ecode); + /* should not be fatal 29 Apr 2015 [rickr] */ + } + + /* compute esize, first : len+8, and take ceiling up to a mult of 16 */ + esize = len+8; + if( esize & 0xf ) esize = (esize + 0xf) & ~0xf; + ext->esize = esize; + + /* allocate esize-8 (maybe more than len), using calloc for fill */ + ext->edata = (char *)calloc(esize-8, sizeof(char)); + if( !ext->edata ){ + Rc_fprintf_stderr("** NFE: failed to alloc %d bytes for extension\n",len); + return -1; + } + + memcpy(ext->edata, data, len); /* copy the data, using len */ + ext->ecode = ecode; /* set the ecode */ + + if( g_opts.debug > 2 ) + Rc_fprintf_stderr("+d alloc %d bytes for ext len %d, ecode %d, esize %d\n", + esize-8, len, ecode, esize); + + return 0; +} + + +/*---------------------------------------------------------------------- + * nifti_read_next_extension - read a single extension from the file + * + * return (>= 0 is okay): + * + * success : esize + * no extension : 0 + * error : -1 + *----------------------------------------------------------------------*/ +static int nifti_read_next_extension( nifti1_extension * nex, nifti_image *nim, + int remain, znzFile fp ) +{ + int swap = nim->byteorder != nifti_short_order(); + int count, size, code; + + /* first clear nex */ + nex->esize = nex->ecode = 0; + nex->edata = NULL; + + if( remain < 16 ){ + if( g_opts.debug > 2 ) + Rc_fprintf_stderr("-d only %d bytes remain, so no extension\n", remain); + return 0; + } + + /* must start with 4-byte size and code */ + count = (int)znzread( &size, 4, 1, fp ); + if( count == 1 ) count += (int)znzread( &code, 4, 1, fp ); + + if( count != 2 ){ + if( g_opts.debug > 2 ) + Rc_fprintf_stderr("-d current extension read failed\n"); + znzseek(fp, -4*count, SEEK_CUR); /* back up past any read */ + return 0; /* no extension, no error condition */ + } + + if( swap ){ + if( g_opts.debug > 2 ) + Rc_fprintf_stderr("-d pre-swap exts: code %d, size %d\n", code, size); + + nifti_swap_4bytes(1, &size); + nifti_swap_4bytes(1, &code); + } + + if( g_opts.debug > 2 ) + Rc_fprintf_stderr("-d potential extension: code %d, size %d\n", code, size); + + if( !nifti_check_extension(nim, size, code, remain) ){ + if( znzseek(fp, -8, SEEK_CUR) < 0 ){ /* back up past any read */ + Rc_fprintf_stderr("** failure to back out of extension read!\n"); + return -1; + } + return 0; + } + + /* now get the actual data */ + nex->esize = size; + nex->ecode = code; + + size -= 8; /* subtract space for size and code in extension */ + nex->edata = (char *)malloc(size * sizeof(char)); + if( !nex->edata ){ + Rc_fprintf_stderr("** failed to allocate %d bytes for extension\n",size); + return -1; + } + + count = (int)znzread(nex->edata, 1, size, fp); + if( count < size ){ + if( g_opts.debug > 0 ) + Rc_fprintf_stderr("-d read only %d (of %d) bytes for extension\n", + count, size); + free(nex->edata); + nex->edata = NULL; + return -1; + } + + /* success! */ + if( g_opts.debug > 2 ) + Rc_fprintf_stderr("+d successfully read extension, code %d, size %d\n", + nex->ecode, nex->esize); + + return nex->esize; +} + + +/*----------------------------------------------------------------------*/ +/*! for each extension, check code, size and data pointer +*//*--------------------------------------------------------------------*/ +int valid_nifti_extensions(const nifti_image * nim) +{ + nifti1_extension * ext; + int c, errs; + + if( nim->num_ext <= 0 || nim->ext_list == NULL ){ + if( g_opts.debug > 2 ) Rc_fprintf_stderr("-d empty extension list\n"); + return 0; + } + + /* for each extension, check code, size and data pointer */ + ext = nim->ext_list; + errs = 0; + for ( c = 0; c < nim->num_ext; c++ ){ + if( ! nifti_is_valid_ecode(ext->ecode) ) { + if( g_opts.debug > 1 ) + Rc_fprintf_stderr("-d ext %d, unknown code %d\n", c, ext->ecode); + /* should not be fatal 29 Apr 2015 [rickr] */ + } + + if( ext->esize <= 0 ){ + if( g_opts.debug > 1 ) + Rc_fprintf_stderr("-d ext %d, bad size = %d\n", c, ext->esize); + errs++; + } else if( ext->esize & 0xf ){ + if( g_opts.debug > 1 ) + Rc_fprintf_stderr("-d ext %d, size %d not multiple of 16\n", + c, ext->esize); + errs++; + } + + if( ext->edata == NULL ){ + if( g_opts.debug > 1 ) Rc_fprintf_stderr("-d ext %d, missing data\n", c); + errs++; + } + + ext++; + } + + if( errs > 0 ){ + if( g_opts.debug > 0 ) + Rc_fprintf_stderr("-d had %d extension errors, none will be written\n", + errs); + return 0; + } + + /* if we're here, we're good */ + return 1; +} + + +/*----------------------------------------------------------------------*/ +/*! check whether the extension code is valid + + \return 1 if valid, 0 otherwise +*//*--------------------------------------------------------------------*/ +int nifti_is_valid_ecode( int ecode ) +{ + if( ecode < NIFTI_ECODE_IGNORE || /* minimum code number (0) */ + ecode > NIFTI_MAX_ECODE || /* maximum code number */ + ecode & 1 ) /* cannot be odd */ + return 0; + + return 1; +} + + +/*---------------------------------------------------------------------- + * check for valid size and code, as well as can be done + *----------------------------------------------------------------------*/ +static int nifti_check_extension(nifti_image *nim, int size, int code, int rem) +{ + /* check for bad code before bad size */ + if( ! nifti_is_valid_ecode(code) ) { + if( g_opts.debug > 2 ) + Rc_fprintf_stderr("-d invalid extension code %d\n",code); + /* should not be fatal 29 Apr 2015 [rickr] */ + } + + if( size < 16 ){ + if( g_opts.debug > 2 ) + Rc_fprintf_stderr("-d ext size %d, no extension\n",size); + return 0; + } + + if( size > rem ){ + if( g_opts.debug > 2 ) + Rc_fprintf_stderr("-d ext size %d, space %d, no extension\n", size, rem); + return 0; + } + + if( size & 0xf ){ + if( g_opts.debug > 2 ) + Rc_fprintf_stderr("-d nifti extension size %d not multiple of 16\n",size); + return 0; + } + + if( nim->nifti_type == NIFTI_FTYPE_ASCII && size > LNI_MAX_NIA_EXT_LEN ){ + if( g_opts.debug > 2 ) + Rc_fprintf_stderr("-d NVE, bad nifti_type 3 size %d\n", size); + return 0; + } + + return 1; +} + + +/*---------------------------------------------------------------------- + * nifti_image_load_prep - prepare to read data + * + * Check nifti_image fields, open the file and seek to the appropriate + * offset for reading. + * + * return NULL on failure + *----------------------------------------------------------------------*/ +static znzFile nifti_image_load_prep( nifti_image *nim ) +{ + /* set up data space, open data file and seek, then call nifti_read_buffer */ + size_t ntot , ii , ioff; + znzFile fp; + char *tmpimgname; + char fname[] = { "nifti_image_load_prep" }; + + /**- perform sanity checks */ + if( nim == NULL || nim->iname == NULL || + nim->nbyper <= 0 || nim->nvox <= 0 ) + { + if ( g_opts.debug > 0 ){ + if( !nim ) Rc_fprintf_stderr("** ERROR: N_image_load: no nifti image\n"); + else Rc_fprintf_stderr("** ERROR: N_image_load: bad params (%p,%d,%u)\n", + nim->iname, nim->nbyper, (unsigned)nim->nvox); + } + return NULL; + } + + ntot = nifti_get_volsize(nim) ; /* total bytes to read */ + + /**- open image data file */ + + tmpimgname = nifti_findimgname(nim->iname , nim->nifti_type); + if( tmpimgname == NULL ){ + if( g_opts.debug > 0 ) + Rc_fprintf_stderr("** no image file found for '%s'\n",nim->iname); + return NULL; + } + + fp = znzopen(tmpimgname, "rb", nifti_is_gzfile(tmpimgname)); + if (znz_isnull(fp)){ + if(g_opts.debug > 0) LNI_FERR(fname,"cannot open data file",tmpimgname); + free(tmpimgname); + return NULL; /* bad open? */ + } + free(tmpimgname); + + /**- get image offset: a negative offset means to figure from end of file */ + if( nim->iname_offset < 0 ){ + if( nifti_is_gzfile(nim->iname) ){ + if( g_opts.debug > 0 ) + LNI_FERR(fname,"negative offset for compressed file",nim->iname); + znzclose(fp); + return NULL; + } + ii = nifti_get_filesize( nim->iname ) ; + if( ii <= 0 ){ + if( g_opts.debug > 0 ) LNI_FERR(fname,"empty data file",nim->iname); + znzclose(fp); + return NULL; + } + ioff = (ii > ntot) ? ii-ntot : 0 ; + } else { /* non-negative offset */ + ioff = nim->iname_offset ; /* means use it directly */ + } + + /**- seek to the appropriate read position */ + if( znzseek(fp , (long)ioff , SEEK_SET) < 0 ){ + Rc_fprintf_stderr("** could not seek to offset %u in file '%s'\n", + (unsigned)ioff, nim->iname); + znzclose(fp); + return NULL; + } + + /**- and return the File pointer */ + return fp; +} + + +/*---------------------------------------------------------------------- + * nifti_image_load + *----------------------------------------------------------------------*/ +/*! \fn int nifti_image_load( nifti_image *nim ) + \brief Load the image blob into a previously initialized nifti_image. + + - If not yet set, the data buffer is allocated with calloc(). + - The data buffer will be byteswapped if necessary. + - The data buffer will not be scaled. + + This function is used to read the image from disk. It should be used + after a function such as nifti_image_read(), so that the nifti_image + structure is already initialized. + + \param nim pointer to a nifti_image (previously initialized) + \return 0 on success, -1 on failure + \sa nifti_image_read, nifti_image_free, nifti_image_unload +*/ +int nifti_image_load( nifti_image *nim ) +{ + /* set up data space, open data file and seek, then call nifti_read_buffer */ + size_t ntot , ii ; + znzFile fp ; + + /**- open the file and position the FILE pointer */ + fp = nifti_image_load_prep( nim ); + + if( fp == NULL ){ + if( g_opts.debug > 0 ) + Rc_fprintf_stderr("** nifti_image_load, failed load_prep\n"); + return -1; + } + + ntot = nifti_get_volsize(nim); + + /**- if the data pointer is not yet set, get memory space for the image */ + + if( nim->data == NULL ) + { + nim->data = (void *)calloc(1,ntot) ; /* create image memory */ + if( nim->data == NULL ){ + if( g_opts.debug > 0 ) + Rc_fprintf_stderr("** failed to alloc %d bytes for image data\n", + (int)ntot); + znzclose(fp); + return -1; + } + } + + /**- now that everything is set up, do the reading */ + ii = nifti_read_buffer(fp,nim->data,ntot,nim); + if( ii < ntot ){ + znzclose(fp) ; + free(nim->data) ; + nim->data = NULL ; + return -1 ; /* errors were printed in nifti_read_buffer() */ + } + + /**- close the file */ + znzclose( fp ) ; + + return 0 ; +} + + +/* 30 Nov 2004 [rickr] +#undef ERREX +#define ERREX(msg) \ + do{ Rc_fprintf_stderr("** ERROR: nifti_read_buffer: %s\n",(msg)) ; \ + return 0; } while(0) +*/ + +/*----------------------------------------------------------------------*/ +/*! read ntot bytes of data from an open file and byte swaps if necessary + + note that nifti_image is required for information on datatype, bsize + (for any needed byte swapping), etc. + + This function does not allocate memory, so dataptr must be valid. +*//*--------------------------------------------------------------------*/ +size_t nifti_read_buffer(znzFile fp, void* dataptr, size_t ntot, + nifti_image *nim) +{ + size_t ii; + + if( dataptr == NULL ){ + if( g_opts.debug > 0 ) + Rc_fprintf_stderr("** ERROR: nifti_read_buffer: NULL dataptr\n"); + return -1; + } + + ii = znzread( dataptr , 1 , ntot , fp ) ; /* data input */ + + /* if read was short, fail */ + if( ii < ntot ){ + if( g_opts.debug > 0 ) + Rc_fprintf_stderr("++ WARNING: nifti_read_buffer(%s):\n" + " data bytes needed = %u\n" + " data bytes input = %u\n" + " number missing = %u (set to 0)\n", + nim->iname , (unsigned int)ntot , + (unsigned int)ii , (unsigned int)(ntot-ii) ) ; + /* memset( (char *)(dataptr)+ii , 0 , ntot-ii ) ; now failure [rickr] */ + return -1 ; + } + + if( g_opts.debug > 2 ) + Rc_fprintf_stderr("+d nifti_read_buffer: read %u bytes\n", (unsigned)ii); + + /* byte swap array if needed */ + + /* ntot/swapsize might not fit as int, use size_t 6 Jul 2010 [rickr] */ + if( nim->swapsize > 1 && nim->byteorder != nifti_short_order() ) { + if( g_opts.debug > 1 ) + Rc_fprintf_stderr("+d nifti_read_buffer: swapping data bytes...\n"); + nifti_swap_Nbytes( (int)(ntot / nim->swapsize), nim->swapsize , dataptr ) ; + } + +#ifdef isfinite +{ + /* check input float arrays for goodness, and fix bad floats */ + int fix_count = 0 ; + + switch( nim->datatype ){ + + case NIFTI_TYPE_FLOAT32: + case NIFTI_TYPE_COMPLEX64:{ + register float *far = (float *)dataptr ; register size_t jj,nj ; + nj = ntot / sizeof(float) ; + for( jj=0 ; jj < nj ; jj++ ) /* count fixes 30 Nov 2004 [rickr] */ + if( !IS_GOOD_FLOAT(far[jj]) ){ + far[jj] = 0 ; + fix_count++ ; + } + } + break ; + + case NIFTI_TYPE_FLOAT64: + case NIFTI_TYPE_COMPLEX128:{ + register double *far = (double *)dataptr ; register size_t jj,nj ; + nj = ntot / sizeof(double) ; + for( jj=0 ; jj < nj ; jj++ ) /* count fixes 30 Nov 2004 [rickr] */ + if( !IS_GOOD_FLOAT(far[jj]) ){ + far[jj] = 0 ; + fix_count++ ; + } + } + break ; + + } + + if( g_opts.debug > 1 ) + Rc_fprintf_stderr("+d in image, %d bad floats were set to 0\n", fix_count); +} +#endif + + return ii; +} + +/*--------------------------------------------------------------------------*/ +/*! Unload the data in a nifti_image struct, but keep the metadata. +*//*------------------------------------------------------------------------*/ +void nifti_image_unload( nifti_image *nim ) +{ + if( nim != NULL && nim->data != NULL ){ + free(nim->data) ; nim->data = NULL ; + } + return ; +} + +/*--------------------------------------------------------------------------*/ +/*! free 'everything' about a nifti_image struct (including the passed struct) + + free (only fields which are not NULL): + - fname and iname + - data + - any ext_list[i].edata + - ext_list + - nim +*//*------------------------------------------------------------------------*/ +void nifti_image_free( nifti_image *nim ) +{ + if( nim == NULL ) return ; + if( nim->fname != NULL ) free(nim->fname) ; + if( nim->iname != NULL ) free(nim->iname) ; + if( nim->data != NULL ) free(nim->data ) ; + (void)nifti_free_extensions( nim ) ; + free(nim) ; return ; +} + + +/*--------------------------------------------------------------------------*/ +/*! free the nifti extensions + + - If any edata pointer is set in the extension list, free() it. + - Free ext_list, if it is set. + - Clear num_ext and ext_list from nim. + + \return 0 on success, -1 on error + + \sa nifti_add_extension, nifti_copy_extensions +*//*------------------------------------------------------------------------*/ +int nifti_free_extensions( nifti_image *nim ) +{ + int c ; + if( nim == NULL ) return -1; + if( nim->num_ext > 0 && nim->ext_list ){ + for( c = 0; c < nim->num_ext; c++ ) + if ( nim->ext_list[c].edata ) free(nim->ext_list[c].edata); + free(nim->ext_list); + } + /* or if it is inconsistent, warn the user (if we are not in quiet mode) */ + else if ( (nim->num_ext > 0 || nim->ext_list != NULL) && (g_opts.debug > 0) ) + Rc_fprintf_stderr("** warning: nifti extension num/ptr mismatch (%d,%p)\n", + nim->num_ext, (void *)nim->ext_list); + + if( g_opts.debug > 2 ) + Rc_fprintf_stderr("+d free'd %d extension(s)\n", nim->num_ext); + + nim->num_ext = 0; + nim->ext_list = NULL; + + return 0; +} + + +/*--------------------------------------------------------------------------*/ +/*! Print to stdout some info about a nifti_image struct. +*//*------------------------------------------------------------------------*/ +void nifti_image_infodump( const nifti_image *nim ) +{ + char *str = nifti_image_to_ascii( nim ) ; + /* stdout -> stderr 2 Dec 2004 [rickr] */ + if( str != NULL ){ Rc_fputs_stderr(str) ; free(str) ; } + return ; +} + + +/*-------------------------------------------------------------------------- + * nifti_write_buffer just check for a null znzFile and call znzwrite + *--------------------------------------------------------------------------*/ +/*! \fn size_t nifti_write_buffer(znzFile fp, void *buffer, size_t numbytes) + \brief write numbytes of buffer to file, fp + + \param fp File pointer (from znzopen) to gzippable nifti datafile + \param buffer data buffer to be written + \param numbytes number of bytes in buffer to write + \return number of bytes successfully written +*/ +size_t nifti_write_buffer(znzFile fp, const void *buffer, size_t numbytes) +{ + /* Write all the image data at once (no swapping here) */ + size_t ss; + if (znz_isnull(fp)){ + Rc_fprintf_stderr("** ERROR: nifti_write_buffer: null file pointer\n"); + return 0; + } + ss = znzwrite( (const void*)buffer , 1 , numbytes , fp ) ; + return ss; +} + + +/*----------------------------------------------------------------------*/ +/*! write the nifti_image data to file (from nim->data or from NBL) + + If NBL is not NULL, write the data from that structure. Otherwise, + write it out from nim->data. No swapping is done here. + + \param fp : File pointer + \param nim : nifti_image corresponding to the data + \param NBL : optional source of write data (if NULL use nim->data) + + \return 0 on success, -1 on failure + + Note: the nifti_image byte_order is set as that of the current CPU. + This is because such a conversion was made to the data upon + reading, while byte_order was not set (so the programs would + know what format the data was on disk). Effectively, since + byte_order should match what is on disk, it should bet set to + that of the current CPU whenever new filenames are assigned. +*//*--------------------------------------------------------------------*/ +int nifti_write_all_data(znzFile fp, nifti_image * nim, + const nifti_brick_list * NBL) +{ + size_t ss; + int bnum; + + if( !NBL ){ /* just write one buffer and get out of here */ + if( nim->data == NULL ){ + Rc_fprintf_stderr("** NWAD: no image data to write\n"); + return -1; + } + + ss = nifti_write_buffer(fp,nim->data,nim->nbyper * nim->nvox); + if (ss < nim->nbyper * nim->nvox){ + Rc_fprintf_stderr("** ERROR: NWAD: wrote only %u of %u bytes to file\n", + (unsigned)ss, (unsigned)(nim->nbyper * nim->nvox)); + return -1; + } + + if( g_opts.debug > 1 ) + Rc_fprintf_stderr("+d wrote single image of %u bytes\n", (unsigned)ss); + } else { + if( ! NBL->bricks || NBL->nbricks <= 0 || NBL->bsize <= 0 ){ + Rc_fprintf_stderr("** NWAD: no brick data to write (%p,%d,%u)\n", + (void *)NBL->bricks, NBL->nbricks, (unsigned)NBL->bsize); + return -1; + } + + for( bnum = 0; bnum < NBL->nbricks; bnum++ ){ + ss = nifti_write_buffer(fp, NBL->bricks[bnum], NBL->bsize); + if( ss < NBL->bsize ){ + Rc_fprintf_stderr("** NWAD ERROR: wrote %u of %u bytes of brick %d of %d to file", + (unsigned)ss, (unsigned)NBL->bsize, bnum+1, NBL->nbricks); + return -1; + } + } + if( g_opts.debug > 1 ) + Rc_fprintf_stderr("+d wrote image of %d brick(s), each of %u bytes\n", + NBL->nbricks, (unsigned int)NBL->bsize); + } + + /* mark as being in this CPU byte order */ + nim->byteorder = nifti_short_order() ; + + return 0; +} + +/* return number of extensions written, or -1 on error */ +static int nifti_write_extensions(znzFile fp, nifti_image *nim) +{ + nifti1_extension * list; + char extdr[4] = { 0, 0, 0, 0 }; + int c, size, ok = 1; + + if( znz_isnull(fp) || !nim || nim->num_ext < 0 ){ + if( g_opts.debug > 0 ) + Rc_fprintf_stderr("** nifti_write_extensions, bad params\n"); + return -1; + } + + /* if no extensions and user requests it, skip extender */ + if( g_opts.skip_blank_ext && (nim->num_ext == 0 || ! nim->ext_list ) ){ + if( g_opts.debug > 1 ) + Rc_fprintf_stderr("-d no exts and skip_blank_ext set, " + "so skipping 4-byte extender\n"); + return 0; + } + + /* if invalid extension list, clear num_ext */ + if( ! valid_nifti_extensions(nim) ) nim->num_ext = 0; + + /* write out extender block */ + if( nim->num_ext > 0 ) extdr[0] = 1; + if( nifti_write_buffer(fp, extdr, 4) != 4 ){ + Rc_fprintf_stderr("** failed to write extender\n"); + return -1; + } + + list = nim->ext_list; + for ( c = 0; c < nim->num_ext; c++ ){ + size = (int)nifti_write_buffer(fp, &list->esize, sizeof(int)); + ok = (size == (int)sizeof(int)); + if( ok ){ + size = (int)nifti_write_buffer(fp, &list->ecode, sizeof(int)); + ok = (size == (int)sizeof(int)); + } + if( ok ){ + size = (int)nifti_write_buffer(fp, list->edata, list->esize - 8); + ok = (size == list->esize - 8); + } + + if( !ok ){ + Rc_fprintf_stderr("** failed while writing extension #%d\n",c); + return -1; + } else if ( g_opts.debug > 2 ) + Rc_fprintf_stderr("+d wrote extension %d of %d bytes\n", c, size); + + list++; + } + + if( g_opts.debug > 1 ) + Rc_fprintf_stderr("+d wrote out %d extension(s)\n", nim->num_ext); + + return nim->num_ext; +} + + +/*----------------------------------------------------------------------*/ +/*! basic initialization of a nifti_image struct (to a 1x1x1 image) +*//*--------------------------------------------------------------------*/ +nifti_image* nifti_simple_init_nim(void) +{ + nifti_image *nim; + struct nifti_1_header nhdr; + int nbyper, swapsize; + + memset(&nhdr,0,sizeof(nhdr)) ; /* zero out header, to be safe */ + + nhdr.sizeof_hdr = sizeof(nhdr) ; + nhdr.regular = 'r' ; /* for some stupid reason */ + + nhdr.dim[0] = 3 ; + nhdr.dim[1] = 1 ; nhdr.dim[2] = 1 ; nhdr.dim[3] = 1 ; + nhdr.dim[4] = 0 ; + + nhdr.pixdim[0] = 0.0f ; + nhdr.pixdim[1] = 1.0f ; nhdr.pixdim[2] = 1.0f ; + nhdr.pixdim[3] = 1.0f ; + + nhdr.datatype = DT_FLOAT32 ; + nifti_datatype_sizes( nhdr.datatype , &nbyper, &swapsize ); + nhdr.bitpix = 8 * nbyper ; + + strcpy(nhdr.magic, "n+1"); /* init to single file */ + + nim = nifti_convert_nhdr2nim(nhdr,NULL); + nim->fname = NULL; + nim->iname = NULL; + return nim; +} + + +/*----------------------------------------------------------------------*/ +/*! basic initialization of a nifti_1_header struct (with given dimensions) + + Return an allocated nifti_1_header struct, based on the given + dimensions and datatype. + + \param arg_dims : optional dim[8] array (default {3,1,1,1,0,0,0,0}) + \param arg_dtype : optional datatype (default DT_FLOAT32) + + \return pointer to allocated nifti_1_header struct +*//*--------------------------------------------------------------------*/ +nifti_1_header * nifti_make_new_header(const int arg_dims[], int arg_dtype) +{ + nifti_1_header * nhdr; + const int default_dims[8] = { 3, 1, 1, 1, 0, 0, 0, 0 }; + const int * dim; /* either passed or default dims */ + int dtype; /* either passed or default dtype */ + int c, nbyper, swapsize; + + /* if arg_dims is passed, apply it */ + if( arg_dims ) dim = arg_dims; + else dim = default_dims; + + /* validate dim: if there is any problem, apply default_dims */ + if( dim[0] < 1 || dim[0] > 7 ) { + Rc_fprintf_stderr("** nifti_simple_hdr_with_dims: bad dim[0]=%d\n",dim[0]); + dim = default_dims; + } else { + for( c = 1; c <= dim[0]; c++ ) + if( dim[c] < 1 ) + { + Rc_fprintf_stderr("** nifti_simple_hdr_with_dims: bad dim[%d]=%d\n",c,dim[c]); + dim = default_dims; + break; + } + } + + /* validate dtype, too */ + dtype = arg_dtype; + if( ! nifti_is_valid_datatype(dtype) ) { + Rc_fprintf_stderr("** nifti_simple_hdr_with_dims: bad dtype %d\n",dtype); + dtype = DT_FLOAT32; + } + + /* now populate the header struct */ + + if( g_opts.debug > 1 ) + Rc_fprintf_stderr("+d nifti_make_new_header, dim[0] = %d, datatype = %d\n", + dim[0], dtype); + + nhdr = (nifti_1_header *)calloc(1,sizeof(nifti_1_header)); + if( !nhdr ){ + Rc_fprintf_stderr("** nifti_make_new_header: failed to alloc hdr\n"); + return NULL; + } + + nhdr->sizeof_hdr = sizeof(nifti_1_header) ; + nhdr->regular = 'r' ; /* for some stupid reason */ + + /* init dim and pixdim */ + nhdr->dim[0] = dim[0] ; + nhdr->pixdim[0] = 0.0f; + for( c = 1; c <= dim[0]; c++ ) { + nhdr->dim[c] = dim[c]; + nhdr->pixdim[c] = 1.0f; + } + + nhdr->datatype = dtype ; + nifti_datatype_sizes( nhdr->datatype , &nbyper, &swapsize ); + nhdr->bitpix = 8 * nbyper ; + + strcpy(nhdr->magic, "n+1"); /* init to single file */ + + return nhdr; +} + + +/*----------------------------------------------------------------------*/ +/*! basic creation of a nifti_image struct + + Create a nifti_image from the given dimensions and data type. + Optinally, allocate zero-filled data. + + \param dims : optional dim[8] (default {3,1,1,1,0,0,0,0}) + \param datatype : optional datatype (default DT_FLOAT32) + \param data_fill : if flag is set, allocate zero-filled data for image + + \return pointer to allocated nifti_image struct +*//*--------------------------------------------------------------------*/ +nifti_image * nifti_make_new_nim(const int dims[], int datatype, int data_fill) +{ + nifti_image * nim; + nifti_1_header * nhdr; + + nhdr = nifti_make_new_header(dims, datatype); + if( !nhdr ) return NULL; /* error already printed */ + + nim = nifti_convert_nhdr2nim(*nhdr,NULL); + free(nhdr); /* in any case, we are done with this */ + if( !nim ){ + Rc_fprintf_stderr("** NMNN: nifti_convert_nhdr2nim failure\n"); + return NULL; + } + + if( g_opts.debug > 1 ) + Rc_fprintf_stderr("+d nifti_make_new_nim, data_fill = %d\n",data_fill); + + if( data_fill ) { + nim->data = calloc(nim->nvox, nim->nbyper); + + /* if we cannot allocate data, take ball and go home */ + if( !nim->data ) { + Rc_fprintf_stderr("** NMNN: failed to alloc %u bytes for data\n", + (unsigned)(nim->nvox*nim->nbyper)); + nifti_image_free(nim); + nim = NULL; + } + } + + return nim; +} + + +/*----------------------------------------------------------------------*/ +/*! convert a nifti_image structure to a nifti_1_header struct + + No allocation is done, this should be used via structure copy. + As in: +
+    nifti_1_header my_header;
+    my_header = nifti_convert_nim2nhdr(my_nim_pointer);
+    
+*//*--------------------------------------------------------------------*/ +struct nifti_1_header nifti_convert_nim2nhdr(const nifti_image * nim) +{ + struct nifti_1_header nhdr; + + memset(&nhdr,0,sizeof(nhdr)) ; /* zero out header, to be safe */ + + + /**- load the ANALYZE-7.5 generic parts of the header struct */ + + nhdr.sizeof_hdr = sizeof(nhdr) ; + nhdr.regular = 'r' ; /* for some stupid reason */ + + nhdr.dim[0] = nim->ndim ; + nhdr.dim[1] = nim->nx ; nhdr.dim[2] = nim->ny ; nhdr.dim[3] = nim->nz ; + nhdr.dim[4] = nim->nt ; nhdr.dim[5] = nim->nu ; nhdr.dim[6] = nim->nv ; + nhdr.dim[7] = nim->nw ; + + nhdr.pixdim[0] = 0.0f ; + nhdr.pixdim[1] = nim->dx ; nhdr.pixdim[2] = nim->dy ; + nhdr.pixdim[3] = nim->dz ; nhdr.pixdim[4] = nim->dt ; + nhdr.pixdim[5] = nim->du ; nhdr.pixdim[6] = nim->dv ; + nhdr.pixdim[7] = nim->dw ; + + nhdr.datatype = nim->datatype ; + nhdr.bitpix = 8 * nim->nbyper ; + + if( nim->cal_max > nim->cal_min ){ + nhdr.cal_max = nim->cal_max ; + nhdr.cal_min = nim->cal_min ; + } + + if( nim->scl_slope != 0.0 ){ + nhdr.scl_slope = nim->scl_slope ; + nhdr.scl_inter = nim->scl_inter ; + } + + if( nim->descrip[0] != '\0' ){ + memcpy(nhdr.descrip ,nim->descrip ,79) ; nhdr.descrip[79] = '\0' ; + } + if( nim->aux_file[0] != '\0' ){ + memcpy(nhdr.aux_file ,nim->aux_file ,23) ; nhdr.aux_file[23] = '\0' ; + } + + /**- Load NIFTI specific stuff into the header */ + + if( nim->nifti_type > NIFTI_FTYPE_ANALYZE ){ /* then not ANALYZE */ + + if( nim->nifti_type == NIFTI_FTYPE_NIFTI1_1 ) strcpy(nhdr.magic,"n+1") ; + else strcpy(nhdr.magic,"ni1") ; + + nhdr.pixdim[1] = (float)fabs(nhdr.pixdim[1]) ; nhdr.pixdim[2] = (float)fabs(nhdr.pixdim[2]) ; + nhdr.pixdim[3] = (float)fabs(nhdr.pixdim[3]) ; nhdr.pixdim[4] = (float)fabs(nhdr.pixdim[4]) ; + nhdr.pixdim[5] = (float)fabs(nhdr.pixdim[5]) ; nhdr.pixdim[6] = (float)fabs(nhdr.pixdim[6]) ; + nhdr.pixdim[7] = (float)fabs(nhdr.pixdim[7]) ; + + nhdr.intent_code = nim->intent_code ; + nhdr.intent_p1 = nim->intent_p1 ; + nhdr.intent_p2 = nim->intent_p2 ; + nhdr.intent_p3 = nim->intent_p3 ; + if( nim->intent_name[0] != '\0' ){ + memcpy(nhdr.intent_name,nim->intent_name,15) ; + nhdr.intent_name[15] = '\0' ; + } + + nhdr.vox_offset = (float) nim->iname_offset ; + nhdr.xyzt_units = SPACE_TIME_TO_XYZT( nim->xyz_units, nim->time_units ) ; + nhdr.toffset = nim->toffset ; + + if( nim->qform_code > 0 ){ + nhdr.qform_code = nim->qform_code ; + nhdr.quatern_b = nim->quatern_b ; + nhdr.quatern_c = nim->quatern_c ; + nhdr.quatern_d = nim->quatern_d ; + nhdr.qoffset_x = nim->qoffset_x ; + nhdr.qoffset_y = nim->qoffset_y ; + nhdr.qoffset_z = nim->qoffset_z ; + nhdr.pixdim[0] = (nim->qfac >= 0.0) ? 1.0f : -1.0f ; + } + + if( nim->sform_code > 0 ){ + nhdr.sform_code = nim->sform_code ; + nhdr.srow_x[0] = nim->sto_xyz.m[0][0] ; + nhdr.srow_x[1] = nim->sto_xyz.m[0][1] ; + nhdr.srow_x[2] = nim->sto_xyz.m[0][2] ; + nhdr.srow_x[3] = nim->sto_xyz.m[0][3] ; + nhdr.srow_y[0] = nim->sto_xyz.m[1][0] ; + nhdr.srow_y[1] = nim->sto_xyz.m[1][1] ; + nhdr.srow_y[2] = nim->sto_xyz.m[1][2] ; + nhdr.srow_y[3] = nim->sto_xyz.m[1][3] ; + nhdr.srow_z[0] = nim->sto_xyz.m[2][0] ; + nhdr.srow_z[1] = nim->sto_xyz.m[2][1] ; + nhdr.srow_z[2] = nim->sto_xyz.m[2][2] ; + nhdr.srow_z[3] = nim->sto_xyz.m[2][3] ; + } + + nhdr.dim_info = FPS_INTO_DIM_INFO( nim->freq_dim , + nim->phase_dim , nim->slice_dim ) ; + nhdr.slice_code = nim->slice_code ; + nhdr.slice_start = nim->slice_start ; + nhdr.slice_end = nim->slice_end ; + nhdr.slice_duration = nim->slice_duration ; + } + + return nhdr; +} + + +/*----------------------------------------------------------------------*/ +/*! \fn int nifti_copy_extensions(nifti_image * nim_dest, nifti_image * nim_src) + \brief copy the nifti1_extension list from src to dest + + Duplicate the list of nifti1_extensions. The dest structure must + be clear of extensions. + \return 0 on success, -1 on failure + + \sa nifti_add_extension, nifti_free_extensions +*/ +int nifti_copy_extensions(nifti_image * nim_dest, const nifti_image * nim_src) +{ + char * data; + size_t bytes; + int c, size, old_size; + + if( nim_dest->num_ext > 0 || nim_dest->ext_list != NULL ){ + Rc_fprintf_stderr("** will not copy extensions over existing ones\n"); + return -1; + } + + if( g_opts.debug > 1 ) + Rc_fprintf_stderr("+d duplicating %d extension(s)\n", nim_src->num_ext); + + if( nim_src->num_ext <= 0 ) return 0; + + bytes = nim_src->num_ext * sizeof(nifti1_extension); /* I'm lazy */ + nim_dest->ext_list = (nifti1_extension *)malloc(bytes); + if( !nim_dest->ext_list ){ + Rc_fprintf_stderr("** failed to allocate %d nifti1_extension structs\n", + nim_src->num_ext); + return -1; + } + + /* copy the extension data */ + nim_dest->num_ext = 0; + for( c = 0; c < nim_src->num_ext; c++ ){ + size = old_size = nim_src->ext_list[c].esize; + if( size & 0xf ) size = (size + 0xf) & ~0xf; /* make multiple of 16 */ + if( g_opts.debug > 2 ) + Rc_fprintf_stderr("+d dup'ing ext #%d of size %d (from size %d)\n", + c, size, old_size); + /* data length is size-8, as esize includes space for esize and ecode */ + data = (char *)calloc(size-8,sizeof(char)); /* maybe size > old */ + if( !data ){ + Rc_fprintf_stderr("** failed to alloc %d bytes for extention\n", size); + if( c == 0 ) { free(nim_dest->ext_list); nim_dest->ext_list = NULL; } + /* otherwise, keep what we have (a.o.t. deleting them all) */ + return -1; + } + /* finally, fill the new structure */ + nim_dest->ext_list[c].esize = size; + nim_dest->ext_list[c].ecode = nim_src->ext_list[c].ecode; + nim_dest->ext_list[c].edata = data; + memcpy(data, nim_src->ext_list[c].edata, old_size-8); + + nim_dest->num_ext++; + } + + return 0; +} + + +/*----------------------------------------------------------------------*/ +/*! compute the total size of all extensions + + \return the total of all esize fields + + Note that each esize includes 4 bytes for ecode, 4 bytes for esize, + and the bytes used for the data. Each esize also needs to be a + multiple of 16, so it may be greater than the sum of its 3 parts. +*//*--------------------------------------------------------------------*/ +int nifti_extension_size(nifti_image *nim) +{ + int c, size = 0; + + if( !nim || nim->num_ext <= 0 ) return 0; + + if( g_opts.debug > 2 ) Rc_fprintf_stderr("-d ext sizes:"); + + for ( c = 0; c < nim->num_ext; c++ ){ + size += nim->ext_list[c].esize; + if( g_opts.debug > 2 ) Rc_fprintf_stderr(" %d",nim->ext_list[c].esize); + } + + if( g_opts.debug > 2 ) Rc_fprintf_stderr(" (total = %d)\n",size); + + return size; +} + + +/*----------------------------------------------------------------------*/ +/*! set the nifti_image iname_offset field, based on nifti_type + + - if writing to 2 files, set offset to 0 + - if writing to a single NIFTI-1 file, set the offset to + 352 + total extension size, then align to 16-byte boundary + - if writing an ASCII header, set offset to -1 +*//*--------------------------------------------------------------------*/ +void nifti_set_iname_offset(nifti_image *nim) +{ + int offset; + + switch( nim->nifti_type ){ + + default: /* writing into 2 files */ + /* we only write files with 0 offset in the 2 file format */ + nim->iname_offset = 0 ; + break ; + + /* NIFTI-1 single binary file - always update */ + case NIFTI_FTYPE_NIFTI1_1: + offset = nifti_extension_size(nim)+sizeof(struct nifti_1_header)+4; + /* be sure offset is aligned to a 16 byte boundary */ + if ( ( offset % 16 ) != 0 ) offset = ((offset + 0xf) & ~0xf); + if( nim->iname_offset != offset ){ + if( g_opts.debug > 1 ) + Rc_fprintf_stderr("+d changing offset from %d to %d\n", + nim->iname_offset, offset); + nim->iname_offset = offset; + } + break ; + + /* non-standard case: NIFTI-1 ASCII header + binary data (single file) */ + case NIFTI_FTYPE_ASCII: + nim->iname_offset = -1 ; /* compute offset from filesize */ + break ; + } +} + + +/*----------------------------------------------------------------------*/ +/*! write the nifti_image dataset to disk, optionally including data + + This is just a front-end for nifti_image_write_hdr_img2. + + \param nim nifti_image to write to disk + \param write_data write options (see nifti_image_write_hdr_img2) + \param opts file open options ("wb" from nifti_image_write) + + \sa nifti_image_write, nifti_image_write_hdr_img2, nifti_image_free, + nifti_set_filenames +*//*--------------------------------------------------------------------*/ +znzFile nifti_image_write_hdr_img( nifti_image *nim , int write_data , + const char* opts ) +{ + return nifti_image_write_hdr_img2(nim,write_data,opts,NULL,NULL); +} + + +#undef ERREX +#define ERREX(msg) \ + do{ Rc_fprintf_stderr("** ERROR: nifti_image_write_hdr_img: %s\n",(msg)) ; \ + return fp ; } while(0) + + +/* ----------------------------------------------------------------------*/ +/*! This writes the header (and optionally the image data) to file + * + * If the image data file is left open it returns a valid znzFile handle. + * It also uses imgfile as the open image file is not null, and modifies + * it inside. + * + * \param nim nifti_image to write to disk + * \param write_opts flags whether to write data and/or close file (see below) + * \param opts file-open options, probably "wb" from nifti_image_write() + * \param imgfile optional open znzFile struct, for writing image data + (may be NULL) + * \param NBL optional nifti_brick_list, containing the image data + (may be NULL) + * + * Values for write_opts mode are based on two binary flags + * ( 0/1 for no-write/write data, and 0/2 for close/leave-open files ) : + * - 0 = do not write data and close (do not open data file) + * - 1 = write data and close + * - 2 = do not write data and leave data file open + * - 3 = write data and leave data file open + * + * \sa nifti_image_write, nifti_image_write_hdr_img, nifti_image_free, + * nifti_set_filenames +*//*---------------------------------------------------------------------*/ +znzFile nifti_image_write_hdr_img2(nifti_image *nim, int write_opts, + const char * opts, znzFile imgfile, const nifti_brick_list * NBL) +{ + struct nifti_1_header nhdr ; + znzFile fp=NULL; + size_t ss ; + int write_data, leave_open; + char func[] = { "nifti_image_write_hdr_img2" }; + + write_data = write_opts & 1; /* just separate the bits now */ + leave_open = write_opts & 2; + + if( ! nim ) ERREX("NULL input") ; + if( ! nifti_validfilename(nim->fname) ) ERREX("bad fname input") ; + if( write_data && ! nim->data && ! NBL ) ERREX("no image data") ; + + if( write_data && NBL && ! nifti_NBL_matches_nim(nim, NBL) ) + ERREX("NBL does not match nim"); + + nifti_set_iname_offset(nim); + + if( g_opts.debug > 1 ){ + Rc_fprintf_stderr("-d writing nifti file '%s'...\n", nim->fname); + if( g_opts.debug > 2 ) + Rc_fprintf_stderr("-d nifti type %d, offset %d\n", + nim->nifti_type, nim->iname_offset); + } + + if( nim->nifti_type == NIFTI_FTYPE_ASCII ) /* non-standard case */ + return nifti_write_ascii_image(nim,NBL,opts,write_data,leave_open); + + nhdr = nifti_convert_nim2nhdr(nim); /* create the nifti1_header struct */ + + /* if writing to 2 files, make sure iname is set and different from fname */ + if( nim->nifti_type != NIFTI_FTYPE_NIFTI1_1 ){ + if( nim->iname && strcmp(nim->iname,nim->fname) == 0 ){ + free(nim->iname) ; nim->iname = NULL ; + } + if( nim->iname == NULL ){ /* then make a new one */ + nim->iname = nifti_makeimgname(nim->fname,nim->nifti_type,0,0); + if( nim->iname == NULL ) return NULL; + } + } + + /* if we have an imgfile and will write the header there, use it */ + if( ! znz_isnull(imgfile) && nim->nifti_type == NIFTI_FTYPE_NIFTI1_1 ){ + if( g_opts.debug > 2 ) Rc_fprintf_stderr("+d using passed file for hdr\n"); + fp = imgfile; + } + else { + if( g_opts.debug > 2 ) + Rc_fprintf_stderr("+d opening output file %s [%s]\n",nim->fname,opts); + fp = znzopen( nim->fname , opts , nifti_is_gzfile(nim->fname) ) ; + if( znz_isnull(fp) ){ + LNI_FERR(func,"cannot open output file",nim->fname); + return fp; + } + } + + /* write the header and extensions */ + + ss = znzwrite(&nhdr , 1 , sizeof(nhdr) , fp); /* write header */ + if( ss < sizeof(nhdr) ){ + LNI_FERR(func,"bad header write to output file",nim->fname); + znzclose(fp); return fp; + } + + /* partial file exists, and errors have been printed, so ignore return */ + if( nim->nifti_type != NIFTI_FTYPE_ANALYZE ) + (void)nifti_write_extensions(fp,nim); + + /* if the header is all we want, we are done */ + if( ! write_data && ! leave_open ){ + if( g_opts.debug > 2 ) Rc_fprintf_stderr("-d header is all we want: done\n"); + znzclose(fp); return(fp); + } + + if( nim->nifti_type != NIFTI_FTYPE_NIFTI1_1 ){ /* get a new file pointer */ + znzclose(fp); /* first, close header file */ + if( ! znz_isnull(imgfile) ){ + if(g_opts.debug > 2) Rc_fprintf_stderr("+d using passed file for img\n"); + fp = imgfile; + } + else { + if( g_opts.debug > 2 ) + Rc_fprintf_stderr("+d opening img file '%s'\n", nim->iname); + fp = znzopen( nim->iname , opts , nifti_is_gzfile(nim->iname) ) ; + if( znz_isnull(fp) ) ERREX("cannot open image file") ; + } + } + + znzseek(fp, nim->iname_offset, SEEK_SET); /* in any case, seek to offset */ + + if( write_data ) nifti_write_all_data(fp,nim,NBL); + if( ! leave_open ) znzclose(fp); + + return fp; +} + + +/*----------------------------------------------------------------------*/ +/*! write a nifti_image to disk in ASCII format +*//*--------------------------------------------------------------------*/ +znzFile nifti_write_ascii_image(nifti_image *nim, const nifti_brick_list * NBL, + const char *opts, int write_data, int leave_open) +{ + znzFile fp; + char * hstr; + + hstr = nifti_image_to_ascii( nim ) ; /* get header in ASCII form */ + if( ! hstr ){ Rc_fprintf_stderr("** failed image_to_ascii()\n"); return NULL; } + + fp = znzopen( nim->fname , opts , nifti_is_gzfile(nim->fname) ) ; + if( znz_isnull(fp) ){ + free(hstr); + Rc_fprintf_stderr("** failed to open '%s' for ascii write\n",nim->fname); + return fp; + } + + znzputs(hstr,fp); /* header */ + nifti_write_extensions(fp,nim); /* extensions */ + + if ( write_data ) { nifti_write_all_data(fp,nim,NBL); } /* data */ + if ( ! leave_open ) { znzclose(fp); } + free(hstr); + return fp; /* returned but may be closed */ +} + + +/*--------------------------------------------------------------------------*/ +/*! Write a nifti_image to disk. + + Since data is properly byte-swapped upon reading, it is assumed + to be in the byte-order of the current CPU at write time. Thus, + nim->byte_order should match that of the current CPU. Note that + the nifti_set_filenames() function takes the flag, set_byte_order. + + The following fields of nim affect how the output appears: + - nifti_type = 0 ==> ANALYZE-7.5 format file pair will be written + - nifti_type = 1 ==> NIFTI-1 format single file will be written + (data offset will be 352+extensions) + - nifti_type = 2 ==> NIFTI_1 format file pair will be written + - nifti_type = 3 ==> NIFTI_1 ASCII single file will be written + - fname is the name of the output file (header or header+data) + - if a file pair is being written, iname is the name of the data file + - existing files WILL be overwritten with extreme prejudice + - if qform_code > 0, the quatern_*, qoffset_*, and qfac fields determine + the qform output, NOT the qto_xyz matrix; if you want to compute these + fields from the qto_xyz matrix, you can use the utility function + nifti_mat44_to_quatern() + + \sa nifti_image_write_bricks, nifti_image_free, nifti_set_filenames, + nifti_image_write_hdr_img +*//*------------------------------------------------------------------------*/ +void nifti_image_write( nifti_image *nim ) +{ + znzFile fp = nifti_image_write_hdr_img(nim,1,"wb"); + if( fp ){ + if( g_opts.debug > 2 ) Rc_fprintf_stderr("-d niw: done with znzFile\n"); + free(fp); + } + if( g_opts.debug > 1 ) Rc_fprintf_stderr("-d nifti_image_write: done\n"); +} + + +/*----------------------------------------------------------------------*/ +/*! similar to nifti_image_write, but data is in NBL struct, not nim->data + + \sa nifti_image_write, nifti_image_free, nifti_set_filenames, nifti_free_NBL +*//*--------------------------------------------------------------------*/ +void nifti_image_write_bricks( nifti_image *nim, const nifti_brick_list * NBL ) +{ + znzFile fp = nifti_image_write_hdr_img2(nim,1,"wb",NULL,NBL); + if( fp ){ + if( g_opts.debug > 2 ) Rc_fprintf_stderr("-d niwb: done with znzFile\n"); + free(fp); + } + if( g_opts.debug > 1 ) Rc_fprintf_stderr("-d niwb: done writing bricks\n"); +} + + +/*----------------------------------------------------------------------*/ +/*! copy the nifti_image structure, without data + + Duplicate the structure, including fname, iname and extensions. + Leave the data pointer as NULL. +*//*--------------------------------------------------------------------*/ +nifti_image * nifti_copy_nim_info(const nifti_image * src) +{ + nifti_image *dest; + dest = (nifti_image *)calloc(1,sizeof(nifti_image)); + if( !dest ){ + Rc_fprintf_stderr("** NCNI: failed to alloc nifti_image\n"); + return NULL; + } + memcpy(dest, src, sizeof(nifti_image)); + if( src->fname ) dest->fname = nifti_strdup(src->fname); + if( src->iname ) dest->iname = nifti_strdup(src->iname); + dest->num_ext = 0; + dest->ext_list = NULL; + /* errors will be printed in NCE(), continue in either case */ + (void)nifti_copy_extensions(dest, src); + + dest->data = NULL; + + return dest; +} + + +/*------------------------------------------------------------------------*/ +/* Un-escape a C string in place -- that is, convert XML escape sequences + back into their characters. (This can be done in place since the + replacement is always smaller than the input.) Escapes recognized are: + - < -> < + - > -> > + - " -> " + - ' -> ' + - & -> & + Also replace CR LF pair (Microsoft), or CR alone (Macintosh) with + LF (Unix), per the XML standard. + Return value is number of replacements made (if you care). +--------------------------------------------------------------------------*/ + +#undef CR +#undef LF +#define CR 0x0D +#define LF 0x0A + +static int unescape_string( char *str ) +{ + int ii,jj , nn,ll ; + + if( str == NULL ) return 0 ; /* no string? */ + ll = (int)strlen(str) ; if( ll == 0 ) return 0 ; + + /* scan for escapes: &something; */ + + for( ii=jj=nn=0 ; ii': lout += 4 ; break ; /* replace '<' with "<" */ + + case '"' : + case '\'': lout += 6 ; break ; /* replace '"' with """ */ + + case CR: + case LF: lout += 6 ; break ; /* replace CR with " " + LF with " " */ + + default: lout++ ; break ; /* copy all other chars */ + } + } + out = (char *)calloc(1,lout) ; /* allocate output string */ + if( !out ){ + Rc_fprintf_stderr("** escapize_string: failed to alloc %d bytes\n",lout); + return NULL; + } + out[0] = '\'' ; /* opening quote mark */ + for( ii=0,jj=1 ; ii < lstr ; ii++ ){ + switch( str[ii] ){ + default: out[jj++] = str[ii] ; break ; /* normal characters */ + + case '&': memcpy(out+jj,"&",5) ; jj+=5 ; break ; + + case '<': memcpy(out+jj,"<",4) ; jj+=4 ; break ; + case '>': memcpy(out+jj,">",4) ; jj+=4 ; break ; + + case '"' : memcpy(out+jj,""",6) ; jj+=6 ; break ; + + case '\'': memcpy(out+jj,"'",6) ; jj+=6 ; break ; + + case CR: memcpy(out+jj," ",6) ; jj+=6 ; break ; + case LF: memcpy(out+jj," ",6) ; jj+=6 ; break ; + } + } + out[jj++] = '\'' ; /* closing quote mark */ + out[jj] = '\0' ; /* terminate the string */ + return out ; +} + +/*---------------------------------------------------------------------------*/ +/*! Dump the information in a NIFTI image header to an XML-ish ASCII string + that can later be converted back into a NIFTI header in + nifti_image_from_ascii(). + + The resulting string can be free()-ed when you are done with it. +*//*-------------------------------------------------------------------------*/ +char *nifti_image_to_ascii( const nifti_image *nim ) +{ + char *buf , *ebuf ; int nbuf ; + + if( nim == NULL ) return NULL ; /* stupid caller */ + + buf = (char *)calloc(1,65534); nbuf = 0; /* longer than needed, to be safe */ + if( !buf ){ + Rc_fprintf_stderr("** NITA: failed to alloc %d bytes\n",65534); + return NULL; + } + + sprintf( buf , "nifti_type == NIFTI_FTYPE_NIFTI1_1) ? "NIFTI-1+" + :(nim->nifti_type == NIFTI_FTYPE_NIFTI1_2) ? "NIFTI-1" + :(nim->nifti_type == NIFTI_FTYPE_ASCII ) ? "NIFTI-1A" + : "ANALYZE-7.5" ) ; + + /** Strings that we don't control (filenames, etc.) that might + contain "weird" characters (like quotes) are "escaped": + - A few special characters are replaced by XML-style escapes, using + the function escapize_string(). + - On input, function unescape_string() reverses this process. + - The result is that the NIFTI ASCII-format header is XML-compliant. */ + + ebuf = escapize_string(nim->fname) ; + sprintf( buf+strlen(buf) , " header_filename = %s\n",ebuf); free(ebuf); + + ebuf = escapize_string(nim->iname) ; + sprintf( buf+strlen(buf) , " image_filename = %s\n", ebuf); free(ebuf); + + sprintf( buf+strlen(buf) , " image_offset = '%d'\n" , nim->iname_offset ); + + sprintf( buf+strlen(buf), " ndim = '%d'\n", nim->ndim); + sprintf( buf+strlen(buf), " nx = '%d'\n", nim->nx ); + if( nim->ndim > 1 ) sprintf( buf+strlen(buf), " ny = '%d'\n", nim->ny ); + if( nim->ndim > 2 ) sprintf( buf+strlen(buf), " nz = '%d'\n", nim->nz ); + if( nim->ndim > 3 ) sprintf( buf+strlen(buf), " nt = '%d'\n", nim->nt ); + if( nim->ndim > 4 ) sprintf( buf+strlen(buf), " nu = '%d'\n", nim->nu ); + if( nim->ndim > 5 ) sprintf( buf+strlen(buf), " nv = '%d'\n", nim->nv ); + if( nim->ndim > 6 ) sprintf( buf+strlen(buf), " nw = '%d'\n", nim->nw ); + sprintf( buf+strlen(buf), " dx = '%g'\n", nim->dx ); + if( nim->ndim > 1 ) sprintf( buf+strlen(buf), " dy = '%g'\n", nim->dy ); + if( nim->ndim > 2 ) sprintf( buf+strlen(buf), " dz = '%g'\n", nim->dz ); + if( nim->ndim > 3 ) sprintf( buf+strlen(buf), " dt = '%g'\n", nim->dt ); + if( nim->ndim > 4 ) sprintf( buf+strlen(buf), " du = '%g'\n", nim->du ); + if( nim->ndim > 5 ) sprintf( buf+strlen(buf), " dv = '%g'\n", nim->dv ); + if( nim->ndim > 6 ) sprintf( buf+strlen(buf), " dw = '%g'\n", nim->dw ); + + sprintf( buf+strlen(buf) , " datatype = '%d'\n" , nim->datatype ) ; + sprintf( buf+strlen(buf) , " datatype_name = '%s'\n" , + nifti_datatype_string(nim->datatype) ) ; + + sprintf( buf+strlen(buf) , " nvox = '%u'\n" , (unsigned)nim->nvox ) ; + sprintf( buf+strlen(buf) , " nbyper = '%d'\n" , nim->nbyper ) ; + + sprintf( buf+strlen(buf) , " byteorder = '%s'\n" , + (nim->byteorder==MSB_FIRST) ? "MSB_FIRST" : "LSB_FIRST" ) ; + + if( nim->cal_min < nim->cal_max ){ + sprintf( buf+strlen(buf) , " cal_min = '%g'\n", nim->cal_min ) ; + sprintf( buf+strlen(buf) , " cal_max = '%g'\n", nim->cal_max ) ; + } + + if( nim->scl_slope != 0.0 ){ + sprintf( buf+strlen(buf) , " scl_slope = '%g'\n" , nim->scl_slope ) ; + sprintf( buf+strlen(buf) , " scl_inter = '%g'\n" , nim->scl_inter ) ; + } + + if( nim->intent_code > 0 ){ + sprintf( buf+strlen(buf) , " intent_code = '%d'\n", nim->intent_code ) ; + sprintf( buf+strlen(buf) , " intent_code_name = '%s'\n" , + nifti_intent_string(nim->intent_code) ) ; + sprintf( buf+strlen(buf) , " intent_p1 = '%g'\n" , nim->intent_p1 ) ; + sprintf( buf+strlen(buf) , " intent_p2 = '%g'\n" , nim->intent_p2 ) ; + sprintf( buf+strlen(buf) , " intent_p3 = '%g'\n" , nim->intent_p3 ) ; + + if( nim->intent_name[0] != '\0' ){ + ebuf = escapize_string(nim->intent_name) ; + sprintf( buf+strlen(buf) , " intent_name = %s\n",ebuf) ; + free(ebuf) ; + } + } + + if( nim->toffset != 0.0 ) + sprintf( buf+strlen(buf) , " toffset = '%g'\n",nim->toffset ) ; + + if( nim->xyz_units > 0 ) + sprintf( buf+strlen(buf) , + " xyz_units = '%d'\n" + " xyz_units_name = '%s'\n" , + nim->xyz_units , nifti_units_string(nim->xyz_units) ) ; + + if( nim->time_units > 0 ) + sprintf( buf+strlen(buf) , + " time_units = '%d'\n" + " time_units_name = '%s'\n" , + nim->time_units , nifti_units_string(nim->time_units) ) ; + + if( nim->freq_dim > 0 ) + sprintf( buf+strlen(buf) , " freq_dim = '%d'\n",nim->freq_dim ) ; + if( nim->phase_dim > 0 ) + sprintf( buf+strlen(buf) , " phase_dim = '%d'\n",nim->phase_dim ) ; + if( nim->slice_dim > 0 ) + sprintf( buf+strlen(buf) , " slice_dim = '%d'\n",nim->slice_dim ) ; + if( nim->slice_code > 0 ) + sprintf( buf+strlen(buf) , + " slice_code = '%d'\n" + " slice_code_name = '%s'\n" , + nim->slice_code , nifti_slice_string(nim->slice_code) ) ; + if( nim->slice_start >= 0 && nim->slice_end > nim->slice_start ) + sprintf( buf+strlen(buf) , + " slice_start = '%d'\n" + " slice_end = '%d'\n" , nim->slice_start , nim->slice_end ) ; + if( nim->slice_duration != 0.0 ) + sprintf( buf+strlen(buf) , " slice_duration = '%g'\n", + nim->slice_duration ) ; + + if( nim->descrip[0] != '\0' ){ + ebuf = escapize_string(nim->descrip) ; + sprintf( buf+strlen(buf) , " descrip = %s\n",ebuf) ; + free(ebuf) ; + } + + if( nim->aux_file[0] != '\0' ){ + ebuf = escapize_string(nim->aux_file) ; + sprintf( buf+strlen(buf) , " aux_file = %s\n",ebuf) ; + free(ebuf) ; + } + + if( nim->qform_code > 0 ){ + int i,j,k ; + + sprintf( buf+strlen(buf) , + " qform_code = '%d'\n" + " qform_code_name = '%s'\n" + " qto_xyz_matrix = '%g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g'\n" , + nim->qform_code , nifti_xform_string(nim->qform_code) , + nim->qto_xyz.m[0][0] , nim->qto_xyz.m[0][1] , + nim->qto_xyz.m[0][2] , nim->qto_xyz.m[0][3] , + nim->qto_xyz.m[1][0] , nim->qto_xyz.m[1][1] , + nim->qto_xyz.m[1][2] , nim->qto_xyz.m[1][3] , + nim->qto_xyz.m[2][0] , nim->qto_xyz.m[2][1] , + nim->qto_xyz.m[2][2] , nim->qto_xyz.m[2][3] , + nim->qto_xyz.m[3][0] , nim->qto_xyz.m[3][1] , + nim->qto_xyz.m[3][2] , nim->qto_xyz.m[3][3] ) ; + + sprintf( buf+strlen(buf) , + " qto_ijk_matrix = '%g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g'\n" , + nim->qto_ijk.m[0][0] , nim->qto_ijk.m[0][1] , + nim->qto_ijk.m[0][2] , nim->qto_ijk.m[0][3] , + nim->qto_ijk.m[1][0] , nim->qto_ijk.m[1][1] , + nim->qto_ijk.m[1][2] , nim->qto_ijk.m[1][3] , + nim->qto_ijk.m[2][0] , nim->qto_ijk.m[2][1] , + nim->qto_ijk.m[2][2] , nim->qto_ijk.m[2][3] , + nim->qto_ijk.m[3][0] , nim->qto_ijk.m[3][1] , + nim->qto_ijk.m[3][2] , nim->qto_ijk.m[3][3] ) ; + + sprintf( buf+strlen(buf) , + " quatern_b = '%g'\n" + " quatern_c = '%g'\n" + " quatern_d = '%g'\n" + " qoffset_x = '%g'\n" + " qoffset_y = '%g'\n" + " qoffset_z = '%g'\n" + " qfac = '%g'\n" , + nim->quatern_b , nim->quatern_c , nim->quatern_d , + nim->qoffset_x , nim->qoffset_y , nim->qoffset_z , nim->qfac ) ; + + nifti_mat44_to_orientation( nim->qto_xyz , &i,&j,&k ) ; + if( i > 0 && j > 0 && k > 0 ) + sprintf( buf+strlen(buf) , + " qform_i_orientation = '%s'\n" + " qform_j_orientation = '%s'\n" + " qform_k_orientation = '%s'\n" , + nifti_orientation_string(i) , + nifti_orientation_string(j) , + nifti_orientation_string(k) ) ; + } + + if( nim->sform_code > 0 ){ + int i,j,k ; + + sprintf( buf+strlen(buf) , + " sform_code = '%d'\n" + " sform_code_name = '%s'\n" + " sto_xyz_matrix = '%g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g'\n" , + nim->sform_code , nifti_xform_string(nim->sform_code) , + nim->sto_xyz.m[0][0] , nim->sto_xyz.m[0][1] , + nim->sto_xyz.m[0][2] , nim->sto_xyz.m[0][3] , + nim->sto_xyz.m[1][0] , nim->sto_xyz.m[1][1] , + nim->sto_xyz.m[1][2] , nim->sto_xyz.m[1][3] , + nim->sto_xyz.m[2][0] , nim->sto_xyz.m[2][1] , + nim->sto_xyz.m[2][2] , nim->sto_xyz.m[2][3] , + nim->sto_xyz.m[3][0] , nim->sto_xyz.m[3][1] , + nim->sto_xyz.m[3][2] , nim->sto_xyz.m[3][3] ) ; + + sprintf( buf+strlen(buf) , + " sto_ijk matrix = '%g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g'\n" , + nim->sto_ijk.m[0][0] , nim->sto_ijk.m[0][1] , + nim->sto_ijk.m[0][2] , nim->sto_ijk.m[0][3] , + nim->sto_ijk.m[1][0] , nim->sto_ijk.m[1][1] , + nim->sto_ijk.m[1][2] , nim->sto_ijk.m[1][3] , + nim->sto_ijk.m[2][0] , nim->sto_ijk.m[2][1] , + nim->sto_ijk.m[2][2] , nim->sto_ijk.m[2][3] , + nim->sto_ijk.m[3][0] , nim->sto_ijk.m[3][1] , + nim->sto_ijk.m[3][2] , nim->sto_ijk.m[3][3] ) ; + + nifti_mat44_to_orientation( nim->sto_xyz , &i,&j,&k ) ; + if( i > 0 && j > 0 && k > 0 ) + sprintf( buf+strlen(buf) , + " sform_i_orientation = '%s'\n" + " sform_j_orientation = '%s'\n" + " sform_k_orientation = '%s'\n" , + nifti_orientation_string(i) , + nifti_orientation_string(j) , + nifti_orientation_string(k) ) ; + } + + sprintf( buf+strlen(buf) , " num_ext = '%d'\n", nim->num_ext ) ; + + sprintf( buf+strlen(buf) , "/>\n" ) ; /* XML-ish closer */ + + nbuf = (int)strlen(buf) ; + buf = (char *)realloc((void *)buf, nbuf+1); /* cut back to proper length */ + if( !buf ) Rc_fprintf_stderr("** NITA: failed to realloc %d bytes\n",nbuf+1); + return buf ; +} + +/*---------------------------------------------------------------------------*/ + +/*----------------------------------------------------------------------*/ +/*! get the byte order for this CPU + + - LSB_FIRST means least significant byte, first (little endian) + - MSB_FIRST means most significant byte, first (big endian) +*//*--------------------------------------------------------------------*/ +int nifti_short_order(void) /* determine this CPU's byte order */ +{ + union { unsigned char bb[2] ; + short ss ; } fred ; + + fred.bb[0] = 1 ; fred.bb[1] = 0 ; + + return (fred.ss == 1) ? LSB_FIRST : MSB_FIRST ; +} + +/*---------------------------------------------------------------------------*/ + +#undef QQNUM +#undef QNUM +#undef QSTR + +/* macro to check lhs string against "n1"; if it matches, + interpret rhs string as a number, and put it into nim->"n2" */ + +#define QQNUM(n1,n2,tt) if( strcmp(lhs,#n1)==0 ) nim->n2=(tt)strtod(rhs,NULL) + +/* same, but where "n1" == "n2" */ + +#define QNUM(nam,tt) QQNUM(nam,nam,tt) + +/* macro to check lhs string against "nam"; if it matches, + put rhs string into nim->"nam" string, with max length = "ml" */ + +#define QSTR(nam,ml) if( strcmp(lhs,#nam) == 0 ) \ + strncpy(nim->nam,rhs,ml), nim->nam[ml]='\0' + +/*---------------------------------------------------------------------------*/ +/*! Take an XML-ish ASCII string and create a NIFTI image header to match. + + NULL is returned if enough information isn't present in the input string. + - The image data can later be loaded with nifti_image_load(). + - The struct returned here can be liberated with nifti_image_free(). + - Not a lot of error checking is done here to make sure that the + input values are reasonable! +*//*-------------------------------------------------------------------------*/ +nifti_image *nifti_image_from_ascii( const char *str, int * bytes_read ) +{ + char lhs[1024] , rhs[1024] ; + int ii , spos, nn ; + nifti_image *nim ; /* will be output */ + + if( str == NULL || *str == '\0' ) return NULL ; /* bad input!? */ + + /* scan for opening string */ + + spos = 0 ; + ii = sscanf( str+spos , "%1023s%n" , lhs , &nn ) ; spos += nn ; + if( ii == 0 || strcmp(lhs,"nx = nim->ny = nim->nz = nim->nt + = nim->nu = nim->nv = nim->nw = 1 ; + nim->dx = nim->dy = nim->dz = nim->dt + = nim->du = nim->dv = nim->dw = 0 ; + nim->qfac = 1.0f ; + + nim->byteorder = nifti_short_order() ; + + /* starting at str[spos], scan for "equations" of the form + lhs = 'rhs' + and assign rhs values into the struct component named by lhs */ + + while(1){ + + while( isspace((int) str[spos]) ) spos++ ; /* skip whitespace */ + if( str[spos] == '\0' ) break ; /* end of string? */ + + /* get lhs string */ + + ii = sscanf( str+spos , "%1023s%n" , lhs , &nn ) ; spos += nn ; + if( ii == 0 || strcmp(lhs,"/>") == 0 ) break ; /* end of input? */ + + /* skip whitespace and the '=' marker */ + + while( isspace((int) str[spos]) || str[spos] == '=' ) spos++ ; + if( str[spos] == '\0' ) break ; /* end of string? */ + + /* if next character is a quote ', copy everything up to next ' + otherwise, copy everything up to next nonblank */ + + if( str[spos] == '\'' ){ + ii = spos+1 ; + while( str[ii] != '\0' && str[ii] != '\'' ) ii++ ; + nn = ii-spos-1 ; if( nn > 1023 ) nn = 1023 ; + memcpy(rhs,str+spos+1,nn) ; rhs[nn] = '\0' ; + spos = (str[ii] == '\'') ? ii+1 : ii ; + } else { + ii = sscanf( str+spos , "%1023s%n" , rhs , &nn ) ; spos += nn ; + if( ii == 0 ) break ; /* nothing found? */ + } + unescape_string(rhs) ; /* remove any XML escape sequences */ + + /* Now can do the assignment, based on lhs string. + Start with special cases that don't fit the QNUM/QSTR macros. */ + + if( strcmp(lhs,"nifti_type") == 0 ){ + if( strcmp(rhs,"ANALYZE-7.5") == 0 ) + nim->nifti_type = NIFTI_FTYPE_ANALYZE ; + else if( strcmp(rhs,"NIFTI-1+") == 0 ) + nim->nifti_type = NIFTI_FTYPE_NIFTI1_1 ; + else if( strcmp(rhs,"NIFTI-1") == 0 ) + nim->nifti_type = NIFTI_FTYPE_NIFTI1_2 ; + else if( strcmp(rhs,"NIFTI-1A") == 0 ) + nim->nifti_type = NIFTI_FTYPE_ASCII ; + } + else if( strcmp(lhs,"header_filename") == 0 ){ + nim->fname = nifti_strdup(rhs) ; + } + else if( strcmp(lhs,"image_filename") == 0 ){ + nim->iname = nifti_strdup(rhs) ; + } + else if( strcmp(lhs,"sto_xyz_matrix") == 0 ){ + sscanf( rhs , "%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f" , + &(nim->sto_xyz.m[0][0]) , &(nim->sto_xyz.m[0][1]) , + &(nim->sto_xyz.m[0][2]) , &(nim->sto_xyz.m[0][3]) , + &(nim->sto_xyz.m[1][0]) , &(nim->sto_xyz.m[1][1]) , + &(nim->sto_xyz.m[1][2]) , &(nim->sto_xyz.m[1][3]) , + &(nim->sto_xyz.m[2][0]) , &(nim->sto_xyz.m[2][1]) , + &(nim->sto_xyz.m[2][2]) , &(nim->sto_xyz.m[2][3]) , + &(nim->sto_xyz.m[3][0]) , &(nim->sto_xyz.m[3][1]) , + &(nim->sto_xyz.m[3][2]) , &(nim->sto_xyz.m[3][3]) ) ; + } + else if( strcmp(lhs,"byteorder") == 0 ){ + if( strcmp(rhs,"MSB_FIRST") == 0 ) nim->byteorder = MSB_FIRST ; + if( strcmp(rhs,"LSB_FIRST") == 0 ) nim->byteorder = LSB_FIRST ; + } + else QQNUM(image_offset,iname_offset,int) ; + else QNUM(datatype,short int) ; + else QNUM(ndim,int) ; + else QNUM(nx,int) ; + else QNUM(ny,int) ; + else QNUM(nz,int) ; + else QNUM(nt,int) ; + else QNUM(nu,int) ; + else QNUM(nv,int) ; + else QNUM(nw,int) ; + else QNUM(dx,float) ; + else QNUM(dy,float) ; + else QNUM(dz,float) ; + else QNUM(dt,float) ; + else QNUM(du,float) ; + else QNUM(dv,float) ; + else QNUM(dw,float) ; + else QNUM(cal_min,float) ; + else QNUM(cal_max,float) ; + else QNUM(scl_slope,float) ; + else QNUM(scl_inter,float) ; + else QNUM(intent_code,short) ; + else QNUM(intent_p1,float) ; + else QNUM(intent_p2,float) ; + else QNUM(intent_p3,float) ; + else QSTR(intent_name,15) ; + else QNUM(toffset,float) ; + else QNUM(xyz_units,int) ; + else QNUM(time_units,int) ; + else QSTR(descrip,79) ; + else QSTR(aux_file,23) ; + else QNUM(qform_code,int) ; + else QNUM(quatern_b,float) ; + else QNUM(quatern_c,float) ; + else QNUM(quatern_d,float) ; + else QNUM(qoffset_x,float) ; + else QNUM(qoffset_y,float) ; + else QNUM(qoffset_z,float) ; + else QNUM(qfac,float) ; + else QNUM(sform_code,int) ; + else QNUM(freq_dim,int) ; + else QNUM(phase_dim,int) ; + else QNUM(slice_dim,int) ; + else QNUM(slice_code,int) ; + else QNUM(slice_start,int) ; + else QNUM(slice_end,int) ; + else QNUM(slice_duration,float) ; + else QNUM(num_ext,int) ; + + } /* end of while loop */ + + if( bytes_read ) *bytes_read = spos+1; /* "process" last '\n' */ + + /* do miscellaneous checking and cleanup */ + + if( nim->ndim <= 0 ){ nifti_image_free(nim); return NULL; } /* bad! */ + + nifti_datatype_sizes( nim->datatype, &(nim->nbyper), &(nim->swapsize) ); + if( nim->nbyper == 0 ){ nifti_image_free(nim); return NULL; } /* bad! */ + + nim->dim[0] = nim->ndim ; + nim->dim[1] = nim->nx ; nim->pixdim[1] = nim->dx ; + nim->dim[2] = nim->ny ; nim->pixdim[2] = nim->dy ; + nim->dim[3] = nim->nz ; nim->pixdim[3] = nim->dz ; + nim->dim[4] = nim->nt ; nim->pixdim[4] = nim->dt ; + nim->dim[5] = nim->nu ; nim->pixdim[5] = nim->du ; + nim->dim[6] = nim->nv ; nim->pixdim[6] = nim->dv ; + nim->dim[7] = nim->nw ; nim->pixdim[7] = nim->dw ; + + nim->nvox = (size_t)nim->nx * nim->ny * nim->nz + * nim->nt * nim->nu * nim->nv * nim->nw ; + + if( nim->qform_code > 0 ) + nim->qto_xyz = nifti_quatern_to_mat44( + nim->quatern_b, nim->quatern_c, nim->quatern_d, + nim->qoffset_x, nim->qoffset_y, nim->qoffset_z, + nim->dx , nim->dy , nim->dz , + nim->qfac ) ; + else + nim->qto_xyz = nifti_quatern_to_mat44( + 0.0f , 0.0f , 0.0f , 0.0f , 0.0f , 0.0f , + nim->dx , nim->dy , nim->dz , 0.0f ) ; + + + nim->qto_ijk = nifti_mat44_inverse( nim->qto_xyz ) ; + + if( nim->sform_code > 0 ) + nim->sto_ijk = nifti_mat44_inverse( nim->sto_xyz ) ; + + return nim ; +} + + +/*---------------------------------------------------------------------------*/ +/*! validate the nifti_image + + \return 1 if the structure seems valid, otherwise 0 + + \sa nifti_nim_has_valid_dims, nifti_hdr_looks_good +*//*-------------------------------------------------------------------------*/ +int nifti_nim_is_valid(nifti_image * nim, int complain) +{ + int errs = 0; + + if( !nim ){ + Rc_fprintf_stderr("** is_valid_nim: nim is NULL\n"); + return 0; + } + + if( g_opts.debug > 2 ) Rc_fprintf_stderr("-d nim_is_valid check...\n"); + + /**- check that dim[] matches the individual values ndim, nx, ny, ... */ + if( ! nifti_nim_has_valid_dims(nim,complain) ){ + if( !complain ) return 0; + errs++; + } + + /* might check nbyper, pixdim, q/sforms, swapsize, nifti_type, ... */ + + /**- be explicit in return of 0 or 1 */ + if( errs > 0 ) return 0; + else return 1; +} + +/*---------------------------------------------------------------------------*/ +/*! validate nifti dimensions + + \return 1 if valid, 0 if not + + \sa nifti_nim_is_valid, nifti_hdr_looks_good + + rely on dim[] as the master +*//*-------------------------------------------------------------------------*/ +int nifti_nim_has_valid_dims(nifti_image * nim, int complain) +{ + size_t prod; + int c, errs = 0; + + /**- start with dim[0]: failure here is considered terminal */ + if( nim->dim[0] <= 0 || nim->dim[0] > 7 ){ + errs++; + if( complain ) + Rc_fprintf_stderr("** NVd: dim[0] (%d) out of range [1,7]\n",nim->dim[0]); + return 0; + } + + /**- check whether ndim equals dim[0] */ + if( nim->ndim != nim->dim[0] ){ + errs++; + if( ! complain ) return 0; + Rc_fprintf_stderr("** NVd: ndim != dim[0] (%d,%d)\n",nim->ndim,nim->dim[0]); + } + + /**- compare each dim[i] to the proper nx, ny, ... */ + if( ( (nim->dim[0] >= 1) && (nim->dim[1] != nim->nx) ) || + ( (nim->dim[0] >= 2) && (nim->dim[2] != nim->ny) ) || + ( (nim->dim[0] >= 3) && (nim->dim[3] != nim->nz) ) || + ( (nim->dim[0] >= 4) && (nim->dim[4] != nim->nt) ) || + ( (nim->dim[0] >= 5) && (nim->dim[5] != nim->nu) ) || + ( (nim->dim[0] >= 6) && (nim->dim[6] != nim->nv) ) || + ( (nim->dim[0] >= 7) && (nim->dim[7] != nim->nw) ) ){ + errs++; + if( !complain ) return 0; + Rc_fprintf_stderr("** NVd mismatch: dims = %d,%d,%d,%d,%d,%d,%d\n" + " nxyz... = %d,%d,%d,%d,%d,%d,%d\n", + nim->dim[1], nim->dim[2], nim->dim[3], + nim->dim[4], nim->dim[5], nim->dim[6], nim->dim[7], + nim->nx, nim->ny, nim->nz, + nim->nt, nim->nu, nim->nv, nim->nw ); + } + + if( g_opts.debug > 2 ){ + Rc_fprintf_stderr("-d check dim[%d] =", nim->dim[0]); + for( c = 0; c < 7; c++ ) Rc_fprintf_stderr(" %d", nim->dim[c]); + Rc_fputc_stderr('\n'); + } + + /**- check the dimensions, and that their product matches nvox */ + prod = 1; + for( c = 1; c <= nim->dim[0]; c++ ){ + if( nim->dim[c] > 0) + prod *= nim->dim[c]; + else if( nim->dim[c] <= 0 ){ + if( !complain ) return 0; + Rc_fprintf_stderr("** NVd: dim[%d] (=%d) <= 0\n",c, nim->dim[c]); + errs++; + } + } + if( prod != nim->nvox ){ + if( ! complain ) return 0; + Rc_fprintf_stderr("** NVd: nvox does not match %d-dim product (%u, %u)\n", + nim->dim[0], (unsigned)nim->nvox, (unsigned)prod); + errs++; + } + + /**- if debug, warn about any remaining dim that is neither 0, nor 1 */ + /* (values in dims above dim[0] are undefined, as reminded by Cinly + Ooi and Alle Meije Wink) 16 Nov 2005 [rickr] */ + if( g_opts.debug > 1 ) + for( c = nim->dim[0]+1; c <= 7; c++ ) + if( nim->dim[c] != 0 && nim->dim[c] != 1 ) + Rc_fprintf_stderr("** NVd warning: dim[%d] = %d, but ndim = %d\n", + c, nim->dim[c], nim->dim[0]); + + if( g_opts.debug > 2 ) + Rc_fprintf_stderr("-d nim_has_valid_dims check, errs = %d\n", errs); + + /**- return invalid or valid */ + if( errs > 0 ) return 0; + else return 1; +} + + +/*---------------------------------------------------------------------------*/ +/*! read a nifti image, collapsed across dimensions according to dims[8]
+
+    This function may be used to read parts of a nifti dataset, such as
+    the time series for a single voxel, or perhaps a slice.  It is similar
+    to nifti_image_load(), though the passed 'data' parameter is used for
+    returning the image, not nim->data.
+
+    \param nim  given nifti_image struct, corresponding to the data file
+    \param dims given list of dimensions (see below)
+    \param data pointer to data pointer (if *data is NULL, data will be
+                allocated, otherwise not)
+
+    Here, dims is an array of 8 ints, similar to nim->dim[8].  While dims[0]
+    is unused at this point, the other indices specify which dimensions to
+    collapse (and at which index), and which not to collapse.  If dims[i] is
+    set to -1, then that entire dimension will be read in, from index 0 to
+    index (nim->dim[i] - 1).  If dims[i] >= 0, then only that index will be
+    read in (so dims[i] must also be < nim->dim[i]).
+
+    Example: given  nim->dim[8] = { 4, 64, 64, 21, 80, 1, 1, 1 } (4-D dataset)
+
+      if dims[8] = { 0,  5,  4, 17, -1, -1, -1, -1 }
+         -> read time series for voxel i,j,k = 5,4,17
+
+      if dims[8] = { 0, -1, -1, -1, 17, -1, -1, -1 }
+         -> read single volume at time point 17
+
+    Example: given  nim->dim[8] = { 6, 64, 64, 21, 80, 4, 3, 1 } (6-D dataset)
+
+      if dims[8] = { 0, 5, 4, 17, -1, 2, 1, 0 }
+         -> read time series for the voxel i,j,k = 5,4,17, and dim 5,6 = 2,1
+
+      if dims[8] = { 0, 5, 4, -1, -1, 0, 0, 0 }
+         -> read time series for slice at i,j = 5,4, and dim 5,6,7 = 0,0,0
+            (note that dims[7] is not relevant, but must be 0 or -1)
+
+    If *data is NULL, then *data will be set as a pointer to new memory,
+    allocated here for the resulting collapsed image data.
+
+      e.g. { int    dims[8] = { 0,  5,  4, 17, -1, -1, -1, -1 };
+             void * data    = NULL;
+             ret_val = nifti_read_collapsed_image(nim, dims, &data);
+             if( ret_val > 0 ){
+                process_time_series(data);
+                if( data != NULL ) free(data);
+             }
+           }
+
+    NOTE: If *data is not NULL, then it will be assumed that it points to
+          valid memory, sufficient to hold the results.  This is done for
+          speed and possibly repeated calls to this function.
+
+      e.g. { int    dims[8] = { 0,  -1, -1, -1, -1, -1, -1, -1 };
+             void * data    = NULL;
+             for( zslice = 0; zslice < nzslices; zslice++ ){
+                dims[3] = zslice;
+                ret_val = nifti_read_collapsed_image(nim, dims, &data);
+                if( ret_val > 0 ) process_slice(zslice, data);
+             }
+             if( data != NULL ) free(data);
+           }
+
+    \return
+        -  the total number of bytes read, or < 0 on failure
+        -  the read and byte-swapped data, in 'data'            
+ + \sa nifti_image_read, nifti_image_free, nifti_image_read_bricks + nifti_image_load +*//*-------------------------------------------------------------------------*/ +int nifti_read_collapsed_image( nifti_image * nim, const int dims [8], + void ** data ) +{ + znzFile fp; + int pivots[8], prods[8], nprods; /* sizes are bounded by dims[], so 8 */ + int c, bytes; + + /** - check pointers for sanity */ + if( !nim || !dims || !data ){ + Rc_fprintf_stderr("** nifti_RCI: bad params %p, %p, %p\n", + (void *)nim, (const void *)dims, (void *)data); + return -1; + } + + if( g_opts.debug > 2 ){ + Rc_fprintf_stderr("-d read_collapsed_image:\n dims ="); + for(c = 0; c < 8; c++) Rc_fprintf_stderr(" %3d", dims[c]); + Rc_fprintf_stderr("\n nim->dims ="); + for(c = 0; c < 8; c++) Rc_fprintf_stderr(" %3d", nim->dim[c]); + Rc_fputc_stderr('\n'); + } + + /** - verify that dim[] makes sense */ + if( ! nifti_nim_is_valid(nim, g_opts.debug > 0) ){ + Rc_fprintf_stderr("** invalid nim (file is '%s')\n", nim->fname ); + return -1; + } + + /** - verify that dims[] makes sense for this dataset */ + for( c = 1; c <= nim->dim[0]; c++ ){ + if( dims[c] >= nim->dim[c] ){ + Rc_fprintf_stderr("** nifti_RCI: dims[%d] >= nim->dim[%d] (%d,%d)\n", + c, c, dims[c], nim->dim[c]); + return -1; + } + } + + /** - prepare pivot list - pivots are fixed indices */ + if( make_pivot_list(nim, dims, pivots, prods, &nprods) < 0 ) return -1; + + bytes = rci_alloc_mem(data, prods, nprods, nim->nbyper); + if( bytes < 0 ) return -1; + + /** - open the image file for reading at the appropriate offset */ + fp = nifti_image_load_prep( nim ); + if( ! fp ){ free(*data); *data = NULL; return -1; } /* failure */ + + /** - call the recursive reading function, passing nim, the pivot info, + location to store memory, and file pointer and position */ + c = rci_read_data(nim, pivots,prods,nprods,dims, + (char *)*data, fp, znztell(fp)); + znzclose(fp); /* in any case, close the file */ + if( c < 0 ){ free(*data); *data = NULL; return -1; } /* failure */ + + if( g_opts.debug > 1 ) + Rc_fprintf_stderr("+d read %d bytes of collapsed image from %s\n", + bytes, nim->fname); + + return bytes; +} + + +/* local function to find strides per dimension. assumes 7D size and +** stride array. +*/ +static void +compute_strides(int *strides,const int *size,int nbyper) +{ + int i; + strides[0] = nbyper; + for(i = 1; i < 7; i++) + { + strides[i] = size[i-1] * strides[i-1]; + } +} + +/*---------------------------------------------------------------------------*/ +/*! read an arbitrary subregion from a nifti image + + This function may be used to read a single arbitary subregion of any + rectangular size from a nifti dataset, such as a small 5x5x5 subregion + around the center of a 3D image. + + \param nim given nifti_image struct, corresponding to the data file + \param start_index the index location of the first voxel that will be returned + \param region_size the size of the subregion to be returned + \param data pointer to data pointer (if *data is NULL, data will be + allocated, otherwise not) + + Example: given nim->dim[8] = {3, 64, 64, 64, 1, 1, 1, 1 } (3-D dataset) + + if start_index[7] = { 29, 29, 29, 0, 0, 0, 0 } and + region_size[7] = { 5, 5, 5, 1, 1, 1, 1 } + -> read 5x5x5 region starting with the first voxel location at (29,29,29) + + NOTE: If *data is not NULL, then it will be assumed that it points to + valid memory, sufficient to hold the results. This is done for + speed and possibly repeated calls to this function. + \return + - the total number of bytes read, or < 0 on failure + - the read and byte-swapped data, in 'data' + + \sa nifti_image_read, nifti_image_free, nifti_image_read_bricks + nifti_image_load, nifti_read_collapsed_image +*//*-------------------------------------------------------------------------*/ +int nifti_read_subregion_image( nifti_image * nim, + int *start_index, + int *region_size, + void ** data ) +{ + znzFile fp; /* file to read */ + int i,j,k,l,m,n; /* indices for dims */ + long int bytes = 0; /* total # bytes read */ + int total_alloc_size; /* size of buffer allocation */ + char *readptr; /* where in *data to read next */ + int strides[7]; /* strides between dimensions */ + int collapsed_dims[8]; /* for read_collapsed_image */ + int *image_size; /* pointer to dimensions in header */ + long int initial_offset; + long int offset; /* seek offset for reading current row */ + + /* probably ignored, but set to ndim for consistency*/ + collapsed_dims[0] = nim->ndim; + + /* build a dims array for collapsed image read */ + for(i = 0; i < nim->ndim; i++) + { + /* if you take the whole extent in this dimension */ + if(start_index[i] == 0 && + region_size[i] == nim->dim[i+1]) + { + collapsed_dims[i+1] = -1; + } + /* if you specify a single element in this dimension */ + else if(region_size[i] == 1) + { + collapsed_dims[i+1] = start_index[i]; + } + else + { + collapsed_dims[i+1] = -2; /* sentinel value */ + } + } + /* fill out end of collapsed_dims */ + for(i = nim->ndim ; i < 7; i++) + { + collapsed_dims[i+1] = -1; + } + + /* check to see whether collapsed read is possible */ + for(i = 1; i <= nim->ndim; i++) + { + if(collapsed_dims[i] == -2) + { + break; + } + } + + /* if you get through all the dimensions without hitting + ** a subrange of size > 1, a collapsed read is possible + */ + if(i > nim->ndim) + { + return nifti_read_collapsed_image(nim, collapsed_dims, data); + } + + /* point past first element of dim, which holds nim->ndim */ + image_size = &(nim->dim[1]); + + /* check region sizes for sanity */ + for(i = 0; i < nim->ndim; i++) + { + if(start_index[i] + region_size[i] > image_size[i]) + { + if(g_opts.debug > 1) + { + Rc_fprintf_stderr("region doesn't fit within image size\n"); + } + return -1; + } + } + + /* get the file open */ + fp = nifti_image_load_prep( nim ); + /* the current offset is just past the nifti header, save + * location so that SEEK_SET can be used below + */ + initial_offset = znztell(fp); + /* get strides*/ + compute_strides(strides,image_size,nim->nbyper); + + total_alloc_size = nim->nbyper; /* size of pixel */ + + /* find alloc size */ + for(i = 0; i < nim->ndim; i++) + { + total_alloc_size *= region_size[i]; + } + /* allocate buffer, if necessary */ + if(*data == 0) + { + *data = (void *)malloc(total_alloc_size); + } + + if(*data == 0) + { + if(g_opts.debug > 1) + { + Rc_fprintf_stderr("allocation of %d bytes failed\n",total_alloc_size); + return -1; + } + } + + /* point to start of data buffer as char * */ + readptr = *((char **)data); + { + /* can't assume that start_index and region_size have any more than + ** nim->ndim elements so make local copies, filled out to seven elements + */ + int si[7], rs[7]; + for(i = 0; i < nim->ndim; i++) + { + si[i] = start_index[i]; + rs[i] = region_size[i]; + } + for(i = nim->ndim; i < 7; i++) + { + si[i] = 0; + rs[i] = 1; + } + /* loop through subregion and read a row at a time */ + for(i = si[6]; i < (si[6] + rs[6]); i++) + { + for(j = si[5]; j < (si[5] + rs[5]); j++) + { + for(k = si[4]; k < (si[4] + rs[4]); k++) + { + for(l = si[3]; l < (si[3] + rs[3]); l++) + { + for(m = si[2]; m < (si[2] + rs[2]); m++) + { + for(n = si[1]; n < (si[1] + rs[1]); n++) + { + int nread,read_amount; + offset = initial_offset + + (i * strides[6]) + + (j * strides[5]) + + (k * strides[4]) + + (l * strides[3]) + + (m * strides[2]) + + (n * strides[1]) + + (si[0] * strides[0]); + znzseek(fp, offset, SEEK_SET); /* seek to current row */ + read_amount = rs[0] * nim->nbyper; /* read a row of the subregion*/ + nread = (int)nifti_read_buffer(fp, readptr, read_amount, nim); + if(nread != read_amount) + { + if(g_opts.debug > 1) + { + Rc_fprintf_stderr("read of %d bytes failed\n",read_amount); + return -1; + } + } + bytes += nread; + readptr += read_amount; + } + } + } + } + } + } + } + return bytes; +} + + +/* read the data from the file pointed to by fp + + - this a recursive function, so start with the base case + - data is now (char *) for easy incrementing + + return 0 on success, < 0 on failure +*/ +static int rci_read_data(nifti_image * nim, int * pivots, int * prods, + int nprods, const int dims[], char * data, znzFile fp, size_t base_offset) +{ + size_t sublen, offset, read_size; + int c; + + /* bad check first - base_offset may not have been checked */ + if( nprods <= 0 ){ + Rc_fprintf_stderr("** rci_read_data, bad prods, %d\n", nprods); + return -1; + } + + /* base case: actually read the data */ + if( nprods == 1 ){ + size_t nread, bytes; + + /* make sure things look good here */ + if( *pivots != 0 ){ + Rc_fprintf_stderr("** rciRD: final pivot == %d!\n", *pivots); + return -1; + } + + /* so just seek and read (prods[0] * nbyper) bytes from the file */ + znzseek(fp, (long)base_offset, SEEK_SET); + bytes = (size_t)prods[0] * nim->nbyper; + nread = nifti_read_buffer(fp, data, bytes, nim); + if( nread != bytes ){ + Rc_fprintf_stderr("** rciRD: read only %u of %u bytes from '%s'\n", + (unsigned)nread, (unsigned)bytes, nim->fname); + return -1; + } else if( g_opts.debug > 3 ) + Rc_fprintf_stderr("+d successful read of %u bytes at offset %u\n", + (unsigned)bytes, (unsigned)base_offset); + + return 0; /* done with base case - return success */ + } + + /* not the base case, so do a set of reduced reads */ + + /* compute size of sub-brick: all dimensions below pivot */ + for( c = 1, sublen = 1; c < *pivots; c++ ) sublen *= nim->dim[c]; + + /* compute number of values to read, i.e. remaining prods */ + for( c = 1, read_size = 1; c < nprods; c++ ) read_size *= prods[c]; + read_size *= nim->nbyper; /* and multiply by bytes per voxel */ + + /* now repeatedly compute offsets, and recursively read */ + for( c = 0; c < prods[0]; c++ ){ + /* offset is (c * sub-block size (including pivot dim)) */ + /* + (dims[] index into pivot sub-block) */ + /* the unneeded multiplication is to make this more clear */ + offset = (size_t)c * sublen * nim->dim[*pivots] + + (size_t)sublen * dims[*pivots]; + offset *= nim->nbyper; + + if( g_opts.debug > 3 ) + Rc_fprintf_stderr("-d reading %u bytes, foff %u + %u, doff %u\n", + (unsigned)read_size, (unsigned)base_offset, (unsigned)offset, + (unsigned)(c*read_size)); + + /* now read the next level down, adding this offset */ + if( rci_read_data(nim, pivots+1, prods+1, nprods-1, dims, + data + c * read_size, fp, base_offset + offset) < 0 ) + return -1; + } + + return 0; +} + + +/* allocate memory for all collapsed image data + + If *data is already set, do not allocate, but still calculate + size for debug report. + + return total size on success, and < 0 on failure +*/ +static int rci_alloc_mem(void ** data, int prods[8], int nprods, int nbyper ) +{ + int size, memindex; + + if( nbyper < 0 || nprods < 1 || nprods > 8 ){ + Rc_fprintf_stderr("** rci_am: bad params, %d, %d\n", nbyper, nprods); + return -1; + } + + for( memindex = 0, size = 1; memindex < nprods; memindex++ ) + size *= prods[memindex]; + + size *= nbyper; + + if( ! *data ){ /* then allocate what is needed */ + if( g_opts.debug > 1 ) + Rc_fprintf_stderr("+d alloc %d (= %d x %d) bytes for collapsed image\n", + size, size/nbyper, nbyper); + + *data = malloc(size); /* actually allocate the memory */ + if( ! *data ){ + Rc_fprintf_stderr("** rci_am: failed to alloc %d bytes for data\n", size); + return -1; + } + } else if( g_opts.debug > 1 ) + Rc_fprintf_stderr("-d rci_am: *data already set, need %d (%d x %d) bytes\n", + size, size/nbyper, nbyper); + + return size; +} + + +/* prepare a pivot list for reading + + The pivot points are the indices into dims where the calling function + wants to collapse a dimension. The last pivot should always be zero + (note that we have space for that in the lists). +*/ +static int make_pivot_list(nifti_image * nim, const int dims[], int pivots[], + int prods[], int * nprods ) +{ + int len, dim_index; + + len = 0; + dim_index = nim->dim[0]; + while( dim_index > 0 ){ + prods[len] = 1; + while( dim_index > 0 && (nim->dim[dim_index] == 1 || dims[dim_index] == -1) ){ + prods[len] *= nim->dim[dim_index]; + dim_index--; + } + pivots[len] = dim_index; + len++; + dim_index--; /* fine, let it drop out at -1 */ + } + + /* make sure to include 0 as a pivot (instead of just 1, if it is) */ + if( pivots[len-1] != 0 ){ + pivots[len] = 0; + prods[len] = 1; + len++; + } + + *nprods = len; + + if( g_opts.debug > 2 ){ + Rc_fprintf_stderr("+d pivot list created, pivots :"); + for(dim_index = 0; dim_index < len; dim_index++) Rc_fprintf_stderr(" %d", pivots[dim_index]); + Rc_fprintf_stderr(", prods :"); + for(dim_index = 0; dim_index < len; dim_index++) Rc_fprintf_stderr(" %d", prods[dim_index]); + Rc_fputc_stderr('\n'); + } + + return 0; +} + + +#undef ISEND +#define ISEND(c) ( (c)==']' || (c)=='}' || (c)=='\0' ) + +/*---------------------------------------------------------------------*/ +/*! Get an integer list in the range 0..(nvals-1), from the + character string str. If we call the output pointer fred, + then fred[0] = number of integers in the list (> 0), and + fred[i] = i-th integer in the list for i=1..fred[0]. + If on return, fred == NULL or fred[0] == 0, then something is + wrong, and the caller must deal with that. + + Syntax of input string: + - initial '{' or '[' is skipped, if present + - ends when '}' or ']' or end of string is found + - contains entries separated by commas + - entries have one of these forms: + - a single number + - a dollar sign '$', which means nvals-1 + - a sequence of consecutive numbers in the form "a..b" or + "a-b", where "a" and "b" are single numbers (or '$') + - a sequence of evenly spaced numbers in the form + "a..b(c)" or "a-b(c)", where "c" encodes the step + - Example: "[2,7..4,3..9(2)]" decodes to the list + 2 7 6 5 4 3 5 7 9 + - entries should be in the range 0..nvals-1 + + (borrowed, with permission, from thd_intlist.c) +*//*-------------------------------------------------------------------*/ +int * nifti_get_intlist( int nvals , const char * str ) +{ + int *subv = NULL ; + int ii , ipos , nout , slen ; + int ibot,itop,istep , nused ; + char *cpt ; + + /* Meaningless input? */ + if( nvals < 1 ) return NULL ; + + /* No selection list? */ + if( str == NULL || str[0] == '\0' ) return NULL ; + + /* skip initial '[' or '{' */ + subv = (int *)malloc( sizeof(int) * 2 ) ; + if( !subv ) { + Rc_fprintf_stderr("** nifti_get_intlist: failed alloc of 2 ints\n"); + return NULL; + } + subv[0] = nout = 0 ; + + ipos = 0 ; + if( str[ipos] == '[' || str[ipos] == '{' ) ipos++ ; + + if( g_opts.debug > 1 ) + Rc_fprintf_stderr("-d making int_list (vals = %d) from '%s'\n", nvals, str); + + /**- for each sub-selector until end of input... */ + + slen = (int)strlen(str) ; + while( ipos < slen && !ISEND(str[ipos]) ){ + + while( isspace((int) str[ipos]) ) ipos++ ; /* skip blanks */ + if( ISEND(str[ipos]) ) break ; /* done */ + + /**- get starting value */ + + if( str[ipos] == '$' ){ /* special case */ + ibot = nvals-1 ; ipos++ ; + } else { /* decode an integer */ + ibot = strtol( str+ipos , &cpt , 10 ) ; + if( ibot < 0 ){ + Rc_fprintf_stderr("** ERROR: list index %d is out of range 0..%d\n", + ibot,nvals-1) ; + free(subv) ; return NULL ; + } + if( ibot >= nvals ){ + Rc_fprintf_stderr("** ERROR: list index %d is out of range 0..%d\n", + ibot,nvals-1) ; + free(subv) ; return NULL ; + } + nused = (cpt-(str+ipos)) ; + if( ibot == 0 && nused == 0 ){ + Rc_fprintf_stderr("** ERROR: list syntax error '%s'\n",str+ipos) ; + free(subv) ; return NULL ; + } + ipos += nused ; + } + + while( isspace((int) str[ipos]) ) ipos++ ; /* skip blanks */ + + /**- if that's it for this sub-selector, add one value to list */ + + if( str[ipos] == ',' || ISEND(str[ipos]) ){ + nout++ ; + subv = (int *)realloc( (char *)subv , sizeof(int) * (nout+1) ) ; + if( !subv ) { + Rc_fprintf_stderr("** nifti_get_intlist: failed realloc of %d ints\n", + nout+1); + return NULL; + } + subv[0] = nout ; + subv[nout] = ibot ; + if( ISEND(str[ipos]) ) break ; /* done */ + ipos++ ; continue ; /* re-start loop at next sub-selector */ + } + + /**- otherwise, must have '..' or '-' as next inputs */ + + if( str[ipos] == '-' ){ + ipos++ ; + } else if( str[ipos] == '.' && str[ipos+1] == '.' ){ + ipos++ ; ipos++ ; + } else { + Rc_fprintf_stderr("** ERROR: index list syntax is bad: '%s'\n", + str+ipos) ; + free(subv) ; return NULL ; + } + + /**- get ending value for loop now */ + + if( str[ipos] == '$' ){ /* special case */ + itop = nvals-1 ; ipos++ ; + } else { /* decode an integer */ + itop = strtol( str+ipos , &cpt , 10 ) ; + if( itop < 0 ){ + Rc_fprintf_stderr("** ERROR: index %d is out of range 0..%d\n", + itop,nvals-1) ; + free(subv) ; return NULL ; + } + if( itop >= nvals ){ + Rc_fprintf_stderr("** ERROR: index %d is out of range 0..%d\n", + itop,nvals-1) ; + free(subv) ; return NULL ; + } + nused = (cpt-(str+ipos)) ; + if( itop == 0 && nused == 0 ){ + Rc_fprintf_stderr("** ERROR: index list syntax error '%s'\n",str+ipos) ; + free(subv) ; return NULL ; + } + ipos += nused ; + } + + /**- set default loop step */ + + istep = (ibot <= itop) ? 1 : -1 ; + + while( isspace((int) str[ipos]) ) ipos++ ; /* skip blanks */ + + /**- check if we have a non-default loop step */ + + if( str[ipos] == '(' ){ /* decode an integer */ + ipos++ ; + istep = strtol( str+ipos , &cpt , 10 ) ; + if( istep == 0 ){ + Rc_fprintf_stderr("** ERROR: index loop step is 0!\n") ; + free(subv) ; return NULL ; + } + nused = (cpt-(str+ipos)) ; + ipos += nused ; + if( str[ipos] == ')' ) ipos++ ; + if( (ibot-itop)*istep > 0 ){ + Rc_fprintf_stderr("** WARNING: index list '%d..%d(%d)' means nothing\n", + ibot,itop,istep ) ; + } + } + + /**- add values to output */ + + for( ii=ibot ; (ii-itop)*istep <= 0 ; ii += istep ){ + nout++ ; + subv = (int *)realloc( (char *)subv , sizeof(int) * (nout+1) ) ; + if( !subv ) { + Rc_fprintf_stderr("** nifti_get_intlist: failed realloc of %d ints\n", + nout+1); + return NULL; + } + subv[0] = nout ; + subv[nout] = ii ; + } + + /**- check if we have a comma to skip over */ + + while( isspace((int) str[ipos]) ) ipos++ ; /* skip blanks */ + if( str[ipos] == ',' ) ipos++ ; /* skip commas */ + + } /* end of loop through selector string */ + + if( g_opts.debug > 1 ) { + Rc_fprintf_stderr("+d int_list (vals = %d): ", subv[0]); + for( ii = 1; ii <= subv[0]; ii++ ) Rc_fprintf_stderr("%d ", subv[ii]); + Rc_fputc_stderr('\n'); + } + + if( subv[0] == 0 ){ free(subv); subv = NULL; } + return subv ; +} + +/*---------------------------------------------------------------------*/ +/*! Given a NIFTI_TYPE string, such as "NIFTI_TYPE_INT16", return the + * corresponding integral type code. The type code is the macro + * value defined in nifti1.h. +*//*-------------------------------------------------------------------*/ +int nifti_datatype_from_string( const char * name ) +{ + int tablen = sizeof(nifti_type_list)/sizeof(nifti_type_ele); + int c; + + if( !name ) return DT_UNKNOWN; + + for( c = tablen-1; c > 0; c-- ) + if( !strcmp(name, nifti_type_list[c].name) ) + break; + + return nifti_type_list[c].type; +} + + +/*---------------------------------------------------------------------*/ +/*! Given a NIFTI_TYPE value, such as NIFTI_TYPE_INT16, return the + * corresponding macro label as a string. The dtype code is the + * macro value defined in nifti1.h. +*//*-------------------------------------------------------------------*/ +const char * nifti_datatype_to_string( int dtype ) +{ + int tablen = sizeof(nifti_type_list)/sizeof(nifti_type_ele); + int c; + + for( c = tablen-1; c > 0; c-- ) + if( nifti_type_list[c].type == dtype ) + break; + + return nifti_type_list[c].name; +} + + +/*---------------------------------------------------------------------*/ +/*! Determine whether dtype is a valid NIFTI_TYPE. + * + * DT_UNKNOWN is considered invalid + * + * The only difference 'for_nifti' makes is that DT_BINARY + * should be invalid for a NIfTI dataset. +*//*-------------------------------------------------------------------*/ +int nifti_datatype_is_valid( int dtype, int for_nifti ) +{ + int tablen = sizeof(nifti_type_list)/sizeof(nifti_type_ele); + int c; + + /* special case */ + if( for_nifti && dtype == DT_BINARY ) return 0; + + for( c = tablen-1; c > 0; c-- ) + if( nifti_type_list[c].type == dtype ) + return 1; + + return 0; +} + + +/*---------------------------------------------------------------------*/ +/*! Only as a test, verify that the new nifti_type_list table matches + * the the usage of nifti_datatype_sizes (which could be changed to + * use the table, if there were interest). + * + * return the number of errors (so 0 is success, as usual) +*//*-------------------------------------------------------------------*/ +int nifti_test_datatype_sizes(int verb) +{ + int tablen = sizeof(nifti_type_list)/sizeof(nifti_type_ele); + int nbyper, ssize; + int c, errs = 0; + + for( c = 0; c < tablen; c++ ) + { + nbyper = ssize = -1; + nifti_datatype_sizes(nifti_type_list[c].type, &nbyper, &ssize); + if( nbyper < 0 || ssize < 0 || + nbyper != nifti_type_list[c].nbyper || + ssize != nifti_type_list[c].swapsize ) + { + if( verb || g_opts.debug > 2 ) + Rc_fprintf_stderr("** type mismatch: %s, %d, %d, %d : %d, %d\n", + nifti_type_list[c].name, nifti_type_list[c].type, + nifti_type_list[c].nbyper, nifti_type_list[c].swapsize, + nbyper, ssize); + errs++; + } + } + + if( errs ) + Rc_fprintf_stderr("** nifti_test_datatype_sizes: found %d errors\n",errs); + else if( verb || g_opts.debug > 1 ) + Rc_fprintf_stderr("-- nifti_test_datatype_sizes: all OK\n"); + + return errs; +} + + +/*---------------------------------------------------------------------*/ +/*! Display the nifti_type_list table. + * + * if which == 1 : display DT_* + * if which == 2 : display NIFTI_TYPE* + * else : display all +*//*-------------------------------------------------------------------*/ +int nifti_disp_type_list( int which ) +{ + const char * style; + int tablen = sizeof(nifti_type_list)/sizeof(nifti_type_ele); + int lwhich, c; + + if ( which == 1 ){ lwhich = 1; style = "DT_"; } + else if( which == 2 ){ lwhich = 2; style = "NIFTI_TYPE_"; } + else { lwhich = 3; style = "ALL"; } + + Rc_printf("nifti_type_list entries (%s) :\n" + " name type nbyper swapsize\n" + " --------------------- ---- ------ --------\n", style); + + for( c = 0; c < tablen; c++ ) + if( (lwhich & 1 && nifti_type_list[c].name[0] == 'D') || + (lwhich & 2 && nifti_type_list[c].name[0] == 'N') ) + Rc_printf(" %-22s %5d %3d %5d\n", + nifti_type_list[c].name, + nifti_type_list[c].type, + nifti_type_list[c].nbyper, + nifti_type_list[c].swapsize); + + return 0; +} + + diff --git a/src/zlib/adler32.c b/src/zlib/adler32.c new file mode 100644 index 0000000..a868f07 --- /dev/null +++ b/src/zlib/adler32.c @@ -0,0 +1,179 @@ +/* adler32.c -- compute the Adler-32 checksum of a data stream + * Copyright (C) 1995-2011 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#include "zutil.h" + +#define local static + +local uLong adler32_combine_ OF((uLong adler1, uLong adler2, z_off64_t len2)); + +#define BASE 65521 /* largest prime smaller than 65536 */ +#define NMAX 5552 +/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ + +#define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;} +#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); +#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); +#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); +#define DO16(buf) DO8(buf,0); DO8(buf,8); + +/* use NO_DIVIDE if your processor does not do division in hardware -- + try it both ways to see which is faster */ +#ifdef NO_DIVIDE +/* note that this assumes BASE is 65521, where 65536 % 65521 == 15 + (thank you to John Reiser for pointing this out) */ +# define CHOP(a) \ + do { \ + unsigned long tmp = a >> 16; \ + a &= 0xffffUL; \ + a += (tmp << 4) - tmp; \ + } while (0) +# define MOD28(a) \ + do { \ + CHOP(a); \ + if (a >= BASE) a -= BASE; \ + } while (0) +# define MOD(a) \ + do { \ + CHOP(a); \ + MOD28(a); \ + } while (0) +# define MOD63(a) \ + do { /* this assumes a is not negative */ \ + z_off64_t tmp = a >> 32; \ + a &= 0xffffffffL; \ + a += (tmp << 8) - (tmp << 5) + tmp; \ + tmp = a >> 16; \ + a &= 0xffffL; \ + a += (tmp << 4) - tmp; \ + tmp = a >> 16; \ + a &= 0xffffL; \ + a += (tmp << 4) - tmp; \ + if (a >= BASE) a -= BASE; \ + } while (0) +#else +# define MOD(a) a %= BASE +# define MOD28(a) a %= BASE +# define MOD63(a) a %= BASE +#endif + +/* ========================================================================= */ +uLong ZEXPORT adler32(adler, buf, len) + uLong adler; + const Bytef *buf; + uInt len; +{ + unsigned long sum2; + unsigned n; + + /* split Adler-32 into component sums */ + sum2 = (adler >> 16) & 0xffff; + adler &= 0xffff; + + /* in case user likes doing a byte at a time, keep it fast */ + if (len == 1) { + adler += buf[0]; + if (adler >= BASE) + adler -= BASE; + sum2 += adler; + if (sum2 >= BASE) + sum2 -= BASE; + return adler | (sum2 << 16); + } + + /* initial Adler-32 value (deferred check for len == 1 speed) */ + if (buf == Z_NULL) + return 1L; + + /* in case short lengths are provided, keep it somewhat fast */ + if (len < 16) { + while (len--) { + adler += *buf++; + sum2 += adler; + } + if (adler >= BASE) + adler -= BASE; + MOD28(sum2); /* only added so many BASE's */ + return adler | (sum2 << 16); + } + + /* do length NMAX blocks -- requires just one modulo operation */ + while (len >= NMAX) { + len -= NMAX; + n = NMAX / 16; /* NMAX is divisible by 16 */ + do { + DO16(buf); /* 16 sums unrolled */ + buf += 16; + } while (--n); + MOD(adler); + MOD(sum2); + } + + /* do remaining bytes (less than NMAX, still just one modulo) */ + if (len) { /* avoid modulos if none remaining */ + while (len >= 16) { + len -= 16; + DO16(buf); + buf += 16; + } + while (len--) { + adler += *buf++; + sum2 += adler; + } + MOD(adler); + MOD(sum2); + } + + /* return recombined sums */ + return adler | (sum2 << 16); +} + +/* ========================================================================= */ +local uLong adler32_combine_(adler1, adler2, len2) + uLong adler1; + uLong adler2; + z_off64_t len2; +{ + unsigned long sum1; + unsigned long sum2; + unsigned rem; + + /* for negative len, return invalid adler32 as a clue for debugging */ + if (len2 < 0) + return 0xffffffffUL; + + /* the derivation of this formula is left as an exercise for the reader */ + MOD63(len2); /* assumes len2 >= 0 */ + rem = (unsigned)len2; + sum1 = adler1 & 0xffff; + sum2 = rem * sum1; + MOD(sum2); + sum1 += (adler2 & 0xffff) + BASE - 1; + sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem; + if (sum1 >= BASE) sum1 -= BASE; + if (sum1 >= BASE) sum1 -= BASE; + if (sum2 >= (BASE << 1)) sum2 -= (BASE << 1); + if (sum2 >= BASE) sum2 -= BASE; + return sum1 | (sum2 << 16); +} + +/* ========================================================================= */ +uLong ZEXPORT adler32_combine(adler1, adler2, len2) + uLong adler1; + uLong adler2; + z_off_t len2; +{ + return adler32_combine_(adler1, adler2, len2); +} + +uLong ZEXPORT adler32_combine64(adler1, adler2, len2) + uLong adler1; + uLong adler2; + z_off64_t len2; +{ + return adler32_combine_(adler1, adler2, len2); +} diff --git a/src/zlib/compress.c b/src/zlib/compress.c new file mode 100644 index 0000000..0302a49 --- /dev/null +++ b/src/zlib/compress.c @@ -0,0 +1,80 @@ +/* compress.c -- compress a memory buffer + * Copyright (C) 1995-2005 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#define ZLIB_INTERNAL +#include "zlib/zlib.h" + +/* =========================================================================== + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least 0.1% larger than sourceLen plus + 12 bytes. Upon exit, destLen is the actual size of the compressed buffer. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ +int ZEXPORT compress2 (dest, destLen, source, sourceLen, level) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; + int level; +{ + z_stream stream; + int err; + + stream.next_in = (z_const Bytef *)source; + stream.avail_in = (uInt)sourceLen; +#ifdef MAXSEG_64K + /* Check for source > 64K on 16-bit machine: */ + if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; +#endif + stream.next_out = dest; + stream.avail_out = (uInt)*destLen; + if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; + + stream.zalloc = (alloc_func)0; + stream.zfree = (free_func)0; + stream.opaque = (voidpf)0; + + err = deflateInit(&stream, level); + if (err != Z_OK) return err; + + err = deflate(&stream, Z_FINISH); + if (err != Z_STREAM_END) { + deflateEnd(&stream); + return err == Z_OK ? Z_BUF_ERROR : err; + } + *destLen = stream.total_out; + + err = deflateEnd(&stream); + return err; +} + +/* =========================================================================== + */ +int ZEXPORT compress (dest, destLen, source, sourceLen) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; +{ + return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION); +} + +/* =========================================================================== + If the default memLevel or windowBits for deflateInit() is changed, then + this function needs to be updated. + */ +uLong ZEXPORT compressBound (sourceLen) + uLong sourceLen; +{ + return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + + (sourceLen >> 25) + 13; +} diff --git a/src/zlib/crc32.c b/src/zlib/crc32.c new file mode 100644 index 0000000..979a719 --- /dev/null +++ b/src/zlib/crc32.c @@ -0,0 +1,425 @@ +/* crc32.c -- compute the CRC-32 of a data stream + * Copyright (C) 1995-2006, 2010, 2011, 2012 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + * + * Thanks to Rodney Brown for his contribution of faster + * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing + * tables for updating the shift register in one step with three exclusive-ors + * instead of four steps with four exclusive-ors. This results in about a + * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3. + */ + +/* @(#) $Id$ */ + +/* + Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore + protection on the static variables used to control the first-use generation + of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should + first call get_crc_table() to initialize the tables before allowing more than + one thread to use crc32(). + + DYNAMIC_CRC_TABLE and MAKECRCH can be #defined to write out crc32.h. + */ + +#ifdef MAKECRCH +# include +# ifndef DYNAMIC_CRC_TABLE +# define DYNAMIC_CRC_TABLE +# endif /* !DYNAMIC_CRC_TABLE */ +#endif /* MAKECRCH */ + +#include "zutil.h" /* for STDC and FAR definitions */ + +#define local static + +/* Definitions for doing the crc four data bytes at a time. */ +#if !defined(NOBYFOUR) && defined(Z_U4) +# define BYFOUR +#endif +#ifdef BYFOUR + local unsigned long crc32_little OF((unsigned long, + const unsigned char FAR *, unsigned)); + local unsigned long crc32_big OF((unsigned long, + const unsigned char FAR *, unsigned)); +# define TBLS 8 +#else +# define TBLS 1 +#endif /* BYFOUR */ + +/* Local functions for crc concatenation */ +local unsigned long gf2_matrix_times OF((unsigned long *mat, + unsigned long vec)); +local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat)); +local uLong crc32_combine_ OF((uLong crc1, uLong crc2, z_off64_t len2)); + + +#ifdef DYNAMIC_CRC_TABLE + +local volatile int crc_table_empty = 1; +local z_crc_t FAR crc_table[TBLS][256]; +local void make_crc_table OF((void)); +#ifdef MAKECRCH + local void write_table OF((FILE *, const z_crc_t FAR *)); +#endif /* MAKECRCH */ +/* + Generate tables for a byte-wise 32-bit CRC calculation on the polynomial: + x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. + + Polynomials over GF(2) are represented in binary, one bit per coefficient, + with the lowest powers in the most significant bit. Then adding polynomials + is just exclusive-or, and multiplying a polynomial by x is a right shift by + one. If we call the above polynomial p, and represent a byte as the + polynomial q, also with the lowest power in the most significant bit (so the + byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, + where a mod b means the remainder after dividing a by b. + + This calculation is done using the shift-register method of multiplying and + taking the remainder. The register is initialized to zero, and for each + incoming bit, x^32 is added mod p to the register if the bit is a one (where + x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by + x (which is shifting right by one and adding x^32 mod p if the bit shifted + out is a one). We start with the highest power (least significant bit) of + q and repeat for all eight bits of q. + + The first table is simply the CRC of all possible eight bit values. This is + all the information needed to generate CRCs on data a byte at a time for all + combinations of CRC register values and incoming bytes. The remaining tables + allow for word-at-a-time CRC calculation for both big-endian and little- + endian machines, where a word is four bytes. +*/ +local void make_crc_table() +{ + z_crc_t c; + int n, k; + z_crc_t poly; /* polynomial exclusive-or pattern */ + /* terms of polynomial defining this crc (except x^32): */ + static volatile int first = 1; /* flag to limit concurrent making */ + static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; + + /* See if another task is already doing this (not thread-safe, but better + than nothing -- significantly reduces duration of vulnerability in + case the advice about DYNAMIC_CRC_TABLE is ignored) */ + if (first) { + first = 0; + + /* make exclusive-or pattern from polynomial (0xedb88320UL) */ + poly = 0; + for (n = 0; n < (int)(sizeof(p)/sizeof(unsigned char)); n++) + poly |= (z_crc_t)1 << (31 - p[n]); + + /* generate a crc for every 8-bit value */ + for (n = 0; n < 256; n++) { + c = (z_crc_t)n; + for (k = 0; k < 8; k++) + c = c & 1 ? poly ^ (c >> 1) : c >> 1; + crc_table[0][n] = c; + } + +#ifdef BYFOUR + /* generate crc for each value followed by one, two, and three zeros, + and then the byte reversal of those as well as the first table */ + for (n = 0; n < 256; n++) { + c = crc_table[0][n]; + crc_table[4][n] = ZSWAP32(c); + for (k = 1; k < 4; k++) { + c = crc_table[0][c & 0xff] ^ (c >> 8); + crc_table[k][n] = c; + crc_table[k + 4][n] = ZSWAP32(c); + } + } +#endif /* BYFOUR */ + + crc_table_empty = 0; + } + else { /* not first */ + /* wait for the other guy to finish (not efficient, but rare) */ + while (crc_table_empty) + ; + } + +#ifdef MAKECRCH + /* write out CRC tables to crc32.h */ + { + FILE *out; + + out = fopen("crc32.h", "w"); + if (out == NULL) return; + fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n"); + fprintf(out, " * Generated automatically by crc32.c\n */\n\n"); + fprintf(out, "local const z_crc_t FAR "); + fprintf(out, "crc_table[TBLS][256] =\n{\n {\n"); + write_table(out, crc_table[0]); +# ifdef BYFOUR + fprintf(out, "#ifdef BYFOUR\n"); + for (k = 1; k < 8; k++) { + fprintf(out, " },\n {\n"); + write_table(out, crc_table[k]); + } + fprintf(out, "#endif\n"); +# endif /* BYFOUR */ + fprintf(out, " }\n};\n"); + fclose(out); + } +#endif /* MAKECRCH */ +} + +#ifdef MAKECRCH +local void write_table(out, table) + FILE *out; + const z_crc_t FAR *table; +{ + int n; + + for (n = 0; n < 256; n++) + fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", + (unsigned long)(table[n]), + n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", ")); +} +#endif /* MAKECRCH */ + +#else /* !DYNAMIC_CRC_TABLE */ +/* ======================================================================== + * Tables of CRC-32s of all single-byte values, made by make_crc_table(). + */ +#include "crc32.h" +#endif /* DYNAMIC_CRC_TABLE */ + +/* ========================================================================= + * This function can be used by asm versions of crc32() + */ +const z_crc_t FAR * ZEXPORT get_crc_table() +{ +#ifdef DYNAMIC_CRC_TABLE + if (crc_table_empty) + make_crc_table(); +#endif /* DYNAMIC_CRC_TABLE */ + return (const z_crc_t FAR *)crc_table; +} + +/* ========================================================================= */ +#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8) +#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1 + +/* ========================================================================= */ +unsigned long ZEXPORT crc32(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + uInt len; +{ + if (buf == Z_NULL) return 0UL; + +#ifdef DYNAMIC_CRC_TABLE + if (crc_table_empty) + make_crc_table(); +#endif /* DYNAMIC_CRC_TABLE */ + +#ifdef BYFOUR + if (sizeof(void *) == sizeof(ptrdiff_t)) { + z_crc_t endian; + + endian = 1; + if (*((unsigned char *)(&endian))) + return crc32_little(crc, buf, len); + else + return crc32_big(crc, buf, len); + } +#endif /* BYFOUR */ + crc = crc ^ 0xffffffffUL; + while (len >= 8) { + DO8; + len -= 8; + } + if (len) do { + DO1; + } while (--len); + return crc ^ 0xffffffffUL; +} + +#ifdef BYFOUR + +/* ========================================================================= */ +#define DOLIT4 c ^= *buf4++; \ + c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \ + crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24] +#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4 + +/* ========================================================================= */ +local unsigned long crc32_little(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + unsigned len; +{ + register z_crc_t c; + register const z_crc_t FAR *buf4; + + c = (z_crc_t)crc; + c = ~c; + while (len && ((ptrdiff_t)buf & 3)) { + c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); + len--; + } + + buf4 = (const z_crc_t FAR *)(const void FAR *)buf; + while (len >= 32) { + DOLIT32; + len -= 32; + } + while (len >= 4) { + DOLIT4; + len -= 4; + } + buf = (const unsigned char FAR *)buf4; + + if (len) do { + c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); + } while (--len); + c = ~c; + return (unsigned long)c; +} + +/* ========================================================================= */ +#define DOBIG4 c ^= *++buf4; \ + c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \ + crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24] +#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4 + +/* ========================================================================= */ +local unsigned long crc32_big(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + unsigned len; +{ + register z_crc_t c; + register const z_crc_t FAR *buf4; + + c = ZSWAP32((z_crc_t)crc); + c = ~c; + while (len && ((ptrdiff_t)buf & 3)) { + c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); + len--; + } + + buf4 = (const z_crc_t FAR *)(const void FAR *)buf; + buf4--; + while (len >= 32) { + DOBIG32; + len -= 32; + } + while (len >= 4) { + DOBIG4; + len -= 4; + } + buf4++; + buf = (const unsigned char FAR *)buf4; + + if (len) do { + c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); + } while (--len); + c = ~c; + return (unsigned long)(ZSWAP32(c)); +} + +#endif /* BYFOUR */ + +#define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */ + +/* ========================================================================= */ +local unsigned long gf2_matrix_times(mat, vec) + unsigned long *mat; + unsigned long vec; +{ + unsigned long sum; + + sum = 0; + while (vec) { + if (vec & 1) + sum ^= *mat; + vec >>= 1; + mat++; + } + return sum; +} + +/* ========================================================================= */ +local void gf2_matrix_square(square, mat) + unsigned long *square; + unsigned long *mat; +{ + int n; + + for (n = 0; n < GF2_DIM; n++) + square[n] = gf2_matrix_times(mat, mat[n]); +} + +/* ========================================================================= */ +local uLong crc32_combine_(crc1, crc2, len2) + uLong crc1; + uLong crc2; + z_off64_t len2; +{ + int n; + unsigned long row; + unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */ + unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */ + + /* degenerate case (also disallow negative lengths) */ + if (len2 <= 0) + return crc1; + + /* put operator for one zero bit in odd */ + odd[0] = 0xedb88320UL; /* CRC-32 polynomial */ + row = 1; + for (n = 1; n < GF2_DIM; n++) { + odd[n] = row; + row <<= 1; + } + + /* put operator for two zero bits in even */ + gf2_matrix_square(even, odd); + + /* put operator for four zero bits in odd */ + gf2_matrix_square(odd, even); + + /* apply len2 zeros to crc1 (first square will put the operator for one + zero byte, eight zero bits, in even) */ + do { + /* apply zeros operator for this bit of len2 */ + gf2_matrix_square(even, odd); + if (len2 & 1) + crc1 = gf2_matrix_times(even, crc1); + len2 >>= 1; + + /* if no more bits set, then done */ + if (len2 == 0) + break; + + /* another iteration of the loop with odd and even swapped */ + gf2_matrix_square(odd, even); + if (len2 & 1) + crc1 = gf2_matrix_times(odd, crc1); + len2 >>= 1; + + /* if no more bits set, then done */ + } while (len2 != 0); + + /* return combined crc */ + crc1 ^= crc2; + return crc1; +} + +/* ========================================================================= */ +uLong ZEXPORT crc32_combine(crc1, crc2, len2) + uLong crc1; + uLong crc2; + z_off_t len2; +{ + return crc32_combine_(crc1, crc2, len2); +} + +uLong ZEXPORT crc32_combine64(crc1, crc2, len2) + uLong crc1; + uLong crc2; + z_off64_t len2; +{ + return crc32_combine_(crc1, crc2, len2); +} diff --git a/src/zlib/crc32.h b/src/zlib/crc32.h new file mode 100644 index 0000000..9e0c778 --- /dev/null +++ b/src/zlib/crc32.h @@ -0,0 +1,441 @@ +/* crc32.h -- tables for rapid CRC calculation + * Generated automatically by crc32.c + */ + +local const z_crc_t FAR crc_table[TBLS][256] = +{ + { + 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL, + 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL, + 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL, + 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL, + 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL, + 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL, + 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL, + 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL, + 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL, + 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL, + 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL, + 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL, + 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL, + 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL, + 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL, + 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL, + 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL, + 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL, + 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL, + 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL, + 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL, + 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL, + 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL, + 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL, + 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL, + 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL, + 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL, + 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL, + 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL, + 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL, + 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL, + 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL, + 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL, + 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL, + 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL, + 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL, + 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL, + 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL, + 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL, + 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL, + 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL, + 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL, + 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL, + 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL, + 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL, + 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL, + 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL, + 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL, + 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL, + 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL, + 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL, + 0x2d02ef8dUL +#ifdef BYFOUR + }, + { + 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL, + 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL, + 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL, + 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL, + 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL, + 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL, + 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL, + 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL, + 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL, + 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL, + 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL, + 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL, + 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL, + 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL, + 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL, + 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL, + 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL, + 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL, + 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL, + 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL, + 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL, + 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL, + 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL, + 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL, + 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL, + 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL, + 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL, + 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL, + 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL, + 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL, + 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL, + 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL, + 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL, + 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL, + 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL, + 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL, + 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL, + 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL, + 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL, + 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL, + 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL, + 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL, + 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL, + 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL, + 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL, + 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL, + 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL, + 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL, + 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL, + 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL, + 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL, + 0x9324fd72UL + }, + { + 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL, + 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL, + 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL, + 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL, + 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL, + 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL, + 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL, + 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL, + 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL, + 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL, + 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL, + 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL, + 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL, + 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL, + 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL, + 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL, + 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL, + 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL, + 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL, + 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL, + 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL, + 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL, + 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL, + 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL, + 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL, + 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL, + 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL, + 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL, + 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL, + 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL, + 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL, + 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL, + 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL, + 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL, + 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL, + 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL, + 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL, + 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL, + 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL, + 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL, + 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL, + 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL, + 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL, + 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL, + 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL, + 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL, + 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL, + 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL, + 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL, + 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL, + 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL, + 0xbe9834edUL + }, + { + 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL, + 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL, + 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL, + 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL, + 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL, + 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL, + 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL, + 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL, + 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL, + 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL, + 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL, + 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL, + 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL, + 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL, + 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL, + 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL, + 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL, + 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL, + 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL, + 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL, + 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL, + 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL, + 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL, + 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL, + 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL, + 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL, + 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL, + 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL, + 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL, + 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL, + 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL, + 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL, + 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL, + 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL, + 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL, + 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL, + 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL, + 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL, + 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL, + 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL, + 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL, + 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL, + 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL, + 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL, + 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL, + 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL, + 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL, + 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL, + 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL, + 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL, + 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL, + 0xde0506f1UL + }, + { + 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL, + 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL, + 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL, + 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL, + 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL, + 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL, + 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL, + 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL, + 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL, + 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL, + 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL, + 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL, + 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL, + 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL, + 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL, + 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL, + 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL, + 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL, + 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL, + 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL, + 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL, + 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL, + 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL, + 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL, + 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL, + 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL, + 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL, + 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL, + 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL, + 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL, + 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL, + 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL, + 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL, + 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL, + 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL, + 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL, + 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL, + 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL, + 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL, + 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL, + 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL, + 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL, + 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL, + 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL, + 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL, + 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL, + 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL, + 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL, + 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL, + 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL, + 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL, + 0x8def022dUL + }, + { + 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL, + 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL, + 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL, + 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL, + 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL, + 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL, + 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL, + 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL, + 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL, + 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL, + 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL, + 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL, + 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL, + 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL, + 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL, + 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL, + 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL, + 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL, + 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL, + 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL, + 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL, + 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL, + 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL, + 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL, + 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL, + 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL, + 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL, + 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL, + 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL, + 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL, + 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL, + 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL, + 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL, + 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL, + 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL, + 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL, + 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL, + 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL, + 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL, + 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL, + 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL, + 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL, + 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL, + 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL, + 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL, + 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL, + 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL, + 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL, + 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL, + 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL, + 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL, + 0x72fd2493UL + }, + { + 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL, + 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL, + 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL, + 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL, + 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL, + 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL, + 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL, + 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL, + 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL, + 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL, + 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL, + 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL, + 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL, + 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL, + 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL, + 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL, + 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL, + 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL, + 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL, + 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL, + 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL, + 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL, + 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL, + 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL, + 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL, + 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL, + 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL, + 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL, + 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL, + 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL, + 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL, + 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL, + 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL, + 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL, + 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL, + 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL, + 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL, + 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL, + 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL, + 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL, + 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL, + 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL, + 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL, + 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL, + 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL, + 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL, + 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL, + 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL, + 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL, + 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL, + 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL, + 0xed3498beUL + }, + { + 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL, + 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL, + 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL, + 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL, + 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL, + 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL, + 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL, + 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL, + 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL, + 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL, + 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL, + 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL, + 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL, + 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL, + 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL, + 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL, + 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL, + 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL, + 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL, + 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL, + 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL, + 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL, + 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL, + 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL, + 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL, + 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL, + 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL, + 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL, + 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL, + 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL, + 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL, + 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL, + 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL, + 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL, + 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL, + 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL, + 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL, + 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL, + 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL, + 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL, + 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL, + 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL, + 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL, + 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL, + 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL, + 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL, + 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL, + 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL, + 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL, + 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL, + 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL, + 0xf10605deUL +#endif + } +}; diff --git a/src/zlib/deflate.c b/src/zlib/deflate.c new file mode 100644 index 0000000..6969577 --- /dev/null +++ b/src/zlib/deflate.c @@ -0,0 +1,1967 @@ +/* deflate.c -- compress data using the deflation algorithm + * Copyright (C) 1995-2013 Jean-loup Gailly and Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * ALGORITHM + * + * The "deflation" process depends on being able to identify portions + * of the input text which are identical to earlier input (within a + * sliding window trailing behind the input currently being processed). + * + * The most straightforward technique turns out to be the fastest for + * most input files: try all possible matches and select the longest. + * The key feature of this algorithm is that insertions into the string + * dictionary are very simple and thus fast, and deletions are avoided + * completely. Insertions are performed at each input character, whereas + * string matches are performed only when the previous match ends. So it + * is preferable to spend more time in matches to allow very fast string + * insertions and avoid deletions. The matching algorithm for small + * strings is inspired from that of Rabin & Karp. A brute force approach + * is used to find longer strings when a small match has been found. + * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze + * (by Leonid Broukhis). + * A previous version of this file used a more sophisticated algorithm + * (by Fiala and Greene) which is guaranteed to run in linear amortized + * time, but has a larger average cost, uses more memory and is patented. + * However the F&G algorithm may be faster for some highly redundant + * files if the parameter max_chain_length (described below) is too large. + * + * ACKNOWLEDGEMENTS + * + * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and + * I found it in 'freeze' written by Leonid Broukhis. + * Thanks to many people for bug reports and testing. + * + * REFERENCES + * + * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification". + * Available in http://tools.ietf.org/html/rfc1951 + * + * A description of the Rabin and Karp algorithm is given in the book + * "Algorithms" by R. Sedgewick, Addison-Wesley, p252. + * + * Fiala,E.R., and Greene,D.H. + * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595 + * + */ + +/* @(#) $Id$ */ + +#include "deflate.h" + +const char deflate_copyright[] = + " deflate 1.2.8 Copyright 1995-2013 Jean-loup Gailly and Mark Adler "; +/* + If you use the zlib library in a product, an acknowledgment is welcome + in the documentation of your product. If for some reason you cannot + include such an acknowledgment, I would appreciate that you keep this + copyright string in the executable of your product. + */ + +/* =========================================================================== + * Function prototypes. + */ +typedef enum { + need_more, /* block not completed, need more input or more output */ + block_done, /* block flush performed */ + finish_started, /* finish started, need only more output at next deflate */ + finish_done /* finish done, accept no more input or output */ +} block_state; + +typedef block_state (*compress_func) OF((deflate_state *s, int flush)); +/* Compression function. Returns the block state after the call. */ + +local void fill_window OF((deflate_state *s)); +local block_state deflate_stored OF((deflate_state *s, int flush)); +local block_state deflate_fast OF((deflate_state *s, int flush)); +#ifndef FASTEST +local block_state deflate_slow OF((deflate_state *s, int flush)); +#endif +local block_state deflate_rle OF((deflate_state *s, int flush)); +local block_state deflate_huff OF((deflate_state *s, int flush)); +local void lm_init OF((deflate_state *s)); +local void putShortMSB OF((deflate_state *s, uInt b)); +local void flush_pending OF((z_streamp strm)); +local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); +#ifdef ASMV + void match_init OF((void)); /* asm code initialization */ + uInt longest_match OF((deflate_state *s, IPos cur_match)); +#else +local uInt longest_match OF((deflate_state *s, IPos cur_match)); +#endif + +#ifdef DEBUG +local void check_match OF((deflate_state *s, IPos start, IPos match, + int length)); +#endif + +/* =========================================================================== + * Local data + */ + +#define NIL 0 +/* Tail of hash chains */ + +#ifndef TOO_FAR +# define TOO_FAR 4096 +#endif +/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +typedef struct config_s { + ush good_length; /* reduce lazy search above this match length */ + ush max_lazy; /* do not perform lazy search above this match length */ + ush nice_length; /* quit search above this match length */ + ush max_chain; + compress_func func; +} config; + +#ifdef FASTEST +local const config configuration_table[2] = { +/* good lazy nice chain */ +/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ +/* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */ +#else +local const config configuration_table[10] = { +/* good lazy nice chain */ +/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ +/* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */ +/* 2 */ {4, 5, 16, 8, deflate_fast}, +/* 3 */ {4, 6, 32, 32, deflate_fast}, + +/* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */ +/* 5 */ {8, 16, 32, 32, deflate_slow}, +/* 6 */ {8, 16, 128, 128, deflate_slow}, +/* 7 */ {8, 32, 128, 256, deflate_slow}, +/* 8 */ {32, 128, 258, 1024, deflate_slow}, +/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */ +#endif + +/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 + * For deflate_fast() (levels <= 3) good is ignored and lazy has a different + * meaning. + */ + +#define EQUAL 0 +/* result of memcmp for equal strings */ + +#ifndef NO_DUMMY_DECL +struct static_tree_desc_s {int dummy;}; /* for buggy compilers */ +#endif + +/* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */ +#define RANK(f) (((f) << 1) - ((f) > 4 ? 9 : 0)) + +/* =========================================================================== + * Update a hash value with the given input byte + * IN assertion: all calls to to UPDATE_HASH are made with consecutive + * input characters, so that a running hash key can be computed from the + * previous key instead of complete recalculation each time. + */ +#define UPDATE_HASH(s,h,c) (h = (((h)<hash_shift) ^ (c)) & s->hash_mask) + + +/* =========================================================================== + * Insert string str in the dictionary and set match_head to the previous head + * of the hash chain (the most recent string with same hash key). Return + * the previous length of the hash chain. + * If this file is compiled with -DFASTEST, the compression level is forced + * to 1, and no hash chains are maintained. + * IN assertion: all calls to to INSERT_STRING are made with consecutive + * input characters and the first MIN_MATCH bytes of str are valid + * (except for the last MIN_MATCH-1 bytes of the input file). + */ +#ifdef FASTEST +#define INSERT_STRING(s, str, match_head) \ + (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ + match_head = s->head[s->ins_h], \ + s->head[s->ins_h] = (Pos)(str)) +#else +#define INSERT_STRING(s, str, match_head) \ + (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ + match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \ + s->head[s->ins_h] = (Pos)(str)) +#endif + +/* =========================================================================== + * Initialize the hash table (avoiding 64K overflow for 16 bit systems). + * prev[] will be initialized on the fly. + */ +#define CLEAR_HASH(s) \ + s->head[s->hash_size-1] = NIL; \ + zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head)); + +/* ========================================================================= */ +int ZEXPORT deflateInit_(strm, level, version, stream_size) + z_streamp strm; + int level; + const char *version; + int stream_size; +{ + return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, + Z_DEFAULT_STRATEGY, version, stream_size); + /* To do: ignore strm->next_in if we use it as window */ +} + +/* ========================================================================= */ +int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, + version, stream_size) + z_streamp strm; + int level; + int method; + int windowBits; + int memLevel; + int strategy; + const char *version; + int stream_size; +{ + deflate_state *s; + int wrap = 1; + static const char my_version[] = ZLIB_VERSION; + + ushf *overlay; + /* We overlay pending_buf and d_buf+l_buf. This works since the average + * output size for (length,distance) codes is <= 24 bits. + */ + + if (version == Z_NULL || version[0] != my_version[0] || + stream_size != sizeof(z_stream)) { + return Z_VERSION_ERROR; + } + if (strm == Z_NULL) return Z_STREAM_ERROR; + + strm->msg = Z_NULL; + if (strm->zalloc == (alloc_func)0) { +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; +#endif + } + if (strm->zfree == (free_func)0) +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zfree = zcfree; +#endif + +#ifdef FASTEST + if (level != 0) level = 1; +#else + if (level == Z_DEFAULT_COMPRESSION) level = 6; +#endif + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } +#ifdef GZIP + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } +#endif + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED) { + return Z_STREAM_ERROR; + } + if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */ + s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state)); + if (s == Z_NULL) return Z_MEM_ERROR; + strm->state = (struct internal_state FAR *)s; + s->strm = strm; + + s->wrap = wrap; + s->gzhead = Z_NULL; + s->w_bits = windowBits; + s->w_size = 1 << s->w_bits; + s->w_mask = s->w_size - 1; + + s->hash_bits = memLevel + 7; + s->hash_size = 1 << s->hash_bits; + s->hash_mask = s->hash_size - 1; + s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); + + s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); + s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); + s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); + + s->high_water = 0; /* nothing written to s->window yet */ + + s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + s->pending_buf = (uchf *) overlay; + s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L); + + if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || + s->pending_buf == Z_NULL) { + s->status = FINISH_STATE; + strm->msg = ERR_MSG(Z_MEM_ERROR); + deflateEnd (strm); + return Z_MEM_ERROR; + } + s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + + s->level = level; + s->strategy = strategy; + s->method = (Byte)method; + + return deflateReset(strm); +} + +/* ========================================================================= */ +int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) + z_streamp strm; + const Bytef *dictionary; + uInt dictLength; +{ + deflate_state *s; + uInt str, n; + int wrap; + unsigned avail; + z_const unsigned char *next; + + if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL) + return Z_STREAM_ERROR; + s = strm->state; + wrap = s->wrap; + if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead) + return Z_STREAM_ERROR; + + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap == 1) + strm->adler = adler32(strm->adler, dictionary, dictLength); + s->wrap = 0; /* avoid computing Adler-32 in read_buf */ + + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s->w_size) { + if (wrap == 0) { /* already empty otherwise */ + CLEAR_HASH(s); + s->strstart = 0; + s->block_start = 0L; + s->insert = 0; + } + dictionary += dictLength - s->w_size; /* use the tail */ + dictLength = s->w_size; + } + + /* insert dictionary into window and hash */ + avail = strm->avail_in; + next = strm->next_in; + strm->avail_in = dictLength; + strm->next_in = (z_const Bytef *)dictionary; + fill_window(s); + while (s->lookahead >= MIN_MATCH) { + str = s->strstart; + n = s->lookahead - (MIN_MATCH-1); + do { + UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); +#ifndef FASTEST + s->prev[str & s->w_mask] = s->head[s->ins_h]; +#endif + s->head[s->ins_h] = (Pos)str; + str++; + } while (--n); + s->strstart = str; + s->lookahead = MIN_MATCH-1; + fill_window(s); + } + s->strstart += s->lookahead; + s->block_start = (long)s->strstart; + s->insert = s->lookahead; + s->lookahead = 0; + s->match_length = s->prev_length = MIN_MATCH-1; + s->match_available = 0; + strm->next_in = next; + strm->avail_in = avail; + s->wrap = wrap; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateResetKeep (strm) + z_streamp strm; +{ + deflate_state *s; + + if (strm == Z_NULL || strm->state == Z_NULL || + strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) { + return Z_STREAM_ERROR; + } + + strm->total_in = strm->total_out = 0; + strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */ + strm->data_type = Z_UNKNOWN; + + s = (deflate_state *)strm->state; + s->pending = 0; + s->pending_out = s->pending_buf; + + if (s->wrap < 0) { + s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */ + } + s->status = s->wrap ? INIT_STATE : BUSY_STATE; + strm->adler = +#ifdef GZIP + s->wrap == 2 ? crc32(0L, Z_NULL, 0) : +#endif + adler32(0L, Z_NULL, 0); + s->last_flush = Z_NO_FLUSH; + + _tr_init(s); + + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateReset (strm) + z_streamp strm; +{ + int ret; + + ret = deflateResetKeep(strm); + if (ret == Z_OK) + lm_init(strm->state); + return ret; +} + +/* ========================================================================= */ +int ZEXPORT deflateSetHeader (strm, head) + z_streamp strm; + gz_headerp head; +{ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + if (strm->state->wrap != 2) return Z_STREAM_ERROR; + strm->state->gzhead = head; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflatePending (strm, pending, bits) + unsigned *pending; + int *bits; + z_streamp strm; +{ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + if (pending != Z_NULL) + *pending = strm->state->pending; + if (bits != Z_NULL) + *bits = strm->state->bi_valid; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflatePrime (strm, bits, value) + z_streamp strm; + int bits; + int value; +{ + deflate_state *s; + int put; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + s = strm->state; + if ((Bytef *)(s->d_buf) < s->pending_out + ((Buf_size + 7) >> 3)) + return Z_BUF_ERROR; + do { + put = Buf_size - s->bi_valid; + if (put > bits) + put = bits; + s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid); + s->bi_valid += put; + _tr_flush_bits(s); + value >>= put; + bits -= put; + } while (bits); + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateParams(strm, level, strategy) + z_streamp strm; + int level; + int strategy; +{ + deflate_state *s; + compress_func func; + int err = Z_OK; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + s = strm->state; + +#ifdef FASTEST + if (level != 0) level = 1; +#else + if (level == Z_DEFAULT_COMPRESSION) level = 6; +#endif + if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { + return Z_STREAM_ERROR; + } + func = configuration_table[s->level].func; + + if ((strategy != s->strategy || func != configuration_table[level].func) && + strm->total_in != 0) { + /* Flush the last buffer: */ + err = deflate(strm, Z_BLOCK); + if (err == Z_BUF_ERROR && s->pending == 0) + err = Z_OK; + } + if (s->level != level) { + s->level = level; + s->max_lazy_match = configuration_table[level].max_lazy; + s->good_match = configuration_table[level].good_length; + s->nice_match = configuration_table[level].nice_length; + s->max_chain_length = configuration_table[level].max_chain; + } + s->strategy = strategy; + return err; +} + +/* ========================================================================= */ +int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain) + z_streamp strm; + int good_length; + int max_lazy; + int nice_length; + int max_chain; +{ + deflate_state *s; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + s = strm->state; + s->good_match = good_length; + s->max_lazy_match = max_lazy; + s->nice_match = nice_length; + s->max_chain_length = max_chain; + return Z_OK; +} + +/* ========================================================================= + * For the default windowBits of 15 and memLevel of 8, this function returns + * a close to exact, as well as small, upper bound on the compressed size. + * They are coded as constants here for a reason--if the #define's are + * changed, then this function needs to be changed as well. The return + * value for 15 and 8 only works for those exact settings. + * + * For any setting other than those defaults for windowBits and memLevel, + * the value returned is a conservative worst case for the maximum expansion + * resulting from using fixed blocks instead of stored blocks, which deflate + * can emit on compressed data for some combinations of the parameters. + * + * This function could be more sophisticated to provide closer upper bounds for + * every combination of windowBits and memLevel. But even the conservative + * upper bound of about 14% expansion does not seem onerous for output buffer + * allocation. + */ +uLong ZEXPORT deflateBound(strm, sourceLen) + z_streamp strm; + uLong sourceLen; +{ + deflate_state *s; + uLong complen, wraplen; + Bytef *str; + + /* conservative upper bound for compressed data */ + complen = sourceLen + + ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5; + + /* if can't get parameters, return conservative bound plus zlib wrapper */ + if (strm == Z_NULL || strm->state == Z_NULL) + return complen + 6; + + /* compute wrapper length */ + s = strm->state; + switch (s->wrap) { + case 0: /* raw deflate */ + wraplen = 0; + break; + case 1: /* zlib wrapper */ + wraplen = 6 + (s->strstart ? 4 : 0); + break; + case 2: /* gzip wrapper */ + wraplen = 18; + if (s->gzhead != Z_NULL) { /* user-supplied gzip header */ + if (s->gzhead->extra != Z_NULL) + wraplen += 2 + s->gzhead->extra_len; + str = s->gzhead->name; + if (str != Z_NULL) + do { + wraplen++; + } while (*str++); + str = s->gzhead->comment; + if (str != Z_NULL) + do { + wraplen++; + } while (*str++); + if (s->gzhead->hcrc) + wraplen += 2; + } + break; + default: /* for compiler happiness */ + wraplen = 6; + } + + /* if not default parameters, return conservative bound */ + if (s->w_bits != 15 || s->hash_bits != 8 + 7) + return complen + wraplen; + + /* default settings: return tight bound for that case */ + return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + + (sourceLen >> 25) + 13 - 6 + wraplen; +} + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +local void putShortMSB (s, b) + deflate_state *s; + uInt b; +{ + put_byte(s, (Byte)(b >> 8)); + put_byte(s, (Byte)(b & 0xff)); +} + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->next_out buffer and copying into it. + * (See also read_buf()). + */ +local void flush_pending(strm) + z_streamp strm; +{ + unsigned len; + deflate_state *s = strm->state; + + _tr_flush_bits(s); + len = s->pending; + if (len > strm->avail_out) len = strm->avail_out; + if (len == 0) return; + + zmemcpy(strm->next_out, s->pending_out, len); + strm->next_out += len; + s->pending_out += len; + strm->total_out += len; + strm->avail_out -= len; + s->pending -= len; + if (s->pending == 0) { + s->pending_out = s->pending_buf; + } +} + +/* ========================================================================= */ +int ZEXPORT deflate (strm, flush) + z_streamp strm; + int flush; +{ + int old_flush; /* value of flush param for previous deflate call */ + deflate_state *s; + + if (strm == Z_NULL || strm->state == Z_NULL || + flush > Z_BLOCK || flush < 0) { + return Z_STREAM_ERROR; + } + s = strm->state; + + if (strm->next_out == Z_NULL || + (strm->next_in == Z_NULL && strm->avail_in != 0) || + (s->status == FINISH_STATE && flush != Z_FINISH)) { + ERR_RETURN(strm, Z_STREAM_ERROR); + } + if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR); + + s->strm = strm; /* just in case */ + old_flush = s->last_flush; + s->last_flush = flush; + + /* Write the header */ + if (s->status == INIT_STATE) { +#ifdef GZIP + if (s->wrap == 2) { + strm->adler = crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (s->gzhead == Z_NULL) { + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s->level == 9 ? 2 : + (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s->status = BUSY_STATE; + } + else { + put_byte(s, (s->gzhead->text ? 1 : 0) + + (s->gzhead->hcrc ? 2 : 0) + + (s->gzhead->extra == Z_NULL ? 0 : 4) + + (s->gzhead->name == Z_NULL ? 0 : 8) + + (s->gzhead->comment == Z_NULL ? 0 : 16) + ); + put_byte(s, (Byte)(s->gzhead->time & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff)); + put_byte(s, s->level == 9 ? 2 : + (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? + 4 : 0)); + put_byte(s, s->gzhead->os & 0xff); + if (s->gzhead->extra != Z_NULL) { + put_byte(s, s->gzhead->extra_len & 0xff); + put_byte(s, (s->gzhead->extra_len >> 8) & 0xff); + } + if (s->gzhead->hcrc) + strm->adler = crc32(strm->adler, s->pending_buf, + s->pending); + s->gzindex = 0; + s->status = EXTRA_STATE; + } + } + else +#endif + { + uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; + uInt level_flags; + + if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2) + level_flags = 0; + else if (s->level < 6) + level_flags = 1; + else if (s->level == 6) + level_flags = 2; + else + level_flags = 3; + header |= (level_flags << 6); + if (s->strstart != 0) header |= PRESET_DICT; + header += 31 - (header % 31); + + s->status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s->strstart != 0) { + putShortMSB(s, (uInt)(strm->adler >> 16)); + putShortMSB(s, (uInt)(strm->adler & 0xffff)); + } + strm->adler = adler32(0L, Z_NULL, 0); + } + } +#ifdef GZIP + if (s->status == EXTRA_STATE) { + if (s->gzhead->extra != Z_NULL) { + uInt beg = s->pending; /* start of bytes to update crc */ + + while (s->gzindex < (s->gzhead->extra_len & 0xffff)) { + if (s->pending == s->pending_buf_size) { + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + flush_pending(strm); + beg = s->pending; + if (s->pending == s->pending_buf_size) + break; + } + put_byte(s, s->gzhead->extra[s->gzindex]); + s->gzindex++; + } + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + if (s->gzindex == s->gzhead->extra_len) { + s->gzindex = 0; + s->status = NAME_STATE; + } + } + else + s->status = NAME_STATE; + } + if (s->status == NAME_STATE) { + if (s->gzhead->name != Z_NULL) { + uInt beg = s->pending; /* start of bytes to update crc */ + int val; + + do { + if (s->pending == s->pending_buf_size) { + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + flush_pending(strm); + beg = s->pending; + if (s->pending == s->pending_buf_size) { + val = 1; + break; + } + } + val = s->gzhead->name[s->gzindex++]; + put_byte(s, val); + } while (val != 0); + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + if (val == 0) { + s->gzindex = 0; + s->status = COMMENT_STATE; + } + } + else + s->status = COMMENT_STATE; + } + if (s->status == COMMENT_STATE) { + if (s->gzhead->comment != Z_NULL) { + uInt beg = s->pending; /* start of bytes to update crc */ + int val; + + do { + if (s->pending == s->pending_buf_size) { + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + flush_pending(strm); + beg = s->pending; + if (s->pending == s->pending_buf_size) { + val = 1; + break; + } + } + val = s->gzhead->comment[s->gzindex++]; + put_byte(s, val); + } while (val != 0); + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + if (val == 0) + s->status = HCRC_STATE; + } + else + s->status = HCRC_STATE; + } + if (s->status == HCRC_STATE) { + if (s->gzhead->hcrc) { + if (s->pending + 2 > s->pending_buf_size) + flush_pending(strm); + if (s->pending + 2 <= s->pending_buf_size) { + put_byte(s, (Byte)(strm->adler & 0xff)); + put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); + strm->adler = crc32(0L, Z_NULL, 0); + s->status = BUSY_STATE; + } + } + else + s->status = BUSY_STATE; + } +#endif + + /* Flush as much pending output as possible */ + if (s->pending != 0) { + flush_pending(strm); + if (strm->avail_out == 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s->last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) && + flush != Z_FINISH) { + ERR_RETURN(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s->status == FINISH_STATE && strm->avail_in != 0) { + ERR_RETURN(strm, Z_BUF_ERROR); + } + + /* Start a new block or continue the current one. + */ + if (strm->avail_in != 0 || s->lookahead != 0 || + (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { + block_state bstate; + + bstate = s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) : + (s->strategy == Z_RLE ? deflate_rle(s, flush) : + (*(configuration_table[s->level].func))(s, flush)); + + if (bstate == finish_started || bstate == finish_done) { + s->status = FINISH_STATE; + } + if (bstate == need_more || bstate == finish_started) { + if (strm->avail_out == 0) { + s->last_flush = -1; /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate == block_done) { + if (flush == Z_PARTIAL_FLUSH) { + _tr_align(s); + } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ + _tr_stored_block(s, (char*)0, 0L, 0); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush == Z_FULL_FLUSH) { + CLEAR_HASH(s); /* forget history */ + if (s->lookahead == 0) { + s->strstart = 0; + s->block_start = 0L; + s->insert = 0; + } + } + } + flush_pending(strm); + if (strm->avail_out == 0) { + s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + Assert(strm->avail_out > 0, "bug2"); + + if (flush != Z_FINISH) return Z_OK; + if (s->wrap <= 0) return Z_STREAM_END; + + /* Write the trailer */ +#ifdef GZIP + if (s->wrap == 2) { + put_byte(s, (Byte)(strm->adler & 0xff)); + put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); + put_byte(s, (Byte)((strm->adler >> 16) & 0xff)); + put_byte(s, (Byte)((strm->adler >> 24) & 0xff)); + put_byte(s, (Byte)(strm->total_in & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 8) & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 16) & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 24) & 0xff)); + } + else +#endif + { + putShortMSB(s, (uInt)(strm->adler >> 16)); + putShortMSB(s, (uInt)(strm->adler & 0xffff)); + } + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */ + return s->pending != 0 ? Z_OK : Z_STREAM_END; +} + +/* ========================================================================= */ +int ZEXPORT deflateEnd (strm) + z_streamp strm; +{ + int status; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + + status = strm->state->status; + if (status != INIT_STATE && + status != EXTRA_STATE && + status != NAME_STATE && + status != COMMENT_STATE && + status != HCRC_STATE && + status != BUSY_STATE && + status != FINISH_STATE) { + return Z_STREAM_ERROR; + } + + /* Deallocate in reverse order of allocations: */ + TRY_FREE(strm, strm->state->pending_buf); + TRY_FREE(strm, strm->state->head); + TRY_FREE(strm, strm->state->prev); + TRY_FREE(strm, strm->state->window); + + ZFREE(strm, strm->state); + strm->state = Z_NULL; + + return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; +} + +/* ========================================================================= + * Copy the source state to the destination state. + * To simplify the source, this is not supported for 16-bit MSDOS (which + * doesn't have enough memory anyway to duplicate compression states). + */ +int ZEXPORT deflateCopy (dest, source) + z_streamp dest; + z_streamp source; +{ +#ifdef MAXSEG_64K + return Z_STREAM_ERROR; +#else + deflate_state *ds; + deflate_state *ss; + ushf *overlay; + + + if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) { + return Z_STREAM_ERROR; + } + + ss = source->state; + + zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream)); + + ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); + if (ds == Z_NULL) return Z_MEM_ERROR; + dest->state = (struct internal_state FAR *) ds; + zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state)); + ds->strm = dest; + + ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); + ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); + ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); + overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2); + ds->pending_buf = (uchf *) overlay; + + if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || + ds->pending_buf == Z_NULL) { + deflateEnd (dest); + return Z_MEM_ERROR; + } + /* following zmemcpy do not work for 16-bit MSDOS */ + zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); + zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos)); + zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos)); + zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); + + ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); + ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush); + ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize; + + ds->l_desc.dyn_tree = ds->dyn_ltree; + ds->d_desc.dyn_tree = ds->dyn_dtree; + ds->bl_desc.dyn_tree = ds->bl_tree; + + return Z_OK; +#endif /* MAXSEG_64K */ +} + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->next_in buffer and copying from it. + * (See also flush_pending()). + */ +local int read_buf(strm, buf, size) + z_streamp strm; + Bytef *buf; + unsigned size; +{ + unsigned len = strm->avail_in; + + if (len > size) len = size; + if (len == 0) return 0; + + strm->avail_in -= len; + + zmemcpy(buf, strm->next_in, len); + if (strm->state->wrap == 1) { + strm->adler = adler32(strm->adler, buf, len); + } +#ifdef GZIP + else if (strm->state->wrap == 2) { + strm->adler = crc32(strm->adler, buf, len); + } +#endif + strm->next_in += len; + strm->total_in += len; + + return (int)len; +} + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +local void lm_init (s) + deflate_state *s; +{ + s->window_size = (ulg)2L*s->w_size; + + CLEAR_HASH(s); + + /* Set the default configuration parameters: + */ + s->max_lazy_match = configuration_table[s->level].max_lazy; + s->good_match = configuration_table[s->level].good_length; + s->nice_match = configuration_table[s->level].nice_length; + s->max_chain_length = configuration_table[s->level].max_chain; + + s->strstart = 0; + s->block_start = 0L; + s->lookahead = 0; + s->insert = 0; + s->match_length = s->prev_length = MIN_MATCH-1; + s->match_available = 0; + s->ins_h = 0; +#ifndef FASTEST +#ifdef ASMV + match_init(); /* initialize the asm code */ +#endif +#endif +} + +#ifndef FASTEST +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +#ifndef ASMV +/* For 80x86 and 680x0, an optimized version will be provided in match.asm or + * match.S. The code will be functionally equivalent. + */ +local uInt longest_match(s, cur_match) + deflate_state *s; + IPos cur_match; /* current match */ +{ + unsigned chain_length = s->max_chain_length;/* max hash chain length */ + register Bytef *scan = s->window + s->strstart; /* current string */ + register Bytef *match; /* matched string */ + register int len; /* length of current match */ + int best_len = s->prev_length; /* best match length so far */ + int nice_match = s->nice_match; /* stop if match long enough */ + IPos limit = s->strstart > (IPos)MAX_DIST(s) ? + s->strstart - (IPos)MAX_DIST(s) : NIL; + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + Posf *prev = s->prev; + uInt wmask = s->w_mask; + +#ifdef UNALIGNED_OK + /* Compare two bytes at a time. Note: this is not always beneficial. + * Try with and without -DUNALIGNED_OK to check. + */ + register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; + register ush scan_start = *(ushf*)scan; + register ush scan_end = *(ushf*)(scan+best_len-1); +#else + register Bytef *strend = s->window + s->strstart + MAX_MATCH; + register Byte scan_end1 = scan[best_len-1]; + register Byte scan_end = scan[best_len]; +#endif + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s->prev_length >= s->good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; + + Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + Assert(cur_match < s->strstart, "no future"); + match = s->window + cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ +#if (defined(UNALIGNED_OK) && MAX_MATCH == 258) + /* This code assumes sizeof(unsigned short) == 2. Do not use + * UNALIGNED_OK if your compiler uses a different size. + */ + if (*(ushf*)(match+best_len-1) != scan_end || + *(ushf*)match != scan_start) continue; + + /* It is not necessary to compare scan[2] and match[2] since they are + * always equal when the other bytes match, given that the hash keys + * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at + * strstart+3, +5, ... up to strstart+257. We check for insufficient + * lookahead only every 4th comparison; the 128th check will be made + * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is + * necessary to put more guard bytes at the end of the window, or + * to check more often for insufficient lookahead. + */ + Assert(scan[2] == match[2], "scan[2]?"); + scan++, match++; + do { + } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + scan < strend); + /* The funny "do {}" generates better code on most compilers */ + + /* Here, scan <= window+strstart+257 */ + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + if (*scan == *match) scan++; + + len = (MAX_MATCH - 1) - (int)(strend-scan); + scan = strend - (MAX_MATCH-1); + +#else /* UNALIGNED_OK */ + + if (match[best_len] != scan_end || + match[best_len-1] != scan_end1 || + *match != *scan || + *++match != scan[1]) continue; + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2, match++; + Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + scan < strend); + + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + scan = strend - MAX_MATCH; + +#endif /* UNALIGNED_OK */ + + if (len > best_len) { + s->match_start = cur_match; + best_len = len; + if (len >= nice_match) break; +#ifdef UNALIGNED_OK + scan_end = *(ushf*)(scan+best_len-1); +#else + scan_end1 = scan[best_len-1]; + scan_end = scan[best_len]; +#endif + } + } while ((cur_match = prev[cur_match & wmask]) > limit + && --chain_length != 0); + + if ((uInt)best_len <= s->lookahead) return (uInt)best_len; + return s->lookahead; +} +#endif /* ASMV */ + +#else /* FASTEST */ + +/* --------------------------------------------------------------------------- + * Optimized version for FASTEST only + */ +local uInt longest_match(s, cur_match) + deflate_state *s; + IPos cur_match; /* current match */ +{ + register Bytef *scan = s->window + s->strstart; /* current string */ + register Bytef *match; /* matched string */ + register int len; /* length of current match */ + register Bytef *strend = s->window + s->strstart + MAX_MATCH; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + Assert(cur_match < s->strstart, "no future"); + + match = s->window + cur_match; + + /* Return failure if the match length is less than 2: + */ + if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1; + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2, match += 2; + Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + scan < strend); + + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + + if (len < MIN_MATCH) return MIN_MATCH - 1; + + s->match_start = cur_match; + return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead; +} + +#endif /* FASTEST */ + +#ifdef DEBUG +/* =========================================================================== + * Check that the match at match_start is indeed a match. + */ +local void check_match(s, start, match, length) + deflate_state *s; + IPos start, match; + int length; +{ + /* check that the match is indeed a match */ + if (zmemcmp(s->window + match, + s->window + start, length) != EQUAL) { + fprintf(stderr, " start %u, match %u, length %d\n", + start, match, length); + do { + fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); + } while (--length != 0); + z_error("invalid match"); + } + if (z_verbose > 1) { + fprintf(stderr,"\\[%d,%d]", start-match, length); + do { putc(s->window[start++], stderr); } while (--length != 0); + } +} +#else +# define check_match(s, start, match, length) +#endif /* DEBUG */ + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +local void fill_window(s) + deflate_state *s; +{ + register unsigned n, m; + register Posf *p; + unsigned more; /* Amount of free space at the end of the window. */ + uInt wsize = s->w_size; + + Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); + + /* Deal with !@#$% 64K limit: */ + if (sizeof(int) <= 2) { + if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + more = wsize; + + } else if (more == (unsigned)(-1)) { + /* Very unlikely, but possible on 16 bit machine if + * strstart == 0 && lookahead == 1 (input done a byte at time) + */ + more--; + } + } + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s->strstart >= wsize+MAX_DIST(s)) { + + zmemcpy(s->window, s->window+wsize, (unsigned)wsize); + s->match_start -= wsize; + s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ + s->block_start -= (long) wsize; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + n = s->hash_size; + p = &s->head[n]; + do { + m = *--p; + *p = (Pos)(m >= wsize ? m-wsize : NIL); + } while (--n); + + n = wsize; +#ifndef FASTEST + p = &s->prev[n]; + do { + m = *--p; + *p = (Pos)(m >= wsize ? m-wsize : NIL); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); +#endif + more += wsize; + } + if (s->strm->avail_in == 0) break; + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + Assert(more >= 2, "more < 2"); + + n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); + s->lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s->lookahead + s->insert >= MIN_MATCH) { + uInt str = s->strstart - s->insert; + s->ins_h = s->window[str]; + UPDATE_HASH(s, s->ins_h, s->window[str + 1]); +#if MIN_MATCH != 3 + Call UPDATE_HASH() MIN_MATCH-3 more times +#endif + while (s->insert) { + UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); +#ifndef FASTEST + s->prev[str & s->w_mask] = s->head[s->ins_h]; +#endif + s->head[s->ins_h] = (Pos)str; + str++; + s->insert--; + if (s->lookahead + s->insert < MIN_MATCH) + break; + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ + if (s->high_water < s->window_size) { + ulg curr = s->strstart + (ulg)(s->lookahead); + ulg init; + + if (s->high_water < curr) { + /* Previous high water mark below current data -- zero WIN_INIT + * bytes or up to end of window, whichever is less. + */ + init = s->window_size - curr; + if (init > WIN_INIT) + init = WIN_INIT; + zmemzero(s->window + curr, (unsigned)init); + s->high_water = curr + init; + } + else if (s->high_water < (ulg)curr + WIN_INIT) { + /* High water mark at or above current data, but below current data + * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up + * to end of window, whichever is less. + */ + init = (ulg)curr + WIN_INIT - s->high_water; + if (init > s->window_size - s->high_water) + init = s->window_size - s->high_water; + zmemzero(s->window + s->high_water, (unsigned)init); + s->high_water += init; + } + } + + Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, + "not enough room for search"); +} + +/* =========================================================================== + * Flush the current block, with given end-of-file flag. + * IN assertion: strstart is set to the end of the current match. + */ +#define FLUSH_BLOCK_ONLY(s, last) { \ + _tr_flush_block(s, (s->block_start >= 0L ? \ + (charf *)&s->window[(unsigned)s->block_start] : \ + (charf *)Z_NULL), \ + (ulg)((long)s->strstart - s->block_start), \ + (last)); \ + s->block_start = s->strstart; \ + flush_pending(s->strm); \ + Tracev((stderr,"[FLUSH]")); \ +} + +/* Same but force premature exit if necessary. */ +#define FLUSH_BLOCK(s, last) { \ + FLUSH_BLOCK_ONLY(s, last); \ + if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \ +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +local block_state deflate_stored(s, flush) + deflate_state *s; + int flush; +{ + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + ulg max_block_size = 0xffff; + ulg max_start; + + if (max_block_size > s->pending_buf_size - 5) { + max_block_size = s->pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s->lookahead <= 1) { + + Assert(s->strstart < s->w_size+MAX_DIST(s) || + s->block_start >= (long)s->w_size, "slide too late"); + + fill_window(s); + if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more; + + if (s->lookahead == 0) break; /* flush the current block */ + } + Assert(s->block_start >= 0L, "block gone"); + + s->strstart += s->lookahead; + s->lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + max_start = s->block_start + max_block_size; + if (s->strstart == 0 || (ulg)s->strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s->lookahead = (uInt)(s->strstart - max_start); + s->strstart = (uInt)max_start; + FLUSH_BLOCK(s, 0); + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) { + FLUSH_BLOCK(s, 0); + } + } + s->insert = 0; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if ((long)s->strstart > s->block_start) + FLUSH_BLOCK(s, 0); + return block_done; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +local block_state deflate_fast(s, flush) + deflate_state *s; + int flush; +{ + IPos hash_head; /* head of the hash chain */ + int bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s->lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = NIL; + if (s->lookahead >= MIN_MATCH) { + INSERT_STRING(s, s->strstart, hash_head); + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s->match_length = longest_match (s, hash_head); + /* longest_match() sets match_start */ + } + if (s->match_length >= MIN_MATCH) { + check_match(s, s->strstart, s->match_start, s->match_length); + + _tr_tally_dist(s, s->strstart - s->match_start, + s->match_length - MIN_MATCH, bflush); + + s->lookahead -= s->match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ +#ifndef FASTEST + if (s->match_length <= s->max_insert_length && + s->lookahead >= MIN_MATCH) { + s->match_length--; /* string at strstart already in table */ + do { + s->strstart++; + INSERT_STRING(s, s->strstart, hash_head); + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s->match_length != 0); + s->strstart++; + } else +#endif + { + s->strstart += s->match_length; + s->match_length = 0; + s->ins_h = s->window[s->strstart]; + UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); +#if MIN_MATCH != 3 + Call UPDATE_HASH() MIN_MATCH-3 more times +#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + } + if (bflush) FLUSH_BLOCK(s, 0); + } + s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} + +#ifndef FASTEST +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +local block_state deflate_slow(s, flush) + deflate_state *s; + int flush; +{ + IPos hash_head; /* head of hash chain */ + int bflush; /* set if current block must be flushed */ + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s->lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = NIL; + if (s->lookahead >= MIN_MATCH) { + INSERT_STRING(s, s->strstart, hash_head); + } + + /* Find the longest match, discarding those <= prev_length. + */ + s->prev_length = s->match_length, s->prev_match = s->match_start; + s->match_length = MIN_MATCH-1; + + if (hash_head != NIL && s->prev_length < s->max_lazy_match && + s->strstart - hash_head <= MAX_DIST(s)) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s->match_length = longest_match (s, hash_head); + /* longest_match() sets match_start */ + + if (s->match_length <= 5 && (s->strategy == Z_FILTERED +#if TOO_FAR <= 32767 + || (s->match_length == MIN_MATCH && + s->strstart - s->match_start > TOO_FAR) +#endif + )) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s->match_length = MIN_MATCH-1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) { + uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + check_match(s, s->strstart-1, s->prev_match, s->prev_length); + + _tr_tally_dist(s, s->strstart -1 - s->prev_match, + s->prev_length - MIN_MATCH, bflush); + + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s->lookahead -= s->prev_length-1; + s->prev_length -= 2; + do { + if (++s->strstart <= max_insert) { + INSERT_STRING(s, s->strstart, hash_head); + } + } while (--s->prev_length != 0); + s->match_available = 0; + s->match_length = MIN_MATCH-1; + s->strstart++; + + if (bflush) FLUSH_BLOCK(s, 0); + + } else if (s->match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + Tracevv((stderr,"%c", s->window[s->strstart-1])); + _tr_tally_lit(s, s->window[s->strstart-1], bflush); + if (bflush) { + FLUSH_BLOCK_ONLY(s, 0); + } + s->strstart++; + s->lookahead--; + if (s->strm->avail_out == 0) return need_more; + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s->match_available = 1; + s->strstart++; + s->lookahead--; + } + } + Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s->match_available) { + Tracevv((stderr,"%c", s->window[s->strstart-1])); + _tr_tally_lit(s, s->window[s->strstart-1], bflush); + s->match_available = 0; + } + s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} +#endif /* FASTEST */ + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +local block_state deflate_rle(s, flush) + deflate_state *s; + int flush; +{ + int bflush; /* set if current block must be flushed */ + uInt prev; /* byte at distance one to match */ + Bytef *scan, *strend; /* scan goes up to strend for length of run */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s->lookahead <= MAX_MATCH) { + fill_window(s); + if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s->match_length = 0; + if (s->lookahead >= MIN_MATCH && s->strstart > 0) { + scan = s->window + s->strstart - 1; + prev = *scan; + if (prev == *++scan && prev == *++scan && prev == *++scan) { + strend = s->window + s->strstart + MAX_MATCH; + do { + } while (prev == *++scan && prev == *++scan && + prev == *++scan && prev == *++scan && + prev == *++scan && prev == *++scan && + prev == *++scan && prev == *++scan && + scan < strend); + s->match_length = MAX_MATCH - (int)(strend - scan); + if (s->match_length > s->lookahead) + s->match_length = s->lookahead; + } + Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s->match_length >= MIN_MATCH) { + check_match(s, s->strstart, s->strstart - 1, s->match_length); + + _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush); + + s->lookahead -= s->match_length; + s->strstart += s->match_length; + s->match_length = 0; + } else { + /* No match, output a literal byte */ + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + } + if (bflush) FLUSH_BLOCK(s, 0); + } + s->insert = 0; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +local block_state deflate_huff(s, flush) + deflate_state *s; + int flush; +{ + int bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s->lookahead == 0) { + fill_window(s); + if (s->lookahead == 0) { + if (flush == Z_NO_FLUSH) + return need_more; + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s->match_length = 0; + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + if (bflush) FLUSH_BLOCK(s, 0); + } + s->insert = 0; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} diff --git a/src/zlib/deflate.h b/src/zlib/deflate.h new file mode 100644 index 0000000..ce0299e --- /dev/null +++ b/src/zlib/deflate.h @@ -0,0 +1,346 @@ +/* deflate.h -- internal compression state + * Copyright (C) 1995-2012 Jean-loup Gailly + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* @(#) $Id$ */ + +#ifndef DEFLATE_H +#define DEFLATE_H + +#include "zutil.h" + +/* define NO_GZIP when compiling if you want to disable gzip header and + trailer creation by deflate(). NO_GZIP would be used to avoid linking in + the crc code when it is not needed. For shared libraries, gzip encoding + should be left enabled. */ +#ifndef NO_GZIP +# define GZIP +#endif + +/* =========================================================================== + * Internal compression state. + */ + +#define LENGTH_CODES 29 +/* number of length codes, not counting the special END_BLOCK code */ + +#define LITERALS 256 +/* number of literal bytes 0..255 */ + +#define L_CODES (LITERALS+1+LENGTH_CODES) +/* number of Literal or Length codes, including the END_BLOCK code */ + +#define D_CODES 30 +/* number of distance codes */ + +#define BL_CODES 19 +/* number of codes used to transfer the bit lengths */ + +#define HEAP_SIZE (2*L_CODES+1) +/* maximum heap size */ + +#define MAX_BITS 15 +/* All codes must not exceed MAX_BITS bits */ + +#define Buf_size 16 +/* size of bit buffer in bi_buf */ + +#define INIT_STATE 42 +#define EXTRA_STATE 69 +#define NAME_STATE 73 +#define COMMENT_STATE 91 +#define HCRC_STATE 103 +#define BUSY_STATE 113 +#define FINISH_STATE 666 +/* Stream status */ + + +/* Data structure describing a single value and its code string. */ +typedef struct ct_data_s { + union { + ush freq; /* frequency count */ + ush code; /* bit string */ + } fc; + union { + ush dad; /* father node in Huffman tree */ + ush len; /* length of bit string */ + } dl; +} FAR ct_data; + +#define Freq fc.freq +#define Code fc.code +#define Dad dl.dad +#define Len dl.len + +typedef struct static_tree_desc_s static_tree_desc; + +typedef struct tree_desc_s { + ct_data *dyn_tree; /* the dynamic tree */ + int max_code; /* largest code with non zero frequency */ + static_tree_desc *stat_desc; /* the corresponding static tree */ +} FAR tree_desc; + +typedef ush Pos; +typedef Pos FAR Posf; +typedef unsigned IPos; + +/* A Pos is an index in the character window. We use short instead of int to + * save space in the various tables. IPos is used only for parameter passing. + */ + +typedef struct internal_state { + z_streamp strm; /* pointer back to this zlib stream */ + int status; /* as the name implies */ + Bytef *pending_buf; /* output still pending */ + ulg pending_buf_size; /* size of pending_buf */ + Bytef *pending_out; /* next pending byte to output to the stream */ + uInt pending; /* nb of bytes in the pending buffer */ + int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ + gz_headerp gzhead; /* gzip header information to write */ + uInt gzindex; /* where in extra, name, or comment */ + Byte method; /* can only be DEFLATED */ + int last_flush; /* value of flush param for previous deflate call */ + + /* used by deflate.c: */ + + uInt w_size; /* LZ77 window size (32K by default) */ + uInt w_bits; /* log2(w_size) (8..16) */ + uInt w_mask; /* w_size - 1 */ + + Bytef *window; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. Also, it limits + * the window size to 64K, which is quite useful on MSDOS. + * To do: use the user input buffer as sliding window. + */ + + ulg window_size; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + Posf *prev; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + Posf *head; /* Heads of the hash chains or NIL. */ + + uInt ins_h; /* hash index of string to be inserted */ + uInt hash_size; /* number of elements in hash table */ + uInt hash_bits; /* log2(hash_size) */ + uInt hash_mask; /* hash_size-1 */ + + uInt hash_shift; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + long block_start; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + uInt match_length; /* length of best match */ + IPos prev_match; /* previous match */ + int match_available; /* set if previous match exists */ + uInt strstart; /* start of string to insert */ + uInt match_start; /* start of matching string */ + uInt lookahead; /* number of valid bytes ahead in window */ + + uInt prev_length; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + uInt max_chain_length; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + uInt max_lazy_match; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ +# define max_insert_length max_lazy_match + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + int level; /* compression level (1..9) */ + int strategy; /* favor or force Huffman coding*/ + + uInt good_match; + /* Use a faster search when the previous match is longer than this */ + + int nice_match; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + /* Didn't use ct_data typedef below to suppress compiler warning */ + struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + struct tree_desc_s l_desc; /* desc. for literal tree */ + struct tree_desc_s d_desc; /* desc. for distance tree */ + struct tree_desc_s bl_desc; /* desc. for bit length tree */ + + ush bl_count[MAX_BITS+1]; + /* number of codes at each bit length for an optimal tree */ + + int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + int heap_len; /* number of elements in the heap */ + int heap_max; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + uch depth[2*L_CODES+1]; + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + uchf *l_buf; /* buffer for literals or lengths */ + + uInt lit_bufsize; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + uInt last_lit; /* running index in l_buf */ + + ushf *d_buf; + /* Buffer for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + ulg opt_len; /* bit length of current block with optimal trees */ + ulg static_len; /* bit length of current block with static trees */ + uInt matches; /* number of string matches in current block */ + uInt insert; /* bytes at end of window left to insert */ + +#ifdef DEBUG + ulg compressed_len; /* total bit length of compressed file mod 2^32 */ + ulg bits_sent; /* bit length of compressed data sent mod 2^32 */ +#endif + + ush bi_buf; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + int bi_valid; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + ulg high_water; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ + +} FAR deflate_state; + +/* Output a byte on the stream. + * IN assertion: there is enough room in pending_buf. + */ +#define put_byte(s, c) {s->pending_buf[s->pending++] = (c);} + + +#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) +/* Minimum amount of lookahead, except at the end of the input file. + * See deflate.c for comments about the MIN_MATCH+1. + */ + +#define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD) +/* In order to simplify the code, particularly on 16 bit machines, match + * distances are limited to MAX_DIST instead of WSIZE. + */ + +#define WIN_INIT MAX_MATCH +/* Number of bytes after end of data in window to initialize in order to avoid + memory checker errors from longest match routines */ + + /* in trees.c */ +void ZLIB_INTERNAL _tr_init OF((deflate_state *s)); +int ZLIB_INTERNAL _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); +void ZLIB_INTERNAL _tr_flush_block OF((deflate_state *s, charf *buf, + ulg stored_len, int last)); +void ZLIB_INTERNAL _tr_flush_bits OF((deflate_state *s)); +void ZLIB_INTERNAL _tr_align OF((deflate_state *s)); +void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf, + ulg stored_len, int last)); + +#define d_code(dist) \ + ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]) +/* Mapping from a distance to a distance code. dist is the distance - 1 and + * must not have side effects. _dist_code[256] and _dist_code[257] are never + * used. + */ + +#ifndef DEBUG +/* Inline versions of _tr_tally for speed: */ + +#if defined(GEN_TREES_H) || !defined(STDC) + extern uch ZLIB_INTERNAL _length_code[]; + extern uch ZLIB_INTERNAL _dist_code[]; +#else + extern const uch ZLIB_INTERNAL _length_code[]; + extern const uch ZLIB_INTERNAL _dist_code[]; +#endif + +# define _tr_tally_lit(s, c, flush) \ + { uch cc = (c); \ + s->d_buf[s->last_lit] = 0; \ + s->l_buf[s->last_lit++] = cc; \ + s->dyn_ltree[cc].Freq++; \ + flush = (s->last_lit == s->lit_bufsize-1); \ + } +# define _tr_tally_dist(s, distance, length, flush) \ + { uch len = (length); \ + ush dist = (distance); \ + s->d_buf[s->last_lit] = dist; \ + s->l_buf[s->last_lit++] = len; \ + dist--; \ + s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ + s->dyn_dtree[d_code(dist)].Freq++; \ + flush = (s->last_lit == s->lit_bufsize-1); \ + } +#else +# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c) +# define _tr_tally_dist(s, distance, length, flush) \ + flush = _tr_tally(s, distance, length) +#endif + +#endif /* DEFLATE_H */ diff --git a/src/zlib/gzclose.c b/src/zlib/gzclose.c new file mode 100644 index 0000000..caeb99a --- /dev/null +++ b/src/zlib/gzclose.c @@ -0,0 +1,25 @@ +/* gzclose.c -- zlib gzclose() function + * Copyright (C) 2004, 2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "gzguts.h" + +/* gzclose() is in a separate file so that it is linked in only if it is used. + That way the other gzclose functions can be used instead to avoid linking in + unneeded compression or decompression routines. */ +int ZEXPORT gzclose(file) + gzFile file; +{ +#ifndef NO_GZCOMPRESS + gz_statep state; + + if (file == NULL) + return Z_STREAM_ERROR; + state = (gz_statep)file; + + return state->mode == GZ_READ ? gzclose_r(file) : gzclose_w(file); +#else + return gzclose_r(file); +#endif +} diff --git a/src/zlib/gzguts.h b/src/zlib/gzguts.h new file mode 100644 index 0000000..2aac3e2 --- /dev/null +++ b/src/zlib/gzguts.h @@ -0,0 +1,209 @@ +/* gzguts.h -- zlib internal header definitions for gz* operations + * Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#ifdef _LARGEFILE64_SOURCE +# ifndef _LARGEFILE_SOURCE +# define _LARGEFILE_SOURCE 1 +# endif +# ifdef _FILE_OFFSET_BITS +# undef _FILE_OFFSET_BITS +# endif +#endif + +#ifdef HAVE_HIDDEN +# define ZLIB_INTERNAL __attribute__((visibility ("hidden"))) +#else +# define ZLIB_INTERNAL +#endif + +#include +#include "zlib/zlib.h" +#ifdef STDC +# include +# include +# include +#endif +#include + +#ifdef _WIN32 +# include +#endif + +#if defined(__TURBOC__) || defined(_MSC_VER) || defined(_WIN32) +# include +#endif + +#ifdef WINAPI_FAMILY +# define open _open +# define read _read +# define write _write +# define close _close +#endif + +#ifdef NO_DEFLATE /* for compatibility with old definition */ +# define NO_GZCOMPRESS +#endif + +#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif + +#if defined(__CYGWIN__) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif + +#if defined(MSDOS) && defined(__BORLANDC__) && (BORLANDC > 0x410) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif + +#ifndef HAVE_VSNPRINTF +# ifdef MSDOS +/* vsnprintf may exist on some MS-DOS compilers (DJGPP?), + but for now we just assume it doesn't. */ +# define NO_vsnprintf +# endif +# ifdef __TURBOC__ +# define NO_vsnprintf +# endif +# ifdef WIN32 +/* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */ +# if !defined(vsnprintf) && !defined(NO_vsnprintf) +# if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 ) +# define vsnprintf _vsnprintf +# endif +# endif +# endif +# ifdef __SASC +# define NO_vsnprintf +# endif +# ifdef VMS +# define NO_vsnprintf +# endif +# ifdef __OS400__ +# define NO_vsnprintf +# endif +# ifdef __MVS__ +# define NO_vsnprintf +# endif +#endif + +/* unlike snprintf (which is required in C99, yet still not supported by + Microsoft more than a decade later!), _snprintf does not guarantee null + termination of the result -- however this is only used in gzlib.c where + the result is assured to fit in the space provided */ +#ifdef _MSC_VER +# define snprintf _snprintf +#endif + +#ifndef local +# define local static +#endif +/* compile with -Dlocal if your debugger can't find static symbols */ + +/* gz* functions always use library allocation functions */ +#ifndef STDC + extern voidp malloc OF((uInt size)); + extern void free OF((voidpf ptr)); +#endif + +/* get errno and strerror definition */ +#if defined UNDER_CE +# include +# define zstrerror() gz_strwinerror((DWORD)GetLastError()) +#else +# ifndef NO_STRERROR +# include +# define zstrerror() strerror(errno) +# else +# define zstrerror() "stdio error (consult errno)" +# endif +#endif + +/* provide prototypes for these when building zlib without LFS */ +#if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); + ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); +#endif + +/* default memLevel */ +#if MAX_MEM_LEVEL >= 8 +# define DEF_MEM_LEVEL 8 +#else +# define DEF_MEM_LEVEL MAX_MEM_LEVEL +#endif + +/* default i/o buffer size -- double this for output when reading (this and + twice this must be able to fit in an unsigned type) */ +#define GZBUFSIZE 8192 + +/* gzip modes, also provide a little integrity check on the passed structure */ +#define GZ_NONE 0 +#define GZ_READ 7247 +#define GZ_WRITE 31153 +#define GZ_APPEND 1 /* mode set to GZ_WRITE after the file is opened */ + +/* values for gz_state how */ +#define LOOK 0 /* look for a gzip header */ +#define COPY 1 /* copy input directly */ +#define GZIP 2 /* decompress a gzip stream */ + +/* internal gzip file state data structure */ +typedef struct { + /* exposed contents for gzgetc() macro */ + struct gzFile_s x; /* "x" for exposed */ + /* x.have: number of bytes available at x.next */ + /* x.next: next output data to deliver or write */ + /* x.pos: current position in uncompressed data */ + /* used for both reading and writing */ + int mode; /* see gzip modes above */ + int fd; /* file descriptor */ + char *path; /* path or fd for error messages */ + unsigned size; /* buffer size, zero if not allocated yet */ + unsigned want; /* requested buffer size, default is GZBUFSIZE */ + unsigned char *in; /* input buffer */ + unsigned char *out; /* output buffer (double-sized when reading) */ + int direct; /* 0 if processing gzip, 1 if transparent */ + /* just for reading */ + int how; /* 0: get header, 1: copy, 2: decompress */ + z_off64_t start; /* where the gzip data started, for rewinding */ + int eof; /* true if end of input file reached */ + int past; /* true if read requested past end */ + /* just for writing */ + int level; /* compression level */ + int strategy; /* compression strategy */ + /* seek request */ + z_off64_t skip; /* amount to skip (already rewound if backwards) */ + int seek; /* true if seek request pending */ + /* error information */ + int err; /* error code */ + char *msg; /* error message */ + /* zlib inflate or deflate stream */ + z_stream strm; /* stream structure in-place (not a pointer) */ +} gz_state; +typedef gz_state FAR *gz_statep; + +/* shared functions */ +void ZLIB_INTERNAL gz_error OF((gz_statep, int, const char *)); +#if defined UNDER_CE +char ZLIB_INTERNAL *gz_strwinerror OF((DWORD error)); +#endif + +/* GT_OFF(x), where x is an unsigned value, is true if x > maximum z_off64_t + value -- needed when comparing unsigned to z_off64_t, which is signed + (possible z_off64_t types off_t, off64_t, and long are all signed) */ +#ifdef INT_MAX +# define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > INT_MAX) +#else +unsigned ZLIB_INTERNAL gz_intmax OF((void)); +# define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > gz_intmax()) +#endif diff --git a/src/zlib/gzlib.c b/src/zlib/gzlib.c new file mode 100644 index 0000000..fae202e --- /dev/null +++ b/src/zlib/gzlib.c @@ -0,0 +1,634 @@ +/* gzlib.c -- zlib functions common to reading and writing gzip files + * Copyright (C) 2004, 2010, 2011, 2012, 2013 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "gzguts.h" + +#if defined(_WIN32) && !defined(__BORLANDC__) +# define LSEEK _lseeki64 +#else +#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 +# define LSEEK lseek64 +#else +# define LSEEK lseek +#endif +#endif + +/* Local functions */ +local void gz_reset OF((gz_statep)); +local gzFile gz_open OF((const void *, int, const char *)); + +#if defined UNDER_CE + +/* Map the Windows error number in ERROR to a locale-dependent error message + string and return a pointer to it. Typically, the values for ERROR come + from GetLastError. + + The string pointed to shall not be modified by the application, but may be + overwritten by a subsequent call to gz_strwinerror + + The gz_strwinerror function does not change the current setting of + GetLastError. */ +char ZLIB_INTERNAL *gz_strwinerror (error) + DWORD error; +{ + static char buf[1024]; + + wchar_t *msgbuf; + DWORD lasterr = GetLastError(); + DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM + | FORMAT_MESSAGE_ALLOCATE_BUFFER, + NULL, + error, + 0, /* Default language */ + (LPVOID)&msgbuf, + 0, + NULL); + if (chars != 0) { + /* If there is an \r\n appended, zap it. */ + if (chars >= 2 + && msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') { + chars -= 2; + msgbuf[chars] = 0; + } + + if (chars > sizeof (buf) - 1) { + chars = sizeof (buf) - 1; + msgbuf[chars] = 0; + } + + wcstombs(buf, msgbuf, chars + 1); + LocalFree(msgbuf); + } + else { + sprintf(buf, "unknown win32 error (%ld)", error); + } + + SetLastError(lasterr); + return buf; +} + +#endif /* UNDER_CE */ + +/* Reset gzip file state */ +local void gz_reset(state) + gz_statep state; +{ + state->x.have = 0; /* no output data available */ + if (state->mode == GZ_READ) { /* for reading ... */ + state->eof = 0; /* not at end of file */ + state->past = 0; /* have not read past end yet */ + state->how = LOOK; /* look for gzip header */ + } + state->seek = 0; /* no seek request pending */ + gz_error(state, Z_OK, NULL); /* clear error */ + state->x.pos = 0; /* no uncompressed data yet */ + state->strm.avail_in = 0; /* no input data yet */ +} + +/* Open a gzip file either by name or file descriptor. */ +local gzFile gz_open(path, fd, mode) + const void *path; + int fd; + const char *mode; +{ + gz_statep state; + size_t len; + int oflag; +#ifdef O_CLOEXEC + int cloexec = 0; +#endif +#ifdef O_EXCL + int exclusive = 0; +#endif + + /* check input */ + if (path == NULL) + return NULL; + + /* allocate gzFile structure to return */ + state = (gz_statep)malloc(sizeof(gz_state)); + if (state == NULL) + return NULL; + state->size = 0; /* no buffers allocated yet */ + state->want = GZBUFSIZE; /* requested buffer size */ + state->msg = NULL; /* no error message yet */ + + /* interpret mode */ + state->mode = GZ_NONE; + state->level = Z_DEFAULT_COMPRESSION; + state->strategy = Z_DEFAULT_STRATEGY; + state->direct = 0; + while (*mode) { + if (*mode >= '0' && *mode <= '9') + state->level = *mode - '0'; + else + switch (*mode) { + case 'r': + state->mode = GZ_READ; + break; +#ifndef NO_GZCOMPRESS + case 'w': + state->mode = GZ_WRITE; + break; + case 'a': + state->mode = GZ_APPEND; + break; +#endif + case '+': /* can't read and write at the same time */ + free(state); + return NULL; + case 'b': /* ignore -- will request binary anyway */ + break; +#ifdef O_CLOEXEC + case 'e': + cloexec = 1; + break; +#endif +#ifdef O_EXCL + case 'x': + exclusive = 1; + break; +#endif + case 'f': + state->strategy = Z_FILTERED; + break; + case 'h': + state->strategy = Z_HUFFMAN_ONLY; + break; + case 'R': + state->strategy = Z_RLE; + break; + case 'F': + state->strategy = Z_FIXED; + break; + case 'T': + state->direct = 1; + break; + default: /* could consider as an error, but just ignore */ + ; + } + mode++; + } + + /* must provide an "r", "w", or "a" */ + if (state->mode == GZ_NONE) { + free(state); + return NULL; + } + + /* can't force transparent read */ + if (state->mode == GZ_READ) { + if (state->direct) { + free(state); + return NULL; + } + state->direct = 1; /* for empty file */ + } + + /* save the path name for error messages */ +#ifdef _WIN32 + if (fd == -2) { + len = wcstombs(NULL, path, 0); + if (len == (size_t)-1) + len = 0; + } + else +#endif + len = strlen((const char *)path); + state->path = (char *)malloc(len + 1); + if (state->path == NULL) { + free(state); + return NULL; + } +#ifdef _WIN32 + if (fd == -2) + if (len) + wcstombs(state->path, path, len + 1); + else + *(state->path) = 0; + else +#endif +#if !defined(NO_snprintf) && !defined(NO_vsnprintf) + snprintf(state->path, len + 1, "%s", (const char *)path); +#else + strcpy(state->path, path); +#endif + + /* compute the flags for open() */ + oflag = +#ifdef O_LARGEFILE + O_LARGEFILE | +#endif +#ifdef O_BINARY + O_BINARY | +#endif +#ifdef O_CLOEXEC + (cloexec ? O_CLOEXEC : 0) | +#endif + (state->mode == GZ_READ ? + O_RDONLY : + (O_WRONLY | O_CREAT | +#ifdef O_EXCL + (exclusive ? O_EXCL : 0) | +#endif + (state->mode == GZ_WRITE ? + O_TRUNC : + O_APPEND))); + + /* open the file with the appropriate flags (or just use fd) */ + state->fd = fd > -1 ? fd : ( +#ifdef _WIN32 + fd == -2 ? _wopen(path, oflag, 0666) : +#endif + open((const char *)path, oflag, 0666)); + if (state->fd == -1) { + free(state->path); + free(state); + return NULL; + } + if (state->mode == GZ_APPEND) + state->mode = GZ_WRITE; /* simplify later checks */ + + /* save the current position for rewinding (only if reading) */ + if (state->mode == GZ_READ) { + state->start = LSEEK(state->fd, 0, SEEK_CUR); + if (state->start == -1) state->start = 0; + } + + /* initialize stream */ + gz_reset(state); + + /* return stream */ + return (gzFile)state; +} + +/* -- see zlib.h -- */ +gzFile ZEXPORT gzopen(path, mode) + const char *path; + const char *mode; +{ + return gz_open(path, -1, mode); +} + +/* -- see zlib.h -- */ +gzFile ZEXPORT gzopen64(path, mode) + const char *path; + const char *mode; +{ + return gz_open(path, -1, mode); +} + +/* -- see zlib.h -- */ +gzFile ZEXPORT gzdopen(fd, mode) + int fd; + const char *mode; +{ + char *path; /* identifier for error messages */ + gzFile gz; + + if (fd == -1 || (path = (char *)malloc(7 + 3 * sizeof(int))) == NULL) + return NULL; +#if !defined(NO_snprintf) && !defined(NO_vsnprintf) + snprintf(path, 7 + 3 * sizeof(int), "", fd); /* for debugging */ +#else + sprintf(path, "", fd); /* for debugging */ +#endif + gz = gz_open(path, fd, mode); + free(path); + return gz; +} + +/* -- see zlib.h -- */ +#ifdef _WIN32 +gzFile ZEXPORT gzopen_w(path, mode) + const wchar_t *path; + const char *mode; +{ + return gz_open(path, -2, mode); +} +#endif + +/* -- see zlib.h -- */ +int ZEXPORT gzbuffer(file, size) + gzFile file; + unsigned size; +{ + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return -1; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return -1; + + /* make sure we haven't already allocated memory */ + if (state->size != 0) + return -1; + + /* check and set requested size */ + if (size < 2) + size = 2; /* need two bytes to check magic header */ + state->want = size; + return 0; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzrewind(file) + gzFile file; +{ + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + + /* check that we're reading and that there's no error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) + return -1; + + /* back up and start over */ + if (LSEEK(state->fd, state->start, SEEK_SET) == -1) + return -1; + gz_reset(state); + return 0; +} + +/* -- see zlib.h -- */ +z_off64_t ZEXPORT gzseek64(file, offset, whence) + gzFile file; + z_off64_t offset; + int whence; +{ + unsigned n; + z_off64_t ret; + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return -1; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return -1; + + /* check that there's no error */ + if (state->err != Z_OK && state->err != Z_BUF_ERROR) + return -1; + + /* can only seek from start or relative to current position */ + if (whence != SEEK_SET && whence != SEEK_CUR) + return -1; + + /* normalize offset to a SEEK_CUR specification */ + if (whence == SEEK_SET) + offset -= state->x.pos; + else if (state->seek) + offset += state->skip; + state->seek = 0; + + /* if within raw area while reading, just go there */ + if (state->mode == GZ_READ && state->how == COPY && + state->x.pos + offset >= 0) { + ret = LSEEK(state->fd, offset - state->x.have, SEEK_CUR); + if (ret == -1) + return -1; + state->x.have = 0; + state->eof = 0; + state->past = 0; + state->seek = 0; + gz_error(state, Z_OK, NULL); + state->strm.avail_in = 0; + state->x.pos += offset; + return state->x.pos; + } + + /* calculate skip amount, rewinding if needed for back seek when reading */ + if (offset < 0) { + if (state->mode != GZ_READ) /* writing -- can't go backwards */ + return -1; + offset += state->x.pos; + if (offset < 0) /* before start of file! */ + return -1; + if (gzrewind(file) == -1) /* rewind, then skip to offset */ + return -1; + } + + /* if reading, skip what's in output buffer (one less gzgetc() check) */ + if (state->mode == GZ_READ) { + n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > offset ? + (unsigned)offset : state->x.have; + state->x.have -= n; + state->x.next += n; + state->x.pos += n; + offset -= n; + } + + /* request skip (if not zero) */ + if (offset) { + state->seek = 1; + state->skip = offset; + } + return state->x.pos + offset; +} + +/* -- see zlib.h -- */ +z_off_t ZEXPORT gzseek(file, offset, whence) + gzFile file; + z_off_t offset; + int whence; +{ + z_off64_t ret; + + ret = gzseek64(file, (z_off64_t)offset, whence); + return ret == (z_off_t)ret ? (z_off_t)ret : -1; +} + +/* -- see zlib.h -- */ +z_off64_t ZEXPORT gztell64(file) + gzFile file; +{ + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return -1; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return -1; + + /* return position */ + return state->x.pos + (state->seek ? state->skip : 0); +} + +/* -- see zlib.h -- */ +z_off_t ZEXPORT gztell(file) + gzFile file; +{ + z_off64_t ret; + + ret = gztell64(file); + return ret == (z_off_t)ret ? (z_off_t)ret : -1; +} + +/* -- see zlib.h -- */ +z_off64_t ZEXPORT gzoffset64(file) + gzFile file; +{ + z_off64_t offset; + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return -1; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return -1; + + /* compute and return effective offset in file */ + offset = LSEEK(state->fd, 0, SEEK_CUR); + if (offset == -1) + return -1; + if (state->mode == GZ_READ) /* reading */ + offset -= state->strm.avail_in; /* don't count buffered input */ + return offset; +} + +/* -- see zlib.h -- */ +z_off_t ZEXPORT gzoffset(file) + gzFile file; +{ + z_off64_t ret; + + ret = gzoffset64(file); + return ret == (z_off_t)ret ? (z_off_t)ret : -1; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzeof(file) + gzFile file; +{ + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return 0; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return 0; + + /* return end-of-file state */ + return state->mode == GZ_READ ? state->past : 0; +} + +/* -- see zlib.h -- */ +const char * ZEXPORT gzerror(file, errnum) + gzFile file; + int *errnum; +{ + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return NULL; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return NULL; + + /* return error information */ + if (errnum != NULL) + *errnum = state->err; + return state->err == Z_MEM_ERROR ? "out of memory" : + (state->msg == NULL ? "" : state->msg); +} + +/* -- see zlib.h -- */ +void ZEXPORT gzclearerr(file) + gzFile file; +{ + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return; + + /* clear error and end-of-file */ + if (state->mode == GZ_READ) { + state->eof = 0; + state->past = 0; + } + gz_error(state, Z_OK, NULL); +} + +/* Create an error message in allocated memory and set state->err and + state->msg accordingly. Free any previous error message already there. Do + not try to free or allocate space if the error is Z_MEM_ERROR (out of + memory). Simply save the error message as a static string. If there is an + allocation failure constructing the error message, then convert the error to + out of memory. */ +void ZLIB_INTERNAL gz_error(state, err, msg) + gz_statep state; + int err; + const char *msg; +{ + /* free previously allocated message and clear */ + if (state->msg != NULL) { + if (state->err != Z_MEM_ERROR) + free(state->msg); + state->msg = NULL; + } + + /* if fatal, set state->x.have to 0 so that the gzgetc() macro fails */ + if (err != Z_OK && err != Z_BUF_ERROR) + state->x.have = 0; + + /* set error code, and if no message, then done */ + state->err = err; + if (msg == NULL) + return; + + /* for an out of memory error, return literal string when requested */ + if (err == Z_MEM_ERROR) + return; + + /* construct error message with path */ + if ((state->msg = (char *)malloc(strlen(state->path) + strlen(msg) + 3)) == + NULL) { + state->err = Z_MEM_ERROR; + return; + } +#if !defined(NO_snprintf) && !defined(NO_vsnprintf) + snprintf(state->msg, strlen(state->path) + strlen(msg) + 3, + "%s%s%s", state->path, ": ", msg); +#else + strcpy(state->msg, state->path); + strcat(state->msg, ": "); + strcat(state->msg, msg); +#endif + return; +} + +#ifndef INT_MAX +/* portably return maximum value for an int (when limits.h presumed not + available) -- we need to do this to cover cases where 2's complement not + used, since C standard permits 1's complement and sign-bit representations, + otherwise we could just use ((unsigned)-1) >> 1 */ +unsigned ZLIB_INTERNAL gz_intmax() +{ + unsigned p, q; + + p = 1; + do { + q = p; + p <<= 1; + p++; + } while (p > q); + return q >> 1; +} +#endif diff --git a/src/zlib/gzread.c b/src/zlib/gzread.c new file mode 100644 index 0000000..bf4538e --- /dev/null +++ b/src/zlib/gzread.c @@ -0,0 +1,594 @@ +/* gzread.c -- zlib functions for reading gzip files + * Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "gzguts.h" + +/* Local functions */ +local int gz_load OF((gz_statep, unsigned char *, unsigned, unsigned *)); +local int gz_avail OF((gz_statep)); +local int gz_look OF((gz_statep)); +local int gz_decomp OF((gz_statep)); +local int gz_fetch OF((gz_statep)); +local int gz_skip OF((gz_statep, z_off64_t)); + +/* Use read() to load a buffer -- return -1 on error, otherwise 0. Read from + state->fd, and update state->eof, state->err, and state->msg as appropriate. + This function needs to loop on read(), since read() is not guaranteed to + read the number of bytes requested, depending on the type of descriptor. */ +local int gz_load(state, buf, len, have) + gz_statep state; + unsigned char *buf; + unsigned len; + unsigned *have; +{ + int ret; + + *have = 0; + do { + ret = read(state->fd, buf + *have, len - *have); + if (ret <= 0) + break; + *have += ret; + } while (*have < len); + if (ret < 0) { + gz_error(state, Z_ERRNO, zstrerror()); + return -1; + } + if (ret == 0) + state->eof = 1; + return 0; +} + +/* Load up input buffer and set eof flag if last data loaded -- return -1 on + error, 0 otherwise. Note that the eof flag is set when the end of the input + file is reached, even though there may be unused data in the buffer. Once + that data has been used, no more attempts will be made to read the file. + If strm->avail_in != 0, then the current data is moved to the beginning of + the input buffer, and then the remainder of the buffer is loaded with the + available data from the input file. */ +local int gz_avail(state) + gz_statep state; +{ + unsigned got; + z_streamp strm = &(state->strm); + + if (state->err != Z_OK && state->err != Z_BUF_ERROR) + return -1; + if (state->eof == 0) { + if (strm->avail_in) { /* copy what's there to the start */ + unsigned char *p = state->in; + unsigned const char *q = strm->next_in; + unsigned n = strm->avail_in; + do { + *p++ = *q++; + } while (--n); + } + if (gz_load(state, state->in + strm->avail_in, + state->size - strm->avail_in, &got) == -1) + return -1; + strm->avail_in += got; + strm->next_in = state->in; + } + return 0; +} + +/* Look for gzip header, set up for inflate or copy. state->x.have must be 0. + If this is the first time in, allocate required memory. state->how will be + left unchanged if there is no more input data available, will be set to COPY + if there is no gzip header and direct copying will be performed, or it will + be set to GZIP for decompression. If direct copying, then leftover input + data from the input buffer will be copied to the output buffer. In that + case, all further file reads will be directly to either the output buffer or + a user buffer. If decompressing, the inflate state will be initialized. + gz_look() will return 0 on success or -1 on failure. */ +local int gz_look(state) + gz_statep state; +{ + z_streamp strm = &(state->strm); + + /* allocate read buffers and inflate memory */ + if (state->size == 0) { + /* allocate buffers */ + state->in = (unsigned char *)malloc(state->want); + state->out = (unsigned char *)malloc(state->want << 1); + if (state->in == NULL || state->out == NULL) { + if (state->out != NULL) + free(state->out); + if (state->in != NULL) + free(state->in); + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + state->size = state->want; + + /* allocate inflate memory */ + state->strm.zalloc = Z_NULL; + state->strm.zfree = Z_NULL; + state->strm.opaque = Z_NULL; + state->strm.avail_in = 0; + state->strm.next_in = Z_NULL; + if (inflateInit2(&(state->strm), 15 + 16) != Z_OK) { /* gunzip */ + free(state->out); + free(state->in); + state->size = 0; + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + } + + /* get at least the magic bytes in the input buffer */ + if (strm->avail_in < 2) { + if (gz_avail(state) == -1) + return -1; + if (strm->avail_in == 0) + return 0; + } + + /* look for gzip magic bytes -- if there, do gzip decoding (note: there is + a logical dilemma here when considering the case of a partially written + gzip file, to wit, if a single 31 byte is written, then we cannot tell + whether this is a single-byte file, or just a partially written gzip + file -- for here we assume that if a gzip file is being written, then + the header will be written in a single operation, so that reading a + single byte is sufficient indication that it is not a gzip file) */ + if (strm->avail_in > 1 && + strm->next_in[0] == 31 && strm->next_in[1] == 139) { + inflateReset(strm); + state->how = GZIP; + state->direct = 0; + return 0; + } + + /* no gzip header -- if we were decoding gzip before, then this is trailing + garbage. Ignore the trailing garbage and finish. */ + if (state->direct == 0) { + strm->avail_in = 0; + state->eof = 1; + state->x.have = 0; + return 0; + } + + /* doing raw i/o, copy any leftover input to output -- this assumes that + the output buffer is larger than the input buffer, which also assures + space for gzungetc() */ + state->x.next = state->out; + if (strm->avail_in) { + memcpy(state->x.next, strm->next_in, strm->avail_in); + state->x.have = strm->avail_in; + strm->avail_in = 0; + } + state->how = COPY; + state->direct = 1; + return 0; +} + +/* Decompress from input to the provided next_out and avail_out in the state. + On return, state->x.have and state->x.next point to the just decompressed + data. If the gzip stream completes, state->how is reset to LOOK to look for + the next gzip stream or raw data, once state->x.have is depleted. Returns 0 + on success, -1 on failure. */ +local int gz_decomp(state) + gz_statep state; +{ + int ret = Z_OK; + unsigned had; + z_streamp strm = &(state->strm); + + /* fill output buffer up to end of deflate stream */ + had = strm->avail_out; + do { + /* get more input for inflate() */ + if (strm->avail_in == 0 && gz_avail(state) == -1) + return -1; + if (strm->avail_in == 0) { + gz_error(state, Z_BUF_ERROR, "unexpected end of file"); + break; + } + + /* decompress and handle errors */ + ret = inflate(strm, Z_NO_FLUSH); + if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) { + gz_error(state, Z_STREAM_ERROR, + "internal error: inflate stream corrupt"); + return -1; + } + if (ret == Z_MEM_ERROR) { + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + if (ret == Z_DATA_ERROR) { /* deflate stream invalid */ + gz_error(state, Z_DATA_ERROR, + strm->msg == NULL ? "compressed data error" : strm->msg); + return -1; + } + } while (strm->avail_out && ret != Z_STREAM_END); + + /* update available output */ + state->x.have = had - strm->avail_out; + state->x.next = strm->next_out - state->x.have; + + /* if the gzip stream completed successfully, look for another */ + if (ret == Z_STREAM_END) + state->how = LOOK; + + /* good decompression */ + return 0; +} + +/* Fetch data and put it in the output buffer. Assumes state->x.have is 0. + Data is either copied from the input file or decompressed from the input + file depending on state->how. If state->how is LOOK, then a gzip header is + looked for to determine whether to copy or decompress. Returns -1 on error, + otherwise 0. gz_fetch() will leave state->how as COPY or GZIP unless the + end of the input file has been reached and all data has been processed. */ +local int gz_fetch(state) + gz_statep state; +{ + z_streamp strm = &(state->strm); + + do { + switch(state->how) { + case LOOK: /* -> LOOK, COPY (only if never GZIP), or GZIP */ + if (gz_look(state) == -1) + return -1; + if (state->how == LOOK) + return 0; + break; + case COPY: /* -> COPY */ + if (gz_load(state, state->out, state->size << 1, &(state->x.have)) + == -1) + return -1; + state->x.next = state->out; + return 0; + case GZIP: /* -> GZIP or LOOK (if end of gzip stream) */ + strm->avail_out = state->size << 1; + strm->next_out = state->out; + if (gz_decomp(state) == -1) + return -1; + } + } while (state->x.have == 0 && (!state->eof || strm->avail_in)); + return 0; +} + +/* Skip len uncompressed bytes of output. Return -1 on error, 0 on success. */ +local int gz_skip(state, len) + gz_statep state; + z_off64_t len; +{ + unsigned n; + + /* skip over len bytes or reach end-of-file, whichever comes first */ + while (len) + /* skip over whatever is in output buffer */ + if (state->x.have) { + n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > len ? + (unsigned)len : state->x.have; + state->x.have -= n; + state->x.next += n; + state->x.pos += n; + len -= n; + } + + /* output buffer empty -- return if we're at the end of the input */ + else if (state->eof && state->strm.avail_in == 0) + break; + + /* need more data to skip -- load up output buffer */ + else { + /* get more output, looking for header if required */ + if (gz_fetch(state) == -1) + return -1; + } + return 0; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzread(file, buf, len) + gzFile file; + voidp buf; + unsigned len; +{ + unsigned got, n; + gz_statep state; + z_streamp strm; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + strm = &(state->strm); + + /* check that we're reading and that there's no (serious) error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) + return -1; + + /* since an int is returned, make sure len fits in one, otherwise return + with an error (this avoids the flaw in the interface) */ + if ((int)len < 0) { + gz_error(state, Z_DATA_ERROR, "requested length does not fit in int"); + return -1; + } + + /* if len is zero, avoid unnecessary operations */ + if (len == 0) + return 0; + + /* process a skip request */ + if (state->seek) { + state->seek = 0; + if (gz_skip(state, state->skip) == -1) + return -1; + } + + /* get len bytes to buf, or less than len if at the end */ + got = 0; + do { + /* first just try copying data from the output buffer */ + if (state->x.have) { + n = state->x.have > len ? len : state->x.have; + memcpy(buf, state->x.next, n); + state->x.next += n; + state->x.have -= n; + } + + /* output buffer empty -- return if we're at the end of the input */ + else if (state->eof && strm->avail_in == 0) { + state->past = 1; /* tried to read past end */ + break; + } + + /* need output data -- for small len or new stream load up our output + buffer */ + else if (state->how == LOOK || len < (state->size << 1)) { + /* get more output, looking for header if required */ + if (gz_fetch(state) == -1) + return -1; + continue; /* no progress yet -- go back to copy above */ + /* the copy above assures that we will leave with space in the + output buffer, allowing at least one gzungetc() to succeed */ + } + + /* large len -- read directly into user buffer */ + else if (state->how == COPY) { /* read directly */ + if (gz_load(state, (unsigned char *)buf, len, &n) == -1) + return -1; + } + + /* large len -- decompress directly into user buffer */ + else { /* state->how == GZIP */ + strm->avail_out = len; + strm->next_out = (unsigned char *)buf; + if (gz_decomp(state) == -1) + return -1; + n = state->x.have; + state->x.have = 0; + } + + /* update progress */ + len -= n; + buf = (char *)buf + n; + got += n; + state->x.pos += n; + } while (len); + + /* return number of bytes read into user buffer (will fit in int) */ + return (int)got; +} + +/* -- see zlib.h -- */ +#ifdef Z_PREFIX_SET +# undef z_gzgetc +#else +# undef gzgetc +#endif +int ZEXPORT gzgetc(file) + gzFile file; +{ + int ret; + unsigned char buf[1]; + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + + /* check that we're reading and that there's no (serious) error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) + return -1; + + /* try output buffer (no need to check for skip request) */ + if (state->x.have) { + state->x.have--; + state->x.pos++; + return *(state->x.next)++; + } + + /* nothing there -- try gzread() */ + ret = gzread(file, buf, 1); + return ret < 1 ? -1 : buf[0]; +} + +int ZEXPORT gzgetc_(file) +gzFile file; +{ + return gzgetc(file); +} + +/* -- see zlib.h -- */ +int ZEXPORT gzungetc(c, file) + int c; + gzFile file; +{ + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + + /* check that we're reading and that there's no (serious) error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) + return -1; + + /* process a skip request */ + if (state->seek) { + state->seek = 0; + if (gz_skip(state, state->skip) == -1) + return -1; + } + + /* can't push EOF */ + if (c < 0) + return -1; + + /* if output buffer empty, put byte at end (allows more pushing) */ + if (state->x.have == 0) { + state->x.have = 1; + state->x.next = state->out + (state->size << 1) - 1; + state->x.next[0] = c; + state->x.pos--; + state->past = 0; + return c; + } + + /* if no room, give up (must have already done a gzungetc()) */ + if (state->x.have == (state->size << 1)) { + gz_error(state, Z_DATA_ERROR, "out of room to push characters"); + return -1; + } + + /* slide output data if needed and insert byte before existing data */ + if (state->x.next == state->out) { + unsigned char *src = state->out + state->x.have; + unsigned char *dest = state->out + (state->size << 1); + while (src > state->out) + *--dest = *--src; + state->x.next = dest; + } + state->x.have++; + state->x.next--; + state->x.next[0] = c; + state->x.pos--; + state->past = 0; + return c; +} + +/* -- see zlib.h -- */ +char * ZEXPORT gzgets(file, buf, len) + gzFile file; + char *buf; + int len; +{ + unsigned left, n; + char *str; + unsigned char *eol; + gz_statep state; + + /* check parameters and get internal structure */ + if (file == NULL || buf == NULL || len < 1) + return NULL; + state = (gz_statep)file; + + /* check that we're reading and that there's no (serious) error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) + return NULL; + + /* process a skip request */ + if (state->seek) { + state->seek = 0; + if (gz_skip(state, state->skip) == -1) + return NULL; + } + + /* copy output bytes up to new line or len - 1, whichever comes first -- + append a terminating zero to the string (we don't check for a zero in + the contents, let the user worry about that) */ + str = buf; + left = (unsigned)len - 1; + if (left) do { + /* assure that something is in the output buffer */ + if (state->x.have == 0 && gz_fetch(state) == -1) + return NULL; /* error */ + if (state->x.have == 0) { /* end of file */ + state->past = 1; /* read past end */ + break; /* return what we have */ + } + + /* look for end-of-line in current output buffer */ + n = state->x.have > left ? left : state->x.have; + eol = (unsigned char *)memchr(state->x.next, '\n', n); + if (eol != NULL) + n = (unsigned)(eol - state->x.next) + 1; + + /* copy through end-of-line, or remainder if not found */ + memcpy(buf, state->x.next, n); + state->x.have -= n; + state->x.next += n; + state->x.pos += n; + left -= n; + buf += n; + } while (left && eol == NULL); + + /* return terminated string, or if nothing, end of file */ + if (buf == str) + return NULL; + buf[0] = 0; + return str; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzdirect(file) + gzFile file; +{ + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return 0; + state = (gz_statep)file; + + /* if the state is not known, but we can find out, then do so (this is + mainly for right after a gzopen() or gzdopen()) */ + if (state->mode == GZ_READ && state->how == LOOK && state->x.have == 0) + (void)gz_look(state); + + /* return 1 if transparent, 0 if processing a gzip stream */ + return state->direct; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzclose_r(file) + gzFile file; +{ + int ret, err; + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return Z_STREAM_ERROR; + state = (gz_statep)file; + + /* check that we're reading */ + if (state->mode != GZ_READ) + return Z_STREAM_ERROR; + + /* free memory and close file */ + if (state->size) { + inflateEnd(&(state->strm)); + free(state->out); + free(state->in); + } + err = state->err == Z_BUF_ERROR ? Z_BUF_ERROR : Z_OK; + gz_error(state, Z_OK, NULL); + free(state->path); + ret = close(state->fd); + free(state); + return ret ? Z_ERRNO : err; +} diff --git a/src/zlib/gzwrite.c b/src/zlib/gzwrite.c new file mode 100644 index 0000000..aa767fb --- /dev/null +++ b/src/zlib/gzwrite.c @@ -0,0 +1,577 @@ +/* gzwrite.c -- zlib functions for writing gzip files + * Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "gzguts.h" + +/* Local functions */ +local int gz_init OF((gz_statep)); +local int gz_comp OF((gz_statep, int)); +local int gz_zero OF((gz_statep, z_off64_t)); + +/* Initialize state for writing a gzip file. Mark initialization by setting + state->size to non-zero. Return -1 on failure or 0 on success. */ +local int gz_init(state) + gz_statep state; +{ + int ret; + z_streamp strm = &(state->strm); + + /* allocate input buffer */ + state->in = (unsigned char *)malloc(state->want); + if (state->in == NULL) { + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + + /* only need output buffer and deflate state if compressing */ + if (!state->direct) { + /* allocate output buffer */ + state->out = (unsigned char *)malloc(state->want); + if (state->out == NULL) { + free(state->in); + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + + /* allocate deflate memory, set up for gzip compression */ + strm->zalloc = Z_NULL; + strm->zfree = Z_NULL; + strm->opaque = Z_NULL; + ret = deflateInit2(strm, state->level, Z_DEFLATED, + MAX_WBITS + 16, DEF_MEM_LEVEL, state->strategy); + if (ret != Z_OK) { + free(state->out); + free(state->in); + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + } + + /* mark state as initialized */ + state->size = state->want; + + /* initialize write buffer if compressing */ + if (!state->direct) { + strm->avail_out = state->size; + strm->next_out = state->out; + state->x.next = strm->next_out; + } + return 0; +} + +/* Compress whatever is at avail_in and next_in and write to the output file. + Return -1 if there is an error writing to the output file, otherwise 0. + flush is assumed to be a valid deflate() flush value. If flush is Z_FINISH, + then the deflate() state is reset to start a new gzip stream. If gz->direct + is true, then simply write to the output file without compressing, and + ignore flush. */ +local int gz_comp(state, flush) + gz_statep state; + int flush; +{ + int ret, got; + unsigned have; + z_streamp strm = &(state->strm); + + /* allocate memory if this is the first time through */ + if (state->size == 0 && gz_init(state) == -1) + return -1; + + /* write directly if requested */ + if (state->direct) { + got = write(state->fd, strm->next_in, strm->avail_in); + if (got < 0 || (unsigned)got != strm->avail_in) { + gz_error(state, Z_ERRNO, zstrerror()); + return -1; + } + strm->avail_in = 0; + return 0; + } + + /* run deflate() on provided input until it produces no more output */ + ret = Z_OK; + do { + /* write out current buffer contents if full, or if flushing, but if + doing Z_FINISH then don't write until we get to Z_STREAM_END */ + if (strm->avail_out == 0 || (flush != Z_NO_FLUSH && + (flush != Z_FINISH || ret == Z_STREAM_END))) { + have = (unsigned)(strm->next_out - state->x.next); + if (have && ((got = write(state->fd, state->x.next, have)) < 0 || + (unsigned)got != have)) { + gz_error(state, Z_ERRNO, zstrerror()); + return -1; + } + if (strm->avail_out == 0) { + strm->avail_out = state->size; + strm->next_out = state->out; + } + state->x.next = strm->next_out; + } + + /* compress */ + have = strm->avail_out; + ret = deflate(strm, flush); + if (ret == Z_STREAM_ERROR) { + gz_error(state, Z_STREAM_ERROR, + "internal error: deflate stream corrupt"); + return -1; + } + have -= strm->avail_out; + } while (have); + + /* if that completed a deflate stream, allow another to start */ + if (flush == Z_FINISH) + deflateReset(strm); + + /* all done, no errors */ + return 0; +} + +/* Compress len zeros to output. Return -1 on error, 0 on success. */ +local int gz_zero(state, len) + gz_statep state; + z_off64_t len; +{ + int first; + unsigned n; + z_streamp strm = &(state->strm); + + /* consume whatever's left in the input buffer */ + if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1) + return -1; + + /* compress len zeros (len guaranteed > 0) */ + first = 1; + while (len) { + n = GT_OFF(state->size) || (z_off64_t)state->size > len ? + (unsigned)len : state->size; + if (first) { + memset(state->in, 0, n); + first = 0; + } + strm->avail_in = n; + strm->next_in = state->in; + state->x.pos += n; + if (gz_comp(state, Z_NO_FLUSH) == -1) + return -1; + len -= n; + } + return 0; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzwrite(file, buf, len) + gzFile file; + voidpc buf; + unsigned len; +{ + unsigned put = len; + gz_statep state; + z_streamp strm; + + /* get internal structure */ + if (file == NULL) + return 0; + state = (gz_statep)file; + strm = &(state->strm); + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return 0; + + /* since an int is returned, make sure len fits in one, otherwise return + with an error (this avoids the flaw in the interface) */ + if ((int)len < 0) { + gz_error(state, Z_DATA_ERROR, "requested length does not fit in int"); + return 0; + } + + /* if len is zero, avoid unnecessary operations */ + if (len == 0) + return 0; + + /* allocate memory if this is the first time through */ + if (state->size == 0 && gz_init(state) == -1) + return 0; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return 0; + } + + /* for small len, copy to input buffer, otherwise compress directly */ + if (len < state->size) { + /* copy to input buffer, compress when full */ + do { + unsigned have, copy; + + if (strm->avail_in == 0) + strm->next_in = state->in; + have = (unsigned)((strm->next_in + strm->avail_in) - state->in); + copy = state->size - have; + if (copy > len) + copy = len; + memcpy(state->in + have, buf, copy); + strm->avail_in += copy; + state->x.pos += copy; + buf = (const char *)buf + copy; + len -= copy; + if (len && gz_comp(state, Z_NO_FLUSH) == -1) + return 0; + } while (len); + } + else { + /* consume whatever's left in the input buffer */ + if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1) + return 0; + + /* directly compress user buffer to file */ + strm->avail_in = len; + strm->next_in = (z_const Bytef *)buf; + state->x.pos += len; + if (gz_comp(state, Z_NO_FLUSH) == -1) + return 0; + } + + /* input was all buffered or compressed (put will fit in int) */ + return (int)put; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzputc(file, c) + gzFile file; + int c; +{ + unsigned have; + unsigned char buf[1]; + gz_statep state; + z_streamp strm; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + strm = &(state->strm); + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return -1; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return -1; + } + + /* try writing to input buffer for speed (state->size == 0 if buffer not + initialized) */ + if (state->size) { + if (strm->avail_in == 0) + strm->next_in = state->in; + have = (unsigned)((strm->next_in + strm->avail_in) - state->in); + if (have < state->size) { + state->in[have] = c; + strm->avail_in++; + state->x.pos++; + return c & 0xff; + } + } + + /* no room in buffer or not initialized, use gz_write() */ + buf[0] = c; + if (gzwrite(file, buf, 1) != 1) + return -1; + return c & 0xff; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzputs(file, str) + gzFile file; + const char *str; +{ + int ret; + unsigned len; + + /* write string */ + len = (unsigned)strlen(str); + ret = gzwrite(file, str, len); + return ret == 0 && len != 0 ? -1 : ret; +} + +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +#include + +/* -- see zlib.h -- */ +int ZEXPORTVA gzvprintf(gzFile file, const char *format, va_list va) +{ + int size, len; + gz_statep state; + z_streamp strm; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + strm = &(state->strm); + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return 0; + + /* make sure we have some buffer space */ + if (state->size == 0 && gz_init(state) == -1) + return 0; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return 0; + } + + /* consume whatever's left in the input buffer */ + if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1) + return 0; + + /* do the printf() into the input buffer, put length in len */ + size = (int)(state->size); + state->in[size - 1] = 0; +#ifdef NO_vsnprintf +# ifdef HAS_vsprintf_void + (void)vsprintf((char *)(state->in), format, va); + for (len = 0; len < size; len++) + if (state->in[len] == 0) break; +# else + len = vsprintf((char *)(state->in), format, va); +# endif +#else +# ifdef HAS_vsnprintf_void + (void)vsnprintf((char *)(state->in), size, format, va); + len = strlen((char *)(state->in)); +# else + len = vsnprintf((char *)(state->in), size, format, va); +# endif +#endif + + /* check that printf() results fit in buffer */ + if (len <= 0 || len >= (int)size || state->in[size - 1] != 0) + return 0; + + /* update buffer and position, defer compression until needed */ + strm->avail_in = (unsigned)len; + strm->next_in = state->in; + state->x.pos += len; + return len; +} + +int ZEXPORTVA gzprintf(gzFile file, const char *format, ...) +{ + va_list va; + int ret; + + va_start(va, format); + ret = gzvprintf(file, format, va); + va_end(va); + return ret; +} + +#else /* !STDC && !Z_HAVE_STDARG_H */ + +/* -- see zlib.h -- */ +int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, + a11, a12, a13, a14, a15, a16, a17, a18, a19, a20) + gzFile file; + const char *format; + int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, + a11, a12, a13, a14, a15, a16, a17, a18, a19, a20; +{ + int size, len; + gz_statep state; + z_streamp strm; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + strm = &(state->strm); + + /* check that can really pass pointer in ints */ + if (sizeof(int) != sizeof(void *)) + return 0; + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return 0; + + /* make sure we have some buffer space */ + if (state->size == 0 && gz_init(state) == -1) + return 0; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return 0; + } + + /* consume whatever's left in the input buffer */ + if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1) + return 0; + + /* do the printf() into the input buffer, put length in len */ + size = (int)(state->size); + state->in[size - 1] = 0; +#ifdef NO_snprintf +# ifdef HAS_sprintf_void + sprintf((char *)(state->in), format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); + for (len = 0; len < size; len++) + if (state->in[len] == 0) break; +# else + len = sprintf((char *)(state->in), format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); +# endif +#else +# ifdef HAS_snprintf_void + snprintf((char *)(state->in), size, format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); + len = strlen((char *)(state->in)); +# else + len = snprintf((char *)(state->in), size, format, a1, a2, a3, a4, a5, a6, + a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, + a19, a20); +# endif +#endif + + /* check that printf() results fit in buffer */ + if (len <= 0 || len >= (int)size || state->in[size - 1] != 0) + return 0; + + /* update buffer and position, defer compression until needed */ + strm->avail_in = (unsigned)len; + strm->next_in = state->in; + state->x.pos += len; + return len; +} + +#endif + +/* -- see zlib.h -- */ +int ZEXPORT gzflush(file, flush) + gzFile file; + int flush; +{ + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return Z_STREAM_ERROR; + + /* check flush parameter */ + if (flush < 0 || flush > Z_FINISH) + return Z_STREAM_ERROR; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return -1; + } + + /* compress remaining data with requested flush */ + gz_comp(state, flush); + return state->err; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzsetparams(file, level, strategy) + gzFile file; + int level; + int strategy; +{ + gz_statep state; + z_streamp strm; + + /* get internal structure */ + if (file == NULL) + return Z_STREAM_ERROR; + state = (gz_statep)file; + strm = &(state->strm); + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return Z_STREAM_ERROR; + + /* if no change is requested, then do nothing */ + if (level == state->level && strategy == state->strategy) + return Z_OK; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return -1; + } + + /* change compression parameters for subsequent input */ + if (state->size) { + /* flush previous input with previous parameters before changing */ + if (strm->avail_in && gz_comp(state, Z_PARTIAL_FLUSH) == -1) + return state->err; + deflateParams(strm, level, strategy); + } + state->level = level; + state->strategy = strategy; + return Z_OK; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzclose_w(file) + gzFile file; +{ + int ret = Z_OK; + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return Z_STREAM_ERROR; + state = (gz_statep)file; + + /* check that we're writing */ + if (state->mode != GZ_WRITE) + return Z_STREAM_ERROR; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + ret = state->err; + } + + /* flush, free memory, and close file */ + if (gz_comp(state, Z_FINISH) == -1) + ret = state->err; + if (state->size) { + if (!state->direct) { + (void)deflateEnd(&(state->strm)); + free(state->out); + } + free(state->in); + } + gz_error(state, Z_OK, NULL); + free(state->path); + if (close(state->fd) == -1) + ret = Z_ERRNO; + free(state); + return ret; +} diff --git a/src/zlib/infback.c b/src/zlib/infback.c new file mode 100644 index 0000000..f3833c2 --- /dev/null +++ b/src/zlib/infback.c @@ -0,0 +1,640 @@ +/* infback.c -- inflate using a call-back interface + * Copyright (C) 1995-2011 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + This code is largely copied from inflate.c. Normally either infback.o or + inflate.o would be linked into an application--not both. The interface + with inffast.c is retained so that optimized assembler-coded versions of + inflate_fast() can be used with either inflate.c or infback.c. + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +/* function prototypes */ +local void fixedtables OF((struct inflate_state FAR *state)); + +/* + strm provides memory allocation functions in zalloc and zfree, or + Z_NULL to use the library memory allocation functions. + + windowBits is in the range 8..15, and window is a user-supplied + window and output buffer that is 2**windowBits bytes. + */ +int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size) +z_streamp strm; +int windowBits; +unsigned char FAR *window; +const char *version; +int stream_size; +{ + struct inflate_state FAR *state; + + if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || + stream_size != (int)(sizeof(z_stream))) + return Z_VERSION_ERROR; + if (strm == Z_NULL || window == Z_NULL || + windowBits < 8 || windowBits > 15) + return Z_STREAM_ERROR; + strm->msg = Z_NULL; /* in case we return an error */ + if (strm->zalloc == (alloc_func)0) { +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; +#endif + } + if (strm->zfree == (free_func)0) +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zfree = zcfree; +#endif + state = (struct inflate_state FAR *)ZALLOC(strm, 1, + sizeof(struct inflate_state)); + if (state == Z_NULL) return Z_MEM_ERROR; + Tracev((stderr, "inflate: allocated\n")); + strm->state = (struct internal_state FAR *)state; + state->dmax = 32768U; + state->wbits = windowBits; + state->wsize = 1U << windowBits; + state->window = window; + state->wnext = 0; + state->whave = 0; + return Z_OK; +} + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +local void fixedtables(state) +struct inflate_state FAR *state; +{ +#ifdef BUILDFIXED + static int virgin = 1; + static code *lenfix, *distfix; + static code fixed[544]; + + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + unsigned sym, bits; + static code *next; + + /* literal/length table */ + sym = 0; + while (sym < 144) state->lens[sym++] = 8; + while (sym < 256) state->lens[sym++] = 9; + while (sym < 280) state->lens[sym++] = 7; + while (sym < 288) state->lens[sym++] = 8; + next = fixed; + lenfix = next; + bits = 9; + inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); + + /* distance table */ + sym = 0; + while (sym < 32) state->lens[sym++] = 5; + distfix = next; + bits = 5; + inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); + + /* do this just once */ + virgin = 0; + } +#else /* !BUILDFIXED */ +# include "inffixed.h" +#endif /* BUILDFIXED */ + state->lencode = lenfix; + state->lenbits = 9; + state->distcode = distfix; + state->distbits = 5; +} + +/* Macros for inflateBack(): */ + +/* Load returned state from inflate_fast() */ +#define LOAD() \ + do { \ + put = strm->next_out; \ + left = strm->avail_out; \ + next = strm->next_in; \ + have = strm->avail_in; \ + hold = state->hold; \ + bits = state->bits; \ + } while (0) + +/* Set state from registers for inflate_fast() */ +#define RESTORE() \ + do { \ + strm->next_out = put; \ + strm->avail_out = left; \ + strm->next_in = next; \ + strm->avail_in = have; \ + state->hold = hold; \ + state->bits = bits; \ + } while (0) + +/* Clear the input bit accumulator */ +#define INITBITS() \ + do { \ + hold = 0; \ + bits = 0; \ + } while (0) + +/* Assure that some input is available. If input is requested, but denied, + then return a Z_BUF_ERROR from inflateBack(). */ +#define PULL() \ + do { \ + if (have == 0) { \ + have = in(in_desc, &next); \ + if (have == 0) { \ + next = Z_NULL; \ + ret = Z_BUF_ERROR; \ + goto inf_leave; \ + } \ + } \ + } while (0) + +/* Get a byte of input into the bit accumulator, or return from inflateBack() + with an error if there is no input available. */ +#define PULLBYTE() \ + do { \ + PULL(); \ + have--; \ + hold += (unsigned long)(*next++) << bits; \ + bits += 8; \ + } while (0) + +/* Assure that there are at least n bits in the bit accumulator. If there is + not enough available input to do that, then return from inflateBack() with + an error. */ +#define NEEDBITS(n) \ + do { \ + while (bits < (unsigned)(n)) \ + PULLBYTE(); \ + } while (0) + +/* Return the low n bits of the bit accumulator (n < 16) */ +#define BITS(n) \ + ((unsigned)hold & ((1U << (n)) - 1)) + +/* Remove n bits from the bit accumulator */ +#define DROPBITS(n) \ + do { \ + hold >>= (n); \ + bits -= (unsigned)(n); \ + } while (0) + +/* Remove zero to seven bits as needed to go to a byte boundary */ +#define BYTEBITS() \ + do { \ + hold >>= bits & 7; \ + bits -= bits & 7; \ + } while (0) + +/* Assure that some output space is available, by writing out the window + if it's full. If the write fails, return from inflateBack() with a + Z_BUF_ERROR. */ +#define ROOM() \ + do { \ + if (left == 0) { \ + put = state->window; \ + left = state->wsize; \ + state->whave = left; \ + if (out(out_desc, put, left)) { \ + ret = Z_BUF_ERROR; \ + goto inf_leave; \ + } \ + } \ + } while (0) + +/* + strm provides the memory allocation functions and window buffer on input, + and provides information on the unused input on return. For Z_DATA_ERROR + returns, strm will also provide an error message. + + in() and out() are the call-back input and output functions. When + inflateBack() needs more input, it calls in(). When inflateBack() has + filled the window with output, or when it completes with data in the + window, it calls out() to write out the data. The application must not + change the provided input until in() is called again or inflateBack() + returns. The application must not change the window/output buffer until + inflateBack() returns. + + in() and out() are called with a descriptor parameter provided in the + inflateBack() call. This parameter can be a structure that provides the + information required to do the read or write, as well as accumulated + information on the input and output such as totals and check values. + + in() should return zero on failure. out() should return non-zero on + failure. If either in() or out() fails, than inflateBack() returns a + Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it + was in() or out() that caused in the error. Otherwise, inflateBack() + returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format + error, or Z_MEM_ERROR if it could not allocate memory for the state. + inflateBack() can also return Z_STREAM_ERROR if the input parameters + are not correct, i.e. strm is Z_NULL or the state was not initialized. + */ +int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc) +z_streamp strm; +in_func in; +void FAR *in_desc; +out_func out; +void FAR *out_desc; +{ + struct inflate_state FAR *state; + z_const unsigned char FAR *next; /* next input */ + unsigned char FAR *put; /* next output */ + unsigned have, left; /* available input and output */ + unsigned long hold; /* bit buffer */ + unsigned bits; /* bits in bit buffer */ + unsigned copy; /* number of stored or match bytes to copy */ + unsigned char FAR *from; /* where to copy match bytes from */ + code here; /* current decoding table entry */ + code last; /* parent table entry */ + unsigned len; /* length to copy for repeats, bits to drop */ + int ret; /* return code */ + static const unsigned short order[19] = /* permutation of code lengths */ + {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + + /* Check that the strm exists and that the state was initialized */ + if (strm == Z_NULL || strm->state == Z_NULL) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* Reset the state */ + strm->msg = Z_NULL; + state->mode = TYPE; + state->last = 0; + state->whave = 0; + next = strm->next_in; + have = next != Z_NULL ? strm->avail_in : 0; + hold = 0; + bits = 0; + put = state->window; + left = state->wsize; + + /* Inflate until end of block marked as last */ + for (;;) + switch (state->mode) { + case TYPE: + /* determine and dispatch block type */ + if (state->last) { + BYTEBITS(); + state->mode = DONE; + break; + } + NEEDBITS(3); + state->last = BITS(1); + DROPBITS(1); + switch (BITS(2)) { + case 0: /* stored block */ + Tracev((stderr, "inflate: stored block%s\n", + state->last ? " (last)" : "")); + state->mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + Tracev((stderr, "inflate: fixed codes block%s\n", + state->last ? " (last)" : "")); + state->mode = LEN; /* decode codes */ + break; + case 2: /* dynamic block */ + Tracev((stderr, "inflate: dynamic codes block%s\n", + state->last ? " (last)" : "")); + state->mode = TABLE; + break; + case 3: + strm->msg = (char *)"invalid block type"; + state->mode = BAD; + } + DROPBITS(2); + break; + + case STORED: + /* get and verify stored block length */ + BYTEBITS(); /* go to byte boundary */ + NEEDBITS(32); + if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { + strm->msg = (char *)"invalid stored block lengths"; + state->mode = BAD; + break; + } + state->length = (unsigned)hold & 0xffff; + Tracev((stderr, "inflate: stored length %u\n", + state->length)); + INITBITS(); + + /* copy stored block from input to output */ + while (state->length != 0) { + copy = state->length; + PULL(); + ROOM(); + if (copy > have) copy = have; + if (copy > left) copy = left; + zmemcpy(put, next, copy); + have -= copy; + next += copy; + left -= copy; + put += copy; + state->length -= copy; + } + Tracev((stderr, "inflate: stored end\n")); + state->mode = TYPE; + break; + + case TABLE: + /* get dynamic table entries descriptor */ + NEEDBITS(14); + state->nlen = BITS(5) + 257; + DROPBITS(5); + state->ndist = BITS(5) + 1; + DROPBITS(5); + state->ncode = BITS(4) + 4; + DROPBITS(4); +#ifndef PKZIP_BUG_WORKAROUND + if (state->nlen > 286 || state->ndist > 30) { + strm->msg = (char *)"too many length or distance symbols"; + state->mode = BAD; + break; + } +#endif + Tracev((stderr, "inflate: table sizes ok\n")); + + /* get code length code lengths (not a typo) */ + state->have = 0; + while (state->have < state->ncode) { + NEEDBITS(3); + state->lens[order[state->have++]] = (unsigned short)BITS(3); + DROPBITS(3); + } + while (state->have < 19) + state->lens[order[state->have++]] = 0; + state->next = state->codes; + state->lencode = (code const FAR *)(state->next); + state->lenbits = 7; + ret = inflate_table(CODES, state->lens, 19, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid code lengths set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: code lengths ok\n")); + + /* get length and distance code code lengths */ + state->have = 0; + while (state->have < state->nlen + state->ndist) { + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.val < 16) { + DROPBITS(here.bits); + state->lens[state->have++] = here.val; + } + else { + if (here.val == 16) { + NEEDBITS(here.bits + 2); + DROPBITS(here.bits); + if (state->have == 0) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + len = (unsigned)(state->lens[state->have - 1]); + copy = 3 + BITS(2); + DROPBITS(2); + } + else if (here.val == 17) { + NEEDBITS(here.bits + 3); + DROPBITS(here.bits); + len = 0; + copy = 3 + BITS(3); + DROPBITS(3); + } + else { + NEEDBITS(here.bits + 7); + DROPBITS(here.bits); + len = 0; + copy = 11 + BITS(7); + DROPBITS(7); + } + if (state->have + copy > state->nlen + state->ndist) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + while (copy--) + state->lens[state->have++] = (unsigned short)len; + } + } + + /* handle error breaks in while */ + if (state->mode == BAD) break; + + /* check for end-of-block code (better have one) */ + if (state->lens[256] == 0) { + strm->msg = (char *)"invalid code -- missing end-of-block"; + state->mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state->next = state->codes; + state->lencode = (code const FAR *)(state->next); + state->lenbits = 9; + ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid literal/lengths set"; + state->mode = BAD; + break; + } + state->distcode = (code const FAR *)(state->next); + state->distbits = 6; + ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, + &(state->next), &(state->distbits), state->work); + if (ret) { + strm->msg = (char *)"invalid distances set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: codes ok\n")); + state->mode = LEN; + + case LEN: + /* use inflate_fast() if we have enough input and output */ + if (have >= 6 && left >= 258) { + RESTORE(); + if (state->whave < state->wsize) + state->whave = state->wsize - left; + inflate_fast(strm, state->wsize); + LOAD(); + break; + } + + /* get a literal, length, or end-of-block code */ + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.op && (here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->lencode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(here.bits); + state->length = (unsigned)here.val; + + /* process literal */ + if (here.op == 0) { + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", here.val)); + ROOM(); + *put++ = (unsigned char)(state->length); + left--; + state->mode = LEN; + break; + } + + /* process end of block */ + if (here.op & 32) { + Tracevv((stderr, "inflate: end of block\n")); + state->mode = TYPE; + break; + } + + /* invalid code */ + if (here.op & 64) { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + + /* length code -- get extra bits, if any */ + state->extra = (unsigned)(here.op) & 15; + if (state->extra != 0) { + NEEDBITS(state->extra); + state->length += BITS(state->extra); + DROPBITS(state->extra); + } + Tracevv((stderr, "inflate: length %u\n", state->length)); + + /* get distance code */ + for (;;) { + here = state->distcode[BITS(state->distbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if ((here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->distcode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(here.bits); + if (here.op & 64) { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + state->offset = (unsigned)here.val; + + /* get distance extra bits, if any */ + state->extra = (unsigned)(here.op) & 15; + if (state->extra != 0) { + NEEDBITS(state->extra); + state->offset += BITS(state->extra); + DROPBITS(state->extra); + } + if (state->offset > state->wsize - (state->whave < state->wsize ? + left : 0)) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } + Tracevv((stderr, "inflate: distance %u\n", state->offset)); + + /* copy match from window to output */ + do { + ROOM(); + copy = state->wsize - state->offset; + if (copy < left) { + from = put + copy; + copy = left - copy; + } + else { + from = put - state->offset; + copy = left; + } + if (copy > state->length) copy = state->length; + state->length -= copy; + left -= copy; + do { + *put++ = *from++; + } while (--copy); + } while (state->length != 0); + break; + + case DONE: + /* inflate stream terminated properly -- write leftover output */ + ret = Z_STREAM_END; + if (left < state->wsize) { + if (out(out_desc, state->window, state->wsize - left)) + ret = Z_BUF_ERROR; + } + goto inf_leave; + + case BAD: + ret = Z_DATA_ERROR; + goto inf_leave; + + default: /* can't happen, but makes compilers happy */ + ret = Z_STREAM_ERROR; + goto inf_leave; + } + + /* Return unused input */ + inf_leave: + strm->next_in = next; + strm->avail_in = have; + return ret; +} + +int ZEXPORT inflateBackEnd(strm) +z_streamp strm; +{ + if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) + return Z_STREAM_ERROR; + ZFREE(strm, strm->state); + strm->state = Z_NULL; + Tracev((stderr, "inflate: end\n")); + return Z_OK; +} diff --git a/src/zlib/inffast.c b/src/zlib/inffast.c new file mode 100644 index 0000000..bda59ce --- /dev/null +++ b/src/zlib/inffast.c @@ -0,0 +1,340 @@ +/* inffast.c -- fast decoding + * Copyright (C) 1995-2008, 2010, 2013 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +#ifndef ASMINF + +/* Allow machine dependent optimization for post-increment or pre-increment. + Based on testing to date, + Pre-increment preferred for: + - PowerPC G3 (Adler) + - MIPS R5000 (Randers-Pehrson) + Post-increment preferred for: + - none + No measurable difference: + - Pentium III (Anderson) + - M68060 (Nikl) + */ +#ifdef POSTINC +# define OFF 0 +# define PUP(a) *(a)++ +#else +# define OFF 1 +# define PUP(a) *++(a) +#endif + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state->mode == LEN + strm->avail_in >= 6 + strm->avail_out >= 258 + start >= strm->avail_out + state->bits < 8 + + On return, state->mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm->avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm->avail_out >= 258 for each loop to avoid checking for + output space. + */ +void ZLIB_INTERNAL inflate_fast(strm, start) +z_streamp strm; +unsigned start; /* inflate()'s starting value for strm->avail_out */ +{ + struct inflate_state FAR *state; + z_const unsigned char FAR *in; /* local strm->next_in */ + z_const unsigned char FAR *last; /* have enough input while in < last */ + unsigned char FAR *out; /* local strm->next_out */ + unsigned char FAR *beg; /* inflate()'s initial strm->next_out */ + unsigned char FAR *end; /* while out < end, enough space available */ +#ifdef INFLATE_STRICT + unsigned dmax; /* maximum distance from zlib header */ +#endif + unsigned wsize; /* window size or zero if not using window */ + unsigned whave; /* valid bytes in the window */ + unsigned wnext; /* window write index */ + unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */ + unsigned long hold; /* local strm->hold */ + unsigned bits; /* local strm->bits */ + code const FAR *lcode; /* local strm->lencode */ + code const FAR *dcode; /* local strm->distcode */ + unsigned lmask; /* mask for first level of length codes */ + unsigned dmask; /* mask for first level of distance codes */ + code here; /* retrieved table entry */ + unsigned op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + unsigned len; /* match length, unused bytes */ + unsigned dist; /* match distance */ + unsigned char FAR *from; /* where to copy match from */ + + /* copy state to local variables */ + state = (struct inflate_state FAR *)strm->state; + in = strm->next_in - OFF; + last = in + (strm->avail_in - 5); + out = strm->next_out - OFF; + beg = out - (start - strm->avail_out); + end = out + (strm->avail_out - 257); +#ifdef INFLATE_STRICT + dmax = state->dmax; +#endif + wsize = state->wsize; + whave = state->whave; + wnext = state->wnext; + window = state->window; + hold = state->hold; + bits = state->bits; + lcode = state->lencode; + dcode = state->distcode; + lmask = (1U << state->lenbits) - 1; + dmask = (1U << state->distbits) - 1; + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + do { + if (bits < 15) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + here = lcode[hold & lmask]; + dolen: + op = (unsigned)(here.bits); + hold >>= op; + bits -= op; + op = (unsigned)(here.op); + if (op == 0) { /* literal */ + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", here.val)); + PUP(out) = (unsigned char)(here.val); + } + else if (op & 16) { /* length base */ + len = (unsigned)(here.val); + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + len += (unsigned)hold & ((1U << op) - 1); + hold >>= op; + bits -= op; + } + Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + here = dcode[hold & dmask]; + dodist: + op = (unsigned)(here.bits); + hold >>= op; + bits -= op; + op = (unsigned)(here.op); + if (op & 16) { /* distance base */ + dist = (unsigned)(here.val); + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + if (bits < op) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + } + dist += (unsigned)hold & ((1U << op) - 1); +#ifdef INFLATE_STRICT + if (dist > dmax) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#endif + hold >>= op; + bits -= op; + Tracevv((stderr, "inflate: distance %u\n", dist)); + op = (unsigned)(out - beg); /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state->sane) { + strm->msg = + (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + if (len <= op - whave) { + do { + PUP(out) = 0; + } while (--len); + continue; + } + len -= op - whave; + do { + PUP(out) = 0; + } while (--op > whave); + if (op == 0) { + from = out - dist; + do { + PUP(out) = PUP(from); + } while (--len); + continue; + } +#endif + } + from = window - OFF; + if (wnext == 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = out - dist; /* rest from output */ + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = window - OFF; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = out - dist; /* rest from output */ + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = out - dist; /* rest from output */ + } + } + while (len > 2) { + PUP(out) = PUP(from); + PUP(out) = PUP(from); + PUP(out) = PUP(from); + len -= 3; + } + if (len) { + PUP(out) = PUP(from); + if (len > 1) + PUP(out) = PUP(from); + } + } + else { + from = out - dist; /* copy direct from output */ + do { /* minimum length is three */ + PUP(out) = PUP(from); + PUP(out) = PUP(from); + PUP(out) = PUP(from); + len -= 3; + } while (len > 2); + if (len) { + PUP(out) = PUP(from); + if (len > 1) + PUP(out) = PUP(from); + } + } + } + else if ((op & 64) == 0) { /* 2nd level distance code */ + here = dcode[here.val + (hold & ((1U << op) - 1))]; + goto dodist; + } + else { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + } + else if ((op & 64) == 0) { /* 2nd level length code */ + here = lcode[here.val + (hold & ((1U << op) - 1))]; + goto dolen; + } + else if (op & 32) { /* end-of-block */ + Tracevv((stderr, "inflate: end of block\n")); + state->mode = TYPE; + break; + } + else { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + } while (in < last && out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + in -= len; + bits -= len << 3; + hold &= (1U << bits) - 1; + + /* update state and return */ + strm->next_in = in + OFF; + strm->next_out = out + OFF; + strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last)); + strm->avail_out = (unsigned)(out < end ? + 257 + (end - out) : 257 - (out - end)); + state->hold = hold; + state->bits = bits; + return; +} + +/* + inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe): + - Using bit fields for code structure + - Different op definition to avoid & for extra bits (do & for table bits) + - Three separate decoding do-loops for direct, window, and wnext == 0 + - Special case for distance > 1 copies to do overlapped load and store copy + - Explicit branch predictions (based on measured branch probabilities) + - Deferring match copy and interspersed it with decoding subsequent codes + - Swapping literal/length else + - Swapping window/direct else + - Larger unrolled copy loops (three is about right) + - Moving len -= 3 statement into middle of loop + */ + +#endif /* !ASMINF */ diff --git a/src/zlib/inffast.h b/src/zlib/inffast.h new file mode 100644 index 0000000..e5c1aa4 --- /dev/null +++ b/src/zlib/inffast.h @@ -0,0 +1,11 @@ +/* inffast.h -- header to use inffast.c + * Copyright (C) 1995-2003, 2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +void ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start)); diff --git a/src/zlib/inffixed.h b/src/zlib/inffixed.h new file mode 100644 index 0000000..d628327 --- /dev/null +++ b/src/zlib/inffixed.h @@ -0,0 +1,94 @@ + /* inffixed.h -- table for decoding fixed codes + * Generated automatically by makefixed(). + */ + + /* WARNING: this file should *not* be used by applications. + It is part of the implementation of this library and is + subject to change. Applications should only use zlib.h. + */ + + static const code lenfix[512] = { + {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48}, + {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128}, + {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59}, + {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176}, + {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20}, + {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100}, + {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8}, + {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216}, + {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76}, + {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114}, + {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2}, + {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148}, + {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42}, + {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86}, + {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15}, + {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236}, + {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62}, + {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142}, + {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31}, + {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162}, + {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25}, + {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105}, + {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4}, + {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202}, + {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69}, + {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125}, + {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13}, + {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195}, + {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35}, + {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91}, + {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19}, + {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246}, + {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55}, + {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135}, + {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99}, + {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190}, + {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16}, + {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96}, + {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6}, + {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209}, + {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72}, + {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116}, + {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4}, + {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153}, + {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44}, + {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82}, + {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11}, + {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229}, + {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58}, + {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138}, + {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51}, + {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173}, + {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30}, + {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110}, + {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0}, + {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195}, + {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65}, + {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121}, + {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9}, + {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258}, + {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37}, + {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93}, + {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23}, + {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251}, + {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51}, + {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131}, + {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67}, + {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183}, + {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23}, + {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103}, + {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9}, + {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223}, + {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79}, + {0,9,255} + }; + + static const code distfix[32] = { + {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025}, + {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193}, + {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385}, + {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577}, + {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073}, + {22,5,193},{64,5,0} + }; diff --git a/src/zlib/inflate.c b/src/zlib/inflate.c new file mode 100644 index 0000000..870f89b --- /dev/null +++ b/src/zlib/inflate.c @@ -0,0 +1,1512 @@ +/* inflate.c -- zlib decompression + * Copyright (C) 1995-2012 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * Change history: + * + * 1.2.beta0 24 Nov 2002 + * - First version -- complete rewrite of inflate to simplify code, avoid + * creation of window when not needed, minimize use of window when it is + * needed, make inffast.c even faster, implement gzip decoding, and to + * improve code readability and style over the previous zlib inflate code + * + * 1.2.beta1 25 Nov 2002 + * - Use pointers for available input and output checking in inffast.c + * - Remove input and output counters in inffast.c + * - Change inffast.c entry and loop from avail_in >= 7 to >= 6 + * - Remove unnecessary second byte pull from length extra in inffast.c + * - Unroll direct copy to three copies per loop in inffast.c + * + * 1.2.beta2 4 Dec 2002 + * - Change external routine names to reduce potential conflicts + * - Correct filename to inffixed.h for fixed tables in inflate.c + * - Make hbuf[] unsigned char to match parameter type in inflate.c + * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset) + * to avoid negation problem on Alphas (64 bit) in inflate.c + * + * 1.2.beta3 22 Dec 2002 + * - Add comments on state->bits assertion in inffast.c + * - Add comments on op field in inftrees.h + * - Fix bug in reuse of allocated window after inflateReset() + * - Remove bit fields--back to byte structure for speed + * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths + * - Change post-increments to pre-increments in inflate_fast(), PPC biased? + * - Add compile time option, POSTINC, to use post-increments instead (Intel?) + * - Make MATCH copy in inflate() much faster for when inflate_fast() not used + * - Use local copies of stream next and avail values, as well as local bit + * buffer and bit count in inflate()--for speed when inflate_fast() not used + * + * 1.2.beta4 1 Jan 2003 + * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings + * - Move a comment on output buffer sizes from inffast.c to inflate.c + * - Add comments in inffast.c to introduce the inflate_fast() routine + * - Rearrange window copies in inflate_fast() for speed and simplification + * - Unroll last copy for window match in inflate_fast() + * - Use local copies of window variables in inflate_fast() for speed + * - Pull out common wnext == 0 case for speed in inflate_fast() + * - Make op and len in inflate_fast() unsigned for consistency + * - Add FAR to lcode and dcode declarations in inflate_fast() + * - Simplified bad distance check in inflate_fast() + * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new + * source file infback.c to provide a call-back interface to inflate for + * programs like gzip and unzip -- uses window as output buffer to avoid + * window copying + * + * 1.2.beta5 1 Jan 2003 + * - Improved inflateBack() interface to allow the caller to provide initial + * input in strm. + * - Fixed stored blocks bug in inflateBack() + * + * 1.2.beta6 4 Jan 2003 + * - Added comments in inffast.c on effectiveness of POSTINC + * - Typecasting all around to reduce compiler warnings + * - Changed loops from while (1) or do {} while (1) to for (;;), again to + * make compilers happy + * - Changed type of window in inflateBackInit() to unsigned char * + * + * 1.2.beta7 27 Jan 2003 + * - Changed many types to unsigned or unsigned short to avoid warnings + * - Added inflateCopy() function + * + * 1.2.0 9 Mar 2003 + * - Changed inflateBack() interface to provide separate opaque descriptors + * for the in() and out() functions + * - Changed inflateBack() argument and in_func typedef to swap the length + * and buffer address return values for the input function + * - Check next_in and next_out for Z_NULL on entry to inflate() + * + * The history for versions after 1.2.0 are in ChangeLog in zlib distribution. + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +#ifdef MAKEFIXED +# ifndef BUILDFIXED +# define BUILDFIXED +# endif +#endif + +/* function prototypes */ +local void fixedtables OF((struct inflate_state FAR *state)); +local int updatewindow OF((z_streamp strm, const unsigned char FAR *end, + unsigned copy)); +#ifdef BUILDFIXED + void makefixed OF((void)); +#endif +local unsigned syncsearch OF((unsigned FAR *have, const unsigned char FAR *buf, + unsigned len)); + +int ZEXPORT inflateResetKeep(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + strm->total_in = strm->total_out = state->total = 0; + strm->msg = Z_NULL; + if (state->wrap) /* to support ill-conceived Java test suite */ + strm->adler = state->wrap & 1; + state->mode = HEAD; + state->last = 0; + state->havedict = 0; + state->dmax = 32768U; + state->head = Z_NULL; + state->hold = 0; + state->bits = 0; + state->lencode = state->distcode = state->next = state->codes; + state->sane = 1; + state->back = -1; + Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +int ZEXPORT inflateReset(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + state->wsize = 0; + state->whave = 0; + state->wnext = 0; + return inflateResetKeep(strm); +} + +int ZEXPORT inflateReset2(strm, windowBits) +z_streamp strm; +int windowBits; +{ + int wrap; + struct inflate_state FAR *state; + + /* get the state */ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 1; +#ifdef GUNZIP + if (windowBits < 48) + windowBits &= 15; +#endif + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) + return Z_STREAM_ERROR; + if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) { + ZFREE(strm, state->window); + state->window = Z_NULL; + } + + /* update state and reset the rest of it */ + state->wrap = wrap; + state->wbits = (unsigned)windowBits; + return inflateReset(strm); +} + +int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size) +z_streamp strm; +int windowBits; +const char *version; +int stream_size; +{ + int ret; + struct inflate_state FAR *state; + + if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || + stream_size != (int)(sizeof(z_stream))) + return Z_VERSION_ERROR; + if (strm == Z_NULL) return Z_STREAM_ERROR; + strm->msg = Z_NULL; /* in case we return an error */ + if (strm->zalloc == (alloc_func)0) { +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; +#endif + } + if (strm->zfree == (free_func)0) +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zfree = zcfree; +#endif + state = (struct inflate_state FAR *) + ZALLOC(strm, 1, sizeof(struct inflate_state)); + if (state == Z_NULL) return Z_MEM_ERROR; + Tracev((stderr, "inflate: allocated\n")); + strm->state = (struct internal_state FAR *)state; + state->window = Z_NULL; + ret = inflateReset2(strm, windowBits); + if (ret != Z_OK) { + ZFREE(strm, state); + strm->state = Z_NULL; + } + return ret; +} + +int ZEXPORT inflateInit_(strm, version, stream_size) +z_streamp strm; +const char *version; +int stream_size; +{ + return inflateInit2_(strm, DEF_WBITS, version, stream_size); +} + +int ZEXPORT inflatePrime(strm, bits, value) +z_streamp strm; +int bits; +int value; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (bits < 0) { + state->hold = 0; + state->bits = 0; + return Z_OK; + } + if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR; + value &= (1L << bits) - 1; + state->hold += value << state->bits; + state->bits += bits; + return Z_OK; +} + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +local void fixedtables(state) +struct inflate_state FAR *state; +{ +#ifdef BUILDFIXED + static int virgin = 1; + static code *lenfix, *distfix; + static code fixed[544]; + + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + unsigned sym, bits; + static code *next; + + /* literal/length table */ + sym = 0; + while (sym < 144) state->lens[sym++] = 8; + while (sym < 256) state->lens[sym++] = 9; + while (sym < 280) state->lens[sym++] = 7; + while (sym < 288) state->lens[sym++] = 8; + next = fixed; + lenfix = next; + bits = 9; + inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); + + /* distance table */ + sym = 0; + while (sym < 32) state->lens[sym++] = 5; + distfix = next; + bits = 5; + inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); + + /* do this just once */ + virgin = 0; + } +#else /* !BUILDFIXED */ +# include "inffixed.h" +#endif /* BUILDFIXED */ + state->lencode = lenfix; + state->lenbits = 9; + state->distcode = distfix; + state->distbits = 5; +} + +#ifdef MAKEFIXED +#include + +/* + Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also + defines BUILDFIXED, so the tables are built on the fly. makefixed() writes + those tables to stdout, which would be piped to inffixed.h. A small program + can simply call makefixed to do this: + + void makefixed(void); + + int main(void) + { + makefixed(); + return 0; + } + + Then that can be linked with zlib built with MAKEFIXED defined and run: + + a.out > inffixed.h + */ +void makefixed() +{ + unsigned low, size; + struct inflate_state state; + + fixedtables(&state); + puts(" /* inffixed.h -- table for decoding fixed codes"); + puts(" * Generated automatically by makefixed()."); + puts(" */"); + puts(""); + puts(" /* WARNING: this file should *not* be used by applications."); + puts(" It is part of the implementation of this library and is"); + puts(" subject to change. Applications should only use zlib.h."); + puts(" */"); + puts(""); + size = 1U << 9; + printf(" static const code lenfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 7) == 0) printf("\n "); + printf("{%u,%u,%d}", (low & 127) == 99 ? 64 : state.lencode[low].op, + state.lencode[low].bits, state.lencode[low].val); + if (++low == size) break; + putchar(','); + } + puts("\n };"); + size = 1U << 5; + printf("\n static const code distfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 6) == 0) printf("\n "); + printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits, + state.distcode[low].val); + if (++low == size) break; + putchar(','); + } + puts("\n };"); +} +#endif /* MAKEFIXED */ + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +local int updatewindow(strm, end, copy) +z_streamp strm; +const Bytef *end; +unsigned copy; +{ + struct inflate_state FAR *state; + unsigned dist; + + state = (struct inflate_state FAR *)strm->state; + + /* if it hasn't been done already, allocate space for the window */ + if (state->window == Z_NULL) { + state->window = (unsigned char FAR *) + ZALLOC(strm, 1U << state->wbits, + sizeof(unsigned char)); + if (state->window == Z_NULL) return 1; + } + + /* if window not in use yet, initialize */ + if (state->wsize == 0) { + state->wsize = 1U << state->wbits; + state->wnext = 0; + state->whave = 0; + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state->wsize) { + zmemcpy(state->window, end - state->wsize, state->wsize); + state->wnext = 0; + state->whave = state->wsize; + } + else { + dist = state->wsize - state->wnext; + if (dist > copy) dist = copy; + zmemcpy(state->window + state->wnext, end - copy, dist); + copy -= dist; + if (copy) { + zmemcpy(state->window, end - copy, copy); + state->wnext = copy; + state->whave = state->wsize; + } + else { + state->wnext += dist; + if (state->wnext == state->wsize) state->wnext = 0; + if (state->whave < state->wsize) state->whave += dist; + } + } + return 0; +} + +/* Macros for inflate(): */ + +/* check function to use adler32() for zlib or crc32() for gzip */ +#ifdef GUNZIP +# define UPDATE(check, buf, len) \ + (state->flags ? crc32(check, buf, len) : adler32(check, buf, len)) +#else +# define UPDATE(check, buf, len) adler32(check, buf, len) +#endif + +/* check macros for header crc */ +#ifdef GUNZIP +# define CRC2(check, word) \ + do { \ + hbuf[0] = (unsigned char)(word); \ + hbuf[1] = (unsigned char)((word) >> 8); \ + check = crc32(check, hbuf, 2); \ + } while (0) + +# define CRC4(check, word) \ + do { \ + hbuf[0] = (unsigned char)(word); \ + hbuf[1] = (unsigned char)((word) >> 8); \ + hbuf[2] = (unsigned char)((word) >> 16); \ + hbuf[3] = (unsigned char)((word) >> 24); \ + check = crc32(check, hbuf, 4); \ + } while (0) +#endif + +/* Load registers with state in inflate() for speed */ +#define LOAD() \ + do { \ + put = strm->next_out; \ + left = strm->avail_out; \ + next = strm->next_in; \ + have = strm->avail_in; \ + hold = state->hold; \ + bits = state->bits; \ + } while (0) + +/* Restore state from registers in inflate() */ +#define RESTORE() \ + do { \ + strm->next_out = put; \ + strm->avail_out = left; \ + strm->next_in = next; \ + strm->avail_in = have; \ + state->hold = hold; \ + state->bits = bits; \ + } while (0) + +/* Clear the input bit accumulator */ +#define INITBITS() \ + do { \ + hold = 0; \ + bits = 0; \ + } while (0) + +/* Get a byte of input into the bit accumulator, or return from inflate() + if there is no input available. */ +#define PULLBYTE() \ + do { \ + if (have == 0) goto inf_leave; \ + have--; \ + hold += (unsigned long)(*next++) << bits; \ + bits += 8; \ + } while (0) + +/* Assure that there are at least n bits in the bit accumulator. If there is + not enough available input to do that, then return from inflate(). */ +#define NEEDBITS(n) \ + do { \ + while (bits < (unsigned)(n)) \ + PULLBYTE(); \ + } while (0) + +/* Return the low n bits of the bit accumulator (n < 16) */ +#define BITS(n) \ + ((unsigned)hold & ((1U << (n)) - 1)) + +/* Remove n bits from the bit accumulator */ +#define DROPBITS(n) \ + do { \ + hold >>= (n); \ + bits -= (unsigned)(n); \ + } while (0) + +/* Remove zero to seven bits as needed to go to a byte boundary */ +#define BYTEBITS() \ + do { \ + hold >>= bits & 7; \ + bits -= bits & 7; \ + } while (0) + +/* + inflate() uses a state machine to process as much input data and generate as + much output data as possible before returning. The state machine is + structured roughly as follows: + + for (;;) switch (state) { + ... + case STATEn: + if (not enough input data or output space to make progress) + return; + ... make progress ... + state = STATEm; + break; + ... + } + + so when inflate() is called again, the same case is attempted again, and + if the appropriate resources are provided, the machine proceeds to the + next state. The NEEDBITS() macro is usually the way the state evaluates + whether it can proceed or should return. NEEDBITS() does the return if + the requested bits are not available. The typical use of the BITS macros + is: + + NEEDBITS(n); + ... do something with BITS(n) ... + DROPBITS(n); + + where NEEDBITS(n) either returns from inflate() if there isn't enough + input left to load n bits into the accumulator, or it continues. BITS(n) + gives the low n bits in the accumulator. When done, DROPBITS(n) drops + the low n bits off the accumulator. INITBITS() clears the accumulator + and sets the number of available bits to zero. BYTEBITS() discards just + enough bits to put the accumulator on a byte boundary. After BYTEBITS() + and a NEEDBITS(8), then BITS(8) would return the next byte in the stream. + + NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return + if there is no input available. The decoding of variable length codes uses + PULLBYTE() directly in order to pull just enough bytes to decode the next + code, and no more. + + Some states loop until they get enough input, making sure that enough + state information is maintained to continue the loop where it left off + if NEEDBITS() returns in the loop. For example, want, need, and keep + would all have to actually be part of the saved state in case NEEDBITS() + returns: + + case STATEw: + while (want < need) { + NEEDBITS(n); + keep[want++] = BITS(n); + DROPBITS(n); + } + state = STATEx; + case STATEx: + + As shown above, if the next state is also the next case, then the break + is omitted. + + A state may also return if there is not enough output space available to + complete that state. Those states are copying stored data, writing a + literal byte, and copying a matching string. + + When returning, a "goto inf_leave" is used to update the total counters, + update the check value, and determine whether any progress has been made + during that inflate() call in order to return the proper return code. + Progress is defined as a change in either strm->avail_in or strm->avail_out. + When there is a window, goto inf_leave will update the window with the last + output written. If a goto inf_leave occurs in the middle of decompression + and there is no window currently, goto inf_leave will create one and copy + output to the window for the next call of inflate(). + + In this implementation, the flush parameter of inflate() only affects the + return code (per zlib.h). inflate() always writes as much as possible to + strm->next_out, given the space available and the provided input--the effect + documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers + the allocation of and copying into a sliding window until necessary, which + provides the effect documented in zlib.h for Z_FINISH when the entire input + stream available. So the only thing the flush parameter actually does is: + when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it + will return Z_BUF_ERROR if it has not reached the end of the stream. + */ + +int ZEXPORT inflate(strm, flush) +z_streamp strm; +int flush; +{ + struct inflate_state FAR *state; + z_const unsigned char FAR *next; /* next input */ + unsigned char FAR *put; /* next output */ + unsigned have, left; /* available input and output */ + unsigned long hold; /* bit buffer */ + unsigned bits; /* bits in bit buffer */ + unsigned in, out; /* save starting available input and output */ + unsigned copy; /* number of stored or match bytes to copy */ + unsigned char FAR *from; /* where to copy match bytes from */ + code here; /* current decoding table entry */ + code last; /* parent table entry */ + unsigned len; /* length to copy for repeats, bits to drop */ + int ret; /* return code */ +#ifdef GUNZIP + unsigned char hbuf[4]; /* buffer for gzip header crc calculation */ +#endif + static const unsigned short order[19] = /* permutation of code lengths */ + {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + + if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL || + (strm->next_in == Z_NULL && strm->avail_in != 0)) + return Z_STREAM_ERROR; + + state = (struct inflate_state FAR *)strm->state; + if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */ + LOAD(); + in = have; + out = left; + ret = Z_OK; + for (;;) + switch (state->mode) { + case HEAD: + if (state->wrap == 0) { + state->mode = TYPEDO; + break; + } + NEEDBITS(16); +#ifdef GUNZIP + if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */ + state->check = crc32(0L, Z_NULL, 0); + CRC2(state->check, hold); + INITBITS(); + state->mode = FLAGS; + break; + } + state->flags = 0; /* expect zlib header */ + if (state->head != Z_NULL) + state->head->done = -1; + if (!(state->wrap & 1) || /* check if zlib header allowed */ +#else + if ( +#endif + ((BITS(8) << 8) + (hold >> 8)) % 31) { + strm->msg = (char *)"incorrect header check"; + state->mode = BAD; + break; + } + if (BITS(4) != Z_DEFLATED) { + strm->msg = (char *)"unknown compression method"; + state->mode = BAD; + break; + } + DROPBITS(4); + len = BITS(4) + 8; + if (state->wbits == 0) + state->wbits = len; + else if (len > state->wbits) { + strm->msg = (char *)"invalid window size"; + state->mode = BAD; + break; + } + state->dmax = 1U << len; + Tracev((stderr, "inflate: zlib header ok\n")); + strm->adler = state->check = adler32(0L, Z_NULL, 0); + state->mode = hold & 0x200 ? DICTID : TYPE; + INITBITS(); + break; +#ifdef GUNZIP + case FLAGS: + NEEDBITS(16); + state->flags = (int)(hold); + if ((state->flags & 0xff) != Z_DEFLATED) { + strm->msg = (char *)"unknown compression method"; + state->mode = BAD; + break; + } + if (state->flags & 0xe000) { + strm->msg = (char *)"unknown header flags set"; + state->mode = BAD; + break; + } + if (state->head != Z_NULL) + state->head->text = (int)((hold >> 8) & 1); + if (state->flags & 0x0200) CRC2(state->check, hold); + INITBITS(); + state->mode = TIME; + case TIME: + NEEDBITS(32); + if (state->head != Z_NULL) + state->head->time = hold; + if (state->flags & 0x0200) CRC4(state->check, hold); + INITBITS(); + state->mode = OS; + case OS: + NEEDBITS(16); + if (state->head != Z_NULL) { + state->head->xflags = (int)(hold & 0xff); + state->head->os = (int)(hold >> 8); + } + if (state->flags & 0x0200) CRC2(state->check, hold); + INITBITS(); + state->mode = EXLEN; + case EXLEN: + if (state->flags & 0x0400) { + NEEDBITS(16); + state->length = (unsigned)(hold); + if (state->head != Z_NULL) + state->head->extra_len = (unsigned)hold; + if (state->flags & 0x0200) CRC2(state->check, hold); + INITBITS(); + } + else if (state->head != Z_NULL) + state->head->extra = Z_NULL; + state->mode = EXTRA; + case EXTRA: + if (state->flags & 0x0400) { + copy = state->length; + if (copy > have) copy = have; + if (copy) { + if (state->head != Z_NULL && + state->head->extra != Z_NULL) { + len = state->head->extra_len - state->length; + zmemcpy(state->head->extra + len, next, + len + copy > state->head->extra_max ? + state->head->extra_max - len : copy); + } + if (state->flags & 0x0200) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + state->length -= copy; + } + if (state->length) goto inf_leave; + } + state->length = 0; + state->mode = NAME; + case NAME: + if (state->flags & 0x0800) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + if (state->head != Z_NULL && + state->head->name != Z_NULL && + state->length < state->head->name_max) + state->head->name[state->length++] = len; + } while (len && copy < have); + if (state->flags & 0x0200) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } + else if (state->head != Z_NULL) + state->head->name = Z_NULL; + state->length = 0; + state->mode = COMMENT; + case COMMENT: + if (state->flags & 0x1000) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + if (state->head != Z_NULL && + state->head->comment != Z_NULL && + state->length < state->head->comm_max) + state->head->comment[state->length++] = len; + } while (len && copy < have); + if (state->flags & 0x0200) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } + else if (state->head != Z_NULL) + state->head->comment = Z_NULL; + state->mode = HCRC; + case HCRC: + if (state->flags & 0x0200) { + NEEDBITS(16); + if (hold != (state->check & 0xffff)) { + strm->msg = (char *)"header crc mismatch"; + state->mode = BAD; + break; + } + INITBITS(); + } + if (state->head != Z_NULL) { + state->head->hcrc = (int)((state->flags >> 9) & 1); + state->head->done = 1; + } + strm->adler = state->check = crc32(0L, Z_NULL, 0); + state->mode = TYPE; + break; +#endif + case DICTID: + NEEDBITS(32); + strm->adler = state->check = ZSWAP32(hold); + INITBITS(); + state->mode = DICT; + case DICT: + if (state->havedict == 0) { + RESTORE(); + return Z_NEED_DICT; + } + strm->adler = state->check = adler32(0L, Z_NULL, 0); + state->mode = TYPE; + case TYPE: + if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave; + case TYPEDO: + if (state->last) { + BYTEBITS(); + state->mode = CHECK; + break; + } + NEEDBITS(3); + state->last = BITS(1); + DROPBITS(1); + switch (BITS(2)) { + case 0: /* stored block */ + Tracev((stderr, "inflate: stored block%s\n", + state->last ? " (last)" : "")); + state->mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + Tracev((stderr, "inflate: fixed codes block%s\n", + state->last ? " (last)" : "")); + state->mode = LEN_; /* decode codes */ + if (flush == Z_TREES) { + DROPBITS(2); + goto inf_leave; + } + break; + case 2: /* dynamic block */ + Tracev((stderr, "inflate: dynamic codes block%s\n", + state->last ? " (last)" : "")); + state->mode = TABLE; + break; + case 3: + strm->msg = (char *)"invalid block type"; + state->mode = BAD; + } + DROPBITS(2); + break; + case STORED: + BYTEBITS(); /* go to byte boundary */ + NEEDBITS(32); + if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { + strm->msg = (char *)"invalid stored block lengths"; + state->mode = BAD; + break; + } + state->length = (unsigned)hold & 0xffff; + Tracev((stderr, "inflate: stored length %u\n", + state->length)); + INITBITS(); + state->mode = COPY_; + if (flush == Z_TREES) goto inf_leave; + case COPY_: + state->mode = COPY; + case COPY: + copy = state->length; + if (copy) { + if (copy > have) copy = have; + if (copy > left) copy = left; + if (copy == 0) goto inf_leave; + zmemcpy(put, next, copy); + have -= copy; + next += copy; + left -= copy; + put += copy; + state->length -= copy; + break; + } + Tracev((stderr, "inflate: stored end\n")); + state->mode = TYPE; + break; + case TABLE: + NEEDBITS(14); + state->nlen = BITS(5) + 257; + DROPBITS(5); + state->ndist = BITS(5) + 1; + DROPBITS(5); + state->ncode = BITS(4) + 4; + DROPBITS(4); +#ifndef PKZIP_BUG_WORKAROUND + if (state->nlen > 286 || state->ndist > 30) { + strm->msg = (char *)"too many length or distance symbols"; + state->mode = BAD; + break; + } +#endif + Tracev((stderr, "inflate: table sizes ok\n")); + state->have = 0; + state->mode = LENLENS; + case LENLENS: + while (state->have < state->ncode) { + NEEDBITS(3); + state->lens[order[state->have++]] = (unsigned short)BITS(3); + DROPBITS(3); + } + while (state->have < 19) + state->lens[order[state->have++]] = 0; + state->next = state->codes; + state->lencode = (const code FAR *)(state->next); + state->lenbits = 7; + ret = inflate_table(CODES, state->lens, 19, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid code lengths set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: code lengths ok\n")); + state->have = 0; + state->mode = CODELENS; + case CODELENS: + while (state->have < state->nlen + state->ndist) { + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.val < 16) { + DROPBITS(here.bits); + state->lens[state->have++] = here.val; + } + else { + if (here.val == 16) { + NEEDBITS(here.bits + 2); + DROPBITS(here.bits); + if (state->have == 0) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + len = state->lens[state->have - 1]; + copy = 3 + BITS(2); + DROPBITS(2); + } + else if (here.val == 17) { + NEEDBITS(here.bits + 3); + DROPBITS(here.bits); + len = 0; + copy = 3 + BITS(3); + DROPBITS(3); + } + else { + NEEDBITS(here.bits + 7); + DROPBITS(here.bits); + len = 0; + copy = 11 + BITS(7); + DROPBITS(7); + } + if (state->have + copy > state->nlen + state->ndist) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + while (copy--) + state->lens[state->have++] = (unsigned short)len; + } + } + + /* handle error breaks in while */ + if (state->mode == BAD) break; + + /* check for end-of-block code (better have one) */ + if (state->lens[256] == 0) { + strm->msg = (char *)"invalid code -- missing end-of-block"; + state->mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state->next = state->codes; + state->lencode = (const code FAR *)(state->next); + state->lenbits = 9; + ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid literal/lengths set"; + state->mode = BAD; + break; + } + state->distcode = (const code FAR *)(state->next); + state->distbits = 6; + ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, + &(state->next), &(state->distbits), state->work); + if (ret) { + strm->msg = (char *)"invalid distances set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: codes ok\n")); + state->mode = LEN_; + if (flush == Z_TREES) goto inf_leave; + case LEN_: + state->mode = LEN; + case LEN: + if (have >= 6 && left >= 258) { + RESTORE(); + inflate_fast(strm, out); + LOAD(); + if (state->mode == TYPE) + state->back = -1; + break; + } + state->back = 0; + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.op && (here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->lencode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + state->back += last.bits; + } + DROPBITS(here.bits); + state->back += here.bits; + state->length = (unsigned)here.val; + if ((int)(here.op) == 0) { + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", here.val)); + state->mode = LIT; + break; + } + if (here.op & 32) { + Tracevv((stderr, "inflate: end of block\n")); + state->back = -1; + state->mode = TYPE; + break; + } + if (here.op & 64) { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + state->extra = (unsigned)(here.op) & 15; + state->mode = LENEXT; + case LENEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->length += BITS(state->extra); + DROPBITS(state->extra); + state->back += state->extra; + } + Tracevv((stderr, "inflate: length %u\n", state->length)); + state->was = state->length; + state->mode = DIST; + case DIST: + for (;;) { + here = state->distcode[BITS(state->distbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if ((here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->distcode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + state->back += last.bits; + } + DROPBITS(here.bits); + state->back += here.bits; + if (here.op & 64) { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + state->offset = (unsigned)here.val; + state->extra = (unsigned)(here.op) & 15; + state->mode = DISTEXT; + case DISTEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->offset += BITS(state->extra); + DROPBITS(state->extra); + state->back += state->extra; + } +#ifdef INFLATE_STRICT + if (state->offset > state->dmax) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#endif + Tracevv((stderr, "inflate: distance %u\n", state->offset)); + state->mode = MATCH; + case MATCH: + if (left == 0) goto inf_leave; + copy = out - left; + if (state->offset > copy) { /* copy from window */ + copy = state->offset - copy; + if (copy > state->whave) { + if (state->sane) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + Trace((stderr, "inflate.c too far\n")); + copy -= state->whave; + if (copy > state->length) copy = state->length; + if (copy > left) copy = left; + left -= copy; + state->length -= copy; + do { + *put++ = 0; + } while (--copy); + if (state->length == 0) state->mode = LEN; + break; +#endif + } + if (copy > state->wnext) { + copy -= state->wnext; + from = state->window + (state->wsize - copy); + } + else + from = state->window + (state->wnext - copy); + if (copy > state->length) copy = state->length; + } + else { /* copy from output */ + from = put - state->offset; + copy = state->length; + } + if (copy > left) copy = left; + left -= copy; + state->length -= copy; + do { + *put++ = *from++; + } while (--copy); + if (state->length == 0) state->mode = LEN; + break; + case LIT: + if (left == 0) goto inf_leave; + *put++ = (unsigned char)(state->length); + left--; + state->mode = LEN; + break; + case CHECK: + if (state->wrap) { + NEEDBITS(32); + out -= left; + strm->total_out += out; + state->total += out; + if (out) + strm->adler = state->check = + UPDATE(state->check, put - out, out); + out = left; + if (( +#ifdef GUNZIP + state->flags ? hold : +#endif + ZSWAP32(hold)) != state->check) { + strm->msg = (char *)"incorrect data check"; + state->mode = BAD; + break; + } + INITBITS(); + Tracev((stderr, "inflate: check matches trailer\n")); + } +#ifdef GUNZIP + state->mode = LENGTH; + case LENGTH: + if (state->wrap && state->flags) { + NEEDBITS(32); + if (hold != (state->total & 0xffffffffUL)) { + strm->msg = (char *)"incorrect length check"; + state->mode = BAD; + break; + } + INITBITS(); + Tracev((stderr, "inflate: length matches trailer\n")); + } +#endif + state->mode = DONE; + case DONE: + ret = Z_STREAM_END; + goto inf_leave; + case BAD: + ret = Z_DATA_ERROR; + goto inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + default: + return Z_STREAM_ERROR; + } + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + inf_leave: + RESTORE(); + if (state->wsize || (out != strm->avail_out && state->mode < BAD && + (state->mode < CHECK || flush != Z_FINISH))) + if (updatewindow(strm, strm->next_out, out - strm->avail_out)) { + state->mode = MEM; + return Z_MEM_ERROR; + } + in -= strm->avail_in; + out -= strm->avail_out; + strm->total_in += in; + strm->total_out += out; + state->total += out; + if (state->wrap && out) + strm->adler = state->check = + UPDATE(state->check, strm->next_out - out, out); + strm->data_type = state->bits + (state->last ? 64 : 0) + + (state->mode == TYPE ? 128 : 0) + + (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0); + if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK) + ret = Z_BUF_ERROR; + return ret; +} + +int ZEXPORT inflateEnd(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (state->window != Z_NULL) ZFREE(strm, state->window); + ZFREE(strm, strm->state); + strm->state = Z_NULL; + Tracev((stderr, "inflate: end\n")); + return Z_OK; +} + +int ZEXPORT inflateGetDictionary(strm, dictionary, dictLength) +z_streamp strm; +Bytef *dictionary; +uInt *dictLength; +{ + struct inflate_state FAR *state; + + /* check state */ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* copy dictionary */ + if (state->whave && dictionary != Z_NULL) { + zmemcpy(dictionary, state->window + state->wnext, + state->whave - state->wnext); + zmemcpy(dictionary + state->whave - state->wnext, + state->window, state->wnext); + } + if (dictLength != Z_NULL) + *dictLength = state->whave; + return Z_OK; +} + +int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength) +z_streamp strm; +const Bytef *dictionary; +uInt dictLength; +{ + struct inflate_state FAR *state; + unsigned long dictid; + int ret; + + /* check state */ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (state->wrap != 0 && state->mode != DICT) + return Z_STREAM_ERROR; + + /* check for correct dictionary identifier */ + if (state->mode == DICT) { + dictid = adler32(0L, Z_NULL, 0); + dictid = adler32(dictid, dictionary, dictLength); + if (dictid != state->check) + return Z_DATA_ERROR; + } + + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow(strm, dictionary + dictLength, dictLength); + if (ret) { + state->mode = MEM; + return Z_MEM_ERROR; + } + state->havedict = 1; + Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK; +} + +int ZEXPORT inflateGetHeader(strm, head) +z_streamp strm; +gz_headerp head; +{ + struct inflate_state FAR *state; + + /* check state */ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if ((state->wrap & 2) == 0) return Z_STREAM_ERROR; + + /* save header structure */ + state->head = head; + head->done = 0; + return Z_OK; +} + +/* + Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found + or when out of input. When called, *have is the number of pattern bytes + found in order so far, in 0..3. On return *have is updated to the new + state. If on return *have equals four, then the pattern was found and the + return value is how many bytes were read including the last byte of the + pattern. If *have is less than four, then the pattern has not been found + yet and the return value is len. In the latter case, syncsearch() can be + called again with more data and the *have state. *have is initialized to + zero for the first call. + */ +local unsigned syncsearch(have, buf, len) +unsigned FAR *have; +const unsigned char FAR *buf; +unsigned len; +{ + unsigned got; + unsigned next; + + got = *have; + next = 0; + while (next < len && got < 4) { + if ((int)(buf[next]) == (got < 2 ? 0 : 0xff)) + got++; + else if (buf[next]) + got = 0; + else + got = 4 - got; + next++; + } + *have = got; + return next; +} + +int ZEXPORT inflateSync(strm) +z_streamp strm; +{ + unsigned len; /* number of bytes to look at or looked at */ + unsigned long in, out; /* temporary to save total_in and total_out */ + unsigned char buf[4]; /* to restore bit buffer to byte string */ + struct inflate_state FAR *state; + + /* check parameters */ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR; + + /* if first time, start search in bit buffer */ + if (state->mode != SYNC) { + state->mode = SYNC; + state->hold <<= state->bits & 7; + state->bits -= state->bits & 7; + len = 0; + while (state->bits >= 8) { + buf[len++] = (unsigned char)(state->hold); + state->hold >>= 8; + state->bits -= 8; + } + state->have = 0; + syncsearch(&(state->have), buf, len); + } + + /* search available input */ + len = syncsearch(&(state->have), strm->next_in, strm->avail_in); + strm->avail_in -= len; + strm->next_in += len; + strm->total_in += len; + + /* return no joy or set up to restart inflate() on a new block */ + if (state->have != 4) return Z_DATA_ERROR; + in = strm->total_in; out = strm->total_out; + inflateReset(strm); + strm->total_in = in; strm->total_out = out; + state->mode = TYPE; + return Z_OK; +} + +/* + Returns true if inflate is currently at the end of a block generated by + Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP + implementation to provide an additional safety check. PPP uses + Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored + block. When decompressing, PPP checks that at the end of input packet, + inflate is waiting for these length bytes. + */ +int ZEXPORT inflateSyncPoint(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + return state->mode == STORED && state->bits == 0; +} + +int ZEXPORT inflateCopy(dest, source) +z_streamp dest; +z_streamp source; +{ + struct inflate_state FAR *state; + struct inflate_state FAR *copy; + unsigned char FAR *window; + unsigned wsize; + + /* check input */ + if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL || + source->zalloc == (alloc_func)0 || source->zfree == (free_func)0) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)source->state; + + /* allocate space */ + copy = (struct inflate_state FAR *) + ZALLOC(source, 1, sizeof(struct inflate_state)); + if (copy == Z_NULL) return Z_MEM_ERROR; + window = Z_NULL; + if (state->window != Z_NULL) { + window = (unsigned char FAR *) + ZALLOC(source, 1U << state->wbits, sizeof(unsigned char)); + if (window == Z_NULL) { + ZFREE(source, copy); + return Z_MEM_ERROR; + } + } + + /* copy state */ + zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream)); + zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state)); + if (state->lencode >= state->codes && + state->lencode <= state->codes + ENOUGH - 1) { + copy->lencode = copy->codes + (state->lencode - state->codes); + copy->distcode = copy->codes + (state->distcode - state->codes); + } + copy->next = copy->codes + (state->next - state->codes); + if (window != Z_NULL) { + wsize = 1U << state->wbits; + zmemcpy(window, state->window, wsize); + } + copy->window = window; + dest->state = (struct internal_state FAR *)copy; + return Z_OK; +} + +int ZEXPORT inflateUndermine(strm, subvert) +z_streamp strm; +int subvert; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + state->sane = !subvert; +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + return Z_OK; +#else + state->sane = 1; + return Z_DATA_ERROR; +#endif +} + +long ZEXPORT inflateMark(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return -1L << 16; + state = (struct inflate_state FAR *)strm->state; + return ((long)(state->back) << 16) + + (state->mode == COPY ? state->length : + (state->mode == MATCH ? state->was - state->length : 0)); +} diff --git a/src/zlib/inflate.h b/src/zlib/inflate.h new file mode 100644 index 0000000..95f4986 --- /dev/null +++ b/src/zlib/inflate.h @@ -0,0 +1,122 @@ +/* inflate.h -- internal inflate state definition + * Copyright (C) 1995-2009 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* define NO_GZIP when compiling if you want to disable gzip header and + trailer decoding by inflate(). NO_GZIP would be used to avoid linking in + the crc code when it is not needed. For shared libraries, gzip decoding + should be left enabled. */ +#ifndef NO_GZIP +# define GUNZIP +#endif + +/* Possible inflate modes between inflate() calls */ +typedef enum { + HEAD, /* i: waiting for magic header */ + FLAGS, /* i: waiting for method and flags (gzip) */ + TIME, /* i: waiting for modification time (gzip) */ + OS, /* i: waiting for extra flags and operating system (gzip) */ + EXLEN, /* i: waiting for extra length (gzip) */ + EXTRA, /* i: waiting for extra bytes (gzip) */ + NAME, /* i: waiting for end of file name (gzip) */ + COMMENT, /* i: waiting for end of comment (gzip) */ + HCRC, /* i: waiting for header crc (gzip) */ + DICTID, /* i: waiting for dictionary check value */ + DICT, /* waiting for inflateSetDictionary() call */ + TYPE, /* i: waiting for type bits, including last-flag bit */ + TYPEDO, /* i: same, but skip check to exit inflate on new block */ + STORED, /* i: waiting for stored size (length and complement) */ + COPY_, /* i/o: same as COPY below, but only first time in */ + COPY, /* i/o: waiting for input or output to copy stored block */ + TABLE, /* i: waiting for dynamic block table lengths */ + LENLENS, /* i: waiting for code length code lengths */ + CODELENS, /* i: waiting for length/lit and distance code lengths */ + LEN_, /* i: same as LEN below, but only first time in */ + LEN, /* i: waiting for length/lit/eob code */ + LENEXT, /* i: waiting for length extra bits */ + DIST, /* i: waiting for distance code */ + DISTEXT, /* i: waiting for distance extra bits */ + MATCH, /* o: waiting for output space to copy string */ + LIT, /* o: waiting for output space to write literal */ + CHECK, /* i: waiting for 32-bit check value */ + LENGTH, /* i: waiting for 32-bit length (gzip) */ + DONE, /* finished check, done -- remain here until reset */ + BAD, /* got a data error -- remain here until reset */ + MEM, /* got an inflate() memory error -- remain here until reset */ + SYNC /* looking for synchronization bytes to restart inflate() */ +} inflate_mode; + +/* + State transitions between above modes - + + (most modes can go to BAD or MEM on error -- not shown for clarity) + + Process header: + HEAD -> (gzip) or (zlib) or (raw) + (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME -> COMMENT -> + HCRC -> TYPE + (zlib) -> DICTID or TYPE + DICTID -> DICT -> TYPE + (raw) -> TYPEDO + Read deflate blocks: + TYPE -> TYPEDO -> STORED or TABLE or LEN_ or CHECK + STORED -> COPY_ -> COPY -> TYPE + TABLE -> LENLENS -> CODELENS -> LEN_ + LEN_ -> LEN + Read deflate codes in fixed or dynamic block: + LEN -> LENEXT or LIT or TYPE + LENEXT -> DIST -> DISTEXT -> MATCH -> LEN + LIT -> LEN + Process trailer: + CHECK -> LENGTH -> DONE + */ + +/* state maintained between inflate() calls. Approximately 10K bytes. */ +struct inflate_state { + inflate_mode mode; /* current inflate mode */ + int last; /* true if processing last block */ + int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ + int havedict; /* true if dictionary provided */ + int flags; /* gzip header method and flags (0 if zlib) */ + unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */ + unsigned long check; /* protected copy of check value */ + unsigned long total; /* protected copy of output count */ + gz_headerp head; /* where to save gzip header information */ + /* sliding window */ + unsigned wbits; /* log base 2 of requested window size */ + unsigned wsize; /* window size or zero if not using window */ + unsigned whave; /* valid bytes in the window */ + unsigned wnext; /* window write index */ + unsigned char FAR *window; /* allocated sliding window, if needed */ + /* bit accumulator */ + unsigned long hold; /* input bit accumulator */ + unsigned bits; /* number of bits in "in" */ + /* for string and stored block copying */ + unsigned length; /* literal or length of data to copy */ + unsigned offset; /* distance back to copy string from */ + /* for table and code decoding */ + unsigned extra; /* extra bits needed */ + /* fixed and dynamic code tables */ + code const FAR *lencode; /* starting table for length/literal codes */ + code const FAR *distcode; /* starting table for distance codes */ + unsigned lenbits; /* index bits for lencode */ + unsigned distbits; /* index bits for distcode */ + /* dynamic table building */ + unsigned ncode; /* number of code length code lengths */ + unsigned nlen; /* number of length code lengths */ + unsigned ndist; /* number of distance code lengths */ + unsigned have; /* number of code lengths in lens[] */ + code FAR *next; /* next available space in codes[] */ + unsigned short lens[320]; /* temporary storage for code lengths */ + unsigned short work[288]; /* work area for code table building */ + code codes[ENOUGH]; /* space for code tables */ + int sane; /* if false, allow invalid distance too far */ + int back; /* bits back of last unprocessed length/lit */ + unsigned was; /* initial length of match */ +}; diff --git a/src/zlib/inftrees.c b/src/zlib/inftrees.c new file mode 100644 index 0000000..44d89cf --- /dev/null +++ b/src/zlib/inftrees.c @@ -0,0 +1,306 @@ +/* inftrees.c -- generate Huffman trees for efficient decoding + * Copyright (C) 1995-2013 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "inftrees.h" + +#define MAXBITS 15 + +const char inflate_copyright[] = + " inflate 1.2.8 Copyright 1995-2013 Mark Adler "; +/* + If you use the zlib library in a product, an acknowledgment is welcome + in the documentation of your product. If for some reason you cannot + include such an acknowledgment, I would appreciate that you keep this + copyright string in the executable of your product. + */ + +/* + Build a set of tables to decode the provided canonical Huffman code. + The code lengths are lens[0..codes-1]. The result starts at *table, + whose indices are 0..2^bits-1. work is a writable array of at least + lens shorts, which is used as a work area. type is the type of code + to be generated, CODES, LENS, or DISTS. On return, zero is success, + -1 is an invalid code, and +1 means that ENOUGH isn't enough. table + on return points to the next available entry's address. bits is the + requested root table index bits, and on return it is the actual root + table index bits. It will differ if the request is greater than the + longest code or if it is less than the shortest code. + */ +int ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work) +codetype type; +unsigned short FAR *lens; +unsigned codes; +code FAR * FAR *table; +unsigned FAR *bits; +unsigned short FAR *work; +{ + unsigned len; /* a code's length in bits */ + unsigned sym; /* index of code symbols */ + unsigned min, max; /* minimum and maximum code lengths */ + unsigned root; /* number of index bits for root table */ + unsigned curr; /* number of index bits for current table */ + unsigned drop; /* code bits to drop for sub-table */ + int left; /* number of prefix codes available */ + unsigned used; /* code entries in table used */ + unsigned huff; /* Huffman code */ + unsigned incr; /* for incrementing code, index */ + unsigned fill; /* index for replicating entries */ + unsigned low; /* low bits for current root entry */ + unsigned mask; /* mask for low root bits */ + code here; /* table entry for duplication */ + code FAR *next; /* next available space in table */ + const unsigned short FAR *base; /* base value table to use */ + const unsigned short FAR *extra; /* extra bits table to use */ + int end; /* use base and extra for symbol > end */ + unsigned short count[MAXBITS+1]; /* number of codes of each length */ + unsigned short offs[MAXBITS+1]; /* offsets in table for each length */ + static const unsigned short lbase[31] = { /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; + static const unsigned short lext[31] = { /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78}; + static const unsigned short dbase[32] = { /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0}; + static const unsigned short dext[32] = { /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64}; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) + count[len] = 0; + for (sym = 0; sym < codes; sym++) + count[lens[sym]]++; + + /* bound code lengths, force root to be within code lengths */ + root = *bits; + for (max = MAXBITS; max >= 1; max--) + if (count[max] != 0) break; + if (root > max) root = max; + if (max == 0) { /* no symbols to code at all */ + here.op = (unsigned char)64; /* invalid code marker */ + here.bits = (unsigned char)1; + here.val = (unsigned short)0; + *(*table)++ = here; /* make a table to force an error */ + *(*table)++ = here; + *bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) + if (count[min] != 0) break; + if (root < min) root = min; + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) return -1; /* over-subscribed */ + } + if (left > 0 && (type == CODES || max != 1)) + return -1; /* incomplete set */ + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) + offs[len + 1] = offs[len] + count[len]; + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) + if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym; + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + switch (type) { + case CODES: + base = extra = work; /* dummy value--not used */ + end = 19; + break; + case LENS: + base = lbase; + base -= 257; + extra = lext; + extra -= 257; + end = 256; + break; + default: /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize state for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = *table; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = (unsigned)(-1); /* trigger new sub-table when len > root */ + used = 1U << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type == LENS && used > ENOUGH_LENS) || + (type == DISTS && used > ENOUGH_DISTS)) + return 1; + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here.bits = (unsigned char)(len - drop); + if ((int)(work[sym]) < end) { + here.op = (unsigned char)0; + here.val = work[sym]; + } + else if ((int)(work[sym]) > end) { + here.op = (unsigned char)(extra[work[sym]]); + here.val = base[work[sym]]; + } + else { + here.op = (unsigned char)(32 + 64); /* end of block */ + here.val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1U << (len - drop); + fill = 1U << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + next[(huff >> drop) + fill] = here; + } while (fill != 0); + + /* backwards increment the len-bit code huff */ + incr = 1U << (len - 1); + while (huff & incr) + incr >>= 1; + if (incr != 0) { + huff &= incr - 1; + huff += incr; + } + else + huff = 0; + + /* go to next symbol, update count, len */ + sym++; + if (--(count[len]) == 0) { + if (len == max) break; + len = lens[work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) != low) { + /* if first time, transition to sub-tables */ + if (drop == 0) + drop = root; + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = (int)(1 << curr); + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) break; + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1U << curr; + if ((type == LENS && used > ENOUGH_LENS) || + (type == DISTS && used > ENOUGH_DISTS)) + return 1; + + /* point entry in root table to sub-table */ + low = huff & mask; + (*table)[low].op = (unsigned char)curr; + (*table)[low].bits = (unsigned char)root; + (*table)[low].val = (unsigned short)(next - *table); + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff != 0) { + here.op = (unsigned char)64; /* invalid code marker */ + here.bits = (unsigned char)(len - drop); + here.val = (unsigned short)0; + next[huff] = here; + } + + /* set return parameters */ + *table += used; + *bits = root; + return 0; +} diff --git a/src/zlib/inftrees.h b/src/zlib/inftrees.h new file mode 100644 index 0000000..baa53a0 --- /dev/null +++ b/src/zlib/inftrees.h @@ -0,0 +1,62 @@ +/* inftrees.h -- header to use inftrees.c + * Copyright (C) 1995-2005, 2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* Structure for decoding tables. Each entry provides either the + information needed to do the operation requested by the code that + indexed that table entry, or it provides a pointer to another + table that indexes more bits of the code. op indicates whether + the entry is a pointer to another table, a literal, a length or + distance, an end-of-block, or an invalid code. For a table + pointer, the low four bits of op is the number of index bits of + that table. For a length or distance, the low four bits of op + is the number of extra bits to get after the code. bits is + the number of bits in this code or part of the code to drop off + of the bit buffer. val is the actual byte to output in the case + of a literal, the base length or distance, or the offset from + the current table to the next table. Each entry is four bytes. */ +typedef struct { + unsigned char op; /* operation, extra bits, table bits */ + unsigned char bits; /* bits in this part of the code */ + unsigned short val; /* offset in table or code value */ +} code; + +/* op values as set by inflate_table(): + 00000000 - literal + 0000tttt - table link, tttt != 0 is the number of table index bits + 0001eeee - length or distance, eeee is the number of extra bits + 01100000 - end of block + 01000000 - invalid code + */ + +/* Maximum size of the dynamic table. The maximum number of code structures is + 1444, which is the sum of 852 for literal/length codes and 592 for distance + codes. These values were found by exhaustive searches using the program + examples/enough.c found in the zlib distribtution. The arguments to that + program are the number of symbols, the initial root table size, and the + maximum bit length of a code. "enough 286 9 15" for literal/length codes + returns returns 852, and "enough 30 6 15" for distance codes returns 592. + The initial root table size (9 or 6) is found in the fifth argument of the + inflate_table() calls in inflate.c and infback.c. If the root table size is + changed, then these maximum sizes would be need to be recalculated and + updated. */ +#define ENOUGH_LENS 852 +#define ENOUGH_DISTS 592 +#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS) + +/* Type of code to build for inflate_table() */ +typedef enum { + CODES, + LENS, + DISTS +} codetype; + +int ZLIB_INTERNAL inflate_table OF((codetype type, unsigned short FAR *lens, + unsigned codes, code FAR * FAR *table, + unsigned FAR *bits, unsigned short FAR *work)); diff --git a/src/zlib/trees.c b/src/zlib/trees.c new file mode 100644 index 0000000..1fd7759 --- /dev/null +++ b/src/zlib/trees.c @@ -0,0 +1,1226 @@ +/* trees.c -- output deflated data using Huffman coding + * Copyright (C) 1995-2012 Jean-loup Gailly + * detect_data_type() function provided freely by Cosmin Truta, 2006 + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * ALGORITHM + * + * The "deflation" process uses several Huffman trees. The more + * common source values are represented by shorter bit sequences. + * + * Each code tree is stored in a compressed form which is itself + * a Huffman encoding of the lengths of all the code strings (in + * ascending order by source values). The actual code strings are + * reconstructed from the lengths in the inflate process, as described + * in the deflate specification. + * + * REFERENCES + * + * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification". + * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc + * + * Storer, James A. + * Data Compression: Methods and Theory, pp. 49-50. + * Computer Science Press, 1988. ISBN 0-7167-8156-5. + * + * Sedgewick, R. + * Algorithms, p290. + * Addison-Wesley, 1983. ISBN 0-201-06672-6. + */ + +/* @(#) $Id$ */ + +/* #define GEN_TREES_H */ + +#include "deflate.h" + +#ifdef DEBUG +# include +#endif + +/* =========================================================================== + * Constants + */ + +#define MAX_BL_BITS 7 +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +#define END_BLOCK 256 +/* end of block literal code */ + +#define REP_3_6 16 +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +#define REPZ_3_10 17 +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +#define REPZ_11_138 18 +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */ + = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; + +local const int extra_dbits[D_CODES] /* extra bits for each distance code */ + = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; + +local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */ + = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; + +local const uch bl_order[BL_CODES] + = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +#define DIST_CODE_LEN 512 /* see definition of array dist_code below */ + +#if defined(GEN_TREES_H) || !defined(STDC) +/* non ANSI compilers may not accept trees.h */ + +local ct_data static_ltree[L_CODES+2]; +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +local ct_data static_dtree[D_CODES]; +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +uch _dist_code[DIST_CODE_LEN]; +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +uch _length_code[MAX_MATCH-MIN_MATCH+1]; +/* length code for each normalized match length (0 == MIN_MATCH) */ + +local int base_length[LENGTH_CODES]; +/* First normalized length for each code (0 = MIN_MATCH) */ + +local int base_dist[D_CODES]; +/* First normalized distance for each code (0 = distance of 1) */ + +#else +# include "trees.h" +#endif /* GEN_TREES_H */ + +struct static_tree_desc_s { + const ct_data *static_tree; /* static tree or NULL */ + const intf *extra_bits; /* extra bits for each code or NULL */ + int extra_base; /* base index for extra_bits */ + int elems; /* max number of elements in the tree */ + int max_length; /* max bit length for the codes */ +}; + +local static_tree_desc static_l_desc = +{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; + +local static_tree_desc static_d_desc = +{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; + +local static_tree_desc static_bl_desc = +{(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; + +/* =========================================================================== + * Local (static) routines in this file. + */ + +local void tr_static_init OF((void)); +local void init_block OF((deflate_state *s)); +local void pqdownheap OF((deflate_state *s, ct_data *tree, int k)); +local void gen_bitlen OF((deflate_state *s, tree_desc *desc)); +local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count)); +local void build_tree OF((deflate_state *s, tree_desc *desc)); +local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code)); +local void send_tree OF((deflate_state *s, ct_data *tree, int max_code)); +local int build_bl_tree OF((deflate_state *s)); +local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes, + int blcodes)); +local void compress_block OF((deflate_state *s, const ct_data *ltree, + const ct_data *dtree)); +local int detect_data_type OF((deflate_state *s)); +local unsigned bi_reverse OF((unsigned value, int length)); +local void bi_windup OF((deflate_state *s)); +local void bi_flush OF((deflate_state *s)); +local void copy_block OF((deflate_state *s, charf *buf, unsigned len, + int header)); + +#ifdef GEN_TREES_H +local void gen_trees_header OF((void)); +#endif + +#ifndef DEBUG +# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) + /* Send a code of the given tree. c and tree must not have side effects */ + +#else /* DEBUG */ +# define send_code(s, c, tree) \ + { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \ + send_bits(s, tree[c].Code, tree[c].Len); } +#endif + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +#define put_short(s, w) { \ + put_byte(s, (uch)((w) & 0xff)); \ + put_byte(s, (uch)((ush)(w) >> 8)); \ +} + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +#ifdef DEBUG +local void send_bits OF((deflate_state *s, int value, int length)); + +local void send_bits(s, value, length) + deflate_state *s; + int value; /* value to send */ + int length; /* number of bits */ +{ + Tracevv((stderr," l %2d v %4x ", length, value)); + Assert(length > 0 && length <= 15, "invalid length"); + s->bits_sent += (ulg)length; + + /* If not enough room in bi_buf, use (valid) bits from bi_buf and + * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid)) + * unused bits in value. + */ + if (s->bi_valid > (int)Buf_size - length) { + s->bi_buf |= (ush)value << s->bi_valid; + put_short(s, s->bi_buf); + s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); + s->bi_valid += length - Buf_size; + } else { + s->bi_buf |= (ush)value << s->bi_valid; + s->bi_valid += length; + } +} +#else /* !DEBUG */ + +#define send_bits(s, value, length) \ +{ int len = length;\ + if (s->bi_valid > (int)Buf_size - len) {\ + int val = value;\ + s->bi_buf |= (ush)val << s->bi_valid;\ + put_short(s, s->bi_buf);\ + s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\ + s->bi_valid += len - Buf_size;\ + } else {\ + s->bi_buf |= (ush)(value) << s->bi_valid;\ + s->bi_valid += len;\ + }\ +} +#endif /* DEBUG */ + + +/* the arguments must not have side effects */ + +/* =========================================================================== + * Initialize the various 'constant' tables. + */ +local void tr_static_init() +{ +#if defined(GEN_TREES_H) || !defined(STDC) + static int static_init_done = 0; + int n; /* iterates over tree elements */ + int bits; /* bit counter */ + int length; /* length value */ + int code; /* code value */ + int dist; /* distance index */ + ush bl_count[MAX_BITS+1]; + /* number of codes at each bit length for an optimal tree */ + + if (static_init_done) return; + + /* For some embedded targets, global variables are not initialized: */ +#ifdef NO_INIT_GLOBAL_POINTERS + static_l_desc.static_tree = static_ltree; + static_l_desc.extra_bits = extra_lbits; + static_d_desc.static_tree = static_dtree; + static_d_desc.extra_bits = extra_dbits; + static_bl_desc.extra_bits = extra_blbits; +#endif + + /* Initialize the mapping length (0..255) -> length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES-1; code++) { + base_length[code] = length; + for (n = 0; n < (1< dist code (0..29) */ + dist = 0; + for (code = 0 ; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1<>= 7; /* from now on, all distances are divided by 128 */ + for ( ; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { + _dist_code[256 + dist++] = (uch)code; + } + } + Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; + n = 0; + while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; + while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; + while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; + while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n].Len = 5; + static_dtree[n].Code = bi_reverse((unsigned)n, 5); + } + static_init_done = 1; + +# ifdef GEN_TREES_H + gen_trees_header(); +# endif +#endif /* defined(GEN_TREES_H) || !defined(STDC) */ +} + +/* =========================================================================== + * Genererate the file trees.h describing the static trees. + */ +#ifdef GEN_TREES_H +# ifndef DEBUG +# include +# endif + +# define SEPARATOR(i, last, width) \ + ((i) == (last)? "\n};\n\n" : \ + ((i) % (width) == (width)-1 ? ",\n" : ", ")) + +void gen_trees_header() +{ + FILE *header = fopen("trees.h", "w"); + int i; + + Assert (header != NULL, "Can't open trees.h"); + fprintf(header, + "/* header created automatically with -DGEN_TREES_H */\n\n"); + + fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n"); + for (i = 0; i < L_CODES+2; i++) { + fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code, + static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5)); + } + + fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code, + static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); + } + + fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n"); + for (i = 0; i < DIST_CODE_LEN; i++) { + fprintf(header, "%2u%s", _dist_code[i], + SEPARATOR(i, DIST_CODE_LEN-1, 20)); + } + + fprintf(header, + "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); + for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { + fprintf(header, "%2u%s", _length_code[i], + SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); + } + + fprintf(header, "local const int base_length[LENGTH_CODES] = {\n"); + for (i = 0; i < LENGTH_CODES; i++) { + fprintf(header, "%1u%s", base_length[i], + SEPARATOR(i, LENGTH_CODES-1, 20)); + } + + fprintf(header, "local const int base_dist[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "%5u%s", base_dist[i], + SEPARATOR(i, D_CODES-1, 10)); + } + + fclose(header); +} +#endif /* GEN_TREES_H */ + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +void ZLIB_INTERNAL _tr_init(s) + deflate_state *s; +{ + tr_static_init(); + + s->l_desc.dyn_tree = s->dyn_ltree; + s->l_desc.stat_desc = &static_l_desc; + + s->d_desc.dyn_tree = s->dyn_dtree; + s->d_desc.stat_desc = &static_d_desc; + + s->bl_desc.dyn_tree = s->bl_tree; + s->bl_desc.stat_desc = &static_bl_desc; + + s->bi_buf = 0; + s->bi_valid = 0; +#ifdef DEBUG + s->compressed_len = 0L; + s->bits_sent = 0L; +#endif + + /* Initialize the first block of the first file: */ + init_block(s); +} + +/* =========================================================================== + * Initialize a new block. + */ +local void init_block(s) + deflate_state *s; +{ + int n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; + for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; + for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; + + s->dyn_ltree[END_BLOCK].Freq = 1; + s->opt_len = s->static_len = 0L; + s->last_lit = s->matches = 0; +} + +#define SMALLEST 1 +/* Index within the heap array of least frequent node in the Huffman tree */ + + +/* =========================================================================== + * Remove the smallest element from the heap and recreate the heap with + * one less element. Updates heap and heap_len. + */ +#define pqremove(s, tree, top) \ +{\ + top = s->heap[SMALLEST]; \ + s->heap[SMALLEST] = s->heap[s->heap_len--]; \ + pqdownheap(s, tree, SMALLEST); \ +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +#define smaller(tree, n, m, depth) \ + (tree[n].Freq < tree[m].Freq || \ + (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +local void pqdownheap(s, tree, k) + deflate_state *s; + ct_data *tree; /* the tree to restore */ + int k; /* node to move down */ +{ + int v = s->heap[k]; + int j = k << 1; /* left son of k */ + while (j <= s->heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s->heap_len && + smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s->heap[j], s->depth)) break; + + /* Exchange v with the smallest son */ + s->heap[k] = s->heap[j]; k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s->heap[k] = v; +} + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +local void gen_bitlen(s, desc) + deflate_state *s; + tree_desc *desc; /* the tree descriptor */ +{ + ct_data *tree = desc->dyn_tree; + int max_code = desc->max_code; + const ct_data *stree = desc->stat_desc->static_tree; + const intf *extra = desc->stat_desc->extra_bits; + int base = desc->stat_desc->extra_base; + int max_length = desc->stat_desc->max_length; + int h; /* heap index */ + int n, m; /* iterate over the tree elements */ + int bits; /* bit length */ + int xbits; /* extra bits */ + ush f; /* frequency */ + int overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ + + for (h = s->heap_max+1; h < HEAP_SIZE; h++) { + n = s->heap[h]; + bits = tree[tree[n].Dad].Len + 1; + if (bits > max_length) bits = max_length, overflow++; + tree[n].Len = (ush)bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) continue; /* not a leaf node */ + + s->bl_count[bits]++; + xbits = 0; + if (n >= base) xbits = extra[n-base]; + f = tree[n].Freq; + s->opt_len += (ulg)f * (bits + xbits); + if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits); + } + if (overflow == 0) return; + + Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length-1; + while (s->bl_count[bits] == 0) bits--; + s->bl_count[bits]--; /* move one leaf down the tree */ + s->bl_count[bits+1] += 2; /* move one overflow item as its brother */ + s->bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits != 0; bits--) { + n = s->bl_count[bits]; + while (n != 0) { + m = s->heap[--h]; + if (m > max_code) continue; + if ((unsigned) tree[m].Len != (unsigned) bits) { + Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s->opt_len += ((long)bits - (long)tree[m].Len) + *(long)tree[m].Freq; + tree[m].Len = (ush)bits; + } + n--; + } + } +} + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +local void gen_codes (tree, max_code, bl_count) + ct_data *tree; /* the tree to decorate */ + int max_code; /* largest code with non zero frequency */ + ushf *bl_count; /* number of codes at each bit length */ +{ + ush next_code[MAX_BITS+1]; /* next code value for each bit length */ + ush code = 0; /* running code value */ + int bits; /* bit index */ + int n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (code + bl_count[bits-1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + Assert (code + bl_count[MAX_BITS]-1 == (1<dyn_tree; + const ct_data *stree = desc->stat_desc->static_tree; + int elems = desc->stat_desc->elems; + int n, m; /* iterate over heap elements */ + int max_code = -1; /* largest code with non zero frequency */ + int node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s->heap_len = 0, s->heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n].Freq != 0) { + s->heap[++(s->heap_len)] = max_code = n; + s->depth[n] = 0; + } else { + tree[n].Len = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s->heap_len < 2) { + node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); + tree[node].Freq = 1; + s->depth[node] = 0; + s->opt_len--; if (stree) s->static_len -= stree[node].Len; + /* node is 0 or 1 so it does not have extra bits */ + } + desc->max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + pqremove(s, tree, n); /* n = node of least frequency */ + m = s->heap[SMALLEST]; /* m = node of next least frequency */ + + s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ + s->heap[--(s->heap_max)] = m; + + /* Create a new node father of n and m */ + tree[node].Freq = tree[n].Freq + tree[m].Freq; + s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ? + s->depth[n] : s->depth[m]) + 1); + tree[n].Dad = tree[m].Dad = (ush)node; +#ifdef DUMP_BL_TREE + if (tree == s->bl_tree) { + fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)", + node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); + } +#endif + /* and insert the new node in the heap */ + s->heap[SMALLEST] = node++; + pqdownheap(s, tree, SMALLEST); + + } while (s->heap_len >= 2); + + s->heap[--(s->heap_max)] = s->heap[SMALLEST]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, (tree_desc *)desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes ((ct_data *)tree, max_code, s->bl_count); +} + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +local void scan_tree (s, tree, max_code) + deflate_state *s; + ct_data *tree; /* the tree to be scanned */ + int max_code; /* and its largest code of non zero frequency */ +{ + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + if (nextlen == 0) max_count = 138, min_count = 3; + tree[max_code+1].Len = (ush)0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + s->bl_tree[curlen].Freq += count; + } else if (curlen != 0) { + if (curlen != prevlen) s->bl_tree[curlen].Freq++; + s->bl_tree[REP_3_6].Freq++; + } else if (count <= 10) { + s->bl_tree[REPZ_3_10].Freq++; + } else { + s->bl_tree[REPZ_11_138].Freq++; + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +local void send_tree (s, tree, max_code) + deflate_state *s; + ct_data *tree; /* the tree to be scanned */ + int max_code; /* and its largest code of non zero frequency */ +{ + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen == 0) max_count = 138, min_count = 3; + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + do { send_code(s, curlen, s->bl_tree); } while (--count != 0); + + } else if (curlen != 0) { + if (curlen != prevlen) { + send_code(s, curlen, s->bl_tree); count--; + } + Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3); + + } else { + send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7); + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +local int build_bl_tree(s) + deflate_state *s; +{ + int max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); + scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, (tree_desc *)(&(s->bl_desc))); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { + if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; + } + /* Update opt_len to include the bit length tree and counts */ + s->opt_len += 3*(max_blindex+1) + 5+5+4; + Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + s->opt_len, s->static_len)); + + return max_blindex; +} + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +local void send_all_trees(s, lcodes, dcodes, blcodes) + deflate_state *s; + int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + int rank; /* index in bl_order */ + + Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + "too many codes"); + Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes-1, 5); + send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); + } + Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ + Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ + Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + +/* =========================================================================== + * Send a stored block + */ +void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last) + deflate_state *s; + charf *buf; /* input block */ + ulg stored_len; /* length of input block */ + int last; /* one if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK<<1)+last, 3); /* send block type */ +#ifdef DEBUG + s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; + s->compressed_len += (stored_len + 4) << 3; +#endif + copy_block(s, buf, (unsigned)stored_len, 1); /* with header */ +} + +/* =========================================================================== + * Flush the bits in the bit buffer to pending output (leaves at most 7 bits) + */ +void ZLIB_INTERNAL _tr_flush_bits(s) + deflate_state *s; +{ + bi_flush(s); +} + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +void ZLIB_INTERNAL _tr_align(s) + deflate_state *s; +{ + send_bits(s, STATIC_TREES<<1, 3); + send_code(s, END_BLOCK, static_ltree); +#ifdef DEBUG + s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ +#endif + bi_flush(s); +} + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) + deflate_state *s; + charf *buf; /* input block, or NULL if too old */ + ulg stored_len; /* length of input block */ + int last; /* one if this is the last block for a file */ +{ + ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + int max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s->level > 0) { + + /* Check if the file is binary or text */ + if (s->strm->data_type == Z_UNKNOWN) + s->strm->data_type = detect_data_type(s); + + /* Construct the literal and distance trees */ + build_tree(s, (tree_desc *)(&(s->l_desc))); + Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + s->static_len)); + + build_tree(s, (tree_desc *)(&(s->d_desc))); + Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s->opt_len+3+7)>>3; + static_lenb = (s->static_len+3+7)>>3; + + Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + s->last_lit)); + + if (static_lenb <= opt_lenb) opt_lenb = static_lenb; + + } else { + Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + +#ifdef FORCE_STORED + if (buf != (char*)0) { /* force stored block */ +#else + if (stored_len+4 <= opt_lenb && buf != (char*)0) { + /* 4: two words for the lengths */ +#endif + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + +#ifdef FORCE_STATIC + } else if (static_lenb >= 0) { /* force static trees */ +#else + } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) { +#endif + send_bits(s, (STATIC_TREES<<1)+last, 3); + compress_block(s, (const ct_data *)static_ltree, + (const ct_data *)static_dtree); +#ifdef DEBUG + s->compressed_len += 3 + s->static_len; +#endif + } else { + send_bits(s, (DYN_TREES<<1)+last, 3); + send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, + max_blindex+1); + compress_block(s, (const ct_data *)s->dyn_ltree, + (const ct_data *)s->dyn_dtree); +#ifdef DEBUG + s->compressed_len += 3 + s->opt_len; +#endif + } + Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); +#ifdef DEBUG + s->compressed_len += 7; /* align on byte boundary */ +#endif + } + Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +int ZLIB_INTERNAL _tr_tally (s, dist, lc) + deflate_state *s; + unsigned dist; /* distance of matched string */ + unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + s->d_buf[s->last_lit] = (ush)dist; + s->l_buf[s->last_lit++] = (uch)lc; + if (dist == 0) { + /* lc is the unmatched char */ + s->dyn_ltree[lc].Freq++; + } else { + s->matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + Assert((ush)dist < (ush)MAX_DIST(s) && + (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; + s->dyn_dtree[d_code(dist)].Freq++; + } + +#ifdef TRUNCATE_BLOCK + /* Try to guess if it is profitable to stop the current block here */ + if ((s->last_lit & 0x1fff) == 0 && s->level > 2) { + /* Compute an upper bound for the compressed length */ + ulg out_length = (ulg)s->last_lit*8L; + ulg in_length = (ulg)((long)s->strstart - s->block_start); + int dcode; + for (dcode = 0; dcode < D_CODES; dcode++) { + out_length += (ulg)s->dyn_dtree[dcode].Freq * + (5L+extra_dbits[dcode]); + } + out_length >>= 3; + Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", + s->last_lit, in_length, out_length, + 100L - out_length*100L/in_length)); + if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1; + } +#endif + return (s->last_lit == s->lit_bufsize-1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +local void compress_block(s, ltree, dtree) + deflate_state *s; + const ct_data *ltree; /* literal tree */ + const ct_data *dtree; /* distance tree */ +{ + unsigned dist; /* distance of matched string */ + int lc; /* match length or unmatched char (if dist == 0) */ + unsigned lx = 0; /* running index in l_buf */ + unsigned code; /* the code to send */ + int extra; /* number of extra bits to send */ + + if (s->last_lit != 0) do { + dist = s->d_buf[lx]; + lc = s->l_buf[lx++]; + if (dist == 0) { + send_code(s, lc, ltree); /* send a literal byte */ + Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code+LITERALS+1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra != 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra != 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + "pendingBuf overflow"); + + } while (lx < s->last_lit); + + send_code(s, END_BLOCK, ltree); +} + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +local int detect_data_type(s) + deflate_state *s; +{ + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + unsigned long black_mask = 0xf3ffc07fUL; + int n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>= 1) + if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0)) + return Z_BINARY; + + /* Check for textual ("white-listed") bytes. */ + if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0 + || s->dyn_ltree[13].Freq != 0) + return Z_TEXT; + for (n = 32; n < LITERALS; n++) + if (s->dyn_ltree[n].Freq != 0) + return Z_TEXT; + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +} + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +local unsigned bi_reverse(code, len) + unsigned code; /* the value to invert */ + int len; /* its bit length */ +{ + register unsigned res = 0; + do { + res |= code & 1; + code >>= 1, res <<= 1; + } while (--len > 0); + return res >> 1; +} + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +local void bi_flush(s) + deflate_state *s; +{ + if (s->bi_valid == 16) { + put_short(s, s->bi_buf); + s->bi_buf = 0; + s->bi_valid = 0; + } else if (s->bi_valid >= 8) { + put_byte(s, (Byte)s->bi_buf); + s->bi_buf >>= 8; + s->bi_valid -= 8; + } +} + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +local void bi_windup(s) + deflate_state *s; +{ + if (s->bi_valid > 8) { + put_short(s, s->bi_buf); + } else if (s->bi_valid > 0) { + put_byte(s, (Byte)s->bi_buf); + } + s->bi_buf = 0; + s->bi_valid = 0; +#ifdef DEBUG + s->bits_sent = (s->bits_sent+7) & ~7; +#endif +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +local void copy_block(s, buf, len, header) + deflate_state *s; + charf *buf; /* the input data */ + unsigned len; /* its length */ + int header; /* true if block header must be written */ +{ + bi_windup(s); /* align on byte boundary */ + + if (header) { + put_short(s, (ush)len); + put_short(s, (ush)~len); +#ifdef DEBUG + s->bits_sent += 2*16; +#endif + } +#ifdef DEBUG + s->bits_sent += (ulg)len<<3; +#endif + while (len--) { + put_byte(s, *buf++); + } +} diff --git a/src/zlib/trees.h b/src/zlib/trees.h new file mode 100644 index 0000000..d35639d --- /dev/null +++ b/src/zlib/trees.h @@ -0,0 +1,128 @@ +/* header created automatically with -DGEN_TREES_H */ + +local const ct_data static_ltree[L_CODES+2] = { +{{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}}, +{{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}}, +{{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}}, +{{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}}, +{{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}}, +{{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}}, +{{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}}, +{{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}}, +{{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}}, +{{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}}, +{{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}}, +{{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}}, +{{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}}, +{{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}}, +{{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}}, +{{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}}, +{{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}}, +{{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}}, +{{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}}, +{{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}}, +{{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}}, +{{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}}, +{{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}}, +{{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}}, +{{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}}, +{{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}}, +{{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}}, +{{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}}, +{{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}}, +{{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}}, +{{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}}, +{{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}}, +{{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}}, +{{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}}, +{{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}}, +{{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}}, +{{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}}, +{{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}}, +{{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}}, +{{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}}, +{{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}}, +{{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}}, +{{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}}, +{{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}}, +{{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}}, +{{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}}, +{{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}}, +{{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}}, +{{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}}, +{{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}}, +{{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}}, +{{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}}, +{{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}}, +{{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}}, +{{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}}, +{{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}}, +{{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}}, +{{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}} +}; + +local const ct_data static_dtree[D_CODES] = { +{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}}, +{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}}, +{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}}, +{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}}, +{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}}, +{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}} +}; + +const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = { + 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, + 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, +10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, +11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, +12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, +13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, +13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, +18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, +23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 +}; + +const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, +13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, +17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, +19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, +21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, +22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, +23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, +25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 +}; + +local const int base_length[LENGTH_CODES] = { +0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, +64, 80, 96, 112, 128, 160, 192, 224, 0 +}; + +local const int base_dist[D_CODES] = { + 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, + 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, + 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 +}; + diff --git a/src/zlib/uncompr.c b/src/zlib/uncompr.c new file mode 100644 index 0000000..5f09f0d --- /dev/null +++ b/src/zlib/uncompr.c @@ -0,0 +1,59 @@ +/* uncompr.c -- decompress a memory buffer + * Copyright (C) 1995-2003, 2010 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#define ZLIB_INTERNAL +#include "zlib/zlib.h" + +/* =========================================================================== + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total + size of the destination buffer, which must be large enough to hold the + entire uncompressed data. (The size of the uncompressed data must have + been saved previously by the compressor and transmitted to the decompressor + by some mechanism outside the scope of this compression library.) + Upon exit, destLen is the actual size of the compressed buffer. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer, or Z_DATA_ERROR if the input data was corrupted. +*/ +int ZEXPORT uncompress (dest, destLen, source, sourceLen) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; +{ + z_stream stream; + int err; + + stream.next_in = (z_const Bytef *)source; + stream.avail_in = (uInt)sourceLen; + /* Check for source > 64K on 16-bit machine: */ + if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; + + stream.next_out = dest; + stream.avail_out = (uInt)*destLen; + if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; + + stream.zalloc = (alloc_func)0; + stream.zfree = (free_func)0; + + err = inflateInit(&stream); + if (err != Z_OK) return err; + + err = inflate(&stream, Z_FINISH); + if (err != Z_STREAM_END) { + inflateEnd(&stream); + if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0)) + return Z_DATA_ERROR; + return err; + } + *destLen = stream.total_out; + + err = inflateEnd(&stream); + return err; +} diff --git a/src/zlib/zutil.c b/src/zlib/zutil.c new file mode 100644 index 0000000..23d2ebe --- /dev/null +++ b/src/zlib/zutil.c @@ -0,0 +1,324 @@ +/* zutil.c -- target dependent utility functions for the compression library + * Copyright (C) 1995-2005, 2010, 2011, 2012 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#include "zutil.h" +#ifndef Z_SOLO +# include "gzguts.h" +#endif + +#ifndef NO_DUMMY_DECL +struct internal_state {int dummy;}; /* for buggy compilers */ +#endif + +z_const char * const z_errmsg[10] = { +"need dictionary", /* Z_NEED_DICT 2 */ +"stream end", /* Z_STREAM_END 1 */ +"", /* Z_OK 0 */ +"file error", /* Z_ERRNO (-1) */ +"stream error", /* Z_STREAM_ERROR (-2) */ +"data error", /* Z_DATA_ERROR (-3) */ +"insufficient memory", /* Z_MEM_ERROR (-4) */ +"buffer error", /* Z_BUF_ERROR (-5) */ +"incompatible version",/* Z_VERSION_ERROR (-6) */ +""}; + + +const char * ZEXPORT zlibVersion() +{ + return ZLIB_VERSION; +} + +uLong ZEXPORT zlibCompileFlags() +{ + uLong flags; + + flags = 0; + switch ((int)(sizeof(uInt))) { + case 2: break; + case 4: flags += 1; break; + case 8: flags += 2; break; + default: flags += 3; + } + switch ((int)(sizeof(uLong))) { + case 2: break; + case 4: flags += 1 << 2; break; + case 8: flags += 2 << 2; break; + default: flags += 3 << 2; + } + switch ((int)(sizeof(voidpf))) { + case 2: break; + case 4: flags += 1 << 4; break; + case 8: flags += 2 << 4; break; + default: flags += 3 << 4; + } + switch ((int)(sizeof(z_off_t))) { + case 2: break; + case 4: flags += 1 << 6; break; + case 8: flags += 2 << 6; break; + default: flags += 3 << 6; + } +#ifdef DEBUG + flags += 1 << 8; +#endif +#if defined(ASMV) || defined(ASMINF) + flags += 1 << 9; +#endif +#ifdef ZLIB_WINAPI + flags += 1 << 10; +#endif +#ifdef BUILDFIXED + flags += 1 << 12; +#endif +#ifdef DYNAMIC_CRC_TABLE + flags += 1 << 13; +#endif +#ifdef NO_GZCOMPRESS + flags += 1L << 16; +#endif +#ifdef NO_GZIP + flags += 1L << 17; +#endif +#ifdef PKZIP_BUG_WORKAROUND + flags += 1L << 20; +#endif +#ifdef FASTEST + flags += 1L << 21; +#endif +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifdef NO_vsnprintf + flags += 1L << 25; +# ifdef HAS_vsprintf_void + flags += 1L << 26; +# endif +# else +# ifdef HAS_vsnprintf_void + flags += 1L << 26; +# endif +# endif +#else + flags += 1L << 24; +# ifdef NO_snprintf + flags += 1L << 25; +# ifdef HAS_sprintf_void + flags += 1L << 26; +# endif +# else +# ifdef HAS_snprintf_void + flags += 1L << 26; +# endif +# endif +#endif + return flags; +} + +#ifdef DEBUG + +# ifndef verbose +# define verbose 0 +# endif +int ZLIB_INTERNAL z_verbose = verbose; + +void ZLIB_INTERNAL z_error (m) + char *m; +{ + fprintf(stderr, "%s\n", m); + exit(1); +} +#endif + +/* exported to allow conversion of error code to string for compress() and + * uncompress() + */ +const char * ZEXPORT zError(err) + int err; +{ + return ERR_MSG(err); +} + +#if defined(_WIN32_WCE) + /* The Microsoft C Run-Time Library for Windows CE doesn't have + * errno. We define it as a global variable to simplify porting. + * Its value is always 0 and should not be used. + */ + int errno = 0; +#endif + +#ifndef HAVE_MEMCPY + +void ZLIB_INTERNAL zmemcpy(dest, source, len) + Bytef* dest; + const Bytef* source; + uInt len; +{ + if (len == 0) return; + do { + *dest++ = *source++; /* ??? to be unrolled */ + } while (--len != 0); +} + +int ZLIB_INTERNAL zmemcmp(s1, s2, len) + const Bytef* s1; + const Bytef* s2; + uInt len; +{ + uInt j; + + for (j = 0; j < len; j++) { + if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1; + } + return 0; +} + +void ZLIB_INTERNAL zmemzero(dest, len) + Bytef* dest; + uInt len; +{ + if (len == 0) return; + do { + *dest++ = 0; /* ??? to be unrolled */ + } while (--len != 0); +} +#endif + +#ifndef Z_SOLO + +#ifdef SYS16BIT + +#ifdef __TURBOC__ +/* Turbo C in 16-bit mode */ + +# define MY_ZCALLOC + +/* Turbo C malloc() does not allow dynamic allocation of 64K bytes + * and farmalloc(64K) returns a pointer with an offset of 8, so we + * must fix the pointer. Warning: the pointer must be put back to its + * original form in order to free it, use zcfree(). + */ + +#define MAX_PTR 10 +/* 10*64K = 640K */ + +local int next_ptr = 0; + +typedef struct ptr_table_s { + voidpf org_ptr; + voidpf new_ptr; +} ptr_table; + +local ptr_table table[MAX_PTR]; +/* This table is used to remember the original form of pointers + * to large buffers (64K). Such pointers are normalized with a zero offset. + * Since MSDOS is not a preemptive multitasking OS, this table is not + * protected from concurrent access. This hack doesn't work anyway on + * a protected system like OS/2. Use Microsoft C instead. + */ + +voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size) +{ + voidpf buf = opaque; /* just to make some compilers happy */ + ulg bsize = (ulg)items*size; + + /* If we allocate less than 65520 bytes, we assume that farmalloc + * will return a usable pointer which doesn't have to be normalized. + */ + if (bsize < 65520L) { + buf = farmalloc(bsize); + if (*(ush*)&buf != 0) return buf; + } else { + buf = farmalloc(bsize + 16L); + } + if (buf == NULL || next_ptr >= MAX_PTR) return NULL; + table[next_ptr].org_ptr = buf; + + /* Normalize the pointer to seg:0 */ + *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4; + *(ush*)&buf = 0; + table[next_ptr++].new_ptr = buf; + return buf; +} + +void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) +{ + int n; + if (*(ush*)&ptr != 0) { /* object < 64K */ + farfree(ptr); + return; + } + /* Find the original pointer */ + for (n = 0; n < next_ptr; n++) { + if (ptr != table[n].new_ptr) continue; + + farfree(table[n].org_ptr); + while (++n < next_ptr) { + table[n-1] = table[n]; + } + next_ptr--; + return; + } + ptr = opaque; /* just to make some compilers happy */ + Assert(0, "zcfree: ptr not found"); +} + +#endif /* __TURBOC__ */ + + +#ifdef M_I86 +/* Microsoft C in 16-bit mode */ + +# define MY_ZCALLOC + +#if (!defined(_MSC_VER) || (_MSC_VER <= 600)) +# define _halloc halloc +# define _hfree hfree +#endif + +voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, uInt items, uInt size) +{ + if (opaque) opaque = 0; /* to make compiler happy */ + return _halloc((long)items, size); +} + +void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) +{ + if (opaque) opaque = 0; /* to make compiler happy */ + _hfree(ptr); +} + +#endif /* M_I86 */ + +#endif /* SYS16BIT */ + + +#ifndef MY_ZCALLOC /* Any system without a special alloc function */ + +#ifndef STDC +extern voidp malloc OF((uInt size)); +extern voidp calloc OF((uInt items, uInt size)); +extern void free OF((voidpf ptr)); +#endif + +voidpf ZLIB_INTERNAL zcalloc (opaque, items, size) + voidpf opaque; + unsigned items; + unsigned size; +{ + if (opaque) items += size - size; /* make compiler happy */ + return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) : + (voidpf)calloc(items, size); +} + +void ZLIB_INTERNAL zcfree (opaque, ptr) + voidpf opaque; + voidpf ptr; +{ + free(ptr); + if (opaque) return; /* make compiler happy */ +} + +#endif /* MY_ZCALLOC */ + +#endif /* !Z_SOLO */ diff --git a/src/zlib/zutil.h b/src/zlib/zutil.h new file mode 100644 index 0000000..bc90ec3 --- /dev/null +++ b/src/zlib/zutil.h @@ -0,0 +1,253 @@ +/* zutil.h -- internal interface and configuration of the compression library + * Copyright (C) 1995-2013 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* @(#) $Id$ */ + +#ifndef ZUTIL_H +#define ZUTIL_H + +#ifdef HAVE_HIDDEN +# define ZLIB_INTERNAL __attribute__((visibility ("hidden"))) +#else +# define ZLIB_INTERNAL +#endif + +#include "zlib/zlib.h" + +#if defined(STDC) && !defined(Z_SOLO) +# if !(defined(_WIN32_WCE) && defined(_MSC_VER)) +# include +# endif +# include +# include +#endif + +#ifdef Z_SOLO + typedef long ptrdiff_t; /* guess -- will be caught if guess is wrong */ +#endif + +#ifndef local +# define local static +#endif +/* compile with -Dlocal if your debugger can't find static symbols */ + +typedef unsigned char uch; +typedef uch FAR uchf; +typedef unsigned short ush; +typedef ush FAR ushf; +typedef unsigned long ulg; + +extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ +/* (size given to avoid silly warnings with Visual C++) */ + +#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] + +#define ERR_RETURN(strm,err) \ + return (strm->msg = ERR_MSG(err), (err)) +/* To be used only when the state is known to be valid */ + + /* common constants */ + +#ifndef DEF_WBITS +# define DEF_WBITS MAX_WBITS +#endif +/* default windowBits for decompression. MAX_WBITS is for compression only */ + +#if MAX_MEM_LEVEL >= 8 +# define DEF_MEM_LEVEL 8 +#else +# define DEF_MEM_LEVEL MAX_MEM_LEVEL +#endif +/* default memLevel */ + +#define STORED_BLOCK 0 +#define STATIC_TREES 1 +#define DYN_TREES 2 +/* The three kinds of block type */ + +#define MIN_MATCH 3 +#define MAX_MATCH 258 +/* The minimum and maximum match lengths */ + +#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ + + /* target dependencies */ + +#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32)) +# define OS_CODE 0x00 +# ifndef Z_SOLO +# if defined(__TURBOC__) || defined(__BORLANDC__) +# if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) + /* Allow compilation with ANSI keywords only enabled */ + void _Cdecl farfree( void *block ); + void *_Cdecl farmalloc( unsigned long nbytes ); +# else +# include +# endif +# else /* MSC or DJGPP */ +# include +# endif +# endif +#endif + +#ifdef AMIGA +# define OS_CODE 0x01 +#endif + +#if defined(VAXC) || defined(VMS) +# define OS_CODE 0x02 +# define F_OPEN(name, mode) \ + fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512") +#endif + +#if defined(ATARI) || defined(atarist) +# define OS_CODE 0x05 +#endif + +#ifdef OS2 +# define OS_CODE 0x06 +# if defined(M_I86) && !defined(Z_SOLO) +# include +# endif +#endif + +#if defined(MACOS) || defined(TARGET_OS_MAC) +# define OS_CODE 0x07 +# ifndef Z_SOLO +# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os +# include /* for fdopen */ +# else +# ifndef fdopen +# define fdopen(fd,mode) NULL /* No fdopen() */ +# endif +# endif +# endif +#endif + +#ifdef TOPS20 +# define OS_CODE 0x0a +#endif + +#ifdef WIN32 +# ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */ +# define OS_CODE 0x0b +# endif +#endif + +#ifdef __50SERIES /* Prime/PRIMOS */ +# define OS_CODE 0x0f +#endif + +#if defined(_BEOS_) || defined(RISCOS) +# define fdopen(fd,mode) NULL /* No fdopen() */ +#endif + +#if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX +# if defined(_WIN32_WCE) +# define fdopen(fd,mode) NULL /* No fdopen() */ +# ifndef _PTRDIFF_T_DEFINED + typedef int ptrdiff_t; +# define _PTRDIFF_T_DEFINED +# endif +# else +# define fdopen(fd,type) _fdopen(fd,type) +# endif +#endif + +#if defined(__BORLANDC__) && !defined(MSDOS) + #pragma warn -8004 + #pragma warn -8008 + #pragma warn -8066 +#endif + +/* provide prototypes for these when building zlib without LFS */ +#if !defined(_WIN32) && \ + (!defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0) + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); +#endif + + /* common defaults */ + +#ifndef OS_CODE +# define OS_CODE 0x03 /* assume Unix */ +#endif + +#ifndef F_OPEN +# define F_OPEN(name, mode) fopen((name), (mode)) +#endif + + /* functions */ + +#if defined(pyr) || defined(Z_SOLO) +# define NO_MEMCPY +#endif +#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__) + /* Use our own functions for small and medium model with MSC <= 5.0. + * You may have to use the same strategy for Borland C (untested). + * The __SC__ check is for Symantec. + */ +# define NO_MEMCPY +#endif +#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY) +# define HAVE_MEMCPY +#endif +#ifdef HAVE_MEMCPY +# ifdef SMALL_MEDIUM /* MSDOS small or medium model */ +# define zmemcpy _fmemcpy +# define zmemcmp _fmemcmp +# define zmemzero(dest, len) _fmemset(dest, 0, len) +# else +# define zmemcpy memcpy +# define zmemcmp memcmp +# define zmemzero(dest, len) memset(dest, 0, len) +# endif +#else + void ZLIB_INTERNAL zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); + int ZLIB_INTERNAL zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); + void ZLIB_INTERNAL zmemzero OF((Bytef* dest, uInt len)); +#endif + +/* Diagnostic functions */ +#ifdef DEBUG +# include + extern int ZLIB_INTERNAL z_verbose; + extern void ZLIB_INTERNAL z_error OF((char *m)); +# define Assert(cond,msg) {if(!(cond)) z_error(msg);} +# define Trace(x) {if (z_verbose>=0) fprintf x ;} +# define Tracev(x) {if (z_verbose>0) fprintf x ;} +# define Tracevv(x) {if (z_verbose>1) fprintf x ;} +# define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;} +# define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;} +#else +# define Assert(cond,msg) +# define Trace(x) +# define Tracev(x) +# define Tracevv(x) +# define Tracec(c,x) +# define Tracecv(c,x) +#endif + +#ifndef Z_SOLO + voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items, + unsigned size)); + void ZLIB_INTERNAL zcfree OF((voidpf opaque, voidpf ptr)); +#endif + +#define ZALLOC(strm, items, size) \ + (*((strm)->zalloc))((strm)->opaque, (items), (size)) +#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) +#define TRY_FREE(s, p) {if (p) ZFREE(s, p);} + +/* Reverse the bytes in a 32-bit value */ +#define ZSWAP32(q) ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ + (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) + +#endif /* ZUTIL_H */ diff --git a/src/znzlib/znzlib.c b/src/znzlib/znzlib.c new file mode 100644 index 0000000..bbda969 --- /dev/null +++ b/src/znzlib/znzlib.c @@ -0,0 +1,323 @@ +/** \file znzlib.c + \brief Low level i/o interface to compressed and noncompressed files. + Written by Mark Jenkinson, FMRIB + +This library provides an interface to both compressed (gzip/zlib) and +uncompressed (normal) file IO. The functions are written to have the +same interface as the standard file IO functions. + +To use this library instead of normal file IO, the following changes +are required: + - replace all instances of FILE* with znzFile + - change the name of all function calls, replacing the initial character + f with the znz (e.g. fseek becomes znzseek) + one exception is rewind() -> znzrewind() + - add a third parameter to all calls to znzopen (previously fopen) + that specifies whether to use compression (1) or not (0) + - use znz_isnull rather than any (pointer == NULL) comparisons in the code + for znzfile types (normally done after a return from znzopen) + +NB: seeks for writable files with compression are quite restricted + + */ + +#include "znzlib/znzlib.h" +#include "lib/print.h" + +/* +znzlib.c (zipped or non-zipped library) + +***** This code is released to the public domain. ***** + +***** Author: Mark Jenkinson, FMRIB Centre, University of Oxford ***** +***** Date: September 2004 ***** + +***** Neither the FMRIB Centre, the University of Oxford, nor any of ***** +***** its employees imply any warranty of usefulness of this software ***** +***** for any purpose, and do not assume any liability for damages, ***** +***** incidental or otherwise, caused by any use of this document. ***** + +*/ + + +/* Note extra argument (use_compression) where + use_compression==0 is no compression + use_compression!=0 uses zlib (gzip) compression +*/ + +znzFile znzopen(const char *path, const char *mode, int use_compression) +{ + znzFile file; + file = (znzFile) calloc(1,sizeof(struct znzptr)); + if( file == NULL ){ + Rc_fprintf_stderr("** ERROR: znzopen failed to alloc znzptr\n"); + return NULL; + } + + file->nzfptr = NULL; + +#ifdef HAVE_ZLIB + file->zfptr = NULL; + + if (use_compression) { + file->withz = 1; + if((file->zfptr = gzopen(path,mode)) == NULL) { + free(file); + file = NULL; + } + } else { +#endif + + file->withz = 0; + if((file->nzfptr = fopen(path,mode)) == NULL) { + free(file); + file = NULL; + } + +#ifdef HAVE_ZLIB + } +#endif + + return file; +} + + +znzFile znzdopen(int fd, const char *mode, int use_compression) +{ + znzFile file; + file = (znzFile) calloc(1,sizeof(struct znzptr)); + if( file == NULL ){ + Rc_fprintf_stderr("** ERROR: znzdopen failed to alloc znzptr\n"); + return NULL; + } +#ifdef HAVE_ZLIB + if (use_compression) { + file->withz = 1; + file->zfptr = gzdopen(fd,mode); + file->nzfptr = NULL; + } else { +#endif + file->withz = 0; +#ifdef HAVE_FDOPEN + file->nzfptr = fdopen(fd,mode); +#endif +#ifdef HAVE_ZLIB + file->zfptr = NULL; + }; +#endif + return file; +} + + +int Xznzclose(znzFile * file) +{ + int retval = 0; + if (*file!=NULL) { +#ifdef HAVE_ZLIB + if ((*file)->zfptr!=NULL) { retval = gzclose((*file)->zfptr); } +#endif + if ((*file)->nzfptr!=NULL) { retval = fclose((*file)->nzfptr); } + + free(*file); + *file = NULL; + } + return retval; +} + + +/* we already assume ints are 4 bytes */ +#undef ZNZ_MAX_BLOCK_SIZE +#define ZNZ_MAX_BLOCK_SIZE (1<<30) + +size_t znzread(void* buf, size_t size, size_t nmemb, znzFile file) +{ + size_t remain = size*nmemb; + char * cbuf = (char *)buf; + unsigned n2read; + int nread; + + if (file==NULL) { return 0; } +#ifdef HAVE_ZLIB + if (file->zfptr!=NULL) { + /* gzread/write take unsigned int length, so maybe read in int pieces + (noted by M Hanke, example given by M Adler) 6 July 2010 [rickr] */ + while( remain > 0 ) { + n2read = (remain < ZNZ_MAX_BLOCK_SIZE) ? remain : ZNZ_MAX_BLOCK_SIZE; + nread = gzread(file->zfptr, (void *)cbuf, n2read); + if( nread < 0 ) return nread; /* returns -1 on error */ + + remain -= nread; + cbuf += nread; + + /* require reading n2read bytes, so we don't get stuck */ + if( nread < (int)n2read ) break; /* return will be short */ + } + + /* warn of a short read that will seem complete */ + if( remain > 0 && remain < size ) + Rc_fprintf_stderr("** znzread: read short by %u bytes\n",(unsigned)remain); + + return nmemb - remain/size; /* return number of members processed */ + } +#endif + return fread(buf,size,nmemb,file->nzfptr); +} + +size_t znzwrite(const void* buf, size_t size, size_t nmemb, znzFile file) +{ + size_t remain = size*nmemb; + const char * cbuf = (const char *)buf; + unsigned n2write; + int nwritten; + + if (file==NULL) { return 0; } +#ifdef HAVE_ZLIB + if (file->zfptr!=NULL) { + while( remain > 0 ) { + n2write = (remain < ZNZ_MAX_BLOCK_SIZE) ? remain : ZNZ_MAX_BLOCK_SIZE; + nwritten = gzwrite(file->zfptr, (const void *)cbuf, n2write); + + /* gzread returns 0 on error, but in case that ever changes... */ + if( nwritten < 0 ) return nwritten; + + remain -= nwritten; + cbuf += nwritten; + + /* require writing n2write bytes, so we don't get stuck */ + if( nwritten < (int)n2write ) break; + } + + /* warn of a short write that will seem complete */ + if( remain > 0 && remain < size ) + Rc_fprintf_stderr("** znzwrite: write short by %u bytes\n",(unsigned)remain); + + return nmemb - remain/size; /* return number of members processed */ + } +#endif + return fwrite(buf,size,nmemb,file->nzfptr); +} + +long znzseek(znzFile file, long offset, int whence) +{ + if (file==NULL) { return 0; } +#ifdef HAVE_ZLIB + if (file->zfptr!=NULL) return (long) gzseek(file->zfptr,offset,whence); +#endif + return fseek(file->nzfptr,offset,whence); +} + +int znzrewind(znzFile stream) +{ + if (stream==NULL) { return 0; } +#ifdef HAVE_ZLIB + /* On some systems, gzrewind() fails for uncompressed files. + Use gzseek(), instead. 10, May 2005 [rickr] + + if (stream->zfptr!=NULL) return gzrewind(stream->zfptr); + */ + + if (stream->zfptr!=NULL) return (int)gzseek(stream->zfptr, 0L, SEEK_SET); +#endif + rewind(stream->nzfptr); + return 0; +} + +long znztell(znzFile file) +{ + if (file==NULL) { return 0; } +#ifdef HAVE_ZLIB + if (file->zfptr!=NULL) return (long) gztell(file->zfptr); +#endif + return ftell(file->nzfptr); +} + +int znzputs(const char * str, znzFile file) +{ + if (file==NULL) { return 0; } +#ifdef HAVE_ZLIB + if (file->zfptr!=NULL) return gzputs(file->zfptr,str); +#endif + return fputs(str,file->nzfptr); +} + + +char * znzgets(char* str, int size, znzFile file) +{ + if (file==NULL) { return NULL; } +#ifdef HAVE_ZLIB + if (file->zfptr!=NULL) return gzgets(file->zfptr,str,size); +#endif + return fgets(str,size,file->nzfptr); +} + + +int znzflush(znzFile file) +{ + if (file==NULL) { return 0; } +#ifdef HAVE_ZLIB + if (file->zfptr!=NULL) return gzflush(file->zfptr,Z_SYNC_FLUSH); +#endif + return fflush(file->nzfptr); +} + + +int znzeof(znzFile file) +{ + if (file==NULL) { return 0; } +#ifdef HAVE_ZLIB + if (file->zfptr!=NULL) return gzeof(file->zfptr); +#endif + return feof(file->nzfptr); +} + + +int znzputc(int c, znzFile file) +{ + if (file==NULL) { return 0; } +#ifdef HAVE_ZLIB + if (file->zfptr!=NULL) return gzputc(file->zfptr,c); +#endif + return fputc(c,file->nzfptr); +} + + +int znzgetc(znzFile file) +{ + if (file==NULL) { return 0; } +#ifdef HAVE_ZLIB + if (file->zfptr!=NULL) return gzgetc(file->zfptr); +#endif + return fgetc(file->nzfptr); +} + +#if !defined (WIN32) +int znzprintf(znzFile stream, const char *format, ...) +{ + int retval=0; + char *tmpstr; + va_list va; + if (stream==NULL) { return 0; } + va_start(va, format); +#ifdef HAVE_ZLIB + if (stream->zfptr!=NULL) { + int size; /* local to HAVE_ZLIB block */ + size = strlen(format) + 1000000; /* overkill I hope */ + tmpstr = (char *)calloc(1, size); + if( tmpstr == NULL ){ + Rc_fprintf_stderr("** ERROR: znzprintf failed to alloc %d bytes\n", size); + return retval; + } + vsprintf(tmpstr,format,va); + retval=gzprintf(stream->zfptr,"%s",tmpstr); + free(tmpstr); + } else +#endif + { + retval=vfprintf(stream->nzfptr,format,va); + } + va_end(va); + return retval; +} + +#endif + diff --git a/tests/testthat.R b/tests/testthat.R new file mode 100644 index 0000000..f61e42c --- /dev/null +++ b/tests/testthat.R @@ -0,0 +1,4 @@ +library(testthat) +library(RNifti) + +test_check("RNifti") diff --git a/tests/testthat/test-05-nifti.R b/tests/testthat/test-05-nifti.R new file mode 100644 index 0000000..0e8f472 --- /dev/null +++ b/tests/testthat/test-05-nifti.R @@ -0,0 +1,30 @@ +context("Reading and writing NIfTI files") + +test_that("NIfTI files can be read and written", { + imagePath <- system.file("extdata", "example.nii.gz", package="RNifti") + tempPath <- tempfile() + + expect_that(dim(readNifti(imagePath,internal=FALSE)), equals(c(96L,96L,60L))) + expect_that(dim(readNifti(imagePath,internal=TRUE)), equals(c(96L,96L,60L))) + expect_that(print(readNifti(imagePath,internal=TRUE)), prints_text("2.5 mm per voxel",fixed=TRUE)) + + image <- readNifti(imagePath) + expect_that(pixunits(image), equals(c("mm","s"))) + + writeNifti(image, tempPath) + expect_that(pixdim(readNifti(tempPath)), equals(c(2.5,2.5,2.5))) + unlink(tempPath) + + writeNifti(image, tempPath, datatype="short") + expect_that(dumpNifti(tempPath)$bitpix, equals(16L)) + unlink(tempPath) + + expect_that(dumpNifti(image)$dim, equals(c(3L,96L,96L,60L,1L,1L,1L,1L))) + pixdim(image) <- c(5,5,5) + expect_that(dumpNifti(image)$pixdim, equals(c(-1,5,5,5,0,0,0,0))) + pixunits(image) <- c("m","ms") + expect_that(dumpNifti(image)$xyzt_units, equals(17L)) + + image <- updateNifti(image, list(intent_code=1000L)) + expect_that(dumpNifti(image)$intent_code, equals(1000L)) +}) diff --git a/tests/testthat/test-10-xform.R b/tests/testthat/test-10-xform.R new file mode 100644 index 0000000..67ed5b1 --- /dev/null +++ b/tests/testthat/test-10-xform.R @@ -0,0 +1,21 @@ +context("NIfTI sform/qform operations") + +test_that("NIfTI sform/qform operations work", { + image <- readNifti(system.file("extdata", "example.nii.gz", package="RNifti")) + + expect_that(diag(xform(image)), equals(c(-2.5,2.5,2.5,1))) + expect_that(diag(xform(image,useQuaternionFirst=FALSE)), equals(c(-2.5,2.5,2.5,1))) + + point <- c(40, 40, 20) + expect_that(round(voxelToWorld(point,image)), equals(c(25,2,-8))) + expect_that(voxelToWorld(point,image,simple=TRUE), equals(c(97.5,97.5,47.5))) + expect_that(worldToVoxel(voxelToWorld(point,image),image), equals(point)) + expect_that(worldToVoxel(voxelToWorld(point,image,simple=TRUE),image,simple=TRUE), equals(point)) + + xform <- structure(round(xform(image)), code=4) + qform(image) <- xform + sform(image) <- xform + expect_that(dumpNifti(image)$qform_code, equals(4L)) + expect_that(dumpNifti(image)$sform_code, equals(4L)) + expect_that(dumpNifti(image)$srow_x, equals(c(-2,0,0,122))) +})