From b117a415aaf58c435805243a930e833f8cf62421 Mon Sep 17 00:00:00 2001 From: giraffedata Date: Thu, 26 Mar 2020 02:53:02 +0000 Subject: Promote trunk (10.90.00) to advanced git-svn-id: http://svn.code.sf.net/p/netpbm/code/advanced@3784 9d0c8265-081b-0410-96cb-a4ca84ce46f8 --- GNUmakefile | 11 +- analyzer/pamgetcolor.c | 6 +- analyzer/pamtilt.c | 13 +- analyzer/pgmtexture.c | 92 +++-- buildtools/README.pkg | 2 +- buildtools/configure.pl | 2 +- buildtools/debian/mkdeb | 4 +- buildtools/installnetpbm.pl | 2 +- buildtools/makeman | 4 +- config.mk.in | 2 +- converter/other/cameratopam/cameratopam.c | 2 +- converter/other/fiasco/codec/coder.c | 142 +++---- converter/other/fiasco/codec/cwfa.h | 2 +- converter/other/fiasco/codec/dfiasco.c | 40 +- converter/other/fiasco/codec/ip.c | 76 ++-- converter/other/fiasco/codec/prediction.c | 114 ++--- converter/other/fiasco/codec/subdivide.c | 124 +++--- converter/other/fiasco/codec/wfa.h | 8 +- converter/other/fiasco/doc/fiasco_c_options_new.3 | 5 +- converter/other/fiasco/doc/fiasco_coder.3 | 2 +- converter/other/fiasco/doc/fiasco_d_options_new.3 | 4 +- converter/other/fiasco/doc/fiasco_decoder_new.3 | 16 +- .../other/fiasco/doc/fiasco_get_error_message.3 | 6 +- converter/other/fiasco/doc/fiasco_image_new.3 | 6 +- converter/other/fiasco/doc/fiasco_options_new.3 | 4 +- converter/other/fiasco/doc/fiasco_renderer_new.3 | 2 +- converter/other/fiasco/input/basis.c | 33 +- converter/other/fiasco/input/matrices.c | 80 ++-- converter/other/fiasco/input/mc.c | 61 +-- converter/other/fiasco/input/nd.c | 31 +- converter/other/fiasco/input/read.c | 89 ++-- converter/other/fiasco/input/tree.c | 46 +-- converter/other/fiasco/lib/arith.c | 130 +++--- converter/other/fiasco/lib/bit-io.c | 56 +-- converter/other/fiasco/output/mc.c | 40 +- converter/other/fiasco/output/nd.c | 38 +- converter/other/fiasco/output/tree.c | 18 +- converter/other/fiasco/params.c | 94 ++--- converter/other/fiasco/pnmtofiasco.c | 77 ++-- converter/other/gemtopnm.c | 2 +- converter/other/giftopnm.c | 4 +- converter/other/infotopam.c | 33 +- converter/other/jbig/libjbig/include/jbig_ar.h | 4 +- converter/other/jbig/libjbig/jbig.c | 10 +- .../other/jpeg2000/libjasper/base/jas_stream.c | 31 +- converter/other/jpeg2000/libjasper/jpc/jpc_dec.h | 2 +- converter/other/jpeg2000/libjasper/jpc/jpc_enc.h | 2 +- converter/other/jpeg2000/libjasper/jpc/jpc_mqenc.c | 31 +- converter/other/pamtogif.c | 4 +- converter/other/pamtopng.c | 4 +- converter/other/pamtosvg/fit.c | 148 +++---- converter/other/pamtotiff.c | 2 +- converter/other/pamtowinicon.c | 2 - converter/other/pbmtopgm.c | 37 +- converter/other/pngtopam.c | 2 +- converter/other/pnmtoddif.c | 4 +- converter/other/pnmtojpeg.c | 163 ++++---- converter/other/pnmtopalm/README | 2 +- converter/other/pnmtopalm/pnmtopalm.c | 2 +- converter/other/pnmtopng.c | 2 +- converter/other/pnmtops.c | 194 ++++----- converter/other/pstopnm.csh | 2 +- converter/other/rlatopam.c | 23 +- converter/other/tifftopnm.c | 229 +++++----- converter/other/winicontopam.c | 2 +- converter/other/xwdtopnm.c | 204 ++++----- converter/pbm/mdatopbm.c | 2 +- converter/pbm/pbmtogem.c | 2 +- converter/pbm/pbmtogo.c | 72 ++-- converter/pbm/pbmtoibm23xx.c | 6 +- converter/pbm/pbmtomacp.c | 2 +- converter/pbm/pbmtopk.c | 120 +++--- converter/pbm/pbmtoppa/README.REDHAT | 2 +- converter/pbm/pbmtoppa/ppa.c | 10 +- converter/pbm/pbmtoptx.c | 11 +- converter/pgm/rawtopgm.c | 21 +- converter/pgm/st4topgm.c | 2 +- converter/ppm/ilbm.h | 92 ++--- converter/ppm/ilbmtoppm.c | 4 +- converter/ppm/picttoppm.c | 8 +- converter/ppm/pjtoppm.c | 2 +- converter/ppm/ppmtoarbtxt.c | 2 +- converter/ppm/ppmtobmp.c | 2 +- converter/ppm/ppmtomitsu.c | 2 +- converter/ppm/ppmtompeg/LOGIC | 2 +- converter/ppm/ppmtompeg/Makefile | 2 +- converter/ppm/ppmtompeg/bsearch.c | 58 +-- converter/ppm/ppmtompeg/docs/template.param | 2 +- converter/ppm/ppmtompeg/examples/payam.param | 2 +- converter/ppm/ppmtompeg/examples/payam18.param | 2 +- converter/ppm/ppmtompeg/examples/template.param | 2 +- converter/ppm/ppmtompeg/frametype.c | 39 +- converter/ppm/ppmtompeg/jpeg.c | 230 +++++------ converter/ppm/ppmtompeg/mheaders.c | 4 +- converter/ppm/ppmtompeg/mpeg.c | 241 +++++------ converter/ppm/ppmtompeg/opts.c | 48 +-- converter/ppm/ppmtompeg/parallel.c | 379 ++++++++--------- converter/ppm/ppmtompeg/param.c | 83 ++-- converter/ppm/ppmtompeg/parse_huff.pl | 2 +- converter/ppm/ppmtompeg/psearch.c | 2 +- converter/ppm/ppmtompeg/psocket.c | 63 +-- converter/ppm/ppmtompeg/rate.c | 192 ++++----- converter/ppm/ppmtopcx.c | 172 ++++---- converter/ppm/ppmtospu.c | 2 +- converter/ppm/sldtoppm.c | 2 +- converter/ppm/xim.h | 8 +- converter/ppm/ximtoppm.c | 43 +- converter/ppm/xpmtoppm.README | 2 +- converter/ppm/xpmtoppm.c | 4 +- doc/COPYRIGHT.PATENT | 2 +- doc/HISTORY | 51 ++- doc/INSTALL | 2 +- editor/pamaltsat.c | 10 +- editor/pamcut.c | 120 +++--- editor/pamdice.c | 158 +++---- editor/pamditherbw.c | 386 +++++++++-------- editor/pamlevels.c | 2 +- editor/pamperspective.c | 2 +- editor/pamthreshold.c | 31 +- editor/pamundice.c | 459 ++++++++++++++------- editor/pgmmedian.c | 26 +- editor/pnmcat.c | 33 +- editor/pnmconvol.c | 6 +- editor/pnmcrop.c | 2 +- editor/pnmgamma.c | 2 +- editor/pnmnlfilt.c | 113 ++--- editor/pnmnorm.c | 6 +- editor/pnmquantall | 1 - editor/pnmshear.c | 74 ++-- editor/pnmstitch.c | 6 +- editor/ppmshadow | 2 +- editor/specialty/pampaintspill.c | 4 +- editor/specialty/pampop9.c | 3 - editor/specialty/pgmabel.c | 18 +- generator/pamtris/boundaries.c | 2 +- generator/pamtris/framebuffer.c | 4 +- generator/pbmtext.c | 4 +- generator/pgmnoise.c | 27 +- generator/ppmforge.c | 4 +- lib/libpamcolor.c | 6 +- lib/libpamd.c | 210 +++++----- lib/libpammap.c | 116 +++--- lib/libpamwrite.c | 68 +-- lib/libpbm3.c | 2 +- lib/libpbmfont1.c | 6 +- lib/libppmd.c | 309 +++++++------- lib/libsystem.c | 38 +- lib/pam.h | 2 +- lib/util/LICENSE.txt | 2 +- lib/util/nstring.c | 80 +++- lib/util/nstring.h | 12 +- lib/util/shhopt.c | 2 +- other/pamunlookup.c | 26 +- test/Test-Order | 8 + test/pamchannel.ok | 7 + test/pamchannel.test | 29 +- test/pamcrater.ok | 7 + test/pamcrater.test | 37 +- test/pamcut.ok | 17 + test/pamcut.test | 66 ++- test/pamdepth.ok | 14 + test/pamdepth.test | 38 ++ test/pamdice-roundtrip.ok | 17 + test/pamdice-roundtrip.test | 34 +- test/pamdice.ok | 21 + test/pamdice.test | 68 +++ test/pamditherbw.ok | 2 +- test/pamditherbw.test | 13 +- test/pamfind.test | 2 +- test/pamhue.ok | 11 + test/pamhue.test | 40 +- test/pamundice.ok | 27 ++ test/pamundice.test | 183 ++++++++ test/pbmclean.ok | 2 + test/pbmclean.test | 17 + test/pbmpscale.ok | 3 + test/pbmpscale.test | 18 + test/pbmtext.test | 2 +- test/pbmtopgm.ok | 25 ++ test/pbmtopgm.test | 32 ++ test/pgmminkowski.ok | 17 + test/pgmminkowski.test | 10 + test/pgmnoise-parameters.ok | 5 + test/pgmnoise-parameters.test | 26 ++ test/pnmcat.ok | 16 + test/pnmcat.test | 61 +++ test/pnmquantall.ok | 6 +- test/pnmquantall.test | 20 + test/pnmtile.ok | 4 + test/pnmtile.test | 21 + test/ppmwheel.ok | 6 + test/ppmwheel.test | 26 ++ test/ps-alt-roundtrip.test | 2 +- test/ps-flate-roundtrip.test | 2 +- urt/rle_open_f.c | 43 +- urt/vaxshort.c | 9 +- version.mk | 4 +- 197 files changed, 4664 insertions(+), 3370 deletions(-) create mode 100644 test/pamdepth.ok create mode 100755 test/pamdepth.test create mode 100644 test/pamdice.ok create mode 100755 test/pamdice.test create mode 100644 test/pamundice.ok create mode 100755 test/pamundice.test create mode 100644 test/pbmtopgm.ok create mode 100755 test/pbmtopgm.test create mode 100644 test/pgmminkowski.ok create mode 100755 test/pgmminkowski.test create mode 100644 test/pgmnoise-parameters.ok create mode 100755 test/pgmnoise-parameters.test diff --git a/GNUmakefile b/GNUmakefile index e5b0265a..e727b00e 100644 --- a/GNUmakefile +++ b/GNUmakefile @@ -266,7 +266,14 @@ init_package: echo "Netpbm install package made by 'make package'" \ >$(PKGDIR)/pkginfo date >>$(PKGDIR)/pkginfo - echo Netpbm $(MAJOR).$(MINOR).$(POINT) >$(PKGDIR)/VERSION +# For many years, the version string was "Netpbm x.y.z" instead of just +# "x.y.z". This was probably related to the fact that when you ask a Netpbm +# program its version, it says "Netpbm x.y.z" to let you know it's the version +# of the whole package, not just that program. And also to distinguish from +# the Pbmplus version of the program. But this is highly unconventional in +# pkg-config or config files, so we removed the "Netpbm" in Netpbm 10.90 +# (March 2020). + echo $(MAJOR).$(MINOR).$(POINT) >$(PKGDIR)/VERSION $(INSTALL) -c -m 664 $(SRCDIR)/buildtools/README.pkg $(PKGDIR)/README $(INSTALL) -c -m 664 $(SRCDIR)/buildtools/config_template \ $(PKGDIR)/config_template @@ -349,7 +356,7 @@ endif # 1) Each directory produces an object file merge.o containing all the code # in that directory and its descendants that needs to go into the 'netpbm' # program. The make files do this recursively, via a link command that -# combines multiple relocateable object files into one. All we do here +# combines multiple relocatable object files into one. All we do here # at the top level is make merge.o and link it with netpbm.o and the # libraries. # diff --git a/analyzer/pamgetcolor.c b/analyzer/pamgetcolor.c index 430f3b07..d1ea3799 100644 --- a/analyzer/pamgetcolor.c +++ b/analyzer/pamgetcolor.c @@ -37,7 +37,7 @@ typedef struct { uint regN; /* number of regions */ uint maxLbLen; /* maximum label length */ RegSpec * regSpecs; - /* list of points to sample, dymamically allocated*/ + /* list of points to sample, dynamically allocated*/ const char * formatStr; /* output color format as string */ uint formatId; /* the Id of the selected color format */ uint formatArg; /* the argument to the color formatting function */ @@ -45,9 +45,9 @@ typedef struct { } CmdLineInfo; /* Generic pointer to a color-formatting function. Returns the textual - representation of the color in terms of the image pointed-to + representation of the color in terms of the image pointed to by . is a generic integer parameter that depends on the - specific funcion and may denote precison or maxval. + specific function and may denote precision or maxval. */ typedef const char * (*FormatColor)(struct pam * const pamP, diff --git a/analyzer/pamtilt.c b/analyzer/pamtilt.c index 70338545..2898d30f 100644 --- a/analyzer/pamtilt.c +++ b/analyzer/pamtilt.c @@ -143,7 +143,7 @@ load(const struct pam * const pamP, sample ** pixels; tuplerow = pnm_allocpamrow(pamP); - + MALLOCARRAY(pixels, pamP->height); if (pixels == NULL) @@ -221,7 +221,7 @@ totalBrightness(sample ** const pixels, /*---------------------------------------------------------------------------- Total brightness of samples in the line that goes from the left edge of Row 'startRow' of 'pixels' down to the right at 'dy' rows per column. - + Note that 'dy' can be negative. Assume that whatever 'dy' is, the sloping line thus described remains @@ -319,7 +319,7 @@ scoreAngle(const struct pam * const pamP, If 'angle' is so great that not a single line goes all the way across the page without running off the top or bottom, we call the score -1. In every other case, it is nonnegative. - + 'pixels' is NOT all the pixels in the image; it is just a sampling. In each row, it contains only 'hsampleCt' pixels, sampled from the image at intervals of 'hstep' pixels. E.g if the image is 1000 @@ -468,7 +468,7 @@ readSampledPixels(const char * const inputFilename, *hstepP = hstep; *vstepP = vstep; - + pm_close(ifP); } @@ -490,7 +490,7 @@ getAngle(const struct pam * const pamP, float a; float da; float lastq; /* quality (s/n ratio) of last measurement */ - + getBestAngleLocal(pamP, pixels, hstep, vstep, hsampleCt, -maxangle, maxangle, astep, verbose, &a, &lastq); @@ -551,3 +551,6 @@ main(int argc, const char ** argv) { return 0; } + + + diff --git a/analyzer/pgmtexture.c b/analyzer/pgmtexture.c index 58833277..c69643e7 100644 --- a/analyzer/pgmtexture.c +++ b/analyzer/pgmtexture.c @@ -1,49 +1,5 @@ /* pgmtexture.c - calculate textural features of a PGM image ** -** Author: James Darrell McCauley -** Texas Agricultural Experiment Station -** Department of Agricultural Engineering -** Texas A&M University -** College Station, Texas 77843-2117 USA -** -** Code written partially taken from pgmtofs.c in the PBMPLUS package -** by Jef Poskanzer. -** -** Algorithms for calculating features (and some explanatory comments) are -** taken from: -** -** Haralick, R.M., K. Shanmugam, and I. Dinstein. 1973. Textural features -** for image classification. IEEE Transactions on Systems, Man, and -** Cybertinetics, SMC-3(6):610-621. -** -** Copyright (C) 1991 Texas Agricultural Experiment Station, employer for -** hire of James Darrell McCauley -** -** Permission to use, copy, modify, and distribute this software and its -** documentation for any purpose and without fee is hereby granted, provided -** that the above copyright notice appear in all copies and that both that -** copyright notice and this permission notice appear in supporting -** documentation. This software is provided "as is" without express or -** implied warranty. -** -** THE TEXAS AGRICULTURAL EXPERIMENT STATION (TAES) AND THE TEXAS A&M -** UNIVERSITY SYSTEM (TAMUS) MAKE NO EXPRESS OR IMPLIED WARRANTIES -** (INCLUDING BY WAY OF EXAMPLE, MERCHANTABILITY) WITH RESPECT TO ANY -** ITEM, AND SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL -** OR CONSEQUENTAL DAMAGES ARISING OUT OF THE POSESSION OR USE OF -** ANY SUCH ITEM. LICENSEE AND/OR USER AGREES TO INDEMNIFY AND HOLD -** TAES AND TAMUS HARMLESS FROM ANY CLAIMS ARISING OUT OF THE USE OR -** POSSESSION OF SUCH ITEMS. -** -** Modification History: -** 24 Jun 91 - J. Michael Carstensen supplied fix for -** correlation function. -** -** 05 Oct 05 - Marc Breithecker -** Fix calculation or normalizing constants for d > 1. -** 9 Jul 11 - Francois P. S. Luus supplied fix for sum -** variance calculation (use F6:savg instead of F8:sentropy in -** F7:svar equation). */ @@ -1172,3 +1128,51 @@ main (int argc, const char ** argv) { return 0; } + + +/* +** Author: James Darrell McCauley +** Texas Agricultural Experiment Station +** Department of Agricultural Engineering +** Texas A&M University +** College Station, Texas 77843-2117 USA +** +** Code written partially taken from pgmtofs.c in the PBMPLUS package +** by Jef Poskanzer. +** +** Algorithms for calculating features (and some explanatory comments) are +** taken from: +** +** Haralick, R.M., K. Shanmugam, and I. Dinstein. 1973. Textural features +** for image classification. IEEE Transactions on Systems, Man, and +** Cybertinetics, SMC-3(6):610-621. +** +** Copyright (C) 1991 Texas Agricultural Experiment Station, employer for +** hire of James Darrell McCauley +** +** Permission to use, copy, modify, and distribute this software and its +** documentation for any purpose and without fee is hereby granted, provided +** that the above copyright notice appear in all copies and that both that +** copyright notice and this permission notice appear in supporting +** documentation. This software is provided "as is" without express or +** implied warranty. +** +** THE TEXAS AGRICULTURAL EXPERIMENT STATION (TAES) AND THE TEXAS A&M +** UNIVERSITY SYSTEM (TAMUS) MAKE NO EXPRESS OR IMPLIED WARRANTIES +** (INCLUDING BY WAY OF EXAMPLE, MERCHANTABILITY) WITH RESPECT TO ANY +** ITEM, AND SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL +** OR CONSEQUENTAL DAMAGES ARISING OUT OF THE POSSESSION OR USE OF +** ANY SUCH ITEM. LICENSEE AND/OR USER AGREES TO INDEMNIFY AND HOLD +** TAES AND TAMUS HARMLESS FROM ANY CLAIMS ARISING OUT OF THE USE OR +** POSSESSION OF SUCH ITEMS. +** +** Modification History: +** 24 Jun 91 - J. Michael Carstensen supplied fix for +** correlation function. +** +** 05 Oct 05 - Marc Breithecker +** Fix calculation or normalizing constants for d > 1. +** 9 Jul 11 - Francois P. S. Luus supplied fix for sum +** variance calculation (use F6:savg instead of F8:sentropy in +** F7:svar equation). +*/ diff --git a/buildtools/README.pkg b/buildtools/README.pkg index d642dee8..71afc000 100644 --- a/buildtools/README.pkg +++ b/buildtools/README.pkg @@ -114,7 +114,7 @@ The parts to be installed are: replacement for the classic Man program that can access both traditional man pages and worldwide web documentation in the Netpbm style with the familiar 'man jpegtopnm' kind of command. The package contains the files - necessary to use Manweb to access Netpbm documention on the web (on + necessary to use Manweb to access Netpbm documentation on the web (on netpbm.sourceforge.net). These files are the contents of the man/web directory and the file 'bin/doc.url'. You should install the 'bin/doc.url' file if you are installing the Netpbm executables in a diff --git a/buildtools/configure.pl b/buildtools/configure.pl index 4e6ff21a..4eeb97de 100755 --- a/buildtools/configure.pl +++ b/buildtools/configure.pl @@ -125,7 +125,7 @@ sub flow($) { my ($unflowed) = @_; #----------------------------------------------------------------------------- # Return the text $unflowed, split with newlines into 72 character lines. -# We assum $unflowed is pure text, without any kind of formatting characters +# We assume $unflowed is pure text, without any kind of formatting characters # such as newlines. #----------------------------------------------------------------------------- my $retval; diff --git a/buildtools/debian/mkdeb b/buildtools/debian/mkdeb index 684ca0fb..f0bd6145 100755 --- a/buildtools/debian/mkdeb +++ b/buildtools/debian/mkdeb @@ -3,7 +3,7 @@ # mkdeb ############################################################################### # -# This generates a Debian packge file (.deb) to install Sourceforge +# This generates a Debian package file (.deb) to install Sourceforge # Netpbm on a Debian system. # # This is especially useful because Debian does not have a good Debian @@ -148,8 +148,6 @@ sub control($$) { 'perl-base, ' . 'bash' ; - $control{'Recommends'} = ''; - $control{'Recommends'} = ''; $control{'Conflicts'} = $debianNativeNetpbm; $control{'Replaces'} = $debianNativeNetpbm; $control{'Provides'} = diff --git a/buildtools/installnetpbm.pl b/buildtools/installnetpbm.pl index d29fda1a..0c3679f8 100755 --- a/buildtools/installnetpbm.pl +++ b/buildtools/installnetpbm.pl @@ -990,7 +990,7 @@ sub installHeader($$$) { my $rc = system("cd $hdrDir; ln -s netpbm/* ."); if ($rc != 0) { - print("Failed to create backward compatibilty symlinks from " . + print("Failed to create backward compatibility symlinks from " . "$hdrDir into $hdrDir/netpbm\n"); print("ln exit code is $rc\n"); } else { diff --git a/buildtools/makeman b/buildtools/makeman index dc8e45ce..196dbd0a 100755 --- a/buildtools/makeman +++ b/buildtools/makeman @@ -152,7 +152,7 @@ def makeman(name, file, indoc): indoc = re.sub(r"\s*\.sp", "\n.sp", indoc) # Format email addresses as italic indoc = re.sub('(?i)([^<]+)', r'\\fI\1\\fP', indoc) - # Format manual crossreferences + # Format manual cross-references def xrefmatch(match): xrefto = match.group(2) xrefurl = match.group(1) @@ -279,7 +279,7 @@ def main(args, mainout=sys.stdout, mainerr=sys.stderr): elif switch == '-v': # Enable verbose error reporting verbosity += 1 try: - # First pass: gather locations for crossreferences: + # First pass: gather locations for cross-references: sectmap = {} for file in arguments: try: diff --git a/config.mk.in b/config.mk.in index ee692332..05cb45d4 100644 --- a/config.mk.in +++ b/config.mk.in @@ -282,7 +282,7 @@ LDSHLIB = -shared -Wl,-soname,$(SONAME) #LDSHLIB=-dynamiclib #LDSHLIB=-dynamiclib -install_name $(NETPBMLIB_RUNTIME_PATH)/libnetpbm.$(MAJ).dylib -# LDRELOC is the command to combine two .o files (relocateable object files) +# LDRELOC is the command to combine two .o files (relocatable object files) # into a single .o file that can later be linked into something else. NONE # means no such command is available. diff --git a/converter/other/cameratopam/cameratopam.c b/converter/other/cameratopam/cameratopam.c index 2c832714..78eb6854 100644 --- a/converter/other/cameratopam/cameratopam.c +++ b/converter/other/cameratopam/cameratopam.c @@ -10,7 +10,7 @@ #define _DEFAULT_SOURCE 1 /* New name for SVID & BSD source defines */ #define _BSD_SOURCE 1 /* Make sure string.h contains strdup() */ #define _XOPEN_SOURCE 500 - /* Make sure unistd.h contains swab(), string.h constains strdup() */ + /* Make sure unistd.h contains swab(), string.h contains strdup() */ #include "pm_config.h" diff --git a/converter/other/fiasco/codec/coder.c b/converter/other/fiasco/codec/coder.c index 1e21994d..dc774a19 100644 --- a/converter/other/fiasco/codec/coder.c +++ b/converter/other/fiasco/codec/coder.c @@ -2,7 +2,7 @@ * coder.c: WFA coder toplevel functions * * Written by: Ullrich Hafner - * + * * This file is part of FIASCO (Fractal Image And Sequence COdec) * Copyright (C) 1994-2000 Ullrich Hafner */ @@ -56,7 +56,7 @@ /***************************************************************************** global variables - + *****************************************************************************/ const real_t MAXCOSTS = 1e20; @@ -64,7 +64,7 @@ const real_t MAXCOSTS = 1e20; /***************************************************************************** private code - + *****************************************************************************/ static char * @@ -109,44 +109,44 @@ get_input_image_name (char const * const *templptr, unsigned ith_image) strcpy (prefix, template); prefix [s - template] = '\0'; - + for (s2 = ++s, n_digits = 0; ISDIGIT (*s2); s2++, n_digits++) ; if (sscanf (s, "%d", &dummy) == 0 || dummy < 0) error ("Input name template conversion failure.\n" "Check spelling of template."); first = (unsigned) dummy; - + if (*s2++ != '-') error ("Input name template conversion failure.\n" "Check spelling of template."); - + for (s = s2; ISDIGIT (*s2); s2++) ; if (sscanf (s, "%d", &dummy) == 0 || dummy < 0) error ("Input name template conversion failure.\n" "Check spelling of template."); last = (unsigned) dummy; - - if (*s2 == '+' || *s2 == '-') + + if (*s2 == '+' || *s2 == '-') { for (s = s2++; ISDIGIT (*s2); s2++) ; if (sscanf (s, "%d", &increment) == 0) error ("Input name template conversion failure.\n" "Check spelling of template."); - } + } if (*s2 != ']') error ("Input name template conversion failure.\n" "Check spelling of template."); suffix = s2 + 1; - + image_num = first + increment * ith_image; if (image_num < 0) error ("Input name template conversion failure.\n" "Check spelling of template."); - - if ((increment > 0 && (unsigned) image_num > last) || + + if ((increment > 0 && (unsigned) image_num > last) || (increment <= 0 && (unsigned) image_num < last)) { /* TODO: check this */ @@ -158,7 +158,7 @@ get_input_image_name (char const * const *templptr, unsigned ith_image) /* format string for image filename */ char image_name [MAXSTRLEN]; /* image file name to be composed */ - + strcpy (formatstr, "%s%0?d%s"); formatstr [4] = '0' + (char) n_digits; sprintf (image_name, formatstr, prefix, image_num, suffix); @@ -167,7 +167,7 @@ get_input_image_name (char const * const *templptr, unsigned ith_image) } } return NULL; -} +} @@ -191,7 +191,7 @@ alloc_coder (char const * const * const inputname, coding_t * c; c = NULL; /* initial value */ - + /* * Check whether all specified image frames are readable and of same type */ @@ -200,7 +200,7 @@ alloc_coder (char const * const * const inputname, int width, w = 0, height, h = 0; bool_t color, c = NO; unsigned n; - + for (n = 0; (filename = get_input_image_name (inputname, n)); n++) { xelval maxval; @@ -220,7 +220,7 @@ alloc_coder (char const * const * const inputname, pm_close(file); } color = (PNM_FORMAT_TYPE(format) == PPM_FORMAT) ? TRUE: FALSE; - + if (n > 0) { if (w != width || h != height || c != color) @@ -249,13 +249,13 @@ alloc_coder (char const * const * const inputname, */ { unsigned lx, ly; - + lx = (unsigned) (log2 (wi->width - 1) + 1); ly = (unsigned) (log2 (wi->height - 1) + 1); - + wi->level = MAX(lx, ly) * 2 - ((ly == lx + 1) ? 1 : 0); } - + c = Calloc (1, sizeof (coding_t)); c->options = *options; @@ -278,10 +278,10 @@ alloc_coder (char const * const * const inputname, c->options.lc_max_level, wi->level - c->tiling->exponent - 1); c->options.lc_max_level = wi->level - c->tiling->exponent - 1; } - + if (c->options.lc_min_level > c->options.lc_max_level) c->options.lc_min_level = c->options.lc_max_level; - + /* * p_min_level, p_max_level min and max level for ND/MC prediction * [p_min_level, p_max_level] must be a subset of [min_level, max_level] ! @@ -293,7 +293,7 @@ alloc_coder (char const * const * const inputname, c->options.images_level = MIN(c->options.images_level, c->options.lc_max_level - 1); - + c->products_level = MAX(0, ((signed int) c->options.lc_max_level - (signed int) c->options.images_level - 1)); c->pixels = Calloc (size_of_level (c->options.lc_max_level), @@ -301,7 +301,7 @@ alloc_coder (char const * const * const inputname, c->images_of_state = Calloc (MAXSTATES, sizeof (real_t *)); c->ip_images_state = Calloc (MAXSTATES, sizeof (real_t *)); c->ip_states_state = Calloc (MAXSTATES * MAXLEVEL, sizeof (real_t *)); - + debug_message ("Imageslevel :%d, Productslevel :%d", c->options.images_level, c->products_level); debug_message ("Memory : (%d + %d + %d * 'states') * 'states' + %d", @@ -309,7 +309,7 @@ alloc_coder (char const * const * const inputname, size_of_tree (c->products_level) * 4, (c->options.lc_max_level - c->options.images_level), size_of_level (c->options.lc_max_level)); - + /* * Domain pools ... */ @@ -333,7 +333,7 @@ alloc_coder (char const * const * const inputname, */ wi->title = strdup (options->title); wi->comment = strdup (options->comment); - + /* * Reduced precision format */ @@ -345,7 +345,7 @@ alloc_coder (char const * const * const inputname, = alloc_rpf (options->d_rpf_mantissa, options->d_rpf_range); wi->d_dc_rpf = alloc_rpf (options->d_dc_rpf_mantissa, options->d_dc_rpf_range); - + /* * Color image options ... */ @@ -361,7 +361,7 @@ alloc_coder (char const * const * const inputname, wi->cross_B_search = options->half_pixel_prediction; wi->B_as_past_ref = options->B_as_past_ref; wi->smoothing = options->smoothing; - + c->mt = alloc_motion (wi); return c; @@ -383,7 +383,7 @@ free_coder (coding_t *c) { free_tiling (c->tiling); free_motion (c->mt); - + Free (c->pixels); Free (c->images_of_state); Free (c->ip_images_state); @@ -424,13 +424,13 @@ print_statistics (char c, real_t costs, const wfa_t *wfa, const image_t *image, const range_t *range) { unsigned max_level, min_level, state, label, lincomb; - + for (max_level = 0, min_level = MAXLEVEL, state = wfa->basis_states; state < wfa->states; state++) { for (lincomb = 0, label = 0; label < MAXLABELS; label++) lincomb += isrange(wfa->tree[state][label]) ? 1 : 0; - + if (lincomb) { max_level = MAX(max_level, @@ -483,10 +483,10 @@ print_statistics (char c, real_t costs, const wfa_t *wfa, const image_t *image, -static void +static void frame_coder (wfa_t *wfa, coding_t *c, bitfile_t *output) /* - * + * * WFA Coding of next frame. All important coding parameters are * stored in 'c'. The generated 'wfa' is written to stream 'output' * immediately after coding. @@ -499,11 +499,11 @@ frame_coder (wfa_t *wfa, coding_t *c, bitfile_t *output) real_t costs; /* total costs (minimized quantity) */ unsigned bits; /* number of bits written on disk */ clock_t ptimer; - + prg_timer (&ptimer, START); bits = bits_processed (output); - + init_tree_model (&c->tree); init_tree_model (&c->p_tree); @@ -552,9 +552,9 @@ frame_coder (wfa_t *wfa, coding_t *c, bitfile_t *output) int YCb_node = -1; int tree [3]; /* 3 root states of each color comp. */ color_e band; - + /* - * When compressing color images, the three color components (YCbCr) + * When compressing color images, the three color components (YCbCr) * are copied into a large image: * [ Y Cr ] * [ Cb 0 ] @@ -573,14 +573,14 @@ frame_coder (wfa_t *wfa, coding_t *c, bitfile_t *output) c->domain_pool->chroma (wfa->wfainfo->chroma_max_states, wfa, c->domain_pool->model); /* - * Don't use a finer partioning for the chrominancy bands than - * for the luminancy band. + * Don't use a finer partitioning for the chrominancy bands + * than for the luminancy band. */ for (min_level = MAXLEVEL, state = wfa->basis_states; state < wfa->states; state++) { unsigned lincomb, label; - + for (lincomb = 0, label = 0; label < MAXLABELS; label++) lincomb += isrange (wfa->tree [state][label]) ? 1 : 0; if (lincomb) @@ -596,23 +596,23 @@ frame_coder (wfa_t *wfa, coding_t *c, bitfile_t *output) memset (&range, 0, sizeof (range_t)); range.level = wfa->wfainfo->level; - + costs = subdivide (MAXCOSTS, band, tree [Y], &range, wfa, c, c->mt->frame_type != I_FRAME && band == Y, NO); if (c->options.progress_meter != FIASCO_PROGRESS_NONE) message (""); { char colors [] = {'Y', 'B', 'R'}; - + print_statistics (colors [band], costs, wfa, c->mt->original, &range); } - + if (isrange (range.tree)) /* whole image is approx. by a l.c. */ error ("No root state generated for color component %d!", band); else tree[band] = range.tree; - + if (band == Cb) { wfa->tree [wfa->states][0] = tree[Y]; @@ -623,13 +623,13 @@ frame_coder (wfa_t *wfa, coding_t *c, bitfile_t *output) } } /* - * generate two virtual states (*) + * generate two virtual states (*) * * * * / \ * + * - * / \ / - * Y CbCr + * / \ / + * Y CbCr */ wfa->tree [wfa->states][0] = tree[Cr]; wfa->tree [wfa->states][1] = RANGE; @@ -646,7 +646,7 @@ frame_coder (wfa_t *wfa, coding_t *c, bitfile_t *output) for (state = wfa->basis_states; state < MAXSTATES; state++) { unsigned level; - + if (c->images_of_state [state]) { Free (c->images_of_state [state]); @@ -665,12 +665,12 @@ frame_coder (wfa_t *wfa, coding_t *c, bitfile_t *output) Free (c->ip_states_state [state][level]); c->ip_states_state [state][level] = NULL; } - + } - + locate_delta_images (wfa); write_next_wfa (wfa, c, output); - + bits = bits_processed (output) - bits; debug_message ("Total number of bits written: %d (%d bytes, %5.3f bpp)", bits, bits >> 3, @@ -712,7 +712,7 @@ video_coder(char const * const * const image_template, /* image name of current frame. File name or "-" for Standard Input */ image_t *reconst = NULL; /* decoded reference image */ bool_t future_frame = NO; /* YES if last frame was in future */ - + debug_message ("Generating %d WFA's ...", wfa->wfainfo->frames); future_display = -1; @@ -722,7 +722,7 @@ video_coder(char const * const * const image_template, while ((image_name = get_input_image_name (image_template, display))) { frame_type_e type; /* current frame type: I, B, P */ - + /* * Determine type of next frame. * Skip already coded frames (future reference!) @@ -731,7 +731,7 @@ video_coder(char const * const * const image_template, type = I_FRAME; /* Force first frame to be intra */ else type = pattern2type (display, c->options.pattern); - + if (type != I_FRAME && c->options.reference_filename) /* Load reference from disk */ { @@ -741,12 +741,12 @@ video_coder(char const * const * const image_template, c->options.reference_filename = NULL; } if ((int) display == future_display) - { + { /* Skip already coded future ref */ display++; continue; - } - else if (type == B_FRAME && (int) display > future_display) + } + else if (type == B_FRAME && (int) display > future_display) { unsigned i = display; /* @@ -758,7 +758,7 @@ video_coder(char const * const * const image_template, i++; name = get_input_image_name (image_template, i); - + if (!name) /* Force last valid frame to be 'P' */ { future_display = i - 1; @@ -766,7 +766,7 @@ video_coder(char const * const * const image_template, } else { - future_display = i; + future_display = i; image_name = name; type = pattern2type (i, c->options.pattern); } @@ -781,7 +781,7 @@ video_coder(char const * const * const image_template, debug_message ("Coding \'%s\' [%c-frame].", image_name, type == I_FRAME ? 'I' : (type == P_FRAME ? 'P' : 'B')); - + /* * Depending on current frame type update past and future frames * which are needed as reference frames. @@ -846,10 +846,10 @@ video_coder(char const * const * const image_template, c->mt->original = read_image_stream(stdin, stdinwidth, stdinheight, stdinmaxval, stdinformat); - else + else c->mt->original = read_image_file(image_name); - if (c->tiling->exponent && type == I_FRAME) + if (c->tiling->exponent && type == I_FRAME) perform_tiling (c->mt->original, c->tiling); frame_coder (wfa, c, output); @@ -869,7 +869,7 @@ video_coder(char const * const * const image_template, if (c->mt->original) free_image (c->mt->original); c->mt->original = NULL; - + remove_states (wfa->basis_states, wfa); /* Clear WFA structure */ } @@ -927,7 +927,7 @@ read_stdin_header(const char * const * const template, /***************************************************************************** public code - + *****************************************************************************/ int @@ -957,7 +957,7 @@ fiasco_coder (char const * const *inputname, const char *outputname, unsigned int stdinheight, stdinwidth; xelval stdinmaxval; int stdinformat; - + /* * Check parameters */ @@ -965,7 +965,7 @@ fiasco_coder (char const * const *inputname, const char *outputname, template = default_input; else template = inputname; - + if (quality <= 0) { set_error (_("Compression quality has to be positive.")); @@ -1013,20 +1013,20 @@ fiasco_coder (char const * const *inputname, const char *outputname, coding_t *c = alloc_coder(template, cop, wfa->wfainfo, stdinwidth, stdinheight, stdinmaxval, stdinformat); - + read_basis (cop->basis_name, wfa); append_basis_states (wfa->basis_states, wfa, c); - + c->price = 128 * 64 / quality; - + video_coder (template, output, wfa, c, stdinwidth, stdinheight, stdinmaxval, stdinformat); - + close_bitfile (output); free_wfa (wfa); free_coder (c); - + if (default_options) fiasco_c_options_delete (default_options); } diff --git a/converter/other/fiasco/codec/cwfa.h b/converter/other/fiasco/codec/cwfa.h index dd86fbfc..e8e2d474 100644 --- a/converter/other/fiasco/codec/cwfa.h +++ b/converter/other/fiasco/codec/cwfa.h @@ -33,7 +33,7 @@ extern const real_t MAXCOSTS; typedef struct motion { image_t *original; /* Current image */ - image_t *past; /* Preceeding image */ + image_t *past; /* Preceding image */ image_t *future; /* Succeeding image */ frame_type_e frame_type; /* frame type: B_, P_ I_FRAME */ unsigned number; /* display number of frame */ diff --git a/converter/other/fiasco/codec/dfiasco.c b/converter/other/fiasco/codec/dfiasco.c index d45c9e39..ce25654a 100644 --- a/converter/other/fiasco/codec/dfiasco.c +++ b/converter/other/fiasco/codec/dfiasco.c @@ -2,11 +2,11 @@ * dfiasco.c: Decoder public interface * * Written by: Ullrich Hafner - * + * * This file is part of FIASCO (Fractal Image And Sequence COdec) * Copyright (C) 1994-2000 Ullrich Hafner */ - + /* * $Date: 2000/10/28 17:39:30 $ * $Author: hafner $ @@ -38,7 +38,7 @@ /***************************************************************************** prototypes - + *****************************************************************************/ static dfiasco_t * @@ -52,7 +52,7 @@ alloc_dfiasco (wfa_t *wfa, video_t *video, bitfile_t *input, /***************************************************************************** public code - + *****************************************************************************/ fiasco_decoder_t * @@ -79,7 +79,7 @@ fiasco_decoder_new (const char *filename, const fiasco_d_options_t *options) default_options = fiasco_d_options_new (); dop = cast_d_options (default_options); } - + wfa = alloc_wfa (NO); video = alloc_video (NO); input = open_wfa (filename, wfa->wfainfo); @@ -102,7 +102,7 @@ fiasco_decoder_new (const char *filename, const fiasco_d_options_t *options) dop->magnification, dop->smoothing, dop->image_format); - + if (default_options) fiasco_d_options_delete (default_options); if (dfiasco->enlarge_factor >= 0) @@ -115,7 +115,7 @@ fiasco_decoder_new (const char *filename, const fiasco_d_options_t *options) if (pixels << (n << 1) > 2048 * 2048) { set_error (_("Magnifaction factor `%d' is too large. " - "Maximium value is %d."), + "Maximum value is %d."), dfiasco->enlarge_factor, MAX(0, n - 1)); fiasco_decoder_delete (decoder); return NULL; @@ -152,7 +152,7 @@ fiasco_decoder_write_frame (fiasco_decoder_t *decoder, const char *filename) { dfiasco_t *dfiasco = cast_dfiasco (decoder); - + if (!dfiasco) return 0; else @@ -177,7 +177,7 @@ fiasco_image_t * fiasco_decoder_get_frame (fiasco_decoder_t *decoder) { dfiasco_t *dfiasco = cast_dfiasco (decoder); - + if (!dfiasco) return NULL; else @@ -197,7 +197,7 @@ fiasco_decoder_get_frame (fiasco_decoder_t *decoder) image->get_width = fiasco_image_get_width; image->get_height = fiasco_image_get_height; image->is_color = fiasco_image_is_color; - + return image; } catch @@ -211,7 +211,7 @@ unsigned fiasco_decoder_get_length (fiasco_decoder_t *decoder) { dfiasco_t *dfiasco = cast_dfiasco (decoder); - + if (!dfiasco) return 0; else @@ -222,7 +222,7 @@ unsigned fiasco_decoder_get_rate (fiasco_decoder_t *decoder) { dfiasco_t *dfiasco = cast_dfiasco (decoder); - + if (!dfiasco) return 0; else @@ -239,12 +239,12 @@ fiasco_decoder_get_width (fiasco_decoder_t *decoder) else { unsigned width; - + if (dfiasco->enlarge_factor >= 0) width = dfiasco->wfa->wfainfo->width << dfiasco->enlarge_factor; else width = dfiasco->wfa->wfainfo->width >> - dfiasco->enlarge_factor; - + return width & 1 ? width + 1 : width; } } @@ -259,7 +259,7 @@ fiasco_decoder_get_height (fiasco_decoder_t *decoder) else { unsigned height; - + if (dfiasco->enlarge_factor >= 0) height = dfiasco->wfa->wfainfo->height << dfiasco->enlarge_factor; else @@ -306,10 +306,10 @@ int fiasco_decoder_delete (fiasco_decoder_t *decoder) { dfiasco_t *dfiasco = cast_dfiasco (decoder); - + if (!dfiasco) return 1; - + try { free_wfa (dfiasco->wfa); @@ -330,7 +330,7 @@ fiasco_decoder_delete (fiasco_decoder_t *decoder) /***************************************************************************** private code - + *****************************************************************************/ static dfiasco_t * @@ -347,14 +347,14 @@ alloc_dfiasco (wfa_t *wfa, video_t *video, bitfile_t *input, dfiasco_t *dfiasco = Calloc (1, sizeof (dfiasco_t)); strcpy (dfiasco->id, "DFIASCO"); - + dfiasco->wfa = wfa; dfiasco->video = video; dfiasco->input = input; dfiasco->enlarge_factor = enlarge_factor; dfiasco->smoothing = smoothing; dfiasco->image_format = image_format; - + return dfiasco; } diff --git a/converter/other/fiasco/codec/ip.c b/converter/other/fiasco/codec/ip.c index 56b0ae9a..18257a06 100644 --- a/converter/other/fiasco/codec/ip.c +++ b/converter/other/fiasco/codec/ip.c @@ -2,7 +2,7 @@ * ip.c: Computation of inner products * * Written by: Ullrich Hafner - * + * * This file is part of FIASCO (Fractal Image And Sequence COdec) * Copyright (C) 1994-2000 Ullrich Hafner */ @@ -27,40 +27,40 @@ /***************************************************************************** prototypes - + *****************************************************************************/ -static real_t +static real_t standard_ip_image_state (unsigned address, unsigned level, unsigned domain, const coding_t *c); -static real_t +static real_t standard_ip_state_state (unsigned domain1, unsigned domain2, unsigned level, const coding_t *c); /***************************************************************************** public code - + *****************************************************************************/ -real_t +real_t get_ip_image_state (unsigned image, unsigned address, unsigned level, unsigned domain, const coding_t *c) /* * Return value: * Inner product between 'image' ('address') and - * 'domain' at given 'level' + * 'domain' at given 'level' */ { if (level <= c->options.images_level) { /* - * Compute the inner product in the standard way by multiplying + * Compute the inner product in the standard way by multiplying * the pixel-values of the given domain and range image. - */ + */ return standard_ip_image_state (address, level, domain, c); } - else + else { /* * Use the already computed inner products stored in 'ip_images_states' @@ -69,29 +69,29 @@ get_ip_image_state (unsigned image, unsigned address, unsigned level, } } -void +void compute_ip_images_state (unsigned image, unsigned address, unsigned level, unsigned n, unsigned from, const wfa_t *wfa, coding_t *c) /* * Compute the inner products between all states * 'from', ... , 'wfa->max_states' and the range images 'image' - * (and childs) up to given level. + * (and children) up to given level. * * No return value. * * Side effects: * inner product tables 'c->ip_images_states' are updated - */ + */ { - if (level > c->options.images_level) + if (level > c->options.images_level) { unsigned state, label; if (level > c->options.images_level + 1) /* recursive computation */ compute_ip_images_state (MAXLABELS * image + 1, address * MAXLABELS, level - 1, MAXLABELS * n, from, wfa, c); - + /* * Compute inner product */ @@ -102,7 +102,7 @@ compute_ip_images_state (unsigned image, unsigned address, unsigned level, unsigned edge, count; int domain; real_t *dst, *src; - + if (ischild (domain = wfa->tree [state][label])) { if (level > c->options.images_level + 1) @@ -116,9 +116,9 @@ compute_ip_images_state (unsigned image, unsigned address, unsigned level, else { unsigned newadr = address * MAXLABELS + label; - + dst = c->ip_images_state [state] + image; - + for (count = n; count; count--, newadr += MAXLABELS) *dst++ += standard_ip_image_state (newadr, level - 1, domain, c); @@ -128,7 +128,7 @@ compute_ip_images_state (unsigned image, unsigned address, unsigned level, edge++) { real_t weight = wfa->weight [state][label][edge]; - + if (level > c->options.images_level + 1) { dst = c->ip_images_state [state] + image; @@ -142,7 +142,7 @@ compute_ip_images_state (unsigned image, unsigned address, unsigned level, unsigned newadr = address * MAXLABELS + label; dst = c->ip_images_state [state] + image; - + for (count = n; count; count--, newadr += MAXLABELS) *dst++ += weight * standard_ip_image_state (newadr, level - 1, @@ -153,7 +153,7 @@ compute_ip_images_state (unsigned image, unsigned address, unsigned level, } } -real_t +real_t get_ip_state_state (unsigned domain1, unsigned domain2, unsigned level, const coding_t *c) /* @@ -164,12 +164,12 @@ get_ip_state_state (unsigned domain1, unsigned domain2, unsigned level, if (level <= c->options.images_level) { /* - * Compute the inner product in the standard way by multiplying + * Compute the inner product in the standard way by multiplying * the pixel-values of both state-images - */ + */ return standard_ip_state_state (domain1, domain2, level, c); } - else + else { /* * Use already computed inner products stored in 'ip_images_states' @@ -181,7 +181,7 @@ get_ip_state_state (unsigned domain1, unsigned domain2, unsigned level, } } -void +void compute_ip_states_state (unsigned from, unsigned to, const wfa_t *wfa, coding_t *c) /* @@ -192,7 +192,7 @@ compute_ip_states_state (unsigned from, unsigned to, * * Side effects: * inner product tables 'c->ip_states_state' are computed. - */ + */ { unsigned level; unsigned state1, state2; @@ -204,25 +204,25 @@ compute_ip_states_state (unsigned from, unsigned to, for (level = c->options.images_level + 1; level <= c->options.lc_max_level; level++) for (state1 = from; state1 <= to; state1++) - for (state2 = 0; state2 <= state1; state2++) + for (state2 = 0; state2 <= state1; state2++) if (need_image (state2, wfa)) { unsigned label; real_t ip = 0; - + for (label = 0; label < MAXLABELS; label++) { int domain1, domain2; unsigned edge1, edge2; real_t sum, weight2; - + if (ischild (domain1 = wfa->tree [state1][label])) { sum = 0; if (ischild (domain2 = wfa->tree [state2][label])) sum = get_ip_state_state (domain1, domain2, level - 1, c); - + for (edge2 = 0; isedge (domain2 = wfa->into [state2][label][edge2]); edge2++) @@ -238,12 +238,12 @@ compute_ip_states_state (unsigned from, unsigned to, edge1++) { real_t weight1 = wfa->weight [state1][label][edge1]; - + sum = 0; if (ischild (domain2 = wfa->tree [state2][label])) sum = get_ip_state_state (domain1, domain2, level - 1, c); - + for (edge2 = 0; isedge (domain2 = wfa->into [state2][label][edge2]); edge2++) @@ -262,10 +262,10 @@ compute_ip_states_state (unsigned from, unsigned to, /***************************************************************************** private code - + *****************************************************************************/ -static real_t +static real_t standard_ip_image_state (unsigned address, unsigned level, unsigned domain, const coding_t *c) /* @@ -283,18 +283,18 @@ standard_ip_image_state (unsigned address, unsigned level, unsigned domain, if (level > c->options.images_level) error ("We cannot interpret a Level %d image.", level); - + imageptr = &c->pixels [address * size_of_level (level)]; stateptr = c->images_of_state [domain] + address_of_level (level); - + for (i = size_of_level (level); i; i--) ip += *imageptr++ * *stateptr++; return ip; } -static real_t +static real_t standard_ip_state_state (unsigned domain1, unsigned domain2, unsigned level, const coding_t *c) /* @@ -315,7 +315,7 @@ standard_ip_state_state (unsigned domain1, unsigned domain2, unsigned level, state1ptr = c->images_of_state [domain1] + address_of_level (level); state2ptr = c->images_of_state [domain2] + address_of_level (level); - + for (i = size_of_level (level); i; i--) ip += *state1ptr++ * *state2ptr++; diff --git a/converter/other/fiasco/codec/prediction.c b/converter/other/fiasco/codec/prediction.c index e78e5acc..c592baa5 100644 --- a/converter/other/fiasco/codec/prediction.c +++ b/converter/other/fiasco/codec/prediction.c @@ -1,9 +1,9 @@ /* - * prediction.c: Range image prediction with MC or ND + * prediction.c: Range image prediction with MC or ND * * Written by: Ullrich Hafner * Michael Unger - * + * * This file is part of FIASCO (Fractal Image And Sequence COdec) * Copyright (C) 1994-2000 Ullrich Hafner */ @@ -41,7 +41,7 @@ /***************************************************************************** local variables - + *****************************************************************************/ typedef struct state_data @@ -71,7 +71,7 @@ typedef struct state_data /***************************************************************************** prototypes - + *****************************************************************************/ static real_t @@ -90,9 +90,9 @@ restore_state_data (unsigned from, unsigned to, unsigned max_level, /***************************************************************************** public code - + *****************************************************************************/ - + real_t predict_range (real_t max_costs, real_t price, range_t *range, wfa_t *wfa, coding_t *c, unsigned band, int y_state, unsigned states, @@ -124,11 +124,11 @@ predict_range (real_t max_costs, real_t price, range_t *range, wfa_t *wfa, rec_d_coeff_model = c->d_coeff->model; rec_tree_model = c->tree; rec_p_tree_model = c->p_tree; - rec_states = wfa->states; + rec_states = wfa->states; rec_pixels = c->pixels; rec_state_data = store_state_data (states, rec_states - 1, c->options.lc_max_level, wfa, c); - + /* * Restore probability models to the state before the recursive subdivision * has been started. @@ -141,14 +141,14 @@ predict_range (real_t max_costs, real_t price, range_t *range, wfa_t *wfa, c->coeff->model = c->coeff->model_duplicate (c->coeff, coeff_model); c->d_coeff->model = c->d_coeff->model_duplicate (c->d_coeff, d_coeff_model); - + if (c->mt->frame_type == I_FRAME) - costs = nd_prediction (max_costs, price, band, y_state, range, wfa, c); + costs = nd_prediction (max_costs, price, band, y_state, range, wfa, c); else costs = mc_prediction (max_costs, price, band, y_state, range, wfa, c); - + c->pixels = rec_pixels; - + if (costs < MAXCOSTS) { /* @@ -187,25 +187,25 @@ predict_range (real_t max_costs, real_t price, range_t *range, wfa_t *wfa, c->d_domain_pool->model_free (c->d_domain_pool->model); c->coeff->model_free (c->coeff->model); c->d_coeff->model_free (c->d_coeff->model); - + c->domain_pool->model = rec_domain_model; c->d_domain_pool->model = rec_d_domain_model; c->coeff->model = rec_coeff_model; c->d_coeff->model = rec_d_coeff_model; c->tree = rec_tree_model; c->p_tree = rec_p_tree_model; - + range->prediction = NO; - + if (wfa->states != states) remove_states (states, wfa); restore_state_data (states, rec_states - 1, c->options.lc_max_level, rec_state_data, wfa, c); costs = MAXCOSTS; } - + return costs; -} +} void clear_norms_table (unsigned level, const wfa_info_t *wi, motion_t *mt) @@ -238,11 +238,11 @@ update_norms_table (unsigned level, const wfa_info_t *wi, motion_t *mt) unsigned range_size = wi->half_pixel ? square (wi->search_range) : square (2 * wi->search_range); - + if (level > wi->p_min_level) { unsigned index; /* index of motion vector */ - + for (index = 0; index < range_size; index++) mt->mc_forward_norms [level][index] += mt->mc_forward_norms [level - 1][index]; @@ -256,7 +256,7 @@ update_norms_table (unsigned level, const wfa_info_t *wi, motion_t *mt) /***************************************************************************** private code - + *****************************************************************************/ static real_t @@ -273,7 +273,7 @@ mc_prediction (real_t max_costs, real_t price, unsigned band, int y_state, * If we are at the bottom level of the mc tree: * Fill in the norms table */ - if (prange.level == wfa->wfainfo->p_min_level) + if (prange.level == wfa->wfainfo->p_min_level) fill_norms_table (prange.x, prange.y, prange.level, wfa->wfainfo, c->mt); /* * Predict 'range' with motion compensation according to frame type. @@ -283,19 +283,19 @@ mc_prediction (real_t max_costs, real_t price, unsigned band, int y_state, find_P_frame_mc (mcpe, price, &prange, wfa->wfainfo, c->mt); else find_B_frame_mc (mcpe, price, &prange, wfa->wfainfo, c->mt); - + costs = (prange.mv_tree_bits + prange.mv_coord_bits) * price; - + if (costs < max_costs) /* motion vector not too expensive */ { unsigned last_state; /* last WFA state before recursion */ real_t *ipi [MAXSTATES]; /* inner products pointers */ unsigned state; real_t mvt, mvc; - + c->pixels = Calloc (width * height, sizeof (real_t)); cut_to_bintree (c->pixels, mcpe, width, height, 0, 0, width, height); - + /* * Approximate MCPE recursively. */ @@ -310,7 +310,7 @@ mc_prediction (real_t max_costs, real_t price, unsigned band, int y_state, mvc = prange.mv_coord_bits; mvt = prange.mv_tree_bits; - + prange.image = 0; prange.address = 0; prange.tree_bits = 0; @@ -329,7 +329,7 @@ mc_prediction (real_t max_costs, real_t price, unsigned band, int y_state, if (costs < max_costs) /* use motion compensation */ { unsigned img, adr; /* temp. values */ - + img = range->image; adr = range->address; *range = prange; @@ -362,7 +362,7 @@ mc_prediction (real_t max_costs, real_t price, unsigned band, int y_state, } else costs = MAXCOSTS; - + Free (mcpe); return costs; @@ -374,7 +374,7 @@ nd_prediction (real_t max_costs, real_t price, unsigned band, int y_state, { real_t costs; /* current approximation costs */ range_t lrange = *range; - + /* * Predict 'range' with DC component approximation */ @@ -397,11 +397,11 @@ nd_prediction (real_t max_costs, real_t price, unsigned band, int y_state, lrange.weights_bits = c->coeff->bits (&w, s, range->level, c->coeff); } costs = price * (lrange.weights_bits + lrange.nd_tree_bits); - + /* - * Recursive aproximation of difference image + * Recursive approximation of difference image */ - if (costs < max_costs) + if (costs < max_costs) { unsigned state; range_t rrange; /* range: recursive subdivision */ @@ -418,14 +418,14 @@ nd_prediction (real_t max_costs, real_t price, unsigned band, int y_state, unsigned n; real_t *src, *dst; /* pointers to image data */ real_t w = - lrange.weight [0] * c->images_of_state [0][0]; - - src = c->pixels + range->address * size_of_level (range->level); + + src = c->pixels + range->address * size_of_level (range->level); dst = c->pixels = pixels = Calloc (width * height, sizeof (real_t)); for (n = width * height; n; n--) *dst++ = *src++ + w; } - + /* * Approximate difference recursively. */ @@ -448,13 +448,13 @@ nd_prediction (real_t max_costs, real_t price, unsigned band, int y_state, c->ip_images_state[state] = Calloc (size_of_tree (c->products_level), sizeof (real_t)); } - + compute_ip_images_state (rrange.image, rrange.address, rrange.level, 1, 0, wfa, c); - + costs += subdivide (max_costs - costs, band, y_state, &rrange, wfa, c, NO, YES); - + Free (pixels); if (costs < max_costs && ischild (rrange.tree)) /* use prediction */ @@ -469,7 +469,7 @@ nd_prediction (real_t max_costs, real_t price, unsigned band, int y_state, range->address = adr; range->nd_tree_bits += lrange.nd_tree_bits; range->nd_weights_bits += lrange.weights_bits; - + for (edge = 0; isedge (lrange.into [edge]); edge++) { range->into [edge] = lrange.into [edge]; @@ -485,7 +485,7 @@ nd_prediction (real_t max_costs, real_t price, unsigned band, int y_state, } else costs = MAXCOSTS; - + for (state = 0; state <= last_state; state++) if (need_image (state, wfa)) { @@ -515,9 +515,9 @@ store_state_data (unsigned from, unsigned to, unsigned max_level, if (to < from) return NULL; /* nothing to do */ - + data = Calloc (to - from + 1, sizeof (state_data_t)); - + for (state = from; state <= to; state++) { sd = &data [state - from]; @@ -527,12 +527,12 @@ store_state_data (unsigned from, unsigned to, unsigned max_level, sd->domain_type = wfa->domain_type [state]; sd->images_of_state = c->images_of_state [state]; sd->inner_products = c->ip_images_state [state]; - + wfa->domain_type [state] = 0; c->images_of_state [state] = NULL; c->ip_images_state [state] = NULL; - - for (label = 0; label < MAXLABELS; label++) + + for (label = 0; label < MAXLABELS; label++) { sd->tree [label] = wfa->tree [state][label]; sd->y_state [label] = wfa->y_state [state][label]; @@ -542,11 +542,11 @@ store_state_data (unsigned from, unsigned to, unsigned max_level, sd->y [label] = wfa->y [state][label]; sd->prediction [label] = wfa->prediction [state][label]; - memcpy (sd->weight [label], wfa->weight [state][label], + memcpy (sd->weight [label], wfa->weight [state][label], sizeof (real_t) * (MAXEDGES + 1)); - memcpy (sd->int_weight [label], wfa->int_weight [state][label], + memcpy (sd->int_weight [label], wfa->int_weight [state][label], sizeof (word_t) * (MAXEDGES + 1)); - memcpy (sd->into [label], wfa->into [state][label], + memcpy (sd->into [label], wfa->into [state][label], sizeof (word_t) * (MAXEDGES + 1)); wfa->into [state][label][0] = NO_EDGE; @@ -569,7 +569,7 @@ restore_state_data (unsigned from, unsigned to, unsigned max_level, state_data_t *data, wfa_t *wfa, coding_t *c) /* * Restore all state data starting from state 'from'. - * + * * No return value. */ { @@ -578,15 +578,15 @@ restore_state_data (unsigned from, unsigned to, unsigned max_level, if (to < from) return; /* nothing to do */ - + for (state = from; state <= to; state++) { sd = &data [state - from]; - + wfa->final_distribution [state] = sd->final_distribution; wfa->level_of_state [state] = sd->level_of_state; wfa->domain_type [state] = sd->domain_type; - + if (c->images_of_state [state] != NULL) Free (c->images_of_state [state]); c->images_of_state [state] = sd->images_of_state; @@ -603,14 +603,14 @@ restore_state_data (unsigned from, unsigned to, unsigned max_level, wfa->x [state][label] = sd->x [label]; wfa->y [state][label] = sd->y [label]; wfa->prediction [state][label] = sd->prediction [label]; - - memcpy (wfa->weight [state][label], sd->weight [label], + + memcpy (wfa->weight [state][label], sd->weight [label], sizeof(real_t) * (MAXEDGES + 1)); - memcpy (wfa->int_weight [state][label], sd->int_weight [label], + memcpy (wfa->int_weight [state][label], sd->int_weight [label], sizeof(word_t) * (MAXEDGES + 1)); - memcpy (wfa->into [state][label], sd->into [label], + memcpy (wfa->into [state][label], sd->into [label], sizeof(word_t) * (MAXEDGES + 1)); - } + } for (level = c->options.images_level + 1; level <= max_level; level++) { diff --git a/converter/other/fiasco/codec/subdivide.c b/converter/other/fiasco/codec/subdivide.c index 348f838a..3ddf1ffc 100644 --- a/converter/other/fiasco/codec/subdivide.c +++ b/converter/other/fiasco/codec/subdivide.c @@ -2,7 +2,7 @@ * subdivide.c: Recursive subdivision of range images * * Written by: Ullrich Hafner - * + * * This file is part of FIASCO (Fractal Image And Sequence COdec) * Copyright (C) 1994-2000 Ullrich Hafner */ @@ -56,10 +56,10 @@ init_range (range_t *range, const image_t *image, unsigned band, /***************************************************************************** public code - + *****************************************************************************/ -real_t +real_t subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, wfa_t *wfa, coding_t *c, bool_t prediction, bool_t delta) /* @@ -71,7 +71,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, * If 'prediction' is TRUE then also test motion compensation or * nondeterministic approximation. * If 'delta' is TRUE then current range is already predicted. - * + * * Return value: * costs of the best approximation or MAXCOSTS if costs exceed 'max_costs' * @@ -82,7 +82,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, */ { real_t subdivide_costs; /* Costs arising from approx. the current - range with two childs */ + range with two children */ real_t lincomb_costs; /* Costs arising from approx. the current range with a linear combination */ int new_y_state [MAXLABELS]; /* Corresponding state of Y */ @@ -91,7 +91,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, bool_t try_nd; /* YES: try ND prediction */ unsigned states; /* Number of states before the recursive subdivision starts */ - void *domain_model; /* copy of domain pool model */ + void *domain_model; /* copy of domain pool model */ void *d_domain_model; /* copy of delta domain pool model */ void *lc_domain_model; /* copy of domain pool model */ void *lc_d_domain_model; /* copy of delta domain pool model */ @@ -103,17 +103,17 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, tree_t p_tree_model; /* copy of pred. tree model */ range_t lrange; /* range of lin. comb. approx. */ range_t rrange; /* range of recursive approx. */ - range_t child [MAXLABELS]; /* new childs of the current range */ + range_t child [MAXLABELS]; /* new children of the current range */ static unsigned percent = 0; /* status of progress meter */ if (wfa->wfainfo->level == range->level) percent = 0; - + range->into [0] = NO_EDGE; /* default approximation: empty */ range->tree = RANGE; if (range->level < 3) /* Don't process small ranges */ - return MAXCOSTS; + return MAXCOSTS; /* * If image permutation (tiling) is performed and the tiling level @@ -123,7 +123,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, && range->level == wfa->wfainfo->level - c->tiling->exponent) { unsigned width, height; /* size of range (dummies)*/ - + if (c->tiling->vorder [range->global_address] < 0) return 0; /* nothing to do */ else @@ -140,7 +140,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, * Check whether prediction is allowed or not * mc == motion compensation, nd == nondeterminism */ - try_mc = (prediction && c->mt->frame_type != I_FRAME + try_mc = (prediction && c->mt->frame_type != I_FRAME && range->level >= wfa->wfainfo->p_min_level && range->level <= wfa->wfainfo->p_max_level && (range->x + width_of_level (range->level) @@ -155,21 +155,21 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, if (try_mc) clear_norms_table (range->level, wfa->wfainfo, c->mt); - + /* * Check if current range must be initialized. I.e. range pixels must * be copied from entire image to bintree pixel buffer. Moreover, * all inner products tables must be initialized. */ - if (range->level == c->options.lc_max_level) + if (range->level == c->options.lc_max_level) init_range (range, c->mt->original, band, wfa, c); - + price = c->price; - if (band != Y) + if (band != Y) price *= c->options.chroma_decrease; /* less quality for chroma bands */ /* - * Compute childs of corresponding state in Y band + * Compute children of corresponding state in Y band */ if (band != Y) /* Cb and Cr bands only */ { @@ -183,7 +183,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, } else new_y_state [0] = new_y_state [1] = RANGE; - + /* * Store contents of all models that may get modified during recursion */ @@ -193,8 +193,8 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, d_coeff_model = c->d_coeff->model_duplicate (c->d_coeff, c->d_coeff->model); tree_model = c->tree; p_tree_model = c->p_tree; - states = wfa->states; - + states = wfa->states; + /* * First alternative of range approximation: * Compute costs of linear combination. @@ -208,10 +208,10 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, lrange.weights_bits = 0; lrange.mv_tree_bits = try_mc ? 1 : 0; /* mc allowed but not used */ lrange.mv_coord_bits = 0; - lrange.nd_tree_bits = 0; - lrange.nd_weights_bits = 0; + lrange.nd_tree_bits = 0; + lrange.nd_weights_bits = 0; lrange.prediction = NO; - + lincomb_costs = approximate_range (max_costs, price, c->options.max_elements, y_state, &lrange, @@ -219,7 +219,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, (delta ? c->d_coeff : c->coeff), wfa, c); } else - lincomb_costs = MAXCOSTS; + lincomb_costs = MAXCOSTS; /* * Store contents of models that have been modified @@ -237,7 +237,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, c->coeff->model = c->coeff->model_duplicate (c->coeff, coeff_model); c->d_coeff->model = c->d_coeff->model_duplicate (c->d_coeff, d_coeff_model); - + /* * Second alternative of range approximation: * Compute costs of recursive subdivision. @@ -245,8 +245,8 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, if (range->level > c->options.lc_min_level) /* range is large enough */ { unsigned label; - - memset (&child [0], 0, 2 * sizeof (range_t)); /* initialize childs */ + + memset (&child [0], 0, 2 * sizeof (range_t)); /* initialize children */ /* * Initialize a new range for recursive approximation @@ -260,7 +260,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, rrange.mv_coord_bits = 0; rrange.nd_tree_bits = try_nd ? tree_bits (CHILD, lrange.level, &c->p_tree): 0; - rrange.nd_weights_bits = 0; + rrange.nd_weights_bits = 0; rrange.prediction = NO; /* @@ -271,11 +271,11 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, + rrange.matrix_bits + rrange.mv_tree_bits + rrange.mv_coord_bits + rrange.nd_tree_bits + rrange.nd_weights_bits) * price; - - for (label = 0; label < MAXLABELS; label++) + + for (label = 0; label < MAXLABELS; label++) { real_t remaining_costs; /* upper limit for next recursion */ - + child[label].image = rrange.image * MAXLABELS + label + 1; child[label].address = rrange.address * MAXLABELS + label; child[label].global_address = rrange.global_address * MAXLABELS @@ -289,8 +289,8 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, ? (rrange.y + label * height_of_level (rrange.level - 1)) : rrange.y; - - /* + + /* * If necessary compute the inner products of the new states * (generated during the recursive approximation of child [0]) */ @@ -298,7 +298,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, compute_ip_images_state (child[label].image, child[label].address, child[label].level, 1, states, wfa, c); /* - * Call subdivide() for both childs. + * Call subdivide() for both children. * Abort the recursion if 'subdivide_costs' exceed 'lincomb_costs' * or 'max_costs'. */ @@ -315,10 +315,10 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, fill_norms_table (child[label].x, child[label].y, child[label].level, wfa->wfainfo, c->mt); } - + if (try_mc) update_norms_table (rrange.level, wfa->wfainfo, c->mt); - + /* * Update of progress meter */ @@ -327,7 +327,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, if (c->options.progress_meter == FIASCO_PROGRESS_PERCENT) { unsigned new_percent; /* new status of progress meter */ - + new_percent = (child[label].global_address + 1) * 100.0 / (1 << (wfa->wfainfo->level - child[label].level)); if (new_percent > percent) @@ -339,7 +339,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, else if (c->options.progress_meter == FIASCO_PROGRESS_BAR) { unsigned new_percent; /* new status of progress meter */ - + new_percent = (child[label].global_address + 1) * 50.0 / (1 << (wfa->wfainfo->level - child[label].level)); @@ -349,15 +349,15 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, } } } - + /* - * If costs of subdivision exceed costs of linear combination + * If costs of subdivision exceed costs of linear combination * then abort recursion. */ - if (subdivide_costs >= MIN(lincomb_costs, max_costs)) + if (subdivide_costs >= MIN(lincomb_costs, max_costs)) { subdivide_costs = MAXCOSTS; - break; + break; } rrange.err += child [label].err; rrange.tree_bits += child [label].tree_bits; @@ -379,8 +379,8 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, /* * Third alternative of range approximation: - * Predict range via motion compensation or nondeterminism and - * approximate delta image. + * Predict range via motion compensation or nondeterminism and + * approximate delta image. */ if (try_mc || try_nd) /* try prediction */ { @@ -403,7 +403,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, c->d_coeff->model_free (d_coeff_model); c->coeff->model_free (lc_coeff_model); c->d_coeff->model_free (lc_d_coeff_model); - + return prediction_costs; } } @@ -423,25 +423,25 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, c->d_coeff->model_free (c->d_coeff->model); c->coeff->model_free (lc_coeff_model); c->d_coeff->model_free (lc_d_coeff_model); - + c->domain_pool->model = domain_model; c->d_domain_pool->model = d_domain_model; c->coeff->model = coeff_model; c->d_coeff->model = d_coeff_model; c->tree = tree_model; c->p_tree = p_tree_model; - + if (wfa->states != states) remove_states (states, wfa); return MAXCOSTS; } - else if (lincomb_costs < subdivide_costs) + else if (lincomb_costs < subdivide_costs) { /* * Use the linear combination: The factors of the linear combination * are stored already in 'range', so revert the probability models - * only. + * only. */ c->domain_pool->model_free (c->domain_pool->model); c->d_domain_pool->model_free (c->d_domain_pool->model); @@ -452,7 +452,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, c->d_coeff->model_free (c->d_coeff->model); c->coeff->model_free (coeff_model); c->d_coeff->model_free (d_coeff_model); - + c->domain_pool->model = lc_domain_model; c->d_domain_pool->model = lc_d_domain_model; c->coeff->model = lc_coeff_model; @@ -461,7 +461,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, c->p_tree = p_tree_model; *range = lrange; - + if (wfa->states != states) remove_states (states, wfa); @@ -474,8 +474,8 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range, * given in child[]. * Don't use state in linear combinations in any of the following cases: * - if color component is Cb or Cr - * - if level of state > tiling level - * - if state is (partially) outside image geometry + * - if level of state > tiling level + * - if state is (partially) outside image geometry */ if (band > Y || (c->tiling->exponent @@ -545,7 +545,7 @@ cut_to_bintree (real_t *dst, const word_t *src, /***************************************************************************** private code - + *****************************************************************************/ static void @@ -558,7 +558,7 @@ init_new_state (bool_t auxiliary_state, bool_t delta, range_t *range, * If flag 'delta' is set then state represents a delta image (prediction via * nondeterminism or motion compensation). * 'range' the current range image, - * 'child []' the left and right childs of 'range'. + * 'child []' the left and right children of 'range'. * * No return value. * @@ -583,11 +583,11 @@ init_new_state (bool_t auxiliary_state, bool_t delta, range_t *range, } else state_is_domain = NO; - + range->into [0] = NO_EDGE; range->tree = wfa->states; - - for (label = 0; label < MAXLABELS; label++) + + for (label = 0; label < MAXLABELS; label++) { wfa->tree [wfa->states][label] = child [label].tree; wfa->y_state [wfa->states][label] = y_state [label]; @@ -605,7 +605,7 @@ init_new_state (bool_t auxiliary_state, bool_t delta, range_t *range, warning ("Negative image norm: %f, %f", child [0].err, child [1].err); /* state_is_domain = YES; */ - + append_state (!state_is_domain, compute_final_distribution (wfa->states, wfa), range->level, wfa, c); @@ -621,13 +621,13 @@ init_range (range_t *range, const image_t *image, unsigned band, * No return value. * * Side effects: - * 'c->pixels' are filled with pixel values of image block - * 'c->ip_images_state' are computed with respect to new image block + * 'c->pixels' are filled with pixel values of image block + * 'c->ip_images_state' are computed with respect to new image block * 'range->address' and 'range->image' are initialized with zero */ { unsigned state; - + /* * Clear already computed products */ @@ -640,7 +640,7 @@ init_range (range_t *range, const image_t *image, unsigned band, image->width, image->height, range->x, range->y, width_of_level (range->level), height_of_level (range->level)); - + range->address = range->image = 0; compute_ip_images_state (0, 0, range->level, 1, 0, wfa, c); } diff --git a/converter/other/fiasco/codec/wfa.h b/converter/other/fiasco/codec/wfa.h index 59020fc1..4e66ccbd 100644 --- a/converter/other/fiasco/codec/wfa.h +++ b/converter/other/fiasco/codec/wfa.h @@ -2,7 +2,7 @@ * wfa.h * * Written by: Ullrich Hafner - * + * * This file is part of FIASCO (Fractal Image And Sequence COdec) * Copyright (C) 1994-2000 Ullrich Hafner */ @@ -20,7 +20,7 @@ #define MAXEDGES 5 #define MAXSTATES 6000 #define MAXLABELS 2 /* only bintree possible anymore */ -#define MAXLEVEL 22 +#define MAXLEVEL 22 #define FIASCO_BINFILE_RELEASE 2 #define FIASCO_MAGIC "FIASCO" /* FIASCO magic number */ @@ -85,7 +85,7 @@ typedef struct wfa_info char *basis_name; /* filename of the initial basis */ char *title; /* title of FIASCO stream */ char *comment; /* comment for FIASCO stream */ - + unsigned max_states; /* max. cardinality of domain pool */ unsigned chroma_max_states; /* max. cardinality of domain pool for chroma band coding */ @@ -111,7 +111,7 @@ typedef struct wfa_info typedef struct wfa /* - * Used to store all informations and data structures of a WFA + * Used to store all information and data structures of a WFA */ { wfa_info_t *wfainfo; /* misc. information about the WFA */ diff --git a/converter/other/fiasco/doc/fiasco_c_options_new.3 b/converter/other/fiasco/doc/fiasco_c_options_new.3 index d873b642..a7a96409 100644 --- a/converter/other/fiasco/doc/fiasco_c_options_new.3 +++ b/converter/other/fiasco/doc/fiasco_c_options_new.3 @@ -407,11 +407,10 @@ during coding. The following types are available: .SH RETURN VALUES The function \fBfiasco_c_options_new()\fP returns a pointer to the -newly allocated coder option object. If an error has been catched, a +newly allocated coder option object. If an error has been caught, a NULL pointer is returned. -All set functions return 1 on success and 0 if an error has been -catched. +All set functions return 1 on success and 0 if an error has been caught. In case of an error, use the function fiasco_get_error_message(3) to get a string with the last error message of FIASCO. diff --git a/converter/other/fiasco/doc/fiasco_coder.3 b/converter/other/fiasco/doc/fiasco_coder.3 index 9f2e0f8e..ce32bb4d 100644 --- a/converter/other/fiasco/doc/fiasco_coder.3 +++ b/converter/other/fiasco/doc/fiasco_coder.3 @@ -73,7 +73,7 @@ available to change the default values. .SH RETURN VALUE The function \fBfiasco_coder()\fP returns 1 if the FIASCO file has -been successfully written. If an error has been catched during +been successfully written. If an error has been caught during compression, 0 is returned - use the function fiasco_get_error_message(3) to get the last error message of FIASCO. diff --git a/converter/other/fiasco/doc/fiasco_d_options_new.3 b/converter/other/fiasco/doc/fiasco_d_options_new.3 index d7f2181a..02feabb0 100644 --- a/converter/other/fiasco/doc/fiasco_d_options_new.3 +++ b/converter/other/fiasco/doc/fiasco_d_options_new.3 @@ -97,11 +97,11 @@ channel is only one half of the width and height of the luminance. .SH RETURN VALUES The function \fBfiasco_d_options_new()\fP returns a pointer to the -newly allocated decoder option object. If an error has been catched, a +newly allocated decoder option object. If an error has been caught, a NULL pointer is returned. All set functions return 1 on success and 0 if an error has been -catched. +caught. In case of an error, use the function fiasco_get_error_message(3) to get a string with the last error message of FIASCO. diff --git a/converter/other/fiasco/doc/fiasco_decoder_new.3 b/converter/other/fiasco/doc/fiasco_decoder_new.3 index 5d1d0d08..2af44f43 100644 --- a/converter/other/fiasco/doc/fiasco_decoder_new.3 +++ b/converter/other/fiasco/doc/fiasco_decoder_new.3 @@ -125,37 +125,37 @@ store the internal state of the decoder. .SH RETURN VALUES The function \fBfiasco_decoder_new()\fP returns a pointer to the newly -allocated decoder object. If an error has been catched, a NULL pointer +allocated decoder object. If an error has been caught, a NULL pointer is returned. The function \fBfiasco_decoder_write_frame()\fP returns 1 if the file has been successfully written. Otherwise, the function returns 0. The function \fBfiasco_decoder_get_frame()\fP returns a pointer to the -newly allocated FIASCO image object. If an error has been catched, a NULL +newly allocated FIASCO image object. If an error has been caught, a NULL pointer is returned. The function \fBfiasco_decoder_get_length()\fP returns the number of -frames of the FIASCO file. If an error has been catched, 0 is +frames of the FIASCO file. If an error has been caught, 0 is returned. The function \fBfiasco_decoder_get_rate()\fP returns the framerate (number of frames per second) of the FIASCO file. If an -error has been catched, 0 is returned. +error has been caught, 0 is returned. The function \fBfiasco_decoder_get_width()\fP returns the width of the -decoded frames of the FIASCO file. If an error has been catched, 0 is +decoded frames of the FIASCO file. If an error has been caught, 0 is returned. The function \fBfiasco_decoder_get_height()\fP returns the height of the -decoded frames of the FIASCO file. If an error has been catched, 0 is +decoded frames of the FIASCO file. If an error has been caught, 0 is returned. The function \fBfiasco_decoder_get_title()\fP returns an optional -title of the FIASCO file. If an error has been catched, 0 is returned. +title of the FIASCO file. If an error has been caught, 0 is returned. The function \fBfiasco_decoder_get_comment()\fP returns an optional -comment of the FIASCO file. If an error has been catched, 0 is returned. +comment of the FIASCO file. If an error has been caught, 0 is returned. The function \fBfiasco_decoder_is_color()\fP returns 0 if the decoded frames are grayscale images, otherwise a non-zero value is diff --git a/converter/other/fiasco/doc/fiasco_get_error_message.3 b/converter/other/fiasco/doc/fiasco_get_error_message.3 index ce53e6d9..da32c94e 100644 --- a/converter/other/fiasco/doc/fiasco_get_error_message.3 +++ b/converter/other/fiasco/doc/fiasco_get_error_message.3 @@ -3,7 +3,7 @@ .SH NAME .B fiasco_get_error_message -\- return string describing last error catched in FIASCO library +\- return string describing last error caught in FIASCO library .SH SYNOPSIS .B #include @@ -15,11 +15,11 @@ .SH DESCRIPTION The \fBfiasco_get_error_message()\fP function returns a string -describing the last error that has been catched in the FIASCO library. +describing the last error that has been caught in the FIASCO library. .SH RETURN VALUE The function \fBfiasco_get_error_message()\fP returns the appropriate -description string, or an empty string if no error has been catched so +description string, or an empty string if no error has been caught so far. .SH "SEE ALSO" diff --git a/converter/other/fiasco/doc/fiasco_image_new.3 b/converter/other/fiasco/doc/fiasco_image_new.3 index ac3297bf..e4701a14 100644 --- a/converter/other/fiasco/doc/fiasco_image_new.3 +++ b/converter/other/fiasco/doc/fiasco_image_new.3 @@ -61,14 +61,14 @@ the environment variable \fBFIASCO_IMAGES\fP. .SH RETURN VALUE The function \fBfiasco_image_new()\fP returns a pointer to the newly -allocated image object. If an error has been catched, a NULL pointer +allocated image object. If an error has been caught, a NULL pointer is returned. The function \fBfiasco_image_get_width()\fP returns the width of the -image. If an error has been catched, 0 is returned. +image. If an error has been caught, 0 is returned. The function \fBfiasco_image_get_height()\fP returns the height of the -image. If an error has been catched, 0 is returned. +image. If an error has been caught, 0 is returned. The function \fBfiasco_image_is_color()\fP returns 0 if the image object is a grayscale image, otherwise a non-zero value is returned. diff --git a/converter/other/fiasco/doc/fiasco_options_new.3 b/converter/other/fiasco/doc/fiasco_options_new.3 index f26586a7..884876c7 100644 --- a/converter/other/fiasco/doc/fiasco_options_new.3 +++ b/converter/other/fiasco/doc/fiasco_options_new.3 @@ -416,11 +416,11 @@ during coding. The following types are available: .SH RETURN VALUES The function \fBfiasco_decoder_new()\fP returns a pointer to the newly -allocated option object. If an error has been catched, a NULL pointer +allocated option object. If an error has been caught, a NULL pointer is returned. All set functions return 1 on success and 0 if an error has been -catched. +caught. In case of an error, use the function fiasco_get_error_message(3) to get a string with the last error message of FIASCO. diff --git a/converter/other/fiasco/doc/fiasco_renderer_new.3 b/converter/other/fiasco/doc/fiasco_renderer_new.3 index 8b5e47cd..54bbdbcf 100644 --- a/converter/other/fiasco/doc/fiasco_renderer_new.3 +++ b/converter/other/fiasco/doc/fiasco_renderer_new.3 @@ -97,7 +97,7 @@ fiasco_image_new(3). .SH RETURN VALUE The function \fBfiasco_renderer_new()\fP returns a pointer to the newly -allocated renderer object. If an error has been catched, a NULL pointer +allocated renderer object. If an error has been caught, a NULL pointer is returned. The function \fBfiasco_renderer_render()\fP returns 1 if the image diff --git a/converter/other/fiasco/input/basis.c b/converter/other/fiasco/input/basis.c index aa371ea1..e5ced0d0 100644 --- a/converter/other/fiasco/input/basis.c +++ b/converter/other/fiasco/input/basis.c @@ -1,8 +1,8 @@ /* - * basis.c: WFA initial basis files + * basis.c: WFA initial basis files * * Written by: Ullrich Hafner - * + * * This file is part of FIASCO (Fractal Image And Sequence COdec) * Copyright (C) 1994-2000 Ullrich Hafner */ @@ -44,29 +44,29 @@ typedef struct /***************************************************************************** prototypes - + *****************************************************************************/ static void small_init (basis_values_t *bv); -static basis_file_t const basis_files[] = { +static basis_file_t const basis_files[] = { {"small.fco", small_init}, {"small.wfa", small_init}, - {NULL, NULL} + {NULL, NULL} }; /***************************************************************************** public code - + *****************************************************************************/ bool_t get_linked_basis (const char *basis_name, wfa_t *wfa) /* - * Check wether given WFA initial basis 'basis_name' is already linked - * with the excecutable. If the basis is available then fill the 'wfa' struct + * Check whether given WFA initial basis 'basis_name' is already linked + * with the executable. If the basis is available then fill the 'wfa' struct * according to the stored data, otherwise print a warning message. * * Return value: @@ -79,18 +79,18 @@ get_linked_basis (const char *basis_name, wfa_t *wfa) bool_t success = NO; /* indicates if basis is found */ unsigned n; /* counter */ basis_values_t bv; /* basis values */ - + for (n = 0; basis_files [n].filename != NULL; n++) if (streq (basis_files [n].filename, basis_name)) /* basis is stored */ { - unsigned state, edge; - + unsigned state, edge; + (*basis_files [n].function) (&bv); /* initialize local variables */ /* * Generate WFA */ wfa->basis_states = wfa->states = bv.states + 1; - wfa->domain_type[0] = USE_DOMAIN_MASK; + wfa->domain_type[0] = USE_DOMAIN_MASK; wfa->final_distribution[0] = 128; append_edge (0, 0, 1.0, 0, wfa); append_edge (0, 0, 1.0, 1, wfa); @@ -105,13 +105,13 @@ get_linked_basis (const char *basis_name, wfa_t *wfa) append_edge (bv.transitions [edge][0], bv.transitions [edge][1], bv.transitions [edge][2], bv.transitions [edge][3], wfa); - + success = YES; break; } if (!success) - warning ("WFA initial basis '%s' isn't linked with the excecutable yet." + warning ("WFA initial basis '%s' isn't linked with the executable yet." "\nLoading basis from disk instead.", basis_name); return success; @@ -120,7 +120,7 @@ get_linked_basis (const char *basis_name, wfa_t *wfa) /***************************************************************************** private code - + *****************************************************************************/ /***************************************************************************** @@ -141,3 +141,6 @@ small_init (basis_values_t *bv) bv->use_domain = use_domain_small; bv->transitions = transitions_small; } + + + diff --git a/converter/other/fiasco/input/matrices.c b/converter/other/fiasco/input/matrices.c index 388855ea..d20a27eb 100644 --- a/converter/other/fiasco/input/matrices.c +++ b/converter/other/fiasco/input/matrices.c @@ -2,7 +2,7 @@ * matrices.c: Input of transition matrices * * Written by: Ullrich Hafner - * + * * This file is part of FIASCO (Fractal Image And Sequence COdec) * Copyright (C) 1994-2000 Ullrich Hafner */ @@ -34,7 +34,7 @@ /***************************************************************************** prototypes - + *****************************************************************************/ static unsigned @@ -49,19 +49,19 @@ compute_y_state (int state, int y_state, wfa_t *wfa); /***************************************************************************** public code - + *****************************************************************************/ unsigned read_matrices (wfa_t *wfa, bitfile_t *input) -/* +/* * Read transitions of WFA given from the stream 'input'. * * Return value: * number of edges * * Side effects: - * 'wfa->into' is filled with decoded values + * 'wfa->into' is filled with decoded values */ { unsigned total; /* total number of edges in the WFA */ @@ -73,14 +73,14 @@ read_matrices (wfa_t *wfa, bitfile_t *input) total += delta_decoding (wfa, root_state, input); if (wfa->wfainfo->color) total += chroma_decoding (wfa, input); - + return total; } /***************************************************************************** private code - + *****************************************************************************/ static unsigned @@ -94,7 +94,7 @@ delta_decoding (wfa_t *wfa, unsigned last_domain, bitfile_t *input) * number of non-zero matrix elements (WFA edges) * * Side effects: - * 'wfa->into' is filled with decoded values + * 'wfa->into' is filled with decoded values */ { range_sort_t rs; /* ranges are sorted as in the coder */ @@ -128,26 +128,26 @@ delta_decoding (wfa_t *wfa, unsigned last_domain, bitfile_t *input) arith_t *decoder; model_t *elements; unsigned max_edges = read_rice_code (3, input); - + /* * Get the probability array of the number of edges distribution * and allocate the corresponding model. */ { unsigned edge; - + for (edge = 0; edge <= max_edges; edge++) count [edge] = read_rice_code ((int) log2 (last_domain) - 2, input); elements = alloc_model (max_edges + 1, 0, 0, count); } - + /* * Get number of elements per matrix row */ { unsigned row; - + n_edges = Calloc (wfa->states, sizeof (unsigned)); decoder = alloc_decoder (input); for (row = range = 0; range < rs.range_no; range++) @@ -155,17 +155,17 @@ delta_decoding (wfa_t *wfa, unsigned last_domain, bitfile_t *input) { state = rs.range_state [range]; label = rs.range_label [range]; - + n_edges [row++] = decode_symbol (decoder, elements) - (isedge (wfa->into [state][label][0]) ? 1 : 0); } - + free_decoder (decoder); free_model (elements); } } - + /* * Get matrix elements */ @@ -177,18 +177,18 @@ delta_decoding (wfa_t *wfa, unsigned last_domain, bitfile_t *input) u_word_t *mapping_coder2 = Calloc (wfa->states, sizeof (word_t)); bool_t use_normal_domains = get_bit (input); bool_t use_delta_domains = get_bit (input); - + /* * Generate array of states which are admitted domains. * When coding intra frames 'mapping1' == 'mapping2' otherwise - * 'mapping1' is a list of 'normal' domains which are admitted for + * 'mapping1' is a list of 'normal' domains which are admitted for * coding intra blocks * 'mapping2' is a list of 'delta' domains which are admitted for - * coding the motion compensated prediction error + * coding the motion compensated prediction error */ { unsigned n1, n2, state; - + for (n1 = n2 = state = 0; state < wfa->states; state++) { mapping1 [n1] = state; @@ -197,7 +197,7 @@ delta_decoding (wfa_t *wfa, unsigned last_domain, bitfile_t *input) && (state < wfa->basis_states || use_delta_domains || !wfa->delta_state [state])) n1++; - + mapping2 [n2] = state; mapping_coder2 [state] = n2; if (usedomain (state, wfa) @@ -206,7 +206,7 @@ delta_decoding (wfa_t *wfa, unsigned last_domain, bitfile_t *input) n2++; } } - + for (row = 0, range = 0; range < rs.range_no; range++) if (!rs.range_subdivided [range]) { @@ -249,7 +249,7 @@ delta_decoding (wfa_t *wfa, unsigned last_domain, bitfile_t *input) Free (mapping2); Free (mapping_coder2); } - + Free (n_edges); Free (rs.range_state); Free (rs.range_label); @@ -265,12 +265,12 @@ column_0_decoding (wfa_t *wfa, unsigned last_row, bitfile_t *input) * Read column 0 of the transition matrices of the 'wfa' which are coded * with quasi arithmetic coding from stream 'input'. * All rows from 'wfa->basis_states' up to 'last_row' are decoded. - * + * * Return value: * number of non-zero matrix elements (WFA edges) * * Side effects: - * 'wfa->into' is filled with decoded values + * 'wfa->into' is filled with decoded values */ { unsigned row; /* current matrix row */ @@ -294,9 +294,9 @@ column_0_decoding (wfa_t *wfa, unsigned last_row, bitfile_t *input) unsigned n; unsigned index; /* probability index */ unsigned exp; /* current exponent */ - + prob = Calloc (1 << (MAX_PROB + 1), sizeof (unsigned)); - + for (index = 0, n = MIN_PROB; n <= MAX_PROB; n++) for (exp = 0; exp < 1U << n; exp++, index++) prob [index] = n; @@ -304,12 +304,12 @@ column_0_decoding (wfa_t *wfa, unsigned last_row, bitfile_t *input) first = prob_ptr = new_prob_ptr = prob; last = first + 1020; - + is_leaf = wfa->tree [wfa->basis_states]; /* use pointer arithmetics ... */ high = HIGH; /* 1.0 */ low = LOW; /* 0.0 */ - code = get_bits (input, 16); + code = get_bits (input, 16); /* * Decode column 0 with a quasi arithmetic coder (QAC). @@ -325,7 +325,7 @@ column_0_decoding (wfa_t *wfa, unsigned last_row, bitfile_t *input) for (row = wfa->basis_states; row <= last_row; row++) { unsigned count; /* value in the current interval */ - + /* * Read label 0 element */ @@ -397,7 +397,7 @@ column_0_decoding (wfa_t *wfa, unsigned last_row, bitfile_t *input) INPUT_BYTE_ALIGN (input); Free (prob); - + return total; } @@ -411,7 +411,7 @@ chroma_decoding (wfa_t *wfa, bitfile_t *input) * number of non-zero matrix elements (WFA edges) * * Side effects: - * 'wfa->into' is filled with decoded values + * 'wfa->into' is filled with decoded values */ { unsigned domain; /* current domain, counter */ @@ -425,7 +425,7 @@ chroma_decoding (wfa_t *wfa, bitfile_t *input) u_word_t low; /* End of the current code range */ u_word_t code; /* The present input code value */ word_t *y_domains; /* domain images corresponding to Y */ - int save_index; /* YES: store current probabilty */ + int save_index; /* YES: store current probability */ /* * Compute the asymmetric probability array @@ -436,9 +436,9 @@ chroma_decoding (wfa_t *wfa, bitfile_t *input) unsigned n; unsigned index; /* probability index */ unsigned exp; /* current exponent */ - + prob = Calloc (1 << (MAX_PROB + 1), sizeof (unsigned)); - + for (index = 0, n = MIN_PROB; n <= MAX_PROB; n++) for (exp = 0; exp < 1U << n; exp++, index++) prob [index] = n; @@ -454,7 +454,7 @@ chroma_decoding (wfa_t *wfa, bitfile_t *input) y_domains = compute_hits (wfa->basis_states, wfa->tree [wfa->tree [wfa->root_state][0]][0], wfa->wfainfo->chroma_max_states, wfa); - + first = prob_ptr = new_prob_ptr = prob; last = first + 1020; @@ -554,7 +554,7 @@ chroma_decoding (wfa_t *wfa, bitfile_t *input) wfa->tree [wfa->tree [wfa->root_state][0]][0], wfa); compute_y_state (wfa->tree [wfa->tree [wfa->root_state][1]][0], wfa->tree [wfa->tree [wfa->root_state][0]][0], wfa); - + first = prob_ptr = new_prob_ptr = prob; /* @@ -566,7 +566,7 @@ chroma_decoding (wfa_t *wfa, bitfile_t *input) */ { unsigned row; - + for (row = wfa->tree [wfa->tree [wfa->root_state][0]][0] + 1; row < wfa->states; row++) { @@ -629,7 +629,7 @@ compute_y_state (int state, int y_state, wfa_t *wfa) */ { unsigned label; - + for (label = 0; label < MAXLABELS; label++) if (isrange (y_state)) wfa->y_state [state][label] = RANGE; @@ -640,5 +640,7 @@ compute_y_state (int state, int y_state, wfa_t *wfa) compute_y_state (wfa->tree [state][label], wfa->y_state [state][label], wfa); } - + } + + diff --git a/converter/other/fiasco/input/mc.c b/converter/other/fiasco/input/mc.c index 2d4a073d..afc0c1c3 100644 --- a/converter/other/fiasco/input/mc.c +++ b/converter/other/fiasco/input/mc.c @@ -1,9 +1,9 @@ /* - * mc.c: Input of motion compensation + * mc.c: Input of motion compensation * * written by: Michael Unger * Ullrich Hafner - * + * * This file is part of FIASCO (Fractal Image And Sequence COdec) * Copyright (C) 1994-2000 Ullrich Hafner */ @@ -32,10 +32,10 @@ /***************************************************************************** local variables - + *****************************************************************************/ -typedef struct huff_node +typedef struct huff_node { int code_index; /* leaf if index >= 0 */ struct huff_node *left; /* follow if '0' bit read */ @@ -46,7 +46,7 @@ typedef struct huff_node /***************************************************************************** prototypes - + *****************************************************************************/ static void @@ -64,7 +64,7 @@ create_huff_node (huff_node_t *hn, int bits_processed); /***************************************************************************** public code - + *****************************************************************************/ void @@ -90,7 +90,7 @@ read_mc (frame_type_e frame_type, wfa_t *wfa, bitfile_t *input) /***************************************************************************** private code - + *****************************************************************************/ static void @@ -114,8 +114,8 @@ decode_mc_tree (frame_type_e frame_type, unsigned max_state, /* * Traverse tree in breadth first order (starting at level - * 'wfa->wfainfo->p_max_level'). Use a queue to store the childs - * of each node ('last' is the next free queue element). + * 'wfa->wfainfo->p_max_level'). Use a queue to store the children + * of each node ('last' is the next free queue element). */ queue = Calloc (MAXSTATES, sizeof (unsigned)); for (last = 0, state = wfa->basis_states; state < max_state; state++) @@ -126,7 +126,7 @@ decode_mc_tree (frame_type_e frame_type, unsigned max_state, { unsigned label; /* current label */ unsigned current; /* current node to process */ - + for (current = 0; current < last; current++) for (label = 0; label < MAXLABELS; label++) { @@ -147,7 +147,7 @@ decode_mc_tree (frame_type_e frame_type, unsigned max_state, if (wfa->mv_tree [state][label].type == NONE && !isrange (wfa->tree [state][label]) && wfa->level_of_state [state] - 1 >= - (int) wfa->wfainfo->p_min_level) + (int) wfa->wfainfo->p_min_level) queue [last++] = wfa->tree [state][label]; /* append child */ } } @@ -155,7 +155,7 @@ decode_mc_tree (frame_type_e frame_type, unsigned max_state, { unsigned label; /* current label */ unsigned current; /* current node to process */ - + for (current = 0; current < last; current++) for (label = 0; label < MAXLABELS; label++) { @@ -172,18 +172,18 @@ decode_mc_tree (frame_type_e frame_type, unsigned max_state, wfa->mv_tree[state][label].type = NONE; else if (get_bit (input)) /* 01 */ wfa->mv_tree[state][label].type = INTERPOLATED; - else if (get_bit (input)) /* 001 */ + else if (get_bit (input)) /* 001 */ wfa->mv_tree[state][label].type = BACKWARD; - else /* 000 */ + else /* 000 */ wfa->mv_tree[state][label].type = FORWARD; if (wfa->mv_tree[state][label].type == NONE && !isrange (wfa->tree[state][label]) && wfa->level_of_state[state] - 1 - >= (int) wfa->wfainfo->p_min_level) + >= (int) wfa->wfainfo->p_min_level) queue[last++] = wfa->tree[state][label]; /* append child */ } } - + INPUT_BYTE_ALIGN (input); Free (queue); } @@ -205,10 +205,10 @@ decode_mc_coords (unsigned max_state, wfa_t *wfa, bitfile_t *input) unsigned state; /* current state */ mv_t *mv; /* current motion vector */ static huff_node_t *huff_mv_root = NULL; /* root of huffman tree */ - + if (huff_mv_root == NULL) huff_mv_root = create_huff_tree (); - + for (state = wfa->basis_states; state < max_state; state++) for (label = 0; label < MAXLABELS; label++) { @@ -220,12 +220,12 @@ decode_mc_coords (unsigned max_state, wfa_t *wfa, bitfile_t *input) case FORWARD: mv->fx = get_mv (1, huff_mv_root, input); mv->fy = get_mv (1, huff_mv_root, input); - break; - case BACKWARD: + break; + case BACKWARD: mv->bx = get_mv (1, huff_mv_root, input); mv->by = get_mv (1, huff_mv_root, input); - break; - case INTERPOLATED: + break; + case INTERPOLATED: mv->fx = get_mv (1, huff_mv_root, input); mv->fy = get_mv (1, huff_mv_root, input); mv->bx = get_mv (1, huff_mv_root, input); @@ -236,11 +236,11 @@ decode_mc_coords (unsigned max_state, wfa_t *wfa, bitfile_t *input) INPUT_BYTE_ALIGN (input); } - + static int get_mv (int f_code, huff_node_t *hn, bitfile_t *input) -/* - * Decode next motion vector component in bitstream +/* + * Decode next motion vector component in bitstream * by traversing the huffman tree. */ { @@ -256,7 +256,7 @@ get_mv (int f_code, huff_node_t *hn, bitfile_t *input) hn = hn->left; } vlc_code = hn->code_index - 16; - if (vlc_code == 0 || f_code == 1) + if (vlc_code == 0 || f_code == 1) return vlc_code; vlc_code_magnitude = abs (vlc_code) - 1; @@ -265,7 +265,7 @@ get_mv (int f_code, huff_node_t *hn, bitfile_t *input) else residual = get_bits (input, f_code - 1); diffvec = (vlc_code_magnitude << (f_code - 1)) + residual + 1; - + return vlc_code > 0 ? diffvec : - diffvec; } @@ -277,7 +277,7 @@ create_huff_tree (void) { unsigned i; huff_node_t *huff_root = Calloc (1, sizeof (huff_node_t)); - + /* * The nodes' index set contains indices of all codewords that are * still decodable by traversing further down from the node. @@ -318,7 +318,7 @@ create_huff_node (huff_node_t *hn, int bits_processed) if (code_len == bits_processed) /* generate leaf */ { hn->code_index = ind; - Free (hn->left); + Free (hn->left); Free (hn->right); return; } @@ -332,3 +332,6 @@ create_huff_node (huff_node_t *hn, int bits_processed) create_huff_node (hn->left, bits_processed + 1); create_huff_node (hn->right, bits_processed + 1); } + + + diff --git a/converter/other/fiasco/input/nd.c b/converter/other/fiasco/input/nd.c index 52d48e61..129a150e 100644 --- a/converter/other/fiasco/input/nd.c +++ b/converter/other/fiasco/input/nd.c @@ -1,8 +1,8 @@ /* - * nd.c: Input of prediction tree + * nd.c: Input of prediction tree * * Written by: Ullrich Hafner - * + * * This file is part of FIASCO (Fractal Image And Sequence COdec) * Copyright (C) 1994-2000 Ullrich Hafner */ @@ -31,7 +31,7 @@ /***************************************************************************** prototypes - + *****************************************************************************/ static void @@ -42,7 +42,7 @@ decode_nd_tree (wfa_t *wfa, bitfile_t *input); /***************************************************************************** public code - + *****************************************************************************/ void @@ -56,7 +56,7 @@ read_nd (wfa_t *wfa, bitfile_t *input) */ { unsigned total = decode_nd_tree (wfa, input); - + if (total > 0) decode_nd_coefficients (total, wfa, input); } @@ -64,7 +64,7 @@ read_nd (wfa_t *wfa, bitfile_t *input) /***************************************************************************** private code - + *****************************************************************************/ static unsigned @@ -106,7 +106,7 @@ decode_nd_tree (wfa_t *wfa, bitfile_t *input) { unsigned label; - if (wfa->level_of_state [next] > wfa->wfainfo->p_max_level + 1) + if (wfa->level_of_state [next] > wfa->wfainfo->p_max_level + 1) { /* * Nondetermismn is not allowed at levels larger than @@ -114,7 +114,7 @@ decode_nd_tree (wfa_t *wfa, bitfile_t *input) */ for (label = 0; label < MAXLABELS; label++) if (ischild (state = wfa->tree [next][label])) - queue_append (queue, &state); /* continue with childs */ + queue_append (queue, &state); /* continue with children */ } else if (wfa->level_of_state [next] > wfa->wfainfo->p_min_level) { @@ -123,7 +123,7 @@ decode_nd_tree (wfa_t *wfa, bitfile_t *input) { unsigned count; /* Current interval count */ unsigned range; /* Current interval range */ - + count = (((code - low) + 1) * sum1 - 1) / ((high - low) + 1); if (count < sum0) { @@ -192,7 +192,7 @@ decode_nd_tree (wfa_t *wfa, bitfile_t *input) static void decode_nd_coefficients (unsigned total, wfa_t *wfa, bitfile_t *input) /* - * Read #'total' weights of nondeterministic part of 'wfa' + * Read #'total' weights of nondeterministic part of 'wfa' * of given 'input' stream. * 'frame' gives the current frame number. * @@ -204,24 +204,24 @@ decode_nd_coefficients (unsigned total, wfa_t *wfa, bitfile_t *input) { unsigned *coefficients; /* array of factors to encode */ unsigned *ptr; /* pointer to current factor */ - + /* * Decode array of coefficients stored with arithmetic coding */ { const int scaling = 50; /* scaling factor of prob. model */ unsigned c_symbols = 1 << (wfa->wfainfo->dc_rpf->mantissa_bits + 1); - + ptr = coefficients = decode_array (input, NULL, &c_symbols, 1, total, scaling); } - + /* * Fill 'wfa->weights' with decoded coefficients */ { unsigned state, label; - + for (state = wfa->basis_states; state < wfa->states; state++) for (label = 0; label < MAXLABELS; label++) if (ischild (wfa->tree [state][label]) @@ -235,3 +235,6 @@ decode_nd_coefficients (unsigned total, wfa_t *wfa, bitfile_t *input) } Free (coefficients); } + + + diff --git a/converter/other/fiasco/input/read.c b/converter/other/fiasco/input/read.c index 9f4ac993..b4fcefc5 100644 --- a/converter/other/fiasco/input/read.c +++ b/converter/other/fiasco/input/read.c @@ -2,7 +2,7 @@ * read.c: Input of WFA files * * Written by: Ullrich Hafner - * + * * This file is part of FIASCO (Fractal Image And Sequence COdec) * Copyright (C) 1994-2000 Ullrich Hafner */ @@ -47,7 +47,7 @@ /***************************************************************************** prototypes - + *****************************************************************************/ static void @@ -57,7 +57,7 @@ read_tiling (tiling_t *tiling, unsigned image_width, unsigned image_height, /***************************************************************************** public code - + *****************************************************************************/ bitfile_t * @@ -69,14 +69,14 @@ open_wfa (const char *filename, wfa_info_t *wi) * Pointer to input stream (fileposition: first WFA frame) * * Side effects: - * The values of the header of 'filename' are copied to 'wfainfo'. + * The values of the header of 'filename' are copied to 'wfainfo'. * */ { bitfile_t *input; /* pointer to WFA bitfile */ - + assert (filename && wi); - + wi->wfa_name = strdup (filename); /* @@ -85,16 +85,16 @@ open_wfa (const char *filename, wfa_info_t *wi) { unsigned n; const char *str; - + if (!(input = open_bitfile (filename, "FIASCO_DATA", READ_ACCESS))) file_error (filename); - + for (str = FIASCO_MAGIC, n = strlen (FIASCO_MAGIC); n; n--) if (get_bits (input, 8) != (unsigned) *str++) error ("Input file %s is not a valid FIASCO file!", filename); get_bits (input, 8); /* fetch newline */ } - + /* * Read WFA header information */ @@ -102,13 +102,13 @@ open_wfa (const char *filename, wfa_info_t *wi) char basis_name [MAXSTRLEN]; /* temp. buffer */ const unsigned rice_k = 8; /* parameter of Rice Code */ char *str = basis_name; - + while ((*str++ = get_bits (input, 8)) != 0 && str < basis_name + MAXSTRLEN) ; if (str == basis_name + MAXSTRLEN) error ("Input file %s is not a valid FIASCO file!", filename); - + { wi->release = read_rice_code (rice_k, input); @@ -121,12 +121,12 @@ open_wfa (const char *filename, wfa_info_t *wi) if (wi->release > 1) { header_type_e type; - + while ((type = read_rice_code (rice_k, input)) != HEADER_END) { char buffer [MAXSTRLEN]; unsigned n = 0; - + switch (type) { case HEADER_TITLE: @@ -157,7 +157,7 @@ open_wfa (const char *filename, wfa_info_t *wi) { unsigned lx = log2 (wi->width - 1) + 1; unsigned ly = log2 (wi->height - 1) + 1; - + wi->level = MAX(lx, ly) * 2 - ((ly == lx + 1) ? 1 : 0); } wi->chroma_max_states = wi->color ? read_rice_code (rice_k, input) : -1; @@ -176,14 +176,14 @@ open_wfa (const char *filename, wfa_info_t *wi) mantissa = get_bits (input, 3) + 2; range = get_bits (input, 2); wi->rpf = alloc_rpf (mantissa, range); - + if (get_bit (input)) /* different DC model */ { mantissa = get_bits (input, 3) + 2; range = get_bits (input, 2); wi->dc_rpf = alloc_rpf (mantissa, range); } - else /* use same model for DC coefficents */ + else /* use same model for DC coefficients */ wi->dc_rpf = alloc_rpf (wi->rpf->mantissa_bits, wi->rpf->range_e); @@ -196,7 +196,7 @@ open_wfa (const char *filename, wfa_info_t *wi) else wi->d_rpf = alloc_rpf (wi->rpf->mantissa_bits, wi->rpf->range_e); - + if (get_bit (input)) /* different DC delta model */ { mantissa = get_bits (input, 3) + 2; @@ -216,7 +216,7 @@ open_wfa (const char *filename, wfa_info_t *wi) wi->B_as_past_ref = get_bit (input) ? YES : NO; } } - + INPUT_BYTE_ALIGN (input); return input; @@ -246,10 +246,10 @@ read_basis (const char *filename, wfa_t *wfa) Free (wfa->wfainfo->basis_name); wfa->wfainfo->basis_name = strdup (filename); } - + if (get_linked_basis (filename, wfa)) - return; /* basis is linked with excecutable */ - + return; /* basis is linked with executable */ + /* * Check whether 'wfa_name' is a regular ASCII WFA initial basis file */ @@ -258,19 +258,19 @@ read_basis (const char *filename, wfa_t *wfa) if (!(input = open_file (filename, "FIASCO_DATA", READ_ACCESS))) file_error(filename); - + if (fscanf (input, MAXSTRLEN_SCANF, magic) != 1) error ("Format error: ASCII FIASCO initial basis file %s", filename); else if (strneq (FIASCO_BASIS_MAGIC, magic)) error ("Input file %s is not an ASCII FIASCO initial basis!", filename); } - + /* * WFA ASCII format: * * Note: State 0 is assumed to be the constant function f(x, y) = 128. - * Don't define any transitions of state 0 in an initial basis. + * Don't define any transitions of state 0 in an initial basis. * * Header: * type |description @@ -307,14 +307,14 @@ read_basis (const char *filename, wfa_t *wfa) /* * State 0 is assumed to be the constant function f(x, y) = 128. */ - wfa->domain_type [0] = USE_DOMAIN_MASK; + wfa->domain_type [0] = USE_DOMAIN_MASK; wfa->final_distribution [0] = 128; wfa->states = wfa->basis_states; wfa->basis_states++; append_edge (0, 0, 1.0, 0, wfa); append_edge (0, 0, 1.0, 1, wfa); - + for (state = 1; state < wfa->basis_states; state++) wfa->domain_type [state] = read_int (input) ? USE_DOMAIN_MASK : AUXILIARY_MASK; @@ -343,7 +343,7 @@ read_basis (const char *filename, wfa_t *wfa) } } } - + fclose (input); } @@ -353,7 +353,7 @@ read_next_wfa (wfa_t *wfa, bitfile_t *input) * Read next WFA frame of the WFA stream 'input'. * WFA header information has to be already present in the 'wfainfo' struct. * (i.e. open_wfa must be called first!) - * + * * No return value. * * Side effects: @@ -364,9 +364,9 @@ read_next_wfa (wfa_t *wfa, bitfile_t *input) { tiling_t tiling; /* tiling information */ unsigned frame_number; /* current frame number */ - + assert (wfa && input); - + /* * Frame header information */ @@ -382,16 +382,16 @@ read_next_wfa (wfa_t *wfa, bitfile_t *input) { INPUT_BYTE_ALIGN (input); } - + /* - * Read image tiling info + * Read image tiling info */ if (get_bit (input)) /* tiling performed ? */ read_tiling (&tiling, wfa->wfainfo->width, wfa->wfainfo->height, wfa->wfainfo->level, input); else tiling.exponent = 0; - + INPUT_BYTE_ALIGN (input); read_tree (wfa, &tiling, input); @@ -402,7 +402,7 @@ read_next_wfa (wfa_t *wfa, bitfile_t *input) */ { unsigned state; - + for (state = wfa->basis_states; state < wfa->states; state++) if ((!wfa->wfainfo->color || (int) state <= wfa->tree [wfa->tree [wfa->root_state][0]][0]) @@ -420,7 +420,7 @@ read_next_wfa (wfa_t *wfa, bitfile_t *input) else wfa->domain_type [state] = 0; } - + if (tiling.exponent) Free (tiling.vorder); @@ -431,12 +431,12 @@ read_next_wfa (wfa_t *wfa, bitfile_t *input) read_mc (wfa->frame_type, wfa, input); locate_delta_images (wfa); - + /* * Read linear combinations (coefficients and indices) */ { - unsigned edges = read_matrices (wfa, input); + unsigned edges = read_matrices (wfa, input); if (edges) read_weights (edges, wfa, input); @@ -447,7 +447,7 @@ read_next_wfa (wfa_t *wfa, bitfile_t *input) */ { unsigned state; - + for (state = wfa->basis_states; state <= wfa->states; state++) wfa->final_distribution[state] = compute_final_distribution (state, wfa); @@ -459,7 +459,7 @@ read_next_wfa (wfa_t *wfa, bitfile_t *input) /***************************************************************************** private code - + *****************************************************************************/ static void @@ -468,14 +468,14 @@ read_tiling (tiling_t *tiling, unsigned image_width, unsigned image_height, /* * Read image tiling information from the given file 'input' * and store parameters in struct 'tiling'. - * + * * No return value. */ { const unsigned rice_k = 8; /* parameter of Rice Code */ - + tiling->exponent = read_rice_code (rice_k, input); - + if (get_bit (input)) /* variance order */ { unsigned tile; /* current image tile */ @@ -487,7 +487,7 @@ read_tiling (tiling_t *tiling, unsigned image_width, unsigned image_height, { locate_subimage (image_level, image_level - tiling->exponent, tile, &x0, &y0, &width, &height); - if (x0 < image_width && y0 < image_height) + if (x0 < image_width && y0 < image_height) tiling->vorder [tile] = get_bits (input, tiling->exponent); else tiling->vorder [tile] = -1; @@ -500,3 +500,6 @@ read_tiling (tiling_t *tiling, unsigned image_width, unsigned image_height, tiling->exponent, get_bit (input) ? YES : NO); } } + + + diff --git a/converter/other/fiasco/input/tree.c b/converter/other/fiasco/input/tree.c index 0ac2b6ae..74ceeb68 100644 --- a/converter/other/fiasco/input/tree.c +++ b/converter/other/fiasco/input/tree.c @@ -2,7 +2,7 @@ * tree.c: Input of bintree partitioning * * Written by: Ullrich Hafner - * + * * This file is part of FIASCO (Fractal Image And Sequence COdec) * Copyright (C) 1994-2000 Ullrich Hafner */ @@ -31,7 +31,7 @@ /***************************************************************************** prototypes - + *****************************************************************************/ static unsigned @@ -39,14 +39,14 @@ restore_depth_first_order (unsigned src_state, unsigned level, unsigned x, unsigned y, unsigned *dst_state, word_t (*bfo_tree)[MAXLABELS], wfa_t *wfa, tiling_t *tiling); -static void +static void decode_tree (bitfile_t *input, byte_t *data, unsigned n_data, unsigned scaling, u_word_t sum0, u_word_t sum1); /***************************************************************************** public code - + *****************************************************************************/ void @@ -64,7 +64,7 @@ read_tree (wfa_t *wfa, tiling_t *tiling, bitfile_t *input) { byte_t *bitstring; /* the encoded data */ word_t (*bfo_tree)[MAXLABELS]; /* node numbers in BFO */ - + /* * Read WFA tree stored in breadth first order */ @@ -75,7 +75,7 @@ read_tree (wfa_t *wfa, tiling_t *tiling, bitfile_t *input) bitstring = Calloc (total, sizeof (byte_t)); decode_tree (input, bitstring, total, scale, 1, 11); } - + /* * Generate tree using a breadth first traversal */ @@ -84,7 +84,7 @@ read_tree (wfa_t *wfa, tiling_t *tiling, bitfile_t *input) unsigned state; unsigned label; byte_t *buffer = bitstring; /* pointer to decoded data */ - + bfo_tree = Calloc (wfa->states * MAXLABELS, sizeof (word_t)); for (state = 0, next = 1; state < next; state++) for (label = 0; label < MAXLABELS; label++) @@ -110,7 +110,7 @@ read_tree (wfa_t *wfa, tiling_t *tiling, bitfile_t *input) /***************************************************************************** private code - + *****************************************************************************/ static unsigned @@ -119,13 +119,13 @@ restore_depth_first_order (unsigned src_state, unsigned level, unsigned x, word_t (*bfo_tree)[MAXLABELS], wfa_t *wfa, tiling_t *tiling) /* - * Map state 'src_state' (breadth first order) + * Map state 'src_state' (breadth first order) * to state '*dst_state' (depth first order) * Add a tree edge 'state' --> 'child' with label and weight 1.0 * if required. * 'x', 'y' give the coordinates of the current state in the 'color' image - * of size 'image_level'. 'tiling' defines the image partitioning. - * + * of size 'image_level'. 'tiling' defines the image partitioning. + * * Return value: * new node number in depth first order * @@ -134,8 +134,8 @@ restore_depth_first_order (unsigned src_state, unsigned level, unsigned x, * are filled with decoded values. */ { - unsigned newx [MAXLABELS]; /* x coordinate of childs */ - unsigned newy [MAXLABELS]; /* y coordinate of childs */ + unsigned newx [MAXLABELS]; /* x coordinate of children */ + unsigned newy [MAXLABELS]; /* y coordinate of children */ unsigned x0, y0; /* NW corner of image tile */ unsigned width, height; /* size of image tile */ @@ -145,7 +145,7 @@ restore_depth_first_order (unsigned src_state, unsigned level, unsigned x, if (tiling->exponent && level == wfa->wfainfo->level - tiling->exponent) { unsigned tile; - + for (tile = 0; tile < 1U << tiling->exponent; tile++) { locate_subimage (wfa->wfainfo->level, level, tile, @@ -159,7 +159,7 @@ restore_depth_first_order (unsigned src_state, unsigned level, unsigned x, } } /* - * Coordinates of childs 0 and 1 + * Coordinates of children 0 and 1 */ if (wfa->wfainfo->color && level == wfa->wfainfo->level + 1) newx[0] = newy[0] = newx[1] = newy[1] = 0; @@ -170,12 +170,12 @@ restore_depth_first_order (unsigned src_state, unsigned level, unsigned x, newx[1] = level & 1 ? x : x + width_of_level (level - 1); newy[1] = level & 1 ? y + height_of_level (level - 1) : y; } - + /* * Remap node numbers */ { - int child [MAXLABELS]; /* childs of current node (state) */ + int child [MAXLABELS]; /* children of current node (state) */ int domain; /* current domain */ unsigned label; @@ -196,17 +196,17 @@ restore_depth_first_order (unsigned src_state, unsigned level, unsigned x, } wfa->level_of_state [*dst_state] = level; } - + return (*dst_state)++; -} +} /**************************************************************************** Binary adaptive arithmetic compression - + ****************************************************************************/ -static void +static void decode_tree (bitfile_t *input, byte_t *data, unsigned n_data, unsigned scaling, u_word_t sum0, u_word_t sum1) /* @@ -235,11 +235,11 @@ decode_tree (bitfile_t *input, byte_t *data, unsigned n_data, unsigned scaling, low = 0; high = 0xffff; - for (n = n_data; n; n--) + for (n = n_data; n; n--) { unsigned count; /* Current interval count */ unsigned range; /* Current interval range */ - + count = (((code - low) + 1) * sum1 - 1) / ((high - low) + 1); if (count < sum0) { diff --git a/converter/other/fiasco/lib/arith.c b/converter/other/fiasco/lib/arith.c index 825d4757..e61e753e 100644 --- a/converter/other/fiasco/lib/arith.c +++ b/converter/other/fiasco/lib/arith.c @@ -2,7 +2,7 @@ * arith.c: Adaptive arithmetic coding and decoding * * Written by: Ullrich Hafner - * + * * This file is part of FIASCO (Fractal Image And Sequence COdec) * Copyright (C) 1994-2000 Ullrich Hafner */ @@ -27,7 +27,7 @@ /****************************************************************************** public code - + ******************************************************************************/ arith_t * @@ -35,7 +35,7 @@ alloc_encoder (bitfile_t *output) /* * Arithmetic coder constructor: * Initialize the arithmetic coder. - * + * * Return value: * A pointer to the new coder structure */ @@ -43,7 +43,7 @@ alloc_encoder (bitfile_t *output) arith_t *arith = Calloc (1, sizeof (arith_t)); assert (output); - + arith->low = LOW; arith->high = HIGH; arith->underflow = 0; @@ -58,7 +58,7 @@ free_encoder (arith_t *arith) * Arithmetic encoder destructor. * Flush the arithmetic coder. Append all remaining bits to the * output stream. Append zero bits to get the output file byte aligned. - * + * * No return value. */ { @@ -66,14 +66,14 @@ free_encoder (arith_t *arith) u_word_t high; /* end of the current code range */ u_word_t underflow; /* number of underflow bits pending */ bitfile_t *output; - + assert (arith); low = arith->low; high = arith->high; underflow = arith->underflow; output = arith->file; - + low = high; RESCALE_OUTPUT_INTERVAL; @@ -92,7 +92,7 @@ encode_symbol (unsigned symbol, arith_t *arith, model_t *model) * * The model is updated after encoding the symbol (if necessary the * symbol counts are rescaled). - * + * * Return value: * information content of the encoded symbol. * @@ -110,7 +110,7 @@ encode_symbol (unsigned symbol, arith_t *arith, model_t *model) u_word_t high; /* end of the current code range */ u_word_t underflow; /* number of underflow bits pending */ bitfile_t *output; /* output file */ - + assert (model && arith); /* @@ -122,7 +122,7 @@ encode_symbol (unsigned symbol, arith_t *arith, model_t *model) output = arith->file; assert (high > low); - + if (model->order > 0) /* order-'n' model*/ { unsigned power; /* multiplicator */ @@ -134,10 +134,10 @@ encode_symbol (unsigned symbol, arith_t *arith, model_t *model) */ power = 1; /* multiplicator */ index = 0; /* address of prob. model */ - - for (i = 0; i < model->order; i++) /* genarate a M-nary number */ + + for (i = 0; i < model->order; i++) /* generate a M-nary number */ { - index += model->context [i] * power; + index += model->context [i] * power; power *= model->symbols; } @@ -160,9 +160,9 @@ encode_symbol (unsigned symbol, arith_t *arith, model_t *model) range = (high - low) + 1; high = low + (u_word_t) ((range * high_count) / scale - 1); low = low + (u_word_t) ((range * low_count) / scale); - + RESCALE_OUTPUT_INTERVAL; - + if (model->scale > 0) /* adaptive model */ { unsigned i; @@ -189,7 +189,7 @@ encode_symbol (unsigned symbol, arith_t *arith, model_t *model) arith->low = low; arith->high = high; arith->underflow = underflow; - + return - log2 ((high_count - low_count) / (real_t) scale); } @@ -214,21 +214,21 @@ encode_array (bitfile_t *output, const unsigned *data, const unsigned *context, assert (output && c_symbols && data); assert (n_context == 1 || context); - + /* * Allocate probability models, start with uniform distribution */ totals = Calloc (n_context, sizeof (u_word_t *)); { unsigned c; - + for (c = 0; c < n_context; c++) { unsigned i; - + totals [c] = Calloc (c_symbols [c] + 1, sizeof (u_word_t)); totals [c][0] = 0; - + for (i = 0; i < c_symbols [c]; i++) totals [c][i + 1] = totals [c][i] + 1; } @@ -242,7 +242,7 @@ encode_array (bitfile_t *output, const unsigned *data, const unsigned *context, u_word_t high = 0xffff; /* End of the current code range */ u_word_t underflow = 0; /* Number of underflow bits pending */ unsigned n; - + for (n = 0; n < n_data; n++) { u_word_t low_count; /* lower bound of 'symbol' interval */ @@ -253,8 +253,8 @@ encode_array (bitfile_t *output, const unsigned *data, const unsigned *context, int c; /* context of current data symbol */ d = data [n]; - c = n_context > 1 ? context [n] : 0; - + c = n_context > 1 ? context [n] : 0; + scale = totals [c][c_symbols [c]]; low_count = totals [c][d]; high_count = totals [c][d + 1]; @@ -266,7 +266,7 @@ encode_array (bitfile_t *output, const unsigned *data, const unsigned *context, high = low + (u_word_t) ((range * high_count) / scale - 1); low = low + (u_word_t) ((range * low_count) / scale); RESCALE_OUTPUT_INTERVAL; - + /* * Update probability models */ @@ -275,7 +275,7 @@ encode_array (bitfile_t *output, const unsigned *data, const unsigned *context, for (i = d + 1; i < c_symbols [c] + 1; i++) totals [c][i]++; - + if (totals [c][c_symbols [c]] > scaling) /* scaling */ for (i = 1; i < c_symbols [c] + 1; i++) { @@ -292,7 +292,7 @@ encode_array (bitfile_t *output, const unsigned *data, const unsigned *context, RESCALE_OUTPUT_INTERVAL; OUTPUT_BYTE_ALIGN (output); } - + /* * Cleanup ... */ @@ -310,16 +310,16 @@ alloc_decoder (bitfile_t *input) * Arithmetic decoder constructor: * Initialize the arithmetic decoder with the first * 16 input bits from the stream 'input'. - * + * * Return value: * A pointer to the new decoder structure */ { arith_t *arith = Calloc (1, sizeof (arith_t)); - + assert (input); - + arith->low = LOW; arith->high = HIGH; arith->code = get_bits (input, 16); @@ -333,8 +333,8 @@ free_decoder (arith_t *arith) /* * Arithmetic decoder destructor: * Flush the arithmetic decoder, i.e., read bits to get the input - * file byte aligned. - * + * file byte aligned. + * * No return value. * * Side effects: @@ -354,8 +354,8 @@ decode_symbol (arith_t *arith, model_t *model) * Decode the next symbol - the state of the arithmetic decoder * is given in 'arith'. Read refinement bits from the stream 'input' * and use the given probability 'model'. Update the probability model after - * deconding the symbol (if necessary also rescale the symbol counts). - * + * decoding the symbol (if necessary also rescale the symbol counts). + * * Return value: * decoded symbol * @@ -375,7 +375,7 @@ decode_symbol (arith_t *arith, model_t *model) bitfile_t *input; /* input file */ assert (arith && model); - + /* * Get interval values */ @@ -385,22 +385,22 @@ decode_symbol (arith_t *arith, model_t *model) input = arith->file; assert (high > low); - + if (model->order > 0) /* order-'n' model */ { unsigned power; /* multiplicator */ unsigned i; - + /* * Compute index of the probability model to use. * See init_model() for more details. */ power = 1; /* multiplicator */ index = 0; /* address of prob. model */ - - for (i = 0; i < model->order; i++) /* genarate a m-nary number */ + + for (i = 0; i < model->order; i++) /* generate a m-nary number */ { - index += model->context[i] * power; + index += model->context[i] * power; power *= model->symbols; } @@ -420,7 +420,7 @@ decode_symbol (arith_t *arith, model_t *model) if (model->order > 0) /* order-'n' model */ { unsigned i; - + for (i = 0; i < model->order - 1; i++) model->context [i] = model->context [i + 1]; model->context [i] = symbol; @@ -432,15 +432,15 @@ decode_symbol (arith_t *arith, model_t *model) { u_word_t low_count; /* lower bound of 'symbol' interval */ u_word_t high_count; /* upper bound of 'symbol' interval */ - + low_count = model->totals [index + symbol]; high_count = model->totals [index + symbol + 1]; high = low + (u_word_t) ((range * high_count) / scale - 1 ); low = low + (u_word_t) ((range * low_count) / scale ); } - + RESCALE_INPUT_INTERVAL; - + if (model->scale > 0) /* adaptive model */ { unsigned i; @@ -460,7 +460,7 @@ decode_symbol (arith_t *arith, model_t *model) } } } - + /* * Store interval values */ @@ -488,28 +488,28 @@ decode_array (bitfile_t *input, const unsigned *context, { unsigned *data; /* array to store decoded symbols */ u_word_t **totals; /* probability model */ - + if (n_context < 1) n_context = 1; /* always use one context */ assert (input && c_symbols); assert (n_context == 1 || context); data = Calloc (n_data, sizeof (unsigned)); - + /* * Allocate probability models, start with uniform distribution */ totals = Calloc (n_context, sizeof (u_word_t *)); { unsigned c; - + for (c = 0; c < n_context; c++) { unsigned i; - + totals [c] = Calloc (c_symbols [c] + 1, sizeof (u_word_t)); totals [c][0] = 0; - + for (i = 0; i < c_symbols [c]; i++) totals [c][i + 1] = totals [c][i] + 1; } @@ -523,8 +523,8 @@ decode_array (bitfile_t *input, const unsigned *context, u_word_t low = 0; /* Start of the current code range */ u_word_t high = 0xffff; /* End of the current code range */ unsigned n; - - for (n = 0; n < n_data; n++) + + for (n = 0; n < n_data; n++) { u_word_t scale; /* range of all 'm' symbol intervals */ u_word_t low_count; /* lower bound of 'symbol' interval */ @@ -534,13 +534,13 @@ decode_array (bitfile_t *input, const unsigned *context, unsigned d; /* current data symbol */ unsigned c; /* context of current data symbol */ - c = n_context > 1 ? context [n] : 0; + c = n_context > 1 ? context [n] : 0; assert (high > low); scale = totals [c][c_symbols [c]]; range = (high - low) + 1; count = (((code - low) + 1 ) * scale - 1) / range; - + for (d = c_symbols [c]; count < totals [c][d]; d--) /* next symbol */ ; low_count = totals [c][d]; @@ -558,7 +558,7 @@ decode_array (bitfile_t *input, const unsigned *context, for (i = d + 1; i < c_symbols [c] + 1; i++) totals [c][i]++; - + if (totals [c][c_symbols [c]] > scaling) /* scaling */ for (i = 1; i < c_symbols [c] + 1; i++) { @@ -577,12 +577,12 @@ decode_array (bitfile_t *input, const unsigned *context, */ { unsigned c; - + for (c = 0; c < n_context; c++) Free (totals [c]); Free (totals); } - + return data; } @@ -600,10 +600,10 @@ alloc_model (unsigned m, unsigned scale, unsigned n, unsigned *totals) * * Return value: * a pointer to the new probability model structure. - * + * * Note: We recommend a small size of the alphabet because no escape codes * are used to encode/decode previously unseen symbols. - * + * */ { model_t *model; /* new probability model */ @@ -621,7 +621,7 @@ alloc_model (unsigned m, unsigned scale, unsigned n, unsigned *totals) model->order = n; model->context = n > 0 ? Calloc (n, sizeof (unsigned)) : NULL; /* - * Allocate memory for the probabilty model. + * Allocate memory for the probability model. * Each of the m^n different contexts requires its own probability model. */ for (num = 1, i = 0; i < model->order; i++) @@ -644,17 +644,17 @@ alloc_model (unsigned m, unsigned scale, unsigned n, unsigned *totals) */ power = 1; /* multiplicator */ index = 0; /* address of prob. model */ - - for (i = 0; i < model->order; i++) /* genarate a m-nary number */ + + for (i = 0; i < model->order; i++) /* generate a m-nary number */ { - index += model->context[i] * power; + index += model->context[i] * power; power *= model->symbols; } index *= model->symbols + 1; /* size of each model is m + 1 */ model->totals [index + 0] = 0; /* always zero */ - + for (i = 1; i <= model->symbols; i++) /* prob of each symbol is 1/m or as given in totals */ model->totals[index + i] = model->totals [index + i - 1] @@ -667,14 +667,14 @@ alloc_model (unsigned m, unsigned scale, unsigned n, unsigned *totals) { dec = NO; model->context[i]++; - if (model->context[i] >= model->symbols) + if (model->context[i] >= model->symbols) { /* change previous context */ model->context[i] = 0; if (i > 0) /* there's still a context remaining */ dec = YES; else - cont = NO; /* all context models initilized */ + cont = NO; /* all context models initialized */ } } } diff --git a/converter/other/fiasco/lib/bit-io.c b/converter/other/fiasco/lib/bit-io.c index f69343e6..04716f05 100644 --- a/converter/other/fiasco/lib/bit-io.c +++ b/converter/other/fiasco/lib/bit-io.c @@ -1,12 +1,12 @@ /* - * bit-io.c: Buffered and bit oriented file I/O + * bit-io.c: Buffered and bit oriented file I/O * * Written by: Ullrich Hafner - * + * * This file is part of FIASCO (Fractal Image And Sequence COdec) * Copyright (C) 1994-2000 Ullrich Hafner */ - + /* * $Date: 2000/06/14 20:49:37 $ * $Author: hafner $ @@ -35,7 +35,7 @@ /***************************************************************************** local constants - + *****************************************************************************/ static const unsigned BUFFER_SIZE = 16350; @@ -48,7 +48,7 @@ static const unsigned mask[] = {0x0001, 0x0002, 0x0004, 0x0008, /***************************************************************************** public code - + *****************************************************************************/ FILE * @@ -57,7 +57,7 @@ open_file (const char *filename, const char *env_var, openmode_e mode) * Try to open file 'filename' with mode 'mode' (READ_ACCESS, WRITE_ACCESS). * Scan the current directory first and then cycle through the * path given in the environment variable 'env_var', if set. - * + * * Return value: * Pointer to open file on success, else NULL. */ @@ -81,42 +81,42 @@ open_file (const char *filename, const char *env_var, openmode_e mode) { if (mode == READ_ACCESS) return stdin; - else + else return stdout; } - + /* * Try to open 'readonly' file in the current directory */ if (mode == READ_ACCESS && (fp = fopen (filename, read_mode))) - return fp; + return fp; if (mode == WRITE_ACCESS && strchr (filename, '/')) /* contains path */ return fopen (filename, write_mode); - + /* * Get value of environment variable 'env_var', if set * else use DEFAULT_PATH ("./") */ if (env_var != NULL) env_path = getenv (env_var); - if (env_path == NULL) + if (env_path == NULL) env_path = strdup (DEFAULT_PATH); else env_path = strdup (env_path); - + /* * Try to open file in the directory given by the environment - * variable env_var - individual path components are separated by PATH_SEP + * variable env_var - individual path components are separated by PATH_SEP */ path = strtok (env_path, PATH_SEP); - do + do { - if (ext_filename) + if (ext_filename) Free (ext_filename); ext_filename = Calloc (strlen (path) + strlen (filename) + 2, sizeof (char)); - strcpy (ext_filename, path); + strcpy (ext_filename, path); if (*(ext_filename + strlen (ext_filename) - 1) != '/') strcat (ext_filename, "/"); strcat (ext_filename, filename); @@ -125,7 +125,7 @@ open_file (const char *filename, const char *env_var, openmode_e mode) while (fp == NULL && (path = strtok (NULL, PATH_SEP)) != NULL); Free (env_path); - + return fp; } @@ -143,7 +143,7 @@ open_bitfile (const char *filename, const char *env_var, openmode_e mode) */ { bitfile_t *bitfile = Calloc (1, sizeof (bitfile_t)); - + bitfile->file = open_file (filename, env_var, mode); if (bitfile->file == NULL) @@ -164,8 +164,8 @@ open_bitfile (const char *filename, const char *env_var, openmode_e mode) bitfile->filename = filename ? strdup (filename) : strdup ("(stdout)"); } else - error ("Unknow file access mode '%d'.", mode); - + error ("Unknown file access mode '%d'.", mode); + bitfile->bits_processed = 0; bitfile->buffer = Calloc (BUFFER_SIZE, sizeof (byte_t)); bitfile->ptr = bitfile->buffer; @@ -187,7 +187,7 @@ get_bit (bitfile_t *bitfile) */ { assert (bitfile); - + if (!bitfile->bitpos--) /* use next byte ? */ { bitfile->ptr++; @@ -226,7 +226,7 @@ get_bits (bitfile_t *bitfile, unsigned bits) */ { unsigned value = 0; /* input value */ - + while (bits--) value = (unsigned) (value << 1) | get_bit (bitfile); @@ -235,7 +235,7 @@ get_bits (bitfile_t *bitfile, unsigned bits) void put_bit (bitfile_t *bitfile, unsigned value) -/* +/* * Put the bit 'value' to the bitfile buffer. * The buffer is written to the file 'bitfile->file' if the number of * buffer bytes exceeds 'BUFFER_SIZE'. @@ -247,7 +247,7 @@ put_bit (bitfile_t *bitfile, unsigned value) */ { assert (bitfile); - + if (!bitfile->bitpos--) /* use next byte ? */ { bitfile->ptr++; @@ -265,7 +265,7 @@ put_bit (bitfile_t *bitfile, unsigned value) } bitfile->bitpos = 7; } - + if (value) *bitfile->ptr |= mask [bitfile->bitpos]; @@ -274,7 +274,7 @@ put_bit (bitfile_t *bitfile, unsigned value) void put_bits (bitfile_t *bitfile, unsigned value, unsigned bits) -/* +/* * Put #'bits' bits of integer 'value' to the bitfile buffer 'bitfile'. * * No return value. @@ -292,7 +292,7 @@ close_bitfile (bitfile_t *bitfile) /* * Bitfile destructor: * Close 'bitfile', if 'bitfile->mode' == WRITE_ACCESS write bit buffer - * to disk. + * to disk. * * No return value. * @@ -301,7 +301,7 @@ close_bitfile (bitfile_t *bitfile) */ { assert (bitfile); - + if (bitfile->mode == WRITE_ACCESS) { unsigned bytes = fwrite (bitfile->buffer, sizeof (byte_t), diff --git a/converter/other/fiasco/output/mc.c b/converter/other/fiasco/output/mc.c index d048bef5..170a2648 100644 --- a/converter/other/fiasco/output/mc.c +++ b/converter/other/fiasco/output/mc.c @@ -1,9 +1,9 @@ /* - * mc.c: Output of motion compensation + * mc.c: Output of motion compensation * * Written by: Michael Unger * Ullrich Hafner - * + * * This file is part of FIASCO (Fractal Image And Sequence COdec) * Copyright (C) 1994-2000 Ullrich Hafner */ @@ -30,7 +30,7 @@ /***************************************************************************** local variables - + *****************************************************************************/ static unsigned p_frame_codes [4][2] = @@ -39,7 +39,7 @@ static unsigned p_frame_codes [4][2] = * NONE, FORWARD */ { - {1, 1}, {0, 1}, {0, 0}, {0, 0} + {1, 1}, {0, 1}, {0, 0}, {0, 0} }; static unsigned b_frame_codes [4][2] = @@ -48,7 +48,7 @@ static unsigned b_frame_codes [4][2] = * NONE, FORWARD, BACKWARD, INTERPOLATED */ { - {1, 1}, {000, 3}, {001, 3}, {01, 2} + {1, 1}, {000, 3}, {001, 3}, {01, 2} }; enum vlc_e {CODE = 0, BITS = 1}; @@ -56,7 +56,7 @@ enum vlc_e {CODE = 0, BITS = 1}; /***************************************************************************** prototypes - + *****************************************************************************/ static void @@ -68,7 +68,7 @@ encode_mc_coords (unsigned max_state, const wfa_t *wfa, bitfile_t *output); /***************************************************************************** public code - + *****************************************************************************/ void @@ -85,7 +85,7 @@ write_mc (frame_type_e frame_type, const wfa_t *wfa, bitfile_t *output) /***************************************************************************** private code - + *****************************************************************************/ static void @@ -108,22 +108,22 @@ encode_mc_tree (unsigned max_state, frame_type_e frame_type, const wfa_t *wfa, mc_type_e type; /* type of motion compensation */ unsigned (*mc_tree_codes)[2]; /* pointer to VLC table */ unsigned bits = bits_processed (output); /* number of bits used */ - + if (frame_type == P_FRAME) mc_tree_codes = p_frame_codes; /* binary code */ - else + else mc_tree_codes = b_frame_codes; /* variable length code */ - + /* * Traverse tree in breadth first order (starting at - * level 'wfa->p_max_level'). Use a queue to store the childs - * of each node ('last' is the next free queue element). + * level 'wfa->p_max_level'). Use a queue to store the children + * of each node ('last' is the next free queue element). */ for (last = 0, state = wfa->basis_states; state < max_state; state++) if (wfa->level_of_state [state] - 1 == (int) wfa->wfainfo->p_max_level) queue [last++] = state; /* init level = 'mc_max_level' */ - + for (current = 0; current < last; current++) for (label = 0; label < MAXLABELS; label++) { @@ -145,7 +145,7 @@ encode_mc_tree (unsigned max_state, frame_type_e frame_type, const wfa_t *wfa, wfa->level_of_state [state] - 1 >= (int) wfa->wfainfo->p_min_level) queue [last++] = wfa->tree [state][label]; /* append child */ - + } OUTPUT_BYTE_ALIGN (output); @@ -174,16 +174,16 @@ encode_mc_coords (unsigned max_state, const wfa_t *wfa, bitfile_t *output) unsigned itotal = 0; /* #interpolated decisions */ unsigned bits = bits_processed (output); /* number of bits used */ unsigned sr = wfa->wfainfo->search_range; /* search range */ - + for (level = wfa->wfainfo->p_max_level; level >= wfa->wfainfo->p_min_level; level--) level_count [level] = 0; - + for (state = wfa->basis_states; state < max_state; state++) for (label = 0; label < MAXLABELS; label++) { mv_t *mv = &wfa->mv_tree[state][label]; /* motion vector info */ - + if (mv->type != NONE) { level_count [wfa->level_of_state [state] - 1]++; @@ -229,14 +229,14 @@ encode_mc_coords (unsigned max_state, const wfa_t *wfa, bitfile_t *output) } OUTPUT_BYTE_ALIGN (output); - + debug_message ("Motion compensation: %d forward, %d backward, " "%d interpolated", ftotal, btotal, itotal); for (level = wfa->wfainfo->p_max_level; level >= wfa->wfainfo->p_min_level; level--) debug_message ("Level %d: %d motion vectors", level, level_count[level]); - + { unsigned total = ftotal * 2 + btotal * 2 + itotal * 4; diff --git a/converter/other/fiasco/output/nd.c b/converter/other/fiasco/output/nd.c index 65a85467..b1dd6746 100644 --- a/converter/other/fiasco/output/nd.c +++ b/converter/other/fiasco/output/nd.c @@ -1,8 +1,8 @@ /* - * nd.c: Output of prediction tree + * nd.c: Output of prediction tree * * Written by: Ullrich Hafner - * + * * This file is part of FIASCO (Fractal Image And Sequence COdec) * Copyright (C) 1994-2000 Ullrich Hafner */ @@ -32,7 +32,7 @@ /***************************************************************************** prototypes - + *****************************************************************************/ static unsigned @@ -43,7 +43,7 @@ encode_nd_coefficients (unsigned total, const wfa_t *wfa, bitfile_t *output); /***************************************************************************** public code - + *****************************************************************************/ void @@ -56,7 +56,7 @@ write_nd (const wfa_t *wfa, bitfile_t *output) */ { unsigned total = encode_nd_tree (wfa, output); - + if (total > 0) encode_nd_coefficients (total, wfa, output); } @@ -64,13 +64,13 @@ write_nd (const wfa_t *wfa, bitfile_t *output) /***************************************************************************** private code - + *****************************************************************************/ static unsigned encode_nd_tree (const wfa_t *wfa, bitfile_t *output) /* - * Write prediction tree of 'wfa' to given stream 'output'. + * Write prediction tree of 'wfa' to given stream 'output'. * * No return value. */ @@ -85,7 +85,7 @@ encode_nd_tree (const wfa_t *wfa, bitfile_t *output) unsigned bits = bits_processed (output); used = not_used = 0; - + /* * Initialize arithmetic coder */ @@ -94,18 +94,18 @@ encode_nd_tree (const wfa_t *wfa, bitfile_t *output) underflow = 0; sum0 = 1; sum1 = 11; - + queue = alloc_queue (sizeof (int)); state = wfa->root_state; queue_append (queue, &state); - + /* * Traverse the WFA tree in breadth first order (using a queue). */ while (queue_remove (queue, &next)) { unsigned label; - + if (wfa->level_of_state [next] > wfa->wfainfo->p_max_level + 1) { /* @@ -114,7 +114,7 @@ encode_nd_tree (const wfa_t *wfa, bitfile_t *output) */ for (label = 0; label < MAXLABELS; label++) if (ischild (state = wfa->tree [next][label])) - queue_append (queue, &state); /* continue with childs */ + queue_append (queue, &state); /* continue with children */ } else if (wfa->level_of_state [next] > wfa->wfainfo->p_min_level) { @@ -126,7 +126,7 @@ encode_nd_tree (const wfa_t *wfa, bitfile_t *output) if (isedge (wfa->into [next][label][0])) /* prediction used */ { used++; - + /* * Encode a '1' symbol */ @@ -134,12 +134,12 @@ encode_nd_tree (const wfa_t *wfa, bitfile_t *output) low = low + (u_word_t) ((range * sum0) / sum1); RESCALE_OUTPUT_INTERVAL; } - else /* no predict., continue with childs */ + else /* no predict., continue with children */ { not_used++; if (wfa->level_of_state [state] > wfa->wfainfo->p_min_level) queue_append (queue, &state); - + /* * Encode a '0' symbol */ @@ -162,7 +162,7 @@ encode_nd_tree (const wfa_t *wfa, bitfile_t *output) sum1 = sum0 + 1; } } - + } } free_queue (queue); @@ -178,7 +178,7 @@ encode_nd_tree (const wfa_t *wfa, bitfile_t *output) used, not_used); { unsigned total = used + not_used; - + debug_message ("nd-tree: %5d bits. (%5d symbols => %5.2f bps)", bits_processed (output) - bits, total, total > 0 ? ((bits_processed (output) - bits) / @@ -205,7 +205,7 @@ encode_nd_coefficients (unsigned total, const wfa_t *wfa, bitfile_t *output) unsigned *ptr; /* pointer to current factor */ unsigned state, label, edge; word_t domain; - + ptr = coefficients = Calloc (total, sizeof (unsigned)); for (state = wfa->basis_states; state < wfa->states; state++) @@ -232,7 +232,7 @@ encode_nd_coefficients (unsigned total, const wfa_t *wfa, bitfile_t *output) encode_array (output, coefficients, NULL, &c_symbols, 1, total, scaling); } - + debug_message ("nd-factors: %5d bits. (%5d symbols => %5.2f bps)", bits_processed (output) - bits, total, total ? ((bits_processed (output) - bits) diff --git a/converter/other/fiasco/output/tree.c b/converter/other/fiasco/output/tree.c index 2eae2df9..55080a51 100644 --- a/converter/other/fiasco/output/tree.c +++ b/converter/other/fiasco/output/tree.c @@ -2,7 +2,7 @@ * tree.c: Output of bintree partitioning * * Written by: Ullrich Hafner - * + * * This file is part of FIASCO (Fractal Image And Sequence COdec) * Copyright (C) 1994-2000 Ullrich Hafner */ @@ -30,7 +30,7 @@ /***************************************************************************** prototypes - + *****************************************************************************/ static void @@ -40,7 +40,7 @@ encode_tree (bitfile_t *output, const byte_t *data, unsigned n_data, /***************************************************************************** public code - + *****************************************************************************/ void @@ -64,9 +64,9 @@ write_tree (const wfa_t *wfa, bitfile_t *output) /* * Traverse tree in breadth first order. Use a queue to store - * the childs of each node ('last' is the next free queue element). + * the children of each node ('last' is the next free queue element). * The first element ('current') of this queue will get the new parent - * node. + * node. */ tree_string = Calloc (MAXSTATES * MAXLABELS, sizeof (byte_t)); queue [0] = wfa->root_state; @@ -83,7 +83,7 @@ write_tree (const wfa_t *wfa, bitfile_t *output) if (total != (wfa->states - wfa->basis_states) * MAXLABELS) error ("total [%d] != (states - basis_states) * 2 [%d]", total, (wfa->states - wfa->basis_states) * MAXLABELS); - + { unsigned scale = total / 20 ; @@ -91,7 +91,7 @@ write_tree (const wfa_t *wfa, bitfile_t *output) } Free (tree_string); - + debug_message ("tree: %5d bits. (%5d symbols => %5.2f bps)", bits_processed (output) - bits, total, total > 0 ? ((bits_processed (output) - bits) @@ -101,7 +101,7 @@ write_tree (const wfa_t *wfa, bitfile_t *output) /***************************************************************************** private code - + *****************************************************************************/ static void @@ -128,7 +128,7 @@ encode_tree (bitfile_t *output, const byte_t *data, unsigned n_data, for (n = n_data; n; n--) { unsigned range; /* Current interval range */ - + if (!*data++) { /* diff --git a/converter/other/fiasco/params.c b/converter/other/fiasco/params.c index 7d0b84ab..29f52afc 100644 --- a/converter/other/fiasco/params.c +++ b/converter/other/fiasco/params.c @@ -3,7 +3,7 @@ * * Written by: Stefan Frank * Ullrich Hafner - * + * * This file is part of FIASCO (Fractal Image And Sequence COdec) * Copyright (C) 1994-2000 Ullrich Hafner */ @@ -28,7 +28,7 @@ #include #include - + #include /* system or ../lib */ #include "pm_c_util.h" @@ -47,7 +47,7 @@ /***************************************************************************** prototypes - + *****************************************************************************/ static void @@ -56,7 +56,7 @@ static int get_parameter_index (const param_t *params, const char *search_string); static void set_parameter (param_t *parameter, const char *value); -static void +static void usage (const param_t *params, const char *progname, const char *synopsis, const char *comment, const char *non_opt_string, bool_t show_all_options, const char *sys_file_name, @@ -65,17 +65,17 @@ usage (const param_t *params, const char *progname, const char *synopsis, /***************************************************************************** public code - + *****************************************************************************/ int -parseargs (param_t *usr_params, - int argc, char **argv, +parseargs (param_t *usr_params, + int argc, char **argv, const char *synopsis, - const char *comment, - const char *non_opt_string, + const char *comment, + const char *non_opt_string, const char *path, - const char *sys_file_name, + const char *sys_file_name, const char *usr_file_name) /* * Perform the command line parsing. @@ -95,7 +95,7 @@ parseargs (param_t *usr_params, * * Side effects: * the elements of ARGV are permuted - * usr_params [].value is modified + * usr_params [].value is modified */ { extern int optind; /* index in ARGV of the 1st element @@ -146,7 +146,7 @@ parseargs (param_t *usr_params, */ { param_t *p; - + for (p = usr_params; p->name != NULL; p++) { set_parameter (p, p->default_value); @@ -155,7 +155,7 @@ parseargs (param_t *usr_params, } sys_params = detailed_help ? detailed_sys_params : short_sys_params; - + for (p = sys_params; p->name != NULL; p++) set_parameter (p, p->default_value); } @@ -210,12 +210,12 @@ parseargs (param_t *usr_params, int optchar; /* found option character */ /* - * Build short option string for getopt_long (). + * Build short option string for getopt_long (). */ { param_t *p; /* counter */ char *ptr_optstr; /* pointer to position in string */ - + ptr_optstr = optstr; for (p = params; p->name != NULL; p++) if (p->optchar != '\0') @@ -231,13 +231,13 @@ parseargs (param_t *usr_params, } *ptr_optstr = '\0'; } - + /* - * Build long option string for getopt_long (). + * Build long option string for getopt_long (). */ { int i; - + long_options = calloc (n1 + n2 + 1, sizeof (struct option)); if (!long_options) error ("Out of memory."); @@ -264,15 +264,15 @@ parseargs (param_t *usr_params, long_options [i].val = 0; } } - + /* - * Parse comand line + * Parse command line */ while ((optchar = getopt_long (argc, argv, optstr, long_options, &option_index)) != EOF) { int param_index = -1; - + switch (optchar) { case 0: @@ -303,7 +303,7 @@ parseargs (param_t *usr_params, default: { int i; - + for (i = 0; params [i].name != NULL; i++) if (params [i].optchar == optchar) { @@ -350,7 +350,7 @@ parseargs (param_t *usr_params, free (long_options); } - + /* * Read config-file if specified by option -f */ @@ -361,7 +361,7 @@ parseargs (param_t *usr_params, if ((filename = (char *) parameter_value (params, "config")) != NULL) { FILE *parameter_file; /* input file */ - + warning ("Options set in file `%s' will override" " command line options.", filename); parameter_file = open_file (filename, NULL, READ_ACCESS); @@ -379,10 +379,10 @@ parseargs (param_t *usr_params, memcpy (usr_params, params, n1 * sizeof (param_t)); /* fill user struct */ free (sys_path); - + return optind; } - + void * parameter_value (const param_t *params, const char *name) /* @@ -399,7 +399,7 @@ parameter_value (const param_t *params, const char *name) if (params [pind].type == PSTR || params [pind].type == POSTR) return (void *) params [pind].value.s; - + return (void *) &(params [pind].value); } @@ -414,7 +414,7 @@ ask_and_set (param_t *params, const char *name, const char *msg) * Side effects: * 'params ['name'].value' is changed */ -{ +{ char answer [MAXSTRLEN]; int index = get_parameter_index (params, name); @@ -423,7 +423,7 @@ ask_and_set (param_t *params, const char *name, const char *msg) if (msg) fprintf (stderr, "%s\n", msg); - + switch (params [index].type) { case PFLAG: /* Unusual, at least. */ @@ -439,7 +439,7 @@ ask_and_set (param_t *params, const char *name, const char *msg) default: error ("Invalid parameter type for %s", name); } -} +} void write_parameters (const param_t *params, FILE *output) @@ -483,7 +483,7 @@ write_parameters (const param_t *params, FILE *output) /***************************************************************************** private code - + *****************************************************************************/ static void @@ -498,7 +498,7 @@ set_parameter (param_t *parameter, const char *value) */ { assert (parameter); - + switch (parameter->type) { case PFLAG: @@ -516,7 +516,7 @@ set_parameter (param_t *parameter, const char *value) { long int data; char *endptr; - + data = strtol (value, &endptr, 0); if (*endptr != '\0' || endptr == value) warning ("Invalid value `%s' converted to %d", @@ -531,7 +531,7 @@ set_parameter (param_t *parameter, const char *value) { long int data; char *endptr; - + data = strtol (value, &endptr, 0); if (*endptr != '\0' || endptr == value) warning ("Invalid value `%s' converted to %d", @@ -543,7 +543,7 @@ set_parameter (param_t *parameter, const char *value) { double data; char *endptr; - + data = strtod (value, &endptr); if (*endptr != '\0' || endptr == value) warning ("Invalid value `%s' converted to %f", @@ -555,7 +555,7 @@ set_parameter (param_t *parameter, const char *value) case POSTR: parameter->value.s = value ? strdup (value) : NULL; break; - default: + default: error ("Invalid parameter type for %s", parameter->name); } } @@ -606,7 +606,7 @@ read_parameter_file (param_t *params, FILE *file) char *name; /* parameter name */ char *value; /* parameter value */ int pind; /* current argument number */ - + b = strchr (buffer, '#'); if (b != NULL) /* Strip comments. */ *b = '\0'; @@ -619,7 +619,7 @@ read_parameter_file (param_t *params, FILE *file) /* * Extract value of parameter */ - for (value = b + 1; ISSPACE (*value); value++) + for (value = b + 1; ISSPACE (*value); value++) ; /* Delete leading spaces */ for (b = value + strlen (value) - 1; b >= value && ISSPACE (*b); b--) @@ -628,7 +628,7 @@ read_parameter_file (param_t *params, FILE *file) /* * Extract parameter name */ - for (name = buffer; ISSPACE (*name); name++) + for (name = buffer; ISSPACE (*name); name++) ; /* Delete leading spaces */ for (b = name + strlen (name) - 1; b >= name && ISSPACE (*b); b--) @@ -637,21 +637,21 @@ read_parameter_file (param_t *params, FILE *file) pind = get_parameter_index (params, name); if (pind >= 0) set_parameter (¶ms [pind], value); - + n++; } -} +} -static void +static void usage (const param_t *params, const char *progname, const char *synopsis, const char *comment, const char *non_opt_string, bool_t show_all_options, const char *sys_file_name, const char *usr_file_name) /* * Generates and prints command line description from param_t struct 'params'. - * 'progname' is the name of the excecutable, 'synopsis' a short program + * 'progname' is the name of the executable, 'synopsis' a short program * description, and 'comment' some more advice. * If flag 'show_all_options' is set then print also options that are not * associated with a short option character. @@ -662,7 +662,7 @@ usage (const param_t *params, const char *progname, const char *synopsis, { int i; size_t width = 0; - + fprintf (stderr, "Usage: %s [OPTION]...%s\n", progname, non_opt_string ? non_opt_string : " "); if (synopsis != NULL) @@ -683,7 +683,7 @@ usage (const param_t *params, const char *progname, const char *synopsis, else width = MAX(width, (strlen (params [i].name)) - 1); } - + for (i = 0; params [i].name != NULL; i++) if (params [i].optchar != '\0' || show_all_options) { @@ -691,7 +691,7 @@ usage (const param_t *params, const char *progname, const char *synopsis, fprintf (stderr, " -%c, --", params [i].optchar); else fprintf (stderr, " --"); - + if (params [i].type == POSTR) fprintf (stderr, "%s=[%s]%-*s ", params [i].name, params [i].argument_name, @@ -707,7 +707,7 @@ usage (const param_t *params, const char *progname, const char *synopsis, (unsigned)(width + 1), params [i].name); fprintf (stderr, params [i].use, params [i].argument_name); - + switch (params [i].type) { case PFLAG: diff --git a/converter/other/fiasco/pnmtofiasco.c b/converter/other/fiasco/pnmtofiasco.c index e2656c71..9f63e7a1 100644 --- a/converter/other/fiasco/pnmtofiasco.c +++ b/converter/other/fiasco/pnmtofiasco.c @@ -2,11 +2,11 @@ * cwfa.c: FIASCO coder * * Written by: Ullrich Hafner - * + * * This file is part of FIASCO (Fractal Image And Sequence COdec) * Copyright (C) 1994-2000 Ullrich Hafner */ - + /* * $Date: 2000/10/28 17:39:29 $ * $Author: hafner $ @@ -33,7 +33,7 @@ /***************************************************************************** local variables - + *****************************************************************************/ static param_t params [] = @@ -107,7 +107,7 @@ static param_t params [] = "Set domain pool of r-lc to `%s'."}, {"coeff", "NAME", '\0', PSTR, {0}, "adaptive", "Set coefficients model to `%s'."}, - /* DELTA APPROXIATION */ + /* DELTA APPROXIMATION */ {"d-domain-pool", "NAME", '\0', PSTR, {0}, "rle", "Set domain pool of d-lc to `%s'."}, {"d-coeff", "NAME", '\0', PSTR, {0}, "adaptive", @@ -132,36 +132,36 @@ static param_t params [] = "Smooth frames by factor `%s' (0.5 - 1.0)"}, {"reference-frame", "FILE", '\0', PSTR, {0}, NULL, "Use PPM/PGM image `%s' as reference frame."}, -#endif +#endif {NULL, NULL, 0, PSTR, {0}, NULL, NULL } }; /***************************************************************************** prototypes - + *****************************************************************************/ -static void +static void checkargs (int argc, char **argv, char const ***image_template, char **wfa_name, float *quality, fiasco_c_options_t **options); /***************************************************************************** public code - + *****************************************************************************/ - -int + +int main (int argc, char **argv) { char const **image_template; /* template for input image files */ char *wfa_name; /* filename of output WFA */ float quality; /* approximation quality */ fiasco_c_options_t *options; /* additional coder options */ - + pnm_init(&argc, argv); - + init_error_handling (argv [0]); checkargs (argc, argv, &image_template, &wfa_name, &quality, &options); @@ -179,10 +179,10 @@ main (int argc, char **argv) /***************************************************************************** private code - + *****************************************************************************/ -static void +static void checkargs (int argc, char **argv, char const ***image_template, char **wfa_name, float *quality, fiasco_c_options_t **options) /* @@ -191,7 +191,7 @@ checkargs (int argc, char **argv, char const ***image_template, * Return value: * 1 on success * 0 otherwise - * + * * * Side effects: * 'image_template', 'wfa_name', 'quality' and 'options' are set. @@ -200,7 +200,7 @@ checkargs (int argc, char **argv, char const ***image_template, int optind; /* last processed commandline param */ char *image_name; /* filename given by option '--input_name' */ int i; /* counter */ - + optind = parseargs (params, argc, argv, "Compress raw PPM/PGM image FILEs to a FIASCO file.", "With no image FILE, or if FILE is -, " @@ -220,7 +220,7 @@ checkargs (int argc, char **argv, char const ***image_template, /* * Default options ... */ - image_name = (char *) parameter_value (params, "image-name"); + image_name = (char *) parameter_value (params, "image-name"); *wfa_name = (char *) parameter_value (params, "output-name"); for (;;) { @@ -233,7 +233,7 @@ checkargs (int argc, char **argv, char const ***image_template, ask_and_set (params, "quality", "Please enter coding quality 'q' ('q' > 0): "); } - + if (optind < argc) /* Additional command line param */ { if (image_name) @@ -260,7 +260,7 @@ checkargs (int argc, char **argv, char const ***image_template, */ { *options = fiasco_c_options_new (); - + { char *pattern = (char *) parameter_value (params, "pattern"); @@ -270,7 +270,7 @@ checkargs (int argc, char **argv, char const ***image_template, { char *basis = (char *) parameter_value (params, "basis-name"); - + if (!fiasco_c_options_set_basisfile (*options, basis)) error (fiasco_get_error_message ()); } @@ -278,41 +278,41 @@ checkargs (int argc, char **argv, char const ***image_template, { int n = * (int *) parameter_value (params, "chroma-dictionary"); float q = * (float *) parameter_value (params, "chroma-qfactor"); - + if (!fiasco_c_options_set_chroma_quality (*options, q, MAX(0, n))) error (fiasco_get_error_message ()); } - + { int n = *((int *) parameter_value (params, "smooth")); - + if (!fiasco_c_options_set_smoothing (*options, MAX(0, n))) error (fiasco_get_error_message ()); } - + { int n = * (int *) parameter_value (params, "progress-meter"); - fiasco_progress_e type = (n < 0) ? + fiasco_progress_e type = (n < 0) ? FIASCO_PROGRESS_NONE : (fiasco_progress_e) n; - + if (!fiasco_c_options_set_progress_meter (*options, type)) error (fiasco_get_error_message ()); } - + { char *t = (char *) parameter_value (params, "title"); - + if (strlen (t) > 0 && !fiasco_c_options_set_title (*options, t)) error (fiasco_get_error_message ()); } - + { char *c = (char *) parameter_value (params, "comment"); if (strlen (c) > 0 && !fiasco_c_options_set_comment (*options, c)) error (fiasco_get_error_message ()); } - + { fiasco_tiling_e method = FIASCO_TILING_VARIANCE_DSC; int e = * (int *) parameter_value (params, "tiling-exponent"); @@ -332,7 +332,7 @@ checkargs (int argc, char **argv, char const ***image_template, if (!fiasco_c_options_set_tiling (*options, method, MAX(0, e))) error (fiasco_get_error_message ()); } - + { int M/* = * (int *) parameter_value (params, "max-level") */; int m/* = * (int *) parameter_value (params, "min-level") */; @@ -354,7 +354,7 @@ checkargs (int argc, char **argv, char const ***image_template, m = 4; N = 5; } - + if (!fiasco_c_options_set_optimizations (*options, m, M, N, MAX(0, D), o)) error (fiasco_get_error_message ()); @@ -363,7 +363,7 @@ checkargs (int argc, char **argv, char const ***image_template, int M = * (int *) parameter_value (params, "max-level"); int m = * (int *) parameter_value (params, "min-level"); int p = * (int *) parameter_value (params, "prediction"); - + if (!fiasco_c_options_set_prediction (*options, p, MAX(0, m), MAX(0, M))) error (fiasco_get_error_message ()); @@ -374,7 +374,7 @@ checkargs (int argc, char **argv, char const ***image_template, int m = * (int *) parameter_value(params, "rpf-mantissa"); int dc_m = * (int *) parameter_value(params, "dc-rpf-mantissa"); fiasco_rpf_range_e range, dc_range; - + if (r < 1) range = FIASCO_RPF_RANGE_0_75; else if (r < 1.5) @@ -383,7 +383,7 @@ checkargs (int argc, char **argv, char const ***image_template, range = FIASCO_RPF_RANGE_1_50; else range = FIASCO_RPF_RANGE_2_00; - + if (dc_r < 1) dc_range = FIASCO_RPF_RANGE_0_75; else if (dc_r < 1.5) @@ -392,7 +392,7 @@ checkargs (int argc, char **argv, char const ***image_template, dc_range = FIASCO_RPF_RANGE_1_50; else dc_range = FIASCO_RPF_RANGE_2_00; - + if (!fiasco_c_options_set_quantization (*options, MAX(0, m), range, MAX(0, dc_m), dc_range)) @@ -402,4 +402,7 @@ checkargs (int argc, char **argv, char const ***image_template, if (fiasco_get_verbosity () == FIASCO_ULTIMATE_VERBOSITY) write_parameters (params, stderr); } -} +} + + + diff --git a/converter/other/gemtopnm.c b/converter/other/gemtopnm.c index d862213f..6bbfcc05 100644 --- a/converter/other/gemtopnm.c +++ b/converter/other/gemtopnm.c @@ -25,7 +25,7 @@ * * 92/07/11 Johann Haider * Changed to read from stdin if file is omitted - * Changed to handle line length not a multipe of 8 + * Changed to handle line length not a multiple of 8 * * 94/01/31 Andreas Schwab (schwab@ls5.informatik.uni-dortmund.de) * Changed to remove architecture dependency and conform to diff --git a/converter/other/giftopnm.c b/converter/other/giftopnm.c index e2d5923d..470c85b7 100644 --- a/converter/other/giftopnm.c +++ b/converter/other/giftopnm.c @@ -867,7 +867,7 @@ termStack(struct Stack * const stackP) { What we call 'dataWidth', others call the "minimum code size," which is a misnomer, because the minimum code size in a stream must be at least one - more than 'dataWidth', to accomodate the clear and end codes. + more than 'dataWidth', to accommmodate the clear and end codes. -----------------------------------------------------------------------------*/ static int const maxLzwCodeCt = (1<depth = 0; infoP->icon = NULL; for ( colorIdx = 0; colorIdx < 4; colorIdx++ ) - infoP->colors[colorIdx] = + infoP->colors[colorIdx] = ppm_parsecolor( (char*) colors[colorIdx], 0xFF ); /* Initialize option structure */ @@ -258,7 +258,7 @@ getDiskObject( IconInfo * const infoP ) { -static void +static void getIconHeader(IconInfo * const infoP) { /*------------------------------------------------------------------------- * Get fields from icon header portion of info file @@ -277,7 +277,7 @@ getIconHeader(IconInfo * const infoP) { "Only read 0x%X of 0x%X bytes", infoP->name, (unsigned)bytesRead, (unsigned)sizeof(ihead)); - /* Get icon width, heigh, and bitplanes */ + /* Get icon width, height, and bitplanes */ infoP->width = (ihead.iconWidth[0] << 8) + ihead.iconWidth[1]; infoP->height = (ihead.iconHeight[0] << 8) + ihead.iconHeight[1]; infoP->depth = (ihead.bpp[0] << 8) + ihead.bpp[1]; @@ -299,7 +299,7 @@ addBitplane(unsigned char * const icon, -----------------------------------------------------------------------------*/ unsigned int i; unsigned int j; - + for (i = j = 0; i < bpsize; ++i, j += 8) { icon[j+0] = (icon[j+0] << 1) | ((buff[i] >> 0) & 0x01); icon[j+1] = (icon[j+1] << 1) | ((buff[i] >> 1) & 0x01); @@ -317,7 +317,7 @@ addBitplane(unsigned char * const icon, static void readIconData(FILE * const fileP, unsigned int const width, - unsigned int const height, + unsigned int const height, unsigned int const depth, unsigned char ** const iconP) { /*------------------------------------------------------------------------- @@ -330,7 +330,7 @@ readIconData(FILE * const fileP, unsigned int const bpsize = height * (((width + 15) / 16) * 2); /* Bitplane size in bytes, with padding */ - + MALLOCARRAY(buff, bpsize); if ( buff == NULL ) pm_error( "Cannot allocate memory to hold icon pixels" ); @@ -350,10 +350,10 @@ readIconData(FILE * const fileP, * points to the next byte in buff to fill in. When the inner * loop is done, bp points to the end of buff. * - * After reading in the entire bitplane, the second inner loop splits the - * eight pixels in each byte of the bitplane into eight separate bytes in - * the icon buffer. The existing contents of each byte in icon are left - * shifted by one to make room for the next bit. + * After reading in the entire bitplane, the second inner loop splits the + * eight pixels in each byte of the bitplane into eight separate bytes in + * the icon buffer. The existing contents of each byte in icon are left + * shifted by one to make room for the next bit. * * Each byte in the completed icon contains a value from 0 to * 2^depth (0 to 1 for depth of 1 and 0 to 3 for a depth of 3). @@ -363,7 +363,7 @@ readIconData(FILE * const fileP, /* Read bitplane into buffer */ int toread; /* Number of bytes left to read */ unsigned char * buffp; /* Buffer point for reading data */ - + toread = bpsize; buffp = &buff[0]; while (toread > 0) { @@ -378,7 +378,7 @@ readIconData(FILE * const fileP, pm_error("Premature end-of-file. " "Still have 0x%X bytes to read", toread ); - + toread -= bytesRead; buffp += bytesRead; } @@ -542,3 +542,6 @@ main( int argc, return 0; } + + + diff --git a/converter/other/jbig/libjbig/include/jbig_ar.h b/converter/other/jbig/libjbig/include/jbig_ar.h index d58b1ae0..ed5f2f86 100644 --- a/converter/other/jbig/libjbig/include/jbig_ar.h +++ b/converter/other/jbig/libjbig/include/jbig_ar.h @@ -14,7 +14,7 @@ struct jbg_arenc_state { unsigned char st[4096]; /* probability status for contexts, MSB = MPS */ - unsigned long c; /* register C: base of coding intervall, * + unsigned long c; /* register C: base of coding interval, * * layout as in Table 23 */ unsigned long a; /* register A: normalized size of coding interval */ long sc; /* number of buffered 0xff values that might still overflow */ @@ -30,7 +30,7 @@ struct jbg_arenc_state { struct jbg_ardec_state { unsigned char st[4096]; /* probability status for contexts, MSB = MPS */ - unsigned long c; /* register C: base of coding intervall, * + unsigned long c; /* register C: base of coding interval, * * layout as in Table 25 */ unsigned long a; /* register A: normalized size of coding interval */ unsigned char *pscd_ptr; /* pointer to next PSCD data byte */ diff --git a/converter/other/jbig/libjbig/jbig.c b/converter/other/jbig/libjbig/jbig.c index e8141070..cf24a93b 100644 --- a/converter/other/jbig/libjbig/jbig.c +++ b/converter/other/jbig/libjbig/jbig.c @@ -109,7 +109,7 @@ static const char *errmsg[] = { * The following three functions are the only places in this code, were * C library memory management functions are called. The whole JBIG * library has been designed in order to allow multi-threaded - * execution. No static or global variables are used, so all fuctions + * execution. No static or global variables are used, so all functions * are fully reentrant. However if you want to use this multi-thread * capability and your malloc, realloc and free are not reentrant, * then simply add the necessary semaphores or mutex primitives below. @@ -776,7 +776,7 @@ void jbg_enc_init(struct jbg_enc_state *s, unsigned long x, unsigned long y, assert(x > 0 && y > 0 && planes > 0 && planes < 256); s->xd = x; s->yd = y; - s->yd1 = y; /* This is the hight initially announced in BIH. To provoke + s->yd1 = y; /* This is the height initially announced in BIH. To provoke generation of NEWLEN for T.85 compatibility tests, overwrite with new value s->yd1 > s->yd */ s->planes = planes; @@ -1106,7 +1106,7 @@ static void encode_sde(struct jbg_enc_state *s, if (!at_determined && j >= s->mx && j < hx-2) { p = (line_h1 & 0x100) != 0; /* current pixel value */ c[0] += ((line_h2 & 0x4000) != 0) == p; /* default position */ - assert(!(((line_h2 >> 6) ^ line_h1) & 0x100) == + assert((!(((line_h2 >> 6) ^ line_h1) & 0x100)) == (((line_h2 & 0x4000) != 0) == p)); for (t = 5; t <= s->mx && t <= j; t++) { o = (j - t) - (j & ~7L); @@ -1151,7 +1151,7 @@ static void encode_sde(struct jbg_enc_state *s, if (!at_determined && j >= s->mx && j < hx-2) { p = (line_h1 & 0x100) != 0; /* current pixel value */ c[0] += ((line_h2 & 0x4000) != 0) == p; /* default position */ - assert(!(((line_h2 >> 6) ^ line_h1) & 0x100) == + assert((!(((line_h2 >> 6) ^ line_h1) & 0x100)) == (((line_h2 & 0x4000) != 0) == p)); for (t = 3; t <= s->mx && t <= j; t++) { o = (j - t) - (j & ~7L); @@ -3240,7 +3240,7 @@ static unsigned char *jbg_next_pscdms(unsigned char *p, size_t len) * depends on the fact that section 6.2.6.2 of ITU-T T.82 says that a * NEWLEN marker segment "could refer to a line in the immediately * preceding stripe due to an unexpected termination of the image or - * the use of only such stripe". ITU-T.85 explicitely suggests the + * the use of only such stripe". ITU-T.85 explicitly suggests the * use of this for fax machines that start transmission before having * encountered the end of the page. None of this is necessary for * BIEs produced by JBIG-KIT, which normally does not use NEWLEN. diff --git a/converter/other/jpeg2000/libjasper/base/jas_stream.c b/converter/other/jpeg2000/libjasper/base/jas_stream.c index 16c948eb..20336fd7 100644 --- a/converter/other/jpeg2000/libjasper/base/jas_stream.c +++ b/converter/other/jpeg2000/libjasper/base/jas_stream.c @@ -6,14 +6,14 @@ */ /* __START_OF_JASPER_LICENSE__ - * + * * JasPer Software License - * + * * IMAGE POWER JPEG-2000 PUBLIC LICENSE * ************************************ - * + * * GRANT: - * + * * Permission is hereby granted, free of charge, to any person (the "User") * obtaining a copy of this software and associated documentation, to deal * in the JasPer Software without restriction, including without limitation @@ -21,22 +21,22 @@ * and/or sell copies of the JasPer Software (in source and binary forms), * and to permit persons to whom the JasPer Software is furnished to do so, * provided further that the License Conditions below are met. - * + * * License Conditions * ****************** - * + * * A. Redistributions of source code must retain the above copyright notice, * and this list of conditions, and the following disclaimer. - * + * * B. Redistributions in binary form must reproduce the above copyright * notice, and this list of conditions, and the following disclaimer in * the documentation and/or other materials provided with the distribution. - * + * * C. Neither the name of Image Power, Inc. nor any other contributor * (including, but not limited to, the University of British Columbia and * Michael David Adams) may be used to endorse or promote products derived * from this software without specific prior written permission. - * + * * D. User agrees that it shall not commence any action against Image Power, * Inc., the University of British Columbia, Michael David Adams, or any * other contributors (collectively "Licensors") for infringement of any @@ -56,17 +56,17 @@ * trade dress, or service mark rights); and (v) divisions, continuations, * renewals, reissues and extensions of the foregoing (as and to the extent * applicable) now existing, hereafter filed, issued or acquired. - * + * * E. If User commences an infringement action against any Licensor(s) then * such Licensor(s) shall have the right to terminate User's license and * all sublicenses that have been granted hereunder by User to other parties. - * + * * F. This software is for use only in hardware or software products that * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license * or right to this Software is granted for products that do not comply * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased * from the ISO. - * + * * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND @@ -106,10 +106,11 @@ * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE * NOTICE SPECIFIED IN THIS SECTION. - * + * * __END_OF_JASPER_LICENSE__ */ +#define _DEFAULT_SOURCE /* New name for SVID & BSD source defines */ #define _SVID_SOURCE /* Make sure P_tmpdir is defined in GNU libc 2.0.7 (_XOPEN_SOURCE 500 does it in other libc's). pm_config.h defines TMPDIR as P_tmpdir @@ -276,7 +277,7 @@ jas_stream_t *jas_stream_memopen(char *buf, int bufsize) obj->len_ = 0; } obj->pos_ = 0; - + return stream; } @@ -409,7 +410,7 @@ jas_stream_t *jas_stream_tmpfile() */ jmp_buf jmpbuf; int rc; - + rc = setjmp(jmpbuf); if (rc == 0) { pm_setjmpbuf(&jmpbuf); diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_dec.h b/converter/other/jpeg2000/libjasper/jpc/jpc_dec.h index 02c5553d..fe0e9616 100644 --- a/converter/other/jpeg2000/libjasper/jpc/jpc_dec.h +++ b/converter/other/jpeg2000/libjasper/jpc/jpc_dec.h @@ -236,7 +236,7 @@ typedef struct { } jpc_dec_ccp_t; -/* Coding paramters. */ +/* Coding parameters. */ typedef struct { diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_enc.h b/converter/other/jpeg2000/libjasper/jpc/jpc_enc.h index cfd754c9..86a8e59c 100644 --- a/converter/other/jpeg2000/libjasper/jpc/jpc_enc.h +++ b/converter/other/jpeg2000/libjasper/jpc/jpc_enc.h @@ -145,7 +145,7 @@ * Coding parameters types. \******************************************************************************/ -/* Per-component coding paramters. */ +/* Per-component coding parameters. */ typedef struct { diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_mqenc.c b/converter/other/jpeg2000/libjasper/jpc/jpc_mqenc.c index 3f6122e3..54472481 100644 --- a/converter/other/jpeg2000/libjasper/jpc/jpc_mqenc.c +++ b/converter/other/jpeg2000/libjasper/jpc/jpc_mqenc.c @@ -6,14 +6,14 @@ */ /* __START_OF_JASPER_LICENSE__ - * + * * JasPer Software License - * + * * IMAGE POWER JPEG-2000 PUBLIC LICENSE * ************************************ - * + * * GRANT: - * + * * Permission is hereby granted, free of charge, to any person (the "User") * obtaining a copy of this software and associated documentation, to deal * in the JasPer Software without restriction, including without limitation @@ -21,22 +21,22 @@ * and/or sell copies of the JasPer Software (in source and binary forms), * and to permit persons to whom the JasPer Software is furnished to do so, * provided further that the License Conditions below are met. - * + * * License Conditions * ****************** - * + * * A. Redistributions of source code must retain the above copyright notice, * and this list of conditions, and the following disclaimer. - * + * * B. Redistributions in binary form must reproduce the above copyright * notice, and this list of conditions, and the following disclaimer in * the documentation and/or other materials provided with the distribution. - * + * * C. Neither the name of Image Power, Inc. nor any other contributor * (including, but not limited to, the University of British Columbia and * Michael David Adams) may be used to endorse or promote products derived * from this software without specific prior written permission. - * + * * D. User agrees that it shall not commence any action against Image Power, * Inc., the University of British Columbia, Michael David Adams, or any * other contributors (collectively "Licensors") for infringement of any @@ -56,17 +56,17 @@ * trade dress, or service mark rights); and (v) divisions, continuations, * renewals, reissues and extensions of the foregoing (as and to the extent * applicable) now existing, hereafter filed, issued or acquired. - * + * * E. If User commences an infringement action against any Licensor(s) then * such Licensor(s) shall have the right to terminate User's license and * all sublicenses that have been granted hereunder by User to other parties. - * + * * F. This software is for use only in hardware or software products that * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license * or right to this Software is granted for products that do not comply * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased * from the ISO. - * + * * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND @@ -106,7 +106,7 @@ * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE * NOTICE SPECIFIED IN THIS SECTION. - * + * * __END_OF_JASPER_LICENSE__ */ @@ -223,7 +223,7 @@ } /******************************************************************************\ -* Local function protoypes. +* Local function prototypes. \******************************************************************************/ static void jpc_mqenc_setbits(jpc_mqenc_t *mqenc); @@ -439,3 +439,6 @@ int jpc_mqenc_dump(jpc_mqenc_t *mqenc, FILE *out) (unsigned)(*mqenc->curctx)->qeval); return 0; } + + + diff --git a/converter/other/pamtogif.c b/converter/other/pamtogif.c index 8d432da1..9b833214 100644 --- a/converter/other/pamtogif.c +++ b/converter/other/pamtogif.c @@ -19,8 +19,6 @@ #define MAXCMAPSIZE 256 -static unsigned int const gifMaxval = 255; - static bool verbose; @@ -796,7 +794,7 @@ typedef struct { */ bool lzw; /* We're actually doing LZW compression. False means we follow - the algorithm enough tht an LZW decompressor will recover the + the algorithm enough that an LZW decompressor will recover the proper data, but always using one code per pixel, and therefore not effecting any compression and not using the LZW patent. */ diff --git a/converter/other/pamtopng.c b/converter/other/pamtopng.c index cfff38cb..3a987820 100644 --- a/converter/other/pamtopng.c +++ b/converter/other/pamtopng.c @@ -16,7 +16,7 @@ had become rather complex. This program is roughly 1/3 the size of pnmtopng.c that it replaces. - - In 1995, bandwith was limited and therefore filesize had to be kept + - In 1995, bandwid was limited and therefore filesize had to be kept small. The original program tried to optimize for that by applying many "clever tricks". Today that isn't an issue anymore, so gone are filters, palettes, etc. Also, image conversions were removed, @@ -278,7 +278,7 @@ colorTypeFromInputType(const struct pam * const pamP) { retval = PNG_COLOR_TYPE_GRAY_ALPHA; else pm_error("Input tuple type is GRAYSCALE_ALPHA, " - "but number of planes is %u instread of 2", + "but number of planes is %u instead of 2", pamP->depth); } else if (strneq(pamP->tuple_type, "GRAYSCALE", 9)) { if (pamP->depth == 1) diff --git a/converter/other/pamtosvg/fit.c b/converter/other/pamtosvg/fit.c index 5ba7a2f6..179b3bdf 100644 --- a/converter/other/pamtosvg/fit.c +++ b/converter/other/pamtosvg/fit.c @@ -67,7 +67,7 @@ real_to_int_coord(float_coord const real_coord) { int_coord.col = ROUND(real_coord.x); int_coord.row = ROUND(real_coord.y); - + return int_coord; } @@ -152,7 +152,7 @@ find_vectors(unsigned int const test_index, in->dx = in->dy = in->dz = 0.0; out->dx = out->dy = out->dz = 0.0; - + /* Add up the differences from p of the `corner_surround' points before p. */ @@ -160,7 +160,7 @@ find_vectors(unsigned int const test_index, n_done < corner_surround; i = O_PREV(outline, i), ++n_done) *in = Vadd(*in, IPsubtract(O_COORDINATE(outline, i), candidate)); - + /* And the points after p. */ for (i = O_NEXT (outline, test_index), n_done = 0; n_done < corner_surround; @@ -207,19 +207,19 @@ lookAheadForBetterCorner(pixel_outline_type const outline, bestCornerIndex = basePixelSeq; /* initial assumption */ bestCornerAngle = baseCornerAngle; /* initial assumption */ - + equallyGoodList = new_index_list(); - + q = basePixelSeq; i = basePixelSeq + 1; /* Start with the next pixel */ - + while (i < bestCornerIndex + cornerSurround && i < O_LENGTH(outline) && !at_exception_got_fatal(exceptionP)) { vector_type inVector, outVector; float cornerAngle; - + /* Check the angle. */ q = i % O_LENGTH(outline); @@ -446,7 +446,7 @@ filter(curve * const curveP, unsigned int iteration, thisPoint; float_coord prevNewPoint; - + /* We must have at least three points -- the previous one, the current one, and the next one. But if we don't have at least five, we will probably collapse the curve down onto a single point, which means @@ -460,26 +460,26 @@ filter(curve * const curveP, prevNewPoint.x = FLT_MAX; prevNewPoint.y = FLT_MAX; prevNewPoint.z = FLT_MAX; - + for (iteration = 0; iteration < fittingOptsP->filter_iterations; ++iteration) { curve * const newcurveP = copy_most_of_curve(curveP); bool collapsed; - + collapsed = false; /* initial value */ /* Keep the first point on the curve. */ if (offset) append_point(newcurveP, CURVE_POINT(curveP, 0)); - + for (thisPoint = offset; thisPoint < CURVE_LENGTH(curveP) - offset; ++thisPoint) { vector_type in, out, sum; float_coord newPoint; - + /* Calculate the vectors in and out, computed by looking at n points on either side of this_point. Experimental it was found that 2 is optimal. @@ -488,12 +488,12 @@ filter(curve * const curveP, signed int prev, prevprev; /* have to be signed */ unsigned int next, nextnext; float_coord candidate = CURVE_POINT(curveP, thisPoint); - + prev = CURVE_PREV(curveP, thisPoint); prevprev = CURVE_PREV(curveP, prev); next = CURVE_NEXT(curveP, thisPoint); nextnext = CURVE_NEXT(curveP, next); - + /* Add up the differences from p of the `surround' points before p. */ @@ -503,18 +503,18 @@ filter(curve * const curveP, if (prevprev >= 0) in = Vadd(in, Psubtract(CURVE_POINT(curveP, prevprev), candidate)); - + /* And the points after p. Don't use more points after p than we ended up with before it. */ out.dx = out.dy = out.dz = 0.0; - + out = Vadd(out, Psubtract(CURVE_POINT(curveP, next), candidate)); if (nextnext < CURVE_LENGTH(curveP)) out = Vadd(out, Psubtract(CURVE_POINT(curveP, nextnext), candidate)); - + /* Start with the old point. */ newPoint = candidate; sum = Vadd(in, out); @@ -528,13 +528,13 @@ filter(curve * const curveP, collapsed = true; break; } - + /* Put the newly computed point into a separate curve, so it doesn't affect future computation (on this iteration). */ append_point(newcurveP, prevNewPoint = newPoint); } - + if (collapsed) free_curve(newcurveP); else { @@ -543,7 +543,7 @@ filter(curve * const curveP, */ if (offset) append_point(newcurveP, LAST_CURVE_POINT(curveP)); - + /* Set the original curve to the newly filtered one, and go again. */ @@ -560,7 +560,7 @@ removeAdjacent(index_list_type * const cornerListP, pixel_outline_type const outline, fitting_opts_type * const fittingOptsP, at_exception_type * const exception) { - + /* We never want two corners next to each other, since the only way to fit such a ``curve'' would be with a straight line, which usually interrupts the continuity dreadfully. @@ -598,7 +598,7 @@ find_corners(pixel_outline_type const outline, establishCornerSearchLimits(outline, fittingOptsP, &firstPixelSeq, &lastPixelSeq); - + /* Consider each pixel on the outline in turn. */ for (p = firstPixelSeq; p <= lastPixelSeq;) { vector_type inVector, outVector; @@ -655,10 +655,10 @@ find_corners(pixel_outline_type const outline, && bestCornerIndex >= p) { unsigned int j; - + appendCorner(&cornerList, bestCornerIndex, outline, bestCornerAngle, '/'); - + for (j = 0; j < INDEX_LIST_LENGTH (equallyGoodList); ++j) appendCorner(&cornerList, GET_INDEX(equallyGoodList, j), outline, bestCornerAngle, '@'); @@ -675,7 +675,7 @@ find_corners(pixel_outline_type const outline, } removeAdjacent(&cornerList, outline, fittingOptsP, exceptionP); -cleanup: +cleanup: return cornerList; } @@ -696,12 +696,12 @@ makeOutlineOneCurve(pixel_outline_type const outline, for (pixelSeq = 0; pixelSeq < O_LENGTH(outline); ++pixelSeq) append_pixel(curveP, O_COORDINATE(outline, pixelSeq)); - + if (outline.open) CURVE_CYCLIC(curveP) = false; else CURVE_CYCLIC(curveP) = true; - + /* Make it a one-curve cycle */ NEXT_CURVE(curveP) = curveP; PREVIOUS_CURVE(curveP) = curveP; @@ -728,23 +728,23 @@ addCurveStartingAtCorner(pixel_outline_type const outline, Don't include beginning and ending slope information for that curve. -----------------------------------------------------------------------------*/ unsigned int const cornerPixelSeq = GET_INDEX(cornerList, cornerSeq); - + unsigned int lastPixelSeq; curve * curveP; unsigned int pixelSeq; - + if (cornerSeq + 1 >= cornerList.length) /* No more corners, so we go through the end of the outline. */ lastPixelSeq = O_LENGTH(outline) - 1; else /* Go through the next corner */ lastPixelSeq = GET_INDEX(cornerList, cornerSeq + 1); - + curveP = new_curve(); for (pixelSeq = cornerPixelSeq; pixelSeq <= lastPixelSeq; ++pixelSeq) append_pixel(curveP, O_COORDINATE(outline, pixelSeq)); - + append_curve(curveListP, curveP); { /* Add the new curve to the outline chain */ @@ -803,7 +803,7 @@ divideOutlineWithCorners(pixel_outline_type const outline, */ curve * curveP; unsigned int pixelSeq; - + curveP = new_curve(); for (pixelSeq = 0; pixelSeq <= GET_INDEX(cornerList, 0); ++pixelSeq) @@ -897,7 +897,7 @@ split_at_corners(pixel_outline_list_type const pixel_list, curve_list.open = outline.open; LOG1("#%u:", outlineSeq); - + /* If the outline does not have enough points, we can't do anything. The endpoints of the outlines are automatically corners. We need at least `corner_surround' more pixels on @@ -926,7 +926,7 @@ split_at_corners(pixel_outline_list_type const pixel_list, makeOutlineOneCurve(outline, &curve_list); else divideOutlineWithCorners(outline, corner_list, &curve_list); - + LOG1(" [%u].\n", corner_list.length); free_index_list(&corner_list); @@ -947,7 +947,7 @@ removeKnees(curve_list_type const curveList) { removing a point that should be a corner. -----------------------------------------------------------------------------*/ unsigned int curveSeq; - + LOG("\nRemoving knees:\n"); for (curveSeq = 0; curveSeq < curveList.length; ++curveSeq) { LOG1("#%u:", curveSeq); @@ -955,7 +955,7 @@ removeKnees(curve_list_type const curveList) { CURVE_LIST_CLOCKWISE(curveList)); } } - + static void @@ -966,7 +966,7 @@ computePointWeights(curve_list_type const curveList, unsigned int const height = distP->height; unsigned int curveSeq; - + for (curveSeq = 0; curveSeq < curveList.length; ++curveSeq) { unsigned pointSeq; curve_type const curve = CURVE_LIST_ELT(curveList, curveSeq); @@ -974,13 +974,13 @@ computePointWeights(curve_list_type const curveList, float_coord * const coordP = &CURVE_POINT(curve, pointSeq); unsigned int x = coordP->x; unsigned int y = height - (unsigned int)coordP->y - 1; - + float width, w; /* Each (x, y) is a point on the skeleton of the curve, which might be offset from the true centerline, where the width is maximal. Therefore, use as the local line width the - maximum distance over the neighborhood of (x, y). + maximum distance over the neighborhood of (x, y). */ width = distP->d[y][x]; /* initial value */ if (y - 1 >= 0) { @@ -1017,7 +1017,7 @@ computePointWeights(curve_list_type const curveList, static void filterCurves(curve_list_type const curveList, fitting_opts_type * const fittingOptsP) { - + unsigned int curveSeq; LOG("\nFiltering curves:\n"); @@ -1044,8 +1044,8 @@ logSplinesForCurve(unsigned int const curveSeq, if (log_file) print_spline(log_file, SPLINE_LIST_ELT(curveSplines, splineSeq)); } -} - +} + static void @@ -1212,7 +1212,7 @@ fitWithLine(curve * const curveP) { #define B3(t) CUBE (t) static spline_type -fitOneSpline(curve * const curveP, +fitOneSpline(curve * const curveP, vector_type const begSlope, vector_type const endSlope, at_exception_type * const exceptionP) { @@ -1311,7 +1311,7 @@ fitOneSpline(curve * const curveP, free(A); C.end.beg = C.beg.end; - + X_Cend_det = X.beg * C.end.end - X.end * C.beg.end; Cbeg_X_det = C.beg.beg * X.end - C.beg.end * X.beg; C_det = C.beg.beg * C.end.end - C.end.beg * C.beg.end; @@ -1328,7 +1328,7 @@ fitOneSpline(curve * const curveP, CONTROL2(spline) = Vadd_point(END_POINT(spline), Vmult_scalar(tang.end, alpha.end)); SPLINE_DEGREE(spline) = CUBICTYPE; - } + } return spline; } @@ -1341,7 +1341,7 @@ logSplineFit(spline_type const spline) { LOG(" fitted to line:\n"); else LOG(" fitted to spline:\n"); - + if (log_file) { LOG (" "); print_spline (log_file, spline); @@ -1458,7 +1458,7 @@ findTangent(curve * const curveP, means the previous curve in the outline chain for the slope at the start point ('toStartPoint' == true), the next curve otherwise. If *curveP is cyclic, then it is its own adjacent curve. - + It is important to compute an accurate approximation, because the control points that we eventually decide upon to fit the curve will be placed on the half-lines defined by the slopes and endpoints, and @@ -1478,7 +1478,7 @@ findTangent(curve * const curveP, vector_type const slopeAdj = findHalfTangent(!toStartPoint, adjacentCurveP, tangentSurround); - + LOG3("(adjacent curve half tangent (%.3f,%.3f,%.3f)) ", slopeAdj.dx, slopeAdj.dy, slopeAdj.dz); slope = Vmult_scalar(Vadd(slope, slopeAdj), 0.5); @@ -1487,7 +1487,7 @@ findTangent(curve * const curveP, } while (slope.dx == 0.0 && slope.dy == 0.0); *tangentP = slope; - + LOG3("(%.3f,%.3f,%.3f).\n", tangentP->dx, tangentP->dy, tangentP->dz); } @@ -1502,8 +1502,8 @@ findError(curve * const curveP, at_exception_type * const exceptionP) { /*---------------------------------------------------------------------------- Tell how good a fit 'spline' is for *curveP. - - Return the error (maximum Euclidian distance between a point on + + Return the error (maximum Euclidean distance between a point on *curveP and the corresponding point on 'spline') as *errorP and the sequence number of the point on the curve where the error is greatest as *worstPointP. @@ -1521,7 +1521,7 @@ findError(curve * const curveP, totalError = 0.0; /* initial value */ worstError = FLT_MIN; /* initial value */ worstPoint = 0; - + for (thisPoint = 0; thisPoint < CURVE_LENGTH(curveP); ++thisPoint) { float_coord const curvePoint = CURVE_POINT(curveP, thisPoint); float const t = CURVE_T(curveP, thisPoint); @@ -1608,7 +1608,7 @@ subdivideCurve(curve * const curveP, Split curve *curveP into two, at 'subdivisionIndex'. (Actually, leave *curveP alone, but return as *leftCurvePP and *rghtCurvePP two new curves that are the pieces). - + Return as *joinSlopeP what should be the slope where the subcurves join, i.e. the slope of the end of the left subcurve and of the start of the right subcurve. @@ -1670,7 +1670,7 @@ leftRightConcat(const spline_list_type * const leftSplineListP, of splines to that side of the curve. -----------------------------------------------------------------------------*/ spline_list_type * retval; - + retval = new_spline_list(); if (leftSplineListP == NULL) { @@ -1678,7 +1678,7 @@ leftRightConcat(const spline_list_type * const leftSplineListP, at_exception_warning(exceptionP, "Could not fit left spline list"); } else concat_spline_lists(retval, *leftSplineListP); - + if (rghtSplineListP == NULL) { LOG("Could not fit spline to right curve.\n"); at_exception_warning(exceptionP, "Could not fit right spline list"); @@ -1742,7 +1742,7 @@ divideAndFit(curve * const curveP, subcurve. */ spline_list_type * leftSplineListP; - + assert(subdivisionIndex > 1); assert(subdivisionIndex < CURVE_LENGTH(curveP)-1); subdivideCurve(curveP, subdivisionIndex, fittingOptsP, @@ -1792,18 +1792,18 @@ fitWithLeastSquares(curve * const curveP, /*---------------------------------------------------------------------------- The least squares method is well described in Schneider's thesis. Briefly, we try to fit the entire curve with one spline. If that - fails, we subdivide the curve. + fails, we subdivide the curve. -----------------------------------------------------------------------------*/ spline_list_type * retval; spline_type spline; - + LOG("\nFitting with least squares:\n"); - + /* Phoenix reduces the number of points with a "linear spline technique." But for fitting letterforms, that is inappropriate. We want all the points we can get. */ - + setInitialParameterValues(curveP); if (CURVE_CYCLIC(curveP) && CURVE_LENGTH(curveP) < 4) { @@ -1822,7 +1822,7 @@ fitWithLeastSquares(curve * const curveP, unsigned int worstPoint; logSplineFit(spline); - + findError(curveP, spline, &error, &worstPoint, exceptionP); assert(worstPoint < CURVE_LENGTH(curveP)); @@ -1873,7 +1873,7 @@ fitCurve(curve * const curveP, if (CURVE_LENGTH(curveP) < 2) { LOG("Tried to fit curve with fewer than two points"); - at_exception_warning(exceptionP, + at_exception_warning(exceptionP, "Tried to fit curve with less than two points"); fittedSplinesP = NULL; } else if (CURVE_LENGTH(curveP) < 4) @@ -1894,12 +1894,12 @@ fitCurves(curve_list_type const curveList, const fitting_opts_type * const fittingOptsP, spline_list_type * const splinesP, at_exception_type * const exceptionP) { - + spline_list_type curveListSplines; unsigned int curveSeq; curveListSplines = empty_spline_list(); - + curveListSplines.open = curveList.open; curveListSplines.clockwise = curveList.clockwise; curveListSplines.color = color; @@ -1932,13 +1932,13 @@ fitCurves(curve_list_type const curveList, at_exception_warning(exceptionP, "Could not fit curve"); } else { logSplinesForCurve(curveSeq, *curveSplinesP); - + /* After fitting, we may need to change some would-be lines back to curves, because they are in a list with other curves. */ change_bad_lines(curveSplinesP, fittingOptsP); - + concat_spline_lists(&curveListSplines, *curveSplinesP); free_spline_list(*curveSplinesP); free(curveSplinesP); @@ -1950,7 +1950,7 @@ fitCurves(curve_list_type const curveList, else *splinesP = curveListSplines; } - + static void @@ -1989,7 +1989,7 @@ fitCurveList(curve_list_type const curveList, if (dist != NULL) computePointWeights(curveList, fittingOptsP, dist); - + /* We filter all the curves in 'curveList' at once; otherwise, we would look at an unfiltered curve when computing tangents. */ @@ -2030,12 +2030,12 @@ fitCurvesToSplines(curve_list_array_type const curveArray, unsigned short const width, unsigned short const height, at_exception_type * const exception, - at_progress_func notifyProgress, + at_progress_func notifyProgress, void * const progressData, at_testcancel_func testCancel, void * const testcancelData, spline_list_array_type * const splineListArrayP) { - + unsigned splineListSeq; bool cancelled; spline_list_array_type splineListArray; @@ -2049,7 +2049,7 @@ fitCurvesToSplines(curve_list_array_type const curveArray, /* Set dummy values. Real value is set in upper context. */ splineListArray.width = width; splineListArray.height = height; - + for (splineListSeq = 0, cancelled = false; splineListSeq < CURVE_LIST_ARRAY_LENGTH(curveArray) && !at_exception_got_fatal(exception) && !cancelled; @@ -2057,7 +2057,7 @@ fitCurvesToSplines(curve_list_array_type const curveArray, curve_list_type const curveList = CURVE_LIST_ARRAY_ELT(curveArray, splineListSeq); - + spline_list_type curveSplineList; if (notifyProgress) @@ -2087,7 +2087,7 @@ fit_outlines_to_splines(pixel_outline_list_type const pixelOutlineList, unsigned short const width, unsigned short const height, at_exception_type * const exception, - at_progress_func notifyProgress, + at_progress_func notifyProgress, void * const progressData, at_testcancel_func testCancel, void * const testcancelData, @@ -2104,7 +2104,7 @@ fit_outlines_to_splines(pixel_outline_list_type const pixelOutlineList, testCancel, testcancelData, splineListArrayP); free_curve_list_array(&curveListArray, notifyProgress, progressData); - + flush_log_output(); } diff --git a/converter/other/pamtotiff.c b/converter/other/pamtotiff.c index 115b8b4a..1718c933 100644 --- a/converter/other/pamtotiff.c +++ b/converter/other/pamtotiff.c @@ -838,7 +838,7 @@ computeRasterParm(struct pam * const pamP, 2. Direct mode (specified with -output) We have the Tiff library write output to the specified file. As the Tiff - library requires taht it be be seekable and readable, we fail the program + library requires that it be be seekable and readable, we fail the program rather than ask the Tiff library to use the file if it does not meet these requirements. diff --git a/converter/other/pamtowinicon.c b/converter/other/pamtowinicon.c index 3d77d731..e8a9cc23 100644 --- a/converter/other/pamtowinicon.c +++ b/converter/other/pamtowinicon.c @@ -71,8 +71,6 @@ parseCommandLine(int argc, const char **argv, static bool verbose; -static unsigned char const pngHeader[] = PNG_HEADER; - struct Palette { diff --git a/converter/other/pbmtopgm.c b/converter/other/pbmtopgm.c index c35e1cbe..817fb5b3 100644 --- a/converter/other/pbmtopgm.c +++ b/converter/other/pbmtopgm.c @@ -6,6 +6,7 @@ #include #include "pm_c_util.h" +#include "nstring.h" #include "pgm.h" int @@ -17,26 +18,23 @@ main(int argc, char *argv[]) { int rows, cols; FILE *ifd; int row; - int width, height; + unsigned int width, height; const char * const usage = " [pbmfile]"; - + const char * error; /* error message of pm_string_to_uint */ pgm_init( &argc, argv ); if (argc > 4 || argc < 3) pm_usage(usage); - width = atoi(argv[1]); - height = atoi(argv[2]); + pm_string_to_uint(argv[1], &width, &error); + if (error) + pm_error("Invalid width argument: %s", error); + pm_string_to_uint(argv[2], &height, &error); + if (error) + pm_error("Invalid height argument: %s", error); if (width < 1 || height < 1) pm_error("width and height must be > 0"); - if (width > INT_MAX / height) - /* prevent overflow of "value" below */ - pm_error("sample area (%u columns %u rows) too large", - width, height); - - left=width/2; right=width-left; - up=height/2; down=height-up; if (argc == 4) ifd = pm_openr(argv[3]); @@ -44,13 +42,22 @@ main(int argc, char *argv[]) { ifd = stdin ; inbits = pbm_readpbm(ifd, &cols, &rows) ; - + if (width > cols) pm_error("You specified a sample width (%u columns) which is greater " "than the image width (%u columns)", height, rows); if (height > rows) pm_error("You specified a sample height (%u rows) which is greater " "than the image height (%u rows)", height, rows); + if (width > INT_MAX / height) + /* prevent overflow of "value" below */ + pm_error("sample area (%u columns %u rows) too large", + width, height); + + left = width / 2; right = width - left; + up = height / 2; down = height - up; + + outrow = pgm_allocrow(cols) ; maxval = MIN(PGM_OVERALLMAXVAL, width*height); @@ -65,7 +72,7 @@ main(int argc, char *argv[]) { int const l = (col > left) ? (col-left) : 0; int const r = (col+right < cols) ? (col+right) : cols; int const onh = width - (l-col+left) - (col+right-r); - int value; + int value; /* See above */ int x; value = 0; /* initial value */ @@ -73,10 +80,10 @@ main(int argc, char *argv[]) { for (x = l; x < r; ++x) { int y; for (y = t; y < b; ++y) - if (inbits[y][x] == PBM_WHITE) + if (inbits[y][x] == PBM_WHITE) ++value; } - outrow[col] = maxval*value/(onh*onv); + outrow[col] = (gray) ((double) maxval*value/(onh*onv)); } pgm_writepgmrow(stdout, outrow, cols, maxval, 0) ; } diff --git a/converter/other/pngtopam.c b/converter/other/pngtopam.c index 1023c6c6..9098154a 100644 --- a/converter/other/pngtopam.c +++ b/converter/other/pngtopam.c @@ -22,7 +22,7 @@ #include #include #include -/* Becaues of a design error in png.h, you must not #include before +/* Because of a design error in png.h, you must not #include before . If you do, png.h won't compile. */ #include diff --git a/converter/other/pnmtoddif.c b/converter/other/pnmtoddif.c index ac02e425..b7b942b3 100644 --- a/converter/other/pnmtoddif.c +++ b/converter/other/pnmtoddif.c @@ -53,7 +53,7 @@ typedef struct { #define CONS 1 /* "tag": Emit an ASN tag of the specified class and tag number. */ -/* This is used in conjuntion with the */ +/* This is used in conjunction with the */ /* wr_xxx routines that follow to construct the various ASN.1 entities. */ /* Writing each entity is a two-step process, where first the tag is */ /* written and then the length and value. */ @@ -263,7 +263,7 @@ write_header(FILE *file, imageparams *ip) tag(&p,CONTEXT,CONS, 0); ind(&p); /* Document Descriptor */ tag(&p,CONTEXT,PRIM, 0); wr_int(&p,1); /* Major Version */ tag(&p,CONTEXT,PRIM, 1); wr_int(&p,3); /* Minor Version */ - tag(&p,CONTEXT,PRIM, 2); wr_string(&p,"PBM+"); /* Product Indentifier */ + tag(&p,CONTEXT,PRIM, 2); wr_string(&p,"PBM+"); /* Product Identifier */ tag(&p,CONTEXT,CONS, 3); ind(&p); /* Product Name */ tag(&p,PRIVATE,PRIM, 9); emit_isolatin1(&p,"PBMPLUS Writer V1.0"); eoc(&p); diff --git a/converter/other/pnmtojpeg.c b/converter/other/pnmtojpeg.c index 44826245..e3458319 100644 --- a/converter/other/pnmtojpeg.c +++ b/converter/other/pnmtojpeg.c @@ -9,7 +9,7 @@ This program is by Bryan Henderson on 2000.03.06, but is derived with permission from the program cjpeg, which is in the Independent Jpeg Group's JPEG library package. Under the terms of that permission, - redistribution of this software is restricted as described in the + redistribution of this software is restricted as described in the file README.JPEG. Copyright (C) 1991-1998, Thomas G. Lane. @@ -84,12 +84,12 @@ struct cmdlineInfo { struct density density; }; -static void -interpret_maxmemory (const char * const maxmemory, - long int * const max_memory_to_use_p) { +static void +interpret_maxmemory (const char * const maxmemory, + long int * const max_memory_to_use_p) { long int lval; char ch; - + if (maxmemory == NULL) { *max_memory_to_use_p = -1; /* unspecified */ } else if (sscanf(maxmemory, "%ld%c", &lval, &ch) < 1) { @@ -119,9 +119,9 @@ interpret_restart(const char * const restart, long lval; char ch; unsigned int matches; - + matches= sscanf(restart, "%ld%c", &lval, &ch); - if (matches == 0) + if (matches == 0) pm_error("Invalid value for the --restart option : '%s'.", restart); else { @@ -160,7 +160,7 @@ interpret_density(const char * const densityString, int horiz, vert; unitName = malloc(strlen(densityString)+1); - + matched = sscanf(densityString, "%dx%d%s", &horiz, &vert, unitName); if (matched < 2) @@ -178,7 +178,7 @@ interpret_density(const char * const densityString, densityP->horiz = horiz; densityP->vert = vert; - if (matched < 3) + if (matched < 3) densityP->unit = DEN_UNSPECIFIED; else { if (streq(unitName, "dpi") || streq(unitName, "DPI")) @@ -235,7 +235,7 @@ parseCommandLine(const int argc, char ** argv, option_def_index = 0; /* incremented by OPTENTRY */ OPTENT3(0, "verbose", OPT_FLAG, NULL, &cmdlineP->verbose, 0); - OPTENT3(0, "quality", OPT_UINT, &cmdlineP->quality, + OPTENT3(0, "quality", OPT_UINT, &cmdlineP->quality, &qualitySpec, 0); OPTENT3(0, "baseline", OPT_FLAG, NULL, &cmdlineP->force_baseline, 0); OPTENT3(0, "progressive", OPT_FLAG, NULL, &cmdlineP->progressive, 0); @@ -250,14 +250,14 @@ parseCommandLine(const int argc, char ** argv, OPTENT3(0, "qtables", OPT_STRING, &cmdlineP->qtablefile, NULL, 0); OPTENT3(0, "sample", OPT_STRING, &cmdlineP->sample, NULL, 0); OPTENT3(0, "scans", OPT_STRING, &cmdlineP->scans, NULL, 0); - OPTENT3(0, "smooth", OPT_UINT, &cmdlineP->smoothing_factor, + OPTENT3(0, "smooth", OPT_UINT, &cmdlineP->smoothing_factor, &smoothSpec, 0); OPTENT3(0, "optimize", OPT_FLAG, NULL, &cmdlineP->optimize, 0); OPTENT3(0, "optimise", OPT_FLAG, NULL, &cmdlineP->optimize, 0); OPTENT3(0, "restart", OPT_STRING, &restart, NULL, 0); OPTENT3(0, "comment", OPT_STRING, &cmdlineP->comment, NULL, 0); OPTENT3(0, "exif", OPT_STRING, &cmdlineP->exif_filespec, NULL, 0); - OPTENT3(0, "density", OPT_STRING, &density, + OPTENT3(0, "density", OPT_STRING, &density, &cmdlineP->density_spec, 0); /* Set the defaults */ @@ -295,7 +295,7 @@ parseCommandLine(const int argc, char ** argv, cmdlineP->input_filespec = strdup("-"); /* he wants stdin */ else if (argc_parse - 1 == 1) cmdlineP->input_filespec = strdup(argv_parse[1]); - else + else pm_error("Too many arguments. The only argument accepted " "is the input file specification."); if (dctval == NULL) @@ -314,15 +314,15 @@ parseCommandLine(const int argc, char ** argv, interpret_maxmemory(maxmemory, &cmdlineP->max_memory_to_use); interpret_restart(restart, &cmdlineP->restart_value, &cmdlineP->restart_unit); - if (cmdlineP->density_spec) + if (cmdlineP->density_spec) interpret_density(density, &cmdlineP->density); - + if (cmdlineP->smoothing_factor > 100) pm_error("Smoothing factor %d is greater than 100 (%%).", cmdlineP->smoothing_factor); if (streq(cmdlineP->input_filespec, "=") && - cmdlineP->exif_filespec && + cmdlineP->exif_filespec && streq(cmdlineP->exif_filespec, "-")) pm_error("Cannot have both input image and exif header be from " @@ -336,7 +336,7 @@ parseCommandLine(const int argc, char ** argv, static void report_compressor(const struct jpeg_compress_struct cinfo) { - + if (cinfo.scan_info == NULL) pm_message("No scan script is being used"); else { @@ -346,7 +346,7 @@ report_compressor(const struct jpeg_compress_struct cinfo) { for (i = 0; i < cinfo.num_scans; i++) { int j; pm_message(" Scan %2d: Ss=%2d Se=%2d Ah=%2d Al=%2d " - "%d components", + "%d components", i, cinfo.scan_info[i].Ss, cinfo.scan_info[i].Se, @@ -364,11 +364,11 @@ report_compressor(const struct jpeg_compress_struct cinfo) { static void -setup_jpeg_source_parameters(struct jpeg_compress_struct * const cinfoP, - int const width, int const height, +setup_jpeg_source_parameters(struct jpeg_compress_struct * const cinfoP, + int const width, int const height, int const format) { /*---------------------------------------------------------------------------- - Set up in the compressor descriptor *cinfoP the description of the + Set up in the compressor descriptor *cinfoP the description of the source image as required by the compressor. -----------------------------------------------------------------------------*/ @@ -379,7 +379,7 @@ setup_jpeg_source_parameters(struct jpeg_compress_struct * const cinfoP, cinfoP->input_components = 1; break; case PPM_TYPE: - cinfoP->in_color_space = JCS_RGB; + cinfoP->in_color_space = JCS_RGB; cinfoP->input_components = 3; break; default: @@ -391,7 +391,7 @@ setup_jpeg_source_parameters(struct jpeg_compress_struct * const cinfoP, static void -setup_jpeg_density(struct jpeg_compress_struct * const cinfoP, +setup_jpeg_density(struct jpeg_compress_struct * const cinfoP, struct density const density) { /*---------------------------------------------------------------------------- Set up in the compressor descriptor *cinfoP the density information @@ -402,7 +402,7 @@ setup_jpeg_density(struct jpeg_compress_struct * const cinfoP, case DEN_DOTS_PER_INCH: cinfoP->density_unit = 1; break; case DEN_DOTS_PER_CM: cinfoP->density_unit = 2; break; } - + cinfoP->X_density = density.horiz; cinfoP->Y_density = density.vert; } @@ -411,7 +411,7 @@ setup_jpeg_density(struct jpeg_compress_struct * const cinfoP, /*---------------------------------------------------------------------------- The functions below here are essentially the file rdswitch.c from - the JPEG library. They perform the functions specifed by the following + the JPEG library. They perform the functions specified by the following pnmtojpeg options: -qtables file Read quantization tables from text file @@ -426,7 +426,7 @@ text_getc (FILE * file) /* A comment/newline sequence is returned as a newline */ { register int ch; - + ch = getc(file); if (ch == '#') { do { @@ -454,12 +454,12 @@ readTextInteger(FILE * const fileP, -----------------------------------------------------------------------------*/ int ch; boolean retval; - + /* Skip any leading whitespace, detect EOF */ do { ch = text_getc(fileP); } while (isspace(ch)); - + if (!isdigit(ch)) retval = FALSE; else { @@ -554,7 +554,7 @@ read_scan_script(j_compress_ptr const cinfo, ncomps = 1; while (termchar == ' ') { if (ncomps >= MAX_COMPS_IN_SCAN) { - pm_message("Too many components in one scan in file %s", + pm_message("Too many components in one scan in file %s", filename); fclose(fp); return FALSE; @@ -603,10 +603,10 @@ read_scan_script(j_compress_ptr const cinfo, /* Stash completed scan list in cinfo structure. NOTE: in this program, JPOOL_IMAGE is the right lifetime for this data, but if you want to compress multiple images you'd - want JPOOL_PERMANENT. + want JPOOL_PERMANENT. */ const unsigned int scan_info_size = nscans * sizeof(jpeg_scan_info); - jpeg_scan_info * const scan_info = + jpeg_scan_info * const scan_info = (jpeg_scan_info *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, scan_info_size); @@ -656,7 +656,7 @@ read_quant_tables (j_compress_ptr cinfo, char * filename, if (tblno >= NUM_QUANT_TBLS) { pm_message("Too many tables in file %s", filename); error = TRUE; - } else { + } else { unsigned int table[DCTSIZE2]; unsigned int i; @@ -686,7 +686,7 @@ read_quant_tables (j_compress_ptr cinfo, char * filename, fclose(fp); retval = !error; } - + return retval; } @@ -717,7 +717,7 @@ set_quant_slots (j_compress_ptr cinfo, char *arg) return FALSE; } cinfo->comp_info[ci].quant_tbl_no = val; - while (*arg && *arg++ != ',') + while (*arg && *arg++ != ',') /* advance to next segment of arg string */ ; } else { @@ -747,7 +747,7 @@ set_sample_factors (j_compress_ptr cinfo, char *arg) if ((ch1 != 'x' && ch1 != 'X') || ch2 != ',') /* syntax check */ return FALSE; if (val1 <= 0 || val1 > 4) { - pm_message("Invalid sampling factor: %d. " + pm_message("Invalid sampling factor: %d. " "JPEG sampling factors must be 1..4", val1); return FALSE; } @@ -758,11 +758,11 @@ set_sample_factors (j_compress_ptr cinfo, char *arg) } cinfo->comp_info[ci].h_samp_factor = val1; cinfo->comp_info[ci].v_samp_factor = val2; - while (*arg && *arg++ != ',') + while (*arg && *arg++ != ',') /* advance to next segment of arg string */ ; } else { - /* reached end of parameter, set remaining components + /* reached end of parameter, set remaining components to 1x1 sampling */ cinfo->comp_info[ci].h_samp_factor = 1; cinfo->comp_info[ci].v_samp_factor = 1; @@ -776,13 +776,13 @@ set_sample_factors (j_compress_ptr cinfo, char *arg) static void setup_jpeg(struct jpeg_compress_struct * const cinfoP, struct jpeg_error_mgr * const jerrP, - struct cmdlineInfo const cmdline, + struct cmdlineInfo const cmdline, int const width, int const height, pixval const maxval, int const input_fmt, FILE * const output_file) { - + int quality; int q_scale_factor; @@ -794,14 +794,14 @@ setup_jpeg(struct jpeg_compress_struct * const cinfoP, jpeg_set_defaults(cinfoP); - cinfoP->data_precision = BITS_IN_JSAMPLE; + cinfoP->data_precision = BITS_IN_JSAMPLE; /* we always rescale data to this */ cinfoP->image_width = (unsigned int) width; cinfoP->image_height = (unsigned int) height; cinfoP->arith_code = cmdline.arith_code; cinfoP->dct_method = cmdline.dct_method; - if (cmdline.trace_level == 0 && cmdline.verbose) + if (cmdline.trace_level == 0 && cmdline.verbose) cinfoP->err->trace_level = 1; else cinfoP->err->trace_level = cmdline.trace_level; if (cmdline.grayscale) @@ -822,26 +822,26 @@ setup_jpeg(struct jpeg_compress_struct * const cinfoP, quality = cmdline.quality; q_scale_factor = jpeg_quality_scaling(cmdline.quality); } - if (cmdline.smoothing_factor != -1) + if (cmdline.smoothing_factor != -1) cinfoP->smoothing_factor = cmdline.smoothing_factor; /* Set quantization tables for selected quality. */ /* Some or all may be overridden if user specified --qtables. */ jpeg_set_quality(cinfoP, quality, cmdline.force_baseline); - + if (cmdline.qtablefile != NULL) { if (! read_quant_tables(cinfoP, cmdline.qtablefile, - q_scale_factor, cmdline.force_baseline)) + q_scale_factor, cmdline.force_baseline)) pm_error("Can't use quantization table file '%s'.", cmdline.qtablefile); } - + if (cmdline.qslots != NULL) { if (! set_quant_slots(cinfoP, cmdline.qslots)) - pm_error("Bad quantization-table-selectors parameter string '%s'.", + pm_error("Bad quantization-table-selectors parameter string '%s'.", cmdline.qslots); } - + if (cmdline.sample != NULL) { if (! set_sample_factors(cinfoP, cmdline.sample)) pm_error("Bad sample-factors parameters string '%s'.", @@ -878,7 +878,7 @@ write_exif_header(struct jpeg_compress_struct * const cinfoP, /*---------------------------------------------------------------------------- Generate an APP1 marker in the JFIF output that is an Exif header. - The contents of the Exif header are in the file with filespec + The contents of the Exif header are in the file with filespec 'exif_filespec' (file spec and contents are not validated). exif_filespec = "-" means Standard Input. @@ -888,7 +888,7 @@ write_exif_header(struct jpeg_compress_struct * const cinfoP, -----------------------------------------------------------------------------*/ FILE * exif_file; unsigned short length; - + exif_file = pm_openr(exif_filespec); pm_readbigshort(exif_file, (short*)&length); @@ -900,7 +900,7 @@ write_exif_header(struct jpeg_compress_struct * const cinfoP, else { unsigned char * exif_data; size_t rc; - size_t const data_length = length - 2; + size_t const data_length = length - 2; /* Subtract 2 byte length field*/ assert(data_length > 0); @@ -917,16 +917,16 @@ write_exif_header(struct jpeg_compress_struct * const cinfoP, "%u bytes of data, read only %u", (unsigned)data_length, (unsigned)rc); - jpeg_write_marker(cinfoP, JPEG_APP0+1, + jpeg_write_marker(cinfoP, JPEG_APP0+1, (const JOCTET *) exif_data, data_length); free(exif_data); } - + pm_close(exif_file); } - + static void compute_rescaling_array(JSAMPLE ** const rescale_p, const pixval maxval, @@ -940,7 +940,7 @@ compute_rescaling_array(JSAMPLE ** const rescale_p, const pixval maxval, *rescale_p = (JSAMPLE *) (cinfo.mem->alloc_small) ((j_common_ptr) &cinfo, JPOOL_IMAGE, - (size_t) (((long) maxval + 1L) * + (size_t) (((long) maxval + 1L) * sizeof(JSAMPLE))); for (val = 0; val <= maxval; val++) { /* The multiplication here must be done in 32 bits to avoid overflow */ @@ -951,9 +951,9 @@ compute_rescaling_array(JSAMPLE ** const rescale_p, const pixval maxval, static void -translate_row(const pixel pnm_buffer[], - JSAMPLE jpeg_buffer[], - int const width, +translate_row(const pixel pnm_buffer[], + JSAMPLE jpeg_buffer[], + int const width, int const input_components, const JSAMPLE translate[]) { /*---------------------------------------------------------------------------- @@ -971,16 +971,16 @@ translate_row(const pixel pnm_buffer[], switch (input_components) { case 1: - for (column = 0; column < width; column++) + for (column = 0; column < width; column++) jpeg_buffer[column] = translate[(int)PNM_GET1(pnm_buffer[column])]; break; case 3: for (column = 0; column < width; column++) { - jpeg_buffer[column*3+0] = + jpeg_buffer[column*3+0] = translate[(int)PPM_GETR(pnm_buffer[column])]; - jpeg_buffer[column*3+1] = + jpeg_buffer[column*3+1] = translate[(int)PPM_GETG(pnm_buffer[column])]; - jpeg_buffer[column*3+2] = + jpeg_buffer[column*3+2] = translate[(int)PPM_GETB(pnm_buffer[column])]; } break; @@ -1000,17 +1000,17 @@ convert_scanlines(struct jpeg_compress_struct * const cinfo_p, int const input_fmt, JSAMPLE xlate_table[]){ /*---------------------------------------------------------------------------- - Read scan lines from the input file, which is already opened in the - netpbm library sense and ready for reading, and write them to the + Read scan lines from the input file, which is already opened in the + netpbm library sense and ready for reading, and write them to the output JPEG object. Translate the pnm sample values to JPEG sample values through the thable xlate_table[]. -----------------------------------------------------------------------------*/ - xel * pnm_buffer; + xel * pnm_buffer; /* contains the row of the input image currently being processed, in pnm_readpnmrow format */ JSAMPARRAY buffer; - /* Row 0 of this array contains the row of the output image currently + /* Row 0 of this array contains the row of the output image currently being processed, in JPEG compressor input format. The array only has that one row. */ @@ -1018,26 +1018,26 @@ convert_scanlines(struct jpeg_compress_struct * const cinfo_p, /* Allocate the libpnm output and compressor input buffers */ buffer = (*cinfo_p->mem->alloc_sarray) ((j_common_ptr) cinfo_p, JPOOL_IMAGE, - (unsigned int) cinfo_p->image_width * cinfo_p->input_components, + (unsigned int) cinfo_p->image_width * cinfo_p->input_components, (unsigned int) 1); - + pnm_buffer = pnm_allocrow(cinfo_p->image_width); while (cinfo_p->next_scanline < cinfo_p->image_height) { - if (cinfo_p->err->trace_level > 1) + if (cinfo_p->err->trace_level > 1) pm_message("Converting Row %d...", cinfo_p->next_scanline); - pnm_readpnmrow(input_file, pnm_buffer, cinfo_p->image_width, + pnm_readpnmrow(input_file, pnm_buffer, cinfo_p->image_width, maxval, input_fmt); - translate_row(pnm_buffer, buffer[0], + translate_row(pnm_buffer, buffer[0], cinfo_p->image_width, cinfo_p->input_components, xlate_table); jpeg_write_scanlines(cinfo_p, buffer, 1); - if (cinfo_p->err->trace_level > 1) + if (cinfo_p->err->trace_level > 1) pm_message("Done."); } pnm_freerow(pnm_buffer); - /* Don't worry about the compressor input buffer; it gets freed + /* Don't worry about the compressor input buffer; it gets freed automatically */ } @@ -1053,11 +1053,11 @@ main(int argc, struct jpeg_error_mgr jerr; FILE * input_file; FILE * output_file; - int height; + int height; /* height of the input image in rows, as specified by its header */ - int width; + int width; /* width of the input image in columns, as specified by its header */ - pixval maxval; + pixval maxval; /* maximum value of an input pixel component, as specified by header */ int input_fmt; /* The input format, as determined by its header. */ @@ -1081,7 +1081,7 @@ main(int argc, if (cmdline.verbose) { pm_message("Input file has format %c%c.\n" "It has %d rows of %d columns of pixels " - "with max sample value of %d.", + "with max sample value of %d.", (char) (input_fmt/256), (char) (input_fmt % 256), height, width, maxval); } @@ -1091,13 +1091,13 @@ main(int argc, compute_rescaling_array(&rescale, maxval, cinfo); - if (cmdline.comment) - jpeg_write_marker(&cinfo, JPEG_COM, (const JOCTET *) cmdline.comment, + if (cmdline.comment) + jpeg_write_marker(&cinfo, JPEG_COM, (const JOCTET *) cmdline.comment, strlen(cmdline.comment)); if (cmdline.exif_filespec) write_exif_header(&cinfo, cmdline.exif_filespec); - + /* Translate and copy over the actual scanlines */ convert_scanlines(&cinfo, input_file, maxval, input_fmt, rescale); @@ -1110,7 +1110,10 @@ main(int argc, pm_close(input_file); /* Program may have exited with non-zero completion code via - various function calls above. + various function calls above. */ return jerr.num_warnings > 0 ? EXIT_WARNING : EXIT_SUCCESS; } + + + diff --git a/converter/other/pnmtopalm/README b/converter/other/pnmtopalm/README index ebae9492..3a2cf18d 100644 --- a/converter/other/pnmtopalm/README +++ b/converter/other/pnmtopalm/README @@ -40,7 +40,7 @@ Usage: ppmtoTbmp [-2bit] [file.ppm] If the ppm file is not specified, one is read from stdin. The -2bit option produces a 2-bit bitmap instead of the normal 1-bit bitmap. The ppm must have at most 4 colors in it (for 2-bit) or at most 2 colors (for 1-bit). -Common invokations might be: +Common invocations might be: xbmtopbm icon.xbm | ppmquant -fs -map q2.map | ppmtoTbmp > tAIB03e8.bin giftopnm image.gif | ppmquant -fs -map q4.map | ppmtoTbmp -2bit > Tbmp0bb8.bin diff --git a/converter/other/pnmtopalm/pnmtopalm.c b/converter/other/pnmtopalm/pnmtopalm.c index 4f535d1a..9fc92790 100644 --- a/converter/other/pnmtopalm/pnmtopalm.c +++ b/converter/other/pnmtopalm/pnmtopalm.c @@ -787,7 +787,7 @@ computeRawRowNonDirect(const xel * const xelrow, sizeof(ColormapEntry), palmcolor_compare_colors); if (!foundEntryP) { - pm_error("INERNAL ERROR: " + pm_error("INTERNAL ERROR: " "Color (%u,%u,%u) not found in colormap, " "though it was supposedly there before", PPM_GETR(xelrow[col]), diff --git a/converter/other/pnmtopng.c b/converter/other/pnmtopng.c index 60b8276b..b7bd6d07 100644 --- a/converter/other/pnmtopng.c +++ b/converter/other/pnmtopng.c @@ -424,7 +424,7 @@ parseCommandLine(int argc, const char ** argv, cmdlineP->palette = NULL; if (filterSpec && (nofilter + sub + up + avg + paeth > 0)) - pm_error("You may mot specify -filter with " + pm_error("You may not specify -filter with " "-nofilter, -sub, -up, -avg, or -paeth"); if (filterSpec) { diff --git a/converter/other/pnmtops.c b/converter/other/pnmtops.c index de0dfd8d..45d856d0 100644 --- a/converter/other/pnmtops.c +++ b/converter/other/pnmtops.c @@ -125,8 +125,8 @@ static bool verbose; static void -parseDpi(const char * const dpiOpt, - unsigned int * const dpiXP, +parseDpi(const char * const dpiOpt, + unsigned int * const dpiXP, unsigned int * const dpiYP) { char *dpistr2; @@ -253,9 +253,9 @@ parseCommandLine(int argc, const char ** argv, OPTENT3(0, "showpage", OPT_FLAG, NULL, &showpage, 0); OPTENT3(0, "verbose", OPT_FLAG, NULL, &cmdlineP->verbose, 0); OPTENT3(0, "debug", OPT_FLAG, NULL, &cmdlineP->debug, 0); - OPTENT3(0, "level", OPT_UINT, &cmdlineP->level, + OPTENT3(0, "level", OPT_UINT, &cmdlineP->level, &cmdlineP->levelSpec, 0); - + opt.opt_table = option_def; opt.short_allowed = FALSE; opt.allowNegNum = FALSE; @@ -293,7 +293,7 @@ parseCommandLine(int argc, const char ** argv, validateCompDimension(width, 72, "-width value"); validateCompDimension(height, 72, "-height value"); - + cmdlineP->width = width * 72; cmdlineP->height = height * 72; @@ -318,7 +318,7 @@ parseCommandLine(int argc, const char ** argv, if (cmdlineP->bitspersampleSpec) validateBps_1_2_4_8_12(cmdlineP->bitspersample); - if (argc-1 == 0) + if (argc-1 == 0) cmdlineP->inputFileName = "-"; else if (argc-1 != 1) pm_error("Program takes zero or one argument (filename). You " @@ -326,7 +326,7 @@ parseCommandLine(int argc, const char ** argv, else cmdlineP->inputFileName = argv[1]; - free(option_def); + free(option_def); } @@ -432,7 +432,7 @@ addToPidList(pid_t * const pidList, /*=========================================================================== The output encoder ===========================================================================*/ - + enum OutputType {AsciiHex, Ascii85}; typedef struct { @@ -453,7 +453,7 @@ bytesPerRow (unsigned int const cols, -----------------------------------------------------------------------------*/ unsigned int retval; - assert(bitsPerSample==1 || bitsPerSample==2 || bitsPerSample==4 || + assert(bitsPerSample==1 || bitsPerSample==2 || bitsPerSample==4 || bitsPerSample==8 || bitsPerSample==12); switch (bitsPerSample) { @@ -519,7 +519,7 @@ typedef void FilterFn(FILE * const ifP, /* This is a function that can be run in a separate process to do arbitrary modifications of the raster data stream. */ - + #ifndef NOFLATE @@ -545,7 +545,7 @@ initZlib(z_stream * const strmP) { static FilterFn flateFilter; -static void +static void flateFilter(FILE * const ifP, FILE * const ofP, OutputEncoder * const oeP) { @@ -600,12 +600,12 @@ flateFilter(FILE * const ifP, } while (flush != Z_FINISH); free(in); - free(out); + free(out); deflateEnd(&strm); fclose(ifP); fclose(ofP); #else - assert(false); /* filter is never used */ + assert(false); /* filter is never used */ #endif } @@ -687,7 +687,7 @@ asciiHexFilter(FILE * const ifP, unsigned int i; for (i = 0; i < readCt; ++i) { - int const item = inbuff[i]; + int const item = inbuff[i]; outbuff[i*2] = hexits[item >> 4]; outbuff[i*2+1] = hexits[item & 15]; } @@ -736,7 +736,7 @@ ascii85Filter(FILE * const ifP, ++outcount; count = 0; } else if (count == 4) { - outbuff[4] = value % 85 + 33; value/=85; + outbuff[4] = value % 85 + 33; value/=85; outbuff[3] = value % 85 + 33; value/=85; outbuff[2] = value % 85 + 33; value/=85; outbuff[1] = value % 85 + 33; @@ -745,7 +745,7 @@ ascii85Filter(FILE * const ifP, writeFileChar(outbuff, count + 1, "ASCII 85 filter", ofP); count = value = 0; - outcount += 5; + outcount += 5; } if (outcount > 75) { @@ -794,9 +794,9 @@ closeAllBut(int const saveFd0, 'saveFd1', and 'saveFd2'. This is helpful because even if this process doesn't touch other file - desriptors, its very existence will keep the files open. + descriptors, its very existence will keep the files open. -----------------------------------------------------------------------------*/ - + /* Unix provides no good way to do this; we just assume file descriptors above 9 are not used in this program; Caller must ensure that is true. */ @@ -829,15 +829,15 @@ spawnFilter(FILE * const ofP, pid_t rc; makePipe(pipeFd); - + rc = fork(); if (rc == (pid_t)-1) - pm_error("fork() of filter process failed. errno=%d (%s)", + pm_error("fork() of filter process failed. errno=%d (%s)", errno, strerror(errno)); else if (rc == 0) { /* This is the child process */ - + FILE * ifP; ifP = fdopen(pipeFd[0], "r"); @@ -892,11 +892,11 @@ addFilter(const char * const description, pid_t pid; spawnFilter(oldFeedFileP, filter, oeP, &newFeedFileP, &pid); - + if (verbose) pm_message("%s filter spawned: pid %u", description, (unsigned)pid); - + if (debug) { int const outFd = fileno(oldFeedFileP); int const supplyFd = fileno(newFeedFileP); @@ -971,7 +971,7 @@ waitForChildren(const pid_t * const pidList) { signal is the default), the process' children do not become zombies. Consequently, waitpid() always fails with ECHILD - but nonetheless waits for the child to exit. - + We expect the process not to have the action for SIGCHLD set that way. */ @@ -1004,9 +1004,9 @@ waitForChildren(const pid_t * const pidList) { static void -validateComputableBoundingBox(float const scols, +validateComputableBoundingBox(float const scols, float const srows, - float const llx, + float const llx, float const lly) { float const bbWidth = llx + scols + 0.5; @@ -1036,22 +1036,22 @@ warnUserRescaling(float const scale) { static void -computeImagePosition(int const dpiX, - int const dpiY, - int const icols, +computeImagePosition(int const dpiX, + int const dpiY, + int const icols, int const irows, bool const mustturn, bool const canturn, bool const center, - int const pagewid, - int const pagehgt, + int const pagewid, + int const pagehgt, float const requestedScale, float const imagewidth, float const imageheight, bool const equalpixels, float * const scolsP, float * const srowsP, - float * const llxP, + float * const llxP, float * const llyP, bool * const turnedP ) { /*---------------------------------------------------------------------------- @@ -1091,7 +1091,7 @@ computeImagePosition(int const dpiX, rotated if applicable */ bool shouldturn; /* The image fits the page better if we turn it */ - + if (icols > irows && pagehgt > pagewid) shouldturn = TRUE; else if (irows > icols && pagewid > pagehgt) @@ -1120,27 +1120,27 @@ computeImagePosition(int const dpiX, scale = (float) imagewidth/cols; else scale = MIN((float)imagewidth/cols, (float)imageheight/rows); - + *scolsP = cols*scale; *srowsP = rows*scale; } else { /* He didn't give us a bounding box for the image so figure out output image size from other inputs. */ - const int devpixX = dpiX / 72.0 + 0.5; - const int devpixY = dpiY / 72.0 + 0.5; + const int devpixX = dpiX / 72.0 + 0.5; + const int devpixY = dpiY / 72.0 + 0.5; /* How many device pixels make up 1/72 inch, rounded to nearest integer */ const float pixfacX = 72.0 / dpiX * devpixX; /* 1, approx. */ const float pixfacY = 72.0 / dpiY * devpixY; /* 1, approx. */ float scale; - scale = MIN(requestedScale, + scale = MIN(requestedScale, MIN((float)pagewid/cols, (float)pagehgt/rows)); *scolsP = scale * cols * pixfacX; *srowsP = scale * rows * pixfacY; - + if (scale != requestedScale) warnUserRescaling(scale); @@ -1236,7 +1236,7 @@ defineReadstring(bool const rle) { static void setupReadstringNative(bool const rle, bool const color, - unsigned int const icols, + unsigned int const icols, unsigned int const bitsPerSample) { /*---------------------------------------------------------------------------- Write to Standard Output statements to define /readstring and also @@ -1247,7 +1247,7 @@ setupReadstringNative(bool const rle, /* Size of row buffer, padded up to byte boundary. */ defineReadstring(rle); - + if (color) { printf("/rpicstr %d string def\n", bytesPerRow); printf("/gpicstr %d string def\n", bytesPerRow); @@ -1266,18 +1266,18 @@ putFilters(unsigned int const postscriptLevel, bool const color) { assert(postscriptLevel > 1); - + /* We say to decode flate, then rle, so Caller must ensure it encodes rel, then flate. */ if (ascii85) printf("/ASCII85Decode filter "); - else + else printf("/ASCIIHexDecode filter "); if (flate) printf("/FlateDecode filter "); - if (rle) + if (rle) printf("/RunLengthDecode filter "); } @@ -1311,7 +1311,7 @@ putSetup(unsigned int const dictSize, if (dictSize > 0) /* inputf {r,g,b,}pictsr readstring readrlestring rlestring */ printf("%u dict begin\n", dictSize); - + if (!psFilter) setupReadstringNative(rle, color, icols, bitsPerSample); @@ -1353,7 +1353,7 @@ putInitPsFilter(unsigned int const postscriptLevel, putFilters(postscriptLevel, rle, flate, ascii85, color); putImage(filterTrue, color); - + printf(" } exec"); } @@ -1365,7 +1365,7 @@ putInitReadstringNative(bool const color) { bool const filterFalse = FALSE; putReadstringNative(color); - + putImage(filterFalse, color); } @@ -1373,18 +1373,18 @@ putInitReadstringNative(bool const color) { static void putInit(unsigned int const postscriptLevel, - char const name[], - int const icols, - int const irows, - float const scols, + char const name[], + int const icols, + int const irows, + float const scols, float const srows, - float const llx, + float const llx, float const lly, int const bitsPerSample, - int const pagewid, + int const pagewid, int const pagehgt, - bool const color, - bool const turned, + bool const color, + bool const turned, bool const rle, bool const flate, bool const ascii85, @@ -1438,7 +1438,7 @@ putInit(unsigned int const postscriptLevel, static void -putEnd(bool const showpage, +putEnd(bool const showpage, bool const psFilter, bool const ascii85, unsigned int const dictSize, @@ -1486,7 +1486,7 @@ validateBpsRequest(unsigned int const bitsPerSampleReq, "-psfilter, the maximum is 8", bitsPerSampleReq); } - + static unsigned int bpsFromInput(unsigned int const bitsRequiredByMaxval, @@ -1553,7 +1553,7 @@ warnUserAboutReducedDepth(unsigned int const bitsGot, static void computeDepth(xelval const inputMaxval, - unsigned int const postscriptLevel, + unsigned int const postscriptLevel, bool const psFilter, unsigned int const bitsPerSampleReq, unsigned int * const bitsPerSampleP) { @@ -1584,7 +1584,7 @@ computeDepth(xelval const inputMaxval, "%u bits per sample, so maxval = %u", inputMaxval, *bitsPerSampleP, psMaxval); } -} +} @@ -1643,7 +1643,7 @@ ba_add(BitAccumulator * const baP, /*---------------------------------------------------------------------------- Combine bit sequences that do not fit into a byte. - Used when bitsPerSample =1, 2, 4. + Used when bitsPerSample =1, 2, 4. Logic also works for bitsPerSample = 8, 16. The accumulator, baP->value is unsigned int (usually 32 bits), but @@ -1725,7 +1725,7 @@ flushOutput(BitAccumulator * const baP, convertRowNative and convertRowPsFilter are the general converters. They are quite similar, the differences being: - (1) Native output separates the color planes: + (1) Native output separates the color planes: (RRR...RRR GGG...GGG BBB...BBB), whereas psFilter does not: (RGB RGB RGB RGB ......... RGB). @@ -1765,10 +1765,10 @@ convertRowPbm(struct pam * const pamP, static void -convertRowNative(struct pam * const pamP, - tuple * tuplerow, +convertRowNative(struct pam * const pamP, + tuple * tuplerow, unsigned int const bitsPerSample, - FILE * const fP) { + FILE * const fP) { unsigned int const psMaxval = pm_bitstomaxval(bitsPerSample); @@ -1795,7 +1795,7 @@ static void convertRowPsFilter(struct pam * const pamP, tuple * tuplerow, unsigned int const bitsPerSample, - FILE * const fP) { + FILE * const fP) { unsigned int const psMaxval = pm_bitstomaxval(bitsPerSample); @@ -1828,7 +1828,7 @@ selectPostscriptLevel(bool const levelIsGiven, bool const psFilter, unsigned int * const postscriptLevelP) { - unsigned int const maxPermittedLevel = + unsigned int const maxPermittedLevel = levelIsGiven ? levelGiven : UINT_MAX; unsigned int minPossibleLevel; @@ -1877,7 +1877,7 @@ convertRaster(struct pam * const inpamP, Read the raster described by *inpamP, and write a bit stream of samples to *fP. This stream has to be compressed and converted to text before it can be part of a Postscript program. - + 'psFilter' means to do the conversion using built in Postscript filters, as opposed to our own filters via /readstring. @@ -1897,7 +1897,7 @@ convertRaster(struct pam * const inpamP, } else { tuple *tuplerow; unsigned int row; - + tuplerow = pnm_allocpamrow(inpamP); for (row = 0; row < inpamP->height; ++row) { @@ -1920,31 +1920,31 @@ convertRaster(struct pam * const inpamP, pipe but this program's output, then we don't want it closed when the filter terminates because we'll need it to be open for the next image the program converts (with a whole new chain of filters). - - To prevent the progam output file from getting closed, we pass a + + To prevent the program output file from getting closed, we pass a duplicate of it to spawnFilters() and keep the original open. */ static void -convertPage(FILE * const ifP, - int const turnflag, - int const turnokflag, +convertPage(FILE * const ifP, + int const turnflag, + int const turnokflag, bool const psFilter, - bool const rle, + bool const rle, bool const flate, bool const ascii85, bool const setpage, bool const showpage, - bool const center, + bool const center, float const scale, - int const dpiX, - int const dpiY, - int const pagewid, + int const dpiX, + int const dpiY, + int const pagewid, int const pagehgt, - int const imagewidth, - int const imageheight, + int const imagewidth, + int const imageheight, bool const equalpixels, unsigned int const bitsPerSampleReq, char const name[], @@ -1952,7 +1952,7 @@ convertPage(FILE * const ifP, bool const vmreclaim, bool const levelIsGiven, unsigned int const levelGiven) { - + struct pam inpam; float scols, srows; float llx, lly; @@ -1960,7 +1960,7 @@ convertPage(FILE * const ifP, bool color; unsigned int postscriptLevel; unsigned int bitsPerSample; - unsigned int dictSize; + unsigned int dictSize; /* Size of Postscript dictionary we should define */ OutputEncoder oe; pid_t filterPidList[MAX_FILTER_CT + 1]; @@ -1974,19 +1974,19 @@ convertPage(FILE * const ifP, pnm_readpaminit(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type)); validateCompDimension(inpam.width, 16, "Input image width"); - + if (!STRSEQ(inpam.tuple_type, PAM_PBM_TUPLETYPE) && !STRSEQ(inpam.tuple_type, PAM_PGM_TUPLETYPE) && !STRSEQ(inpam.tuple_type, PAM_PPM_TUPLETYPE)) pm_error("Unrecognized tuple type %s. This program accepts only " - "PBM, PGM, PPM, and equivalent PAM input images", + "PBM, PGM, PPM, and equivalent PAM input images", inpam.tuple_type); color = STRSEQ(inpam.tuple_type, PAM_PPM_TUPLETYPE); - - selectPostscriptLevel(levelIsGiven, levelGiven, color, + + selectPostscriptLevel(levelIsGiven, levelGiven, color, dict, flate, ascii85, psFilter, &postscriptLevel); - + if (color) pm_message("generating color Postscript program."); @@ -1996,16 +1996,16 @@ convertPage(FILE * const ifP, /* In positioning/scaling the image, we treat the input image as if it has a density of 72 pixels per inch. */ - computeImagePosition(dpiX, dpiY, inpam.width, inpam.height, + computeImagePosition(dpiX, dpiY, inpam.width, inpam.height, turnflag, turnokflag, center, pagewid, pagehgt, scale, imagewidth, imageheight, equalpixels, &scols, &srows, &llx, &lly, &turned); determineDictionaryRequirement(dict, psFilter, &dictSize); - - putInit(postscriptLevel, name, inpam.width, inpam.height, - scols, srows, llx, lly, bitsPerSample, + + putInit(postscriptLevel, name, inpam.width, inpam.height, + scols, srows, llx, lly, bitsPerSample, pagewid, pagehgt, color, turned, rle, flate, ascii85, setpage, psFilter, dictSize); @@ -2017,7 +2017,7 @@ convertPage(FILE * const ifP, /* spawnFilters() closes this. See FILE MANAGEMENT above */ spawnFilters(filterChainOfP, &oe, &feedFileP, filterPidList); - + convertRaster(&inpam, bitsPerSample, psFilter, feedFileP); fflush(feedFileP); @@ -2081,17 +2081,17 @@ main(int argc, const char * argv[]) { eof = FALSE; /* There is always at least one image */ for (imageSeq = 0; !eof; ++imageSeq) { - convertPage(ifP, cmdline.mustturn, cmdline.canturn, + convertPage(ifP, cmdline.mustturn, cmdline.canturn, cmdline.psfilter, - cmdline.rle, cmdline.flate, cmdline.ascii85, + cmdline.rle, cmdline.flate, cmdline.ascii85, cmdline.setpage, cmdline.showpage, cmdline.center, cmdline.scale, cmdline.dpiX, cmdline.dpiY, - cmdline.width, cmdline.height, - cmdline.imagewidth, cmdline.imageheight, + cmdline.width, cmdline.height, + cmdline.imagewidth, cmdline.imageheight, cmdline.equalpixels, cmdline.bitspersampleSpec ? cmdline.bitspersample : 0, - name, + name, cmdline.dict, cmdline.vmreclaim, cmdline.levelSpec, cmdline.level); pnm_nextimage(ifP, &eof); @@ -2121,7 +2121,7 @@ main(int argc, const char * argv[]) { ** wrzl@gup.uni-linz.ac.at. ** ** July 2011 afu -** row convertors rewritten, fast PBM-only row convertor added, +** row converters rewritten, fast PBM-only row converter added, ** rle compression slightly modified, flate compression added ** ascii85 output end added. ** diff --git a/converter/other/pstopnm.csh b/converter/other/pstopnm.csh index adde3e6f..22e3306d 100755 --- a/converter/other/pstopnm.csh +++ b/converter/other/pstopnm.csh @@ -5,7 +5,7 @@ # pstopnm will create as many files as the number of pages in # the Postscript document. The name of the files will be # psfile001.ppm, psfile002.ppm, etc. -# The ouput files will contain the area inside the BoundingBox. +# The output files will contain the area inside the BoundingBox. # If BoundingBox parameters are not found in the PostScript # document, default values are used. # diff --git a/converter/other/rlatopam.c b/converter/other/rlatopam.c index 703c4820..2c694bd4 100644 --- a/converter/other/rlatopam.c +++ b/converter/other/rlatopam.c @@ -85,9 +85,9 @@ read_header(FILE * const ifP, rlahdr hdr; size_t bytesRead; - + fseek (ifP, 0, SEEK_SET); - + /* Here we have a hack. The bytes in the file are almost in the same format as the compiler stores 'hdr' in memory. The only difference is that the compiler may store the integer values @@ -185,7 +185,7 @@ decode(unsigned char * const input, x = xFile; bytes = 0; useX = 0; - + while (x > 0) { int count; @@ -246,7 +246,7 @@ decode_row(FILE * const ifP, for (chan = 0; chan < outpam.depth; ++chan) { unsigned short length; size_t bytesRead; - + pm_readbigshortu(ifP, &length); if (length > width * 4) pm_error("Line too long - row %u, channel %u", row, chan); @@ -266,7 +266,7 @@ decode_row(FILE * const ifP, decode(newpos, rb + chan * 2 + 1, width, width, outpam.depth * 2); } else - decode(read_buffer, rb + chan, width, width, outpam.depth); + decode(read_buffer, rb + chan, width, width, outpam.depth); } } @@ -280,7 +280,7 @@ getHeaderInfo(FILE * const ifP, bool * const hasMatteP, unsigned int * const chanBitsP, short * const storageType) { - + rlahdr hdr; int width, height; @@ -350,7 +350,7 @@ readAndWriteRaster(FILE * const ifP, /* Hold one row of all image planes */ rowBuffer = calloc(1, width * outpamP->depth * 4); if (rowBuffer == NULL) - pm_error("Unable to allocate memor for row buffer."); + pm_error("Unable to allocate memory for row buffer."); tuplerow = pnm_allocpamrow(outpamP); @@ -403,7 +403,7 @@ main(int argc, outpam.height = height; outpam.width = width; outpam.depth = numChan + (has_matte ? 1 : 0); - outpam.maxval = (1 << (chanBits > 16 ? + outpam.maxval = (1 << (chanBits > 16 ? (9 + (chanBits - 1) % 8) /* Take top 2 of 3 or 4 bytes */ : chanBits)) - 1; @@ -427,8 +427,11 @@ main(int argc, readAndWriteRaster(ifP, &outpam); destroyOffsetArray(offsets); - + pm_close(ifP); - return 0; + return 0; } + + + diff --git a/converter/other/tifftopnm.c b/converter/other/tifftopnm.c index c1e7af85..05493e73 100644 --- a/converter/other/tifftopnm.c +++ b/converter/other/tifftopnm.c @@ -24,16 +24,16 @@ /* Design note: We have two different ways of converting from Tiff, as provided by the - Tiff library: + Tiff library: 1) decode the entire image into memory at once, using TIFFRGBAImageGet(), then convert to PNM and output row by row. - + 2) read, convert, and output one row at a time using TIFFReadScanline(). (1) is preferable because the Tiff library does more of the work, which - means it understands more of the Tiff format possibilities now and in - the future. Also, some compressed TIFF formats don't allow you to + means it understands more of the Tiff format possibilities now and in + the future. Also, some compressed TIFF formats don't allow you to extract an individual row. (2) uses far less memory, and because our code does more of the work, @@ -117,17 +117,17 @@ parseCommandLine(int argc, const char ** const argv, opt.allowNegNum = FALSE; option_def_index = 0; /* incremented by OPTENT3 */ - OPTENT3(0, "verbose", + OPTENT3(0, "verbose", OPT_FLAG, NULL, &cmdlineP->verbose, 0); - OPTENT3(0, "respectfillorder", + OPTENT3(0, "respectfillorder", OPT_FLAG, NULL, &cmdlineP->respectfillorder, 0); - OPTENT3(0, "byrow", + OPTENT3(0, "byrow", OPT_FLAG, NULL, &cmdlineP->byrow, 0); - OPTENT3(0, "orientraw", + OPTENT3(0, "orientraw", OPT_FLAG, NULL, &cmdlineP->orientraw, 0); - OPTENT3('h', "headerdump", + OPTENT3('h', "headerdump", OPT_FLAG, NULL, &cmdlineP->headerdump, 0); - OPTENT3(0, "alphaout", + OPTENT3(0, "alphaout", OPT_STRING, &cmdlineP->alphaFilename, &alphaSpec, 0); pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0); @@ -136,7 +136,7 @@ parseCommandLine(int argc, const char ** const argv, cmdlineP->inputFilename = strdup("-"); /* he wants stdin */ else if (argc - 1 == 1) cmdlineP->inputFilename = strdup(argv[1]); - else + else pm_error("Too many arguments. The only argument accepted " "is the input file name"); @@ -309,11 +309,11 @@ validatePlanarConfig(unsigned short const planarconfig, case PLANARCONFIG_CONTIG: break; case PLANARCONFIG_SEPARATE: - if (photomet != PHOTOMETRIC_RGB && + if (photomet != PHOTOMETRIC_RGB && photomet != PHOTOMETRIC_SEPARATED) pm_error("This program can handle separate planes only " "with RGB (PHOTOMETRIC tag = %u) or SEPARATED " - "(PHOTOMETRIC tag = %u) data. The input Tiff file " + "(PHOTOMETRIC tag = %u) data. The input Tiff file " "has PHOTOMETRIC tag = %hu.", PHOTOMETRIC_RGB, PHOTOMETRIC_SEPARATED, photomet); @@ -351,7 +351,7 @@ dumpHeader(const struct tiffDirInfo * const headerP) { -static void +static void readDirectory(TIFF * const tiffP, bool const headerdump, struct tiffDirInfo * const headerP) { @@ -409,11 +409,11 @@ readDirectory(TIFF * const tiffP, static void -readscanline(TIFF * const tif, +readscanline(TIFF * const tif, unsigned char * const scanbuf, - int const row, + int const row, int const plane, - unsigned int const cols, + unsigned int const cols, unsigned short const bps, unsigned short const spp, unsigned short const fillorder, @@ -433,7 +433,7 @@ readscanline(TIFF * const tif, /* The TIFFReadScanline man page doesn't tell the format of its 'buf' return value, but it is exactly the same format as the 'buf' - input to TIFFWriteScanline. The man page for that doesn't say + input to TIFFWriteScanline. The man page for that doesn't say anything either, but the source code for Pamtotiff contains a specification. */ @@ -446,7 +446,7 @@ readscanline(TIFF * const tif, row, plane); else if (bps == 8) { unsigned int sample; - for (sample = 0; sample < cols * spp; ++sample) + for (sample = 0; sample < cols * spp; ++sample) samplebuf[sample] = scanbuf[sample]; } else if (bps < 8) { /* Note that in this format, samples do not span bytes. Rather, @@ -458,26 +458,26 @@ readscanline(TIFF * const tif, unsigned int bitsleft; unsigned char * inP; - for (sample = 0, bitsleft = 8, inP = scanbuf; - sample < cols * spp; + for (sample = 0, bitsleft = 8, inP = scanbuf; + sample < cols * spp; ++sample) { if (bitsleft == 0) { - ++inP; + ++inP; bitsleft = 8; - } + } switch (fillorder) { case FILLORDER_MSB2LSB: - samplebuf[sample] = (*inP >> (bitsleft-bps)) & bpsmask; + samplebuf[sample] = (*inP >> (bitsleft-bps)) & bpsmask; break; case FILLORDER_LSB2MSB: samplebuf[sample] = (*inP >> (8-bitsleft)) & bpsmask; break; default: - pm_error("Internal error: invalid value for fillorder: %u", + pm_error("Internal error: invalid value for fillorder: %u", fillorder); } assert(bitsleft >= bps); - bitsleft -= bps; + bitsleft -= bps; if (bitsleft < bps) /* Don't count dregs at end of byte */ bitsleft = 0; @@ -490,7 +490,7 @@ readscanline(TIFF * const tif, none of our concern). The pre-9.17 code also presumed that the TIFF "FILLORDER" tag determined the order in which the bytes of each sample appear in a TIFF file, which is - contrary to the TIFF spec. + contrary to the TIFF spec. */ const uint16 * const scanbuf16 = (const uint16 *) scanbuf; unsigned int sample; @@ -500,10 +500,10 @@ readscanline(TIFF * const tif, } else if (bps == 32) { const uint32 * const scanbuf32 = (const uint32 *) scanbuf; unsigned int sample; - + for (sample = 0; sample < cols * spp; ++sample) samplebuf[sample] = scanbuf32[sample]; - } else + } else pm_error("Internal error: invalid bits per sample passed to " "readscanline()"); } @@ -528,7 +528,7 @@ pick_cmyk_pixel(unsigned int const samplebuf[], unsigned int const y = samplebuf[sampleCursor + 2]; unsigned int const k = samplebuf[sampleCursor + 3]; - /* The CMYK->RGB formula used by TIFFRGBAImageGet() in the TIFF + /* The CMYK->RGB formula used by TIFFRGBAImageGet() in the TIFF library is the following, (with some apparent confusion with the names of the yellow and magenta pigments being reversed). @@ -539,9 +539,9 @@ pick_cmyk_pixel(unsigned int const samplebuf[], We used that too before Netpbm 10.21 (March 2004). Now we use the inverse of what Pnmtotiffcmyk has always used, which - makes sense as follows: A microliter of black ink is simply a + makes sense as follows: A microliter of black ink is simply a substitute for a microliter each of cyan, magenta, and yellow ink. - Yellow ink removes blue light from what the white paper reflects. + Yellow ink removes blue light from what the white paper reflects. */ *redP = 255 - MIN(255, c + k); @@ -552,16 +552,16 @@ pick_cmyk_pixel(unsigned int const samplebuf[], static void -computeFillorder(unsigned short const fillorderTag, - unsigned short * const fillorderP, +computeFillorder(unsigned short const fillorderTag, + unsigned short * const fillorderP, bool const respectfillorder) { if (respectfillorder) { - if (fillorderTag != FILLORDER_MSB2LSB && + if (fillorderTag != FILLORDER_MSB2LSB && fillorderTag != FILLORDER_LSB2MSB) pm_error("Invalid value in Tiff input for the FILLORDER tag: %u. " "Valid values are %u and %u. Try omitting the " - "-respectfillorder option.", + "-respectfillorder option.", fillorderTag, FILLORDER_MSB2LSB, FILLORDER_LSB2MSB); else *fillorderP = fillorderTag; @@ -577,12 +577,12 @@ computeFillorder(unsigned short const fillorderTag, static void -analyzeImageType(TIFF * const tiffP, - unsigned short const bps, - unsigned short const spp, +analyzeImageType(TIFF * const tiffP, + unsigned short const bps, + unsigned short const spp, unsigned short const photomet, - xelval * const maxvalP, - int * const formatP, + xelval * const maxvalP, + int * const formatP, xel * const colormap, bool const headerdump, struct CmdlineInfo const cmdline) { @@ -604,13 +604,13 @@ analyzeImageType(TIFF * const tiffP, *maxvalP = pm_bitstomaxval(MIN(bps, 16)); if (headerdump) - pm_message("grayscale image, (min=%s) output maxval %u ", - photomet == PHOTOMETRIC_MINISBLACK ? + pm_message("grayscale image, (min=%s) output maxval %u ", + photomet == PHOTOMETRIC_MINISBLACK ? "black" : "white", *maxvalP ); break; - + case PHOTOMETRIC_PALETTE: { int fldPresent; int i; @@ -627,7 +627,7 @@ analyzeImageType(TIFF * const tiffP, "We understand only 1.", spp); fldPresent = TIFFGetField( - tiffP, TIFFTAG_COLORMAP, + tiffP, TIFFTAG_COLORMAP, &redcolormap, &greencolormap, &bluecolormap); if (!fldPresent) @@ -662,7 +662,7 @@ analyzeImageType(TIFF * const tiffP, if (fldPresent && inkset != INKSET_CMYK) pm_error("This color separation file uses an inkset (%d) " "we can't handle. We handle only CMYK.", inkset); - if (spp != 4) + if (spp != 4) pm_error("This CMYK color separation file is %d samples per " "pixel. " "We need 4 samples, though: C, M, Y, and K. ", @@ -673,7 +673,7 @@ analyzeImageType(TIFF * const tiffP, *maxvalP = (1 << bps) - 1; } break; - + case PHOTOMETRIC_RGB: if (headerdump) pm_message("RGB truecolor"); @@ -704,7 +704,7 @@ analyzeImageType(TIFF * const tiffP, case PHOTOMETRIC_LOGLUV: pm_error("don't know how to handle PHOTOMETRIC_LOGLUV"); - + default: pm_error("unknown photometric: %d", photomet); } @@ -778,7 +778,7 @@ static const char * xformNeeded(unsigned short const tiffOrientation) { /*---------------------------------------------------------------------------- Return the value of the Pamflip -xform option that causes Pamflip - to change a raster from orienation 'tiffOrientation' to Row 0 top, + to change a raster from orientation 'tiffOrientation' to Row 0 top, Column 0 left. -----------------------------------------------------------------------------*/ switch (tiffOrientation) { @@ -829,7 +829,7 @@ spawnWithInputPipe(const char * const shellCmd, *pidP = childPid; *pipePP = fdopen(fd[PIPE_WRITE], "w"); - + if (*pipePP == NULL) pm_asprintf(errorP,"Unable to create stream from pipe. " "fdopen() fails with errno=%d (%s)", @@ -858,7 +858,7 @@ spawnWithInputPipe(const char * const shellCmd, } } - + static void createFlipProcess(FILE * const outFileP, @@ -964,7 +964,7 @@ setupFlipper(pnmOut * const pnmOutP, pnmOutP->flipping = FALSE; *flipOkP = FALSE; *noflipOkP = TRUE; - } else { + } else { if (flipIfNeeded) { if (verbose) pm_message("Transforming raster with Pamflip"); @@ -979,7 +979,7 @@ setupFlipper(pnmOut * const pnmOutP, verbose, &pnmOutP->imagePipeP, &pnmOutP->imageFlipPid); - + /* The stream will flip it, so Caller must not: */ pnmOutP->flipping = TRUE; *flipOkP = FALSE; @@ -1081,22 +1081,22 @@ pnmOut_init(FILE * const imageoutFileP, } else { pnmOutP->inCols = pnmOutP->outCols; /* Caller will flip */ pnmOutP->inRows = pnmOutP->outRows; - } + } if (pnmOutP->flipping) { - if (pnmOutP->imagePipeP != NULL) + if (pnmOutP->imagePipeP != NULL) pnm_writepnminit(pnmOutP->imagePipeP, pnmOutP->inCols, pnmOutP->inRows, pnmOutP->maxval, pnmOutP->format, 0); - if (pnmOutP->alphaPipeP != NULL) + if (pnmOutP->alphaPipeP != NULL) pgm_writepgminit(pnmOutP->alphaPipeP, pnmOutP->inCols, pnmOutP->inRows, pnmOutP->alphaMaxval, 0); } else { - if (imageoutFileP != NULL) + if (imageoutFileP != NULL) pnm_writepnminit(pnmOutP->imageoutFileP, pnmOutP->outCols, pnmOutP->outRows, pnmOutP->maxval, pnmOutP->format, 0); - if (alphaFileP != NULL) + if (alphaFileP != NULL) pgm_writepgminit(pnmOutP->alphaFileP, pnmOutP->outCols, pnmOutP->outRows, pnmOutP->alphaMaxval, 0); @@ -1149,19 +1149,19 @@ pnmOut_writeRow(pnmOut * const pnmOutP, assert(cols == pnmOutP->inCols); if (pnmOutP->flipping) { - if (pnmOutP->imagePipeP != NULL) + if (pnmOutP->imagePipeP != NULL) pnm_writepnmrow(pnmOutP->imagePipeP, (xel *)imageRow, pnmOutP->inCols, pnmOutP->maxval, pnmOutP->format, 0); - if (pnmOutP->alphaPipeP != NULL) + if (pnmOutP->alphaPipeP != NULL) pgm_writepgmrow(pnmOutP->alphaPipeP, alphaRow, pnmOutP->inCols, pnmOutP->alphaMaxval, 0); } else { - if (pnmOutP->imageoutFileP != NULL) + if (pnmOutP->imageoutFileP != NULL) pnm_writepnmrow(pnmOutP->imageoutFileP, (xel *)imageRow, pnmOutP->outCols, pnmOutP->maxval, pnmOutP->format, 0); - if (pnmOutP->alphaFileP != NULL) + if (pnmOutP->alphaFileP != NULL) pgm_writepgmrow(pnmOutP->alphaFileP, alphaRow, pnmOutP->outCols, pnmOutP->alphaMaxval, 0); } @@ -1170,12 +1170,12 @@ pnmOut_writeRow(pnmOut * const pnmOutP, static void -convertRow(unsigned int const samplebuf[], - xel * const xelrow, +convertRow(unsigned int const samplebuf[], + xel * const xelrow, gray * const alpharow, - int const cols, - xelval const maxval, - unsigned short const photomet, + int const cols, + xelval const maxval, + unsigned short const photomet, unsigned short const spp, xel const colormap[]) { /*---------------------------------------------------------------------------- @@ -1191,7 +1191,7 @@ convertRow(unsigned int const samplebuf[], } } break; - + case PHOTOMETRIC_MINISWHITE: { int col; for (col = 0; col < cols; ++col) { @@ -1220,7 +1220,7 @@ convertRow(unsigned int const samplebuf[], for (col = 0, sample = 0; col < cols; ++col, sample+=spp) { xelval r, g, b; pick_cmyk_pixel(samplebuf, sample, &r, &b, &g); - + PPM_ASSIGN(xelrow[col], r, g, b); alpharow[col] = 0; } @@ -1238,7 +1238,7 @@ convertRow(unsigned int const samplebuf[], alpharow[col] = 0; } break; - } + } default: pm_error("internal error: unknown photometric in the picking " "routine: %d", photomet); @@ -1257,7 +1257,7 @@ scale32to16(unsigned int * const samplebuf, -----------------------------------------------------------------------------*/ unsigned int i; for (i = 0; i < cols * spp; ++i) - samplebuf[i] >>= 16; + samplebuf[i] >>= 16; } @@ -1288,39 +1288,39 @@ convertMultiPlaneRow(TIFF * const tif, unsigned int col; /* First, clear the buffer so we can add red, green, - and blue one at a time. + and blue one at a time. */ - for (col = 0; col < cols; ++col) + for (col = 0; col < cols; ++col) PPM_ASSIGN(xelrow[col], 0, 0, 0); /* Read the reds */ - readscanline(tif, scanbuf, row, 0, cols, bps, spp, fillorder, + readscanline(tif, scanbuf, row, 0, cols, bps, spp, fillorder, samplebuf); if (bps == 32) scale32to16(samplebuf, cols, spp); - for (col = 0; col < cols; ++col) + for (col = 0; col < cols; ++col) PPM_PUTR(xelrow[col], samplebuf[col]); - + /* Next the greens */ readscanline(tif, scanbuf, row, 1, cols, bps, spp, fillorder, samplebuf); if (bps == 32) scale32to16(samplebuf, cols, spp); - for (col = 0; col < cols; ++col) + for (col = 0; col < cols; ++col) PPM_PUTG( xelrow[col], samplebuf[col] ); - + /* And finally the blues */ readscanline(tif, scanbuf, row, 2, cols, bps, spp, fillorder, samplebuf); if (bps == 32) scale32to16(samplebuf, cols, spp); - for (col = 0; col < cols; ++col) + for (col = 0; col < cols; ++col) PPM_PUTB(xelrow[col], samplebuf[col]); /* Could there be an alpha plane? (We assume no. But if so, - here is where to read it) + here is where to read it) */ - for (col = 0; col < cols; ++col) + for (col = 0; col < cols; ++col) alpharow[col] = 0; } } @@ -1329,11 +1329,11 @@ convertMultiPlaneRow(TIFF * const tif, static void convertRasterByRows(pnmOut * const pnmOutP, - unsigned int const cols, + unsigned int const cols, unsigned int const rows, xelval const maxval, TIFF * const tif, - unsigned short const photomet, + unsigned short const photomet, unsigned short const planarconfig, unsigned short const bps, unsigned short const spp, @@ -1341,7 +1341,7 @@ convertRasterByRows(pnmOut * const pnmOutP, xel const colormap[], bool const verbose) { /*---------------------------------------------------------------------------- - With the TIFF header all processed (and relevant information from it in + With the TIFF header all processed (and relevant information from it in our arguments), write out the TIFF raster to the Netpbm output files as described by *pnmOutP. @@ -1359,7 +1359,7 @@ convertRasterByRows(pnmOut * const pnmOutP, xel * xelrow; /* The ppm-format row of the image row we are presently converting */ gray * alpharow; - /* The pgm-format row representing the alpha values for the image + /* The pgm-format row representing the alpha values for the image row we are presently converting. */ @@ -1383,13 +1383,13 @@ convertRasterByRows(pnmOut * const pnmOutP, /* Read one row of samples into samplebuf[] */ if (planarconfig == PLANARCONFIG_CONTIG) { - readscanline(tif, scanbuf, row, 0, cols, bps, spp, fillorder, + readscanline(tif, scanbuf, row, 0, cols, bps, spp, fillorder, samplebuf); if (bps == 32) scale32to16(samplebuf, cols, spp); - convertRow(samplebuf, xelrow, alpharow, cols, maxval, + convertRow(samplebuf, xelrow, alpharow, cols, maxval, photomet, spp, colormap); - } else + } else convertMultiPlaneRow(tif, xelrow, alpharow, cols, maxval, row, photomet, bps, spp, fillorder, scanbuf, samplebuf); @@ -1401,7 +1401,7 @@ convertRasterByRows(pnmOut * const pnmOutP, free(samplebuf); free(scanbuf); -} +} @@ -1416,7 +1416,7 @@ warnBrokenTiffLibrary(TIFF * const tiffP) { the transposition part, so e.g. it treats ORIENTATION_LEFTBOT as ORIENTATION_BOTLEFT. And because we provide a raster buffer dimensioned for the properly transposed image, the result is somewhat of a mess. - + We have found no documentation of the TIFF library that suggests this behavior is as designed, so it's probably not a good idea to work around it; it might be fixed somewhere. @@ -1452,8 +1452,8 @@ warnBrokenTiffLibrary(TIFF * const tiffP) { -static void -convertTiffRaster(uint32 * const raster, +static void +convertTiffRaster(uint32 * const raster, unsigned int const cols, unsigned int const rows, xelval const maxval, @@ -1465,11 +1465,11 @@ convertTiffRaster(uint32 * const raster, -----------------------------------------------------------------------------*/ xel * xelrow; /* The ppm-format row of the image row we are - presently converting + presently converting */ gray * alpharow; /* The pgm-format row representing the alpha values - for the image row we are presently converting. + for the image row we are presently converting. */ unsigned int row; @@ -1477,35 +1477,35 @@ convertTiffRaster(uint32 * const raster, alpharow = pgm_allocrow(cols); for (row = 0; row < rows; ++row) { - uint32 * rp; + uint32 * rp; /* Address of pixel in 'raster' we are presently converting */ unsigned int col; /* Start at beginning of row: */ rp = raster + (rows - row - 1) * cols; - + for (col = 0; col < cols; ++col) { uint32 const tiffPixel = *rp++; - - PPM_ASSIGN(xelrow[col], - TIFFGetR(tiffPixel) * maxval / 255, - TIFFGetG(tiffPixel) * maxval / 255, + + PPM_ASSIGN(xelrow[col], + TIFFGetR(tiffPixel) * maxval / 255, + TIFFGetG(tiffPixel) * maxval / 255, TIFFGetB(tiffPixel) * maxval / 255); alpharow[col] = TIFFGetA(tiffPixel) * maxval / 255 ; } pnmOut_writeRow(pnmOutP, cols, xelrow, alpharow); } - + pgm_freerow(alpharow); pnm_freerow(xelrow); -} +} enum convertDisp {CONV_DONE, CONV_OOM, CONV_UNABLE, - CONV_FAILED, + CONV_FAILED, CONV_NOTATTEMPTED}; @@ -1524,7 +1524,7 @@ convertRasterIntoProvidedMemory(pnmOut * const pnmOutP, TIFFRGBAImage img; char emsg[1024]; int ok; - + ok = TIFFRGBAImageBegin(&img, tif, stopOnErrorFalse, emsg); if (!ok) { pm_message("%s", emsg); @@ -1540,7 +1540,7 @@ convertRasterIntoProvidedMemory(pnmOut * const pnmOutP, *statusP = CONV_DONE; convertTiffRaster(raster, cols, rows, maxval, pnmOutP); } - } + } } @@ -1584,7 +1584,7 @@ convertRasterInMemory(pnmOut * const pnmOutP, unsigned int cols, rows; /* Dimensions of output image */ getTiffDimensions(tif, &cols, &rows); - if (rows == 0 || cols == 0) + if (rows == 0 || cols == 0) *statusP = CONV_DONE; else { if (cols > UINT_MAX/rows) { @@ -1608,7 +1608,7 @@ convertRasterInMemory(pnmOut * const pnmOutP, convertRasterIntoProvidedMemory( pnmOutP, cols, rows, maxval, tif, verbose, raster, statusP); - + free(raster); } } @@ -1653,7 +1653,7 @@ convertRaster(pnmOut * const pnmOutP, "and we already committed to in-memory " "conversion. To avoid this failure, " "use -byrow ."); - } + } convertRasterByRows( pnmOutP, tiffDir.width, tiffDir.height, maxval, tifP, tiffDir.photomet, tiffDir.planarconfig, @@ -1681,7 +1681,7 @@ convertImage(TIFF * const tifP, computeFillorder(tiffDir.fillorder, &fillorder, cmdline.respectfillorder); - analyzeImageType(tifP, tiffDir.bps, tiffDir.spp, tiffDir.photomet, + analyzeImageType(tifP, tiffDir.bps, tiffDir.spp, tiffDir.photomet, &maxval, &format, colormap, cmdline.headerdump, cmdline); reportOutputFormat(format); @@ -1704,7 +1704,7 @@ convertImage(TIFF * const tifP, static void convertIt(TIFF * const tifP, - FILE * const alphaFile, + FILE * const alphaFile, FILE * const imageoutFile, struct CmdlineInfo const cmdline) { @@ -1744,19 +1744,19 @@ main(int argc, const char * argv[]) { if (cmdline.alphaStdout) alphaFile = stdout; - else if (cmdline.alphaFilename == NULL) + else if (cmdline.alphaFilename == NULL) alphaFile = NULL; else alphaFile = pm_openw(cmdline.alphaFilename); - if (cmdline.alphaStdout) + if (cmdline.alphaStdout) imageoutFile = NULL; else imageoutFile = stdout; convertIt(tiffP, alphaFile, imageoutFile, cmdline); - if (imageoutFile != NULL) + if (imageoutFile != NULL) pm_close( imageoutFile ); if (alphaFile != NULL) pm_close( alphaFile ); @@ -1770,3 +1770,6 @@ main(int argc, const char * argv[]) { */ return 0; } + + + diff --git a/converter/other/winicontopam.c b/converter/other/winicontopam.c index 69ce7f05..2ddf56b1 100644 --- a/converter/other/winicontopam.c +++ b/converter/other/winicontopam.c @@ -246,7 +246,7 @@ readIconDir(struct File * const fP, MALLOCVAR(dirP); if (dirP == NULL) - pm_error("Could't allocate memory for Icon directory"); + pm_error("Couldn't allocate memory for Icon directory"); MALLOCARRAY(dirP->entries, head.count); diff --git a/converter/other/xwdtopnm.c b/converter/other/xwdtopnm.c index df3c7375..a74da341 100644 --- a/converter/other/xwdtopnm.c +++ b/converter/other/xwdtopnm.c @@ -70,14 +70,14 @@ static unsigned int pixel_count = 0; static int zero_bits(const unsigned long mask) { /*---------------------------------------------------------------------------- - Return the number of consective zero bits at the least significant end + Return the number of consecutive zero bits at the least significant end of the binary representation of 'mask'. E.g. if mask == 0x00fff800, we would return 11. -----------------------------------------------------------------------------*/ int i; unsigned long shifted_mask; - for (i=0, shifted_mask = mask; + for (i=0, shifted_mask = mask; i < sizeof(mask)*8 && (shifted_mask & 0x00000001) == 0; i++, shifted_mask >>= 1 ); return(i); @@ -122,9 +122,9 @@ parseCommandLine(int argc, char ** argv, else if (argc - 1 == 1) { if (streq(argv[1], "-")) cmdlineP->inputFilename = NULL; /* he wants stdin */ - else + else cmdlineP->inputFilename = strdup(argv[1]); - } else + } else pm_error("Too many arguments. The only argument accepted\n" "is the input file specification"); } @@ -132,17 +132,17 @@ parseCommandLine(int argc, char ** argv, static void -processX10Header(X10WDFileHeader * const h10P, +processX10Header(X10WDFileHeader * const h10P, FILE * const file, - int * const colsP, - int * const rowsP, - unsigned int * const padrightP, - xelval * const maxvalP, - enum visualclass * const visualclassP, - int * const formatP, - xel ** const colorsP, - int * const bits_per_pixelP, - int * const bits_per_itemP, + int * const colsP, + int * const rowsP, + unsigned int * const padrightP, + xelval * const maxvalP, + enum visualclass * const visualclassP, + int * const formatP, + xel ** const colorsP, + int * const bits_per_pixelP, + int * const bits_per_itemP, struct compMask * const compMaskP, enum byteorder * const byte_orderP, enum byteorder * const bit_orderP) { @@ -214,7 +214,7 @@ processX10Header(X10WDFileHeader * const h10P, (((h10P->pixmap_width + 15) / 16) * 16 - h10P->pixmap_width) * 8; *bits_per_itemP = 16; *bits_per_pixelP = 1; - } else if (h10P->window_ncolors == 0) { + } else if (h10P->window_ncolors == 0) { /* Must be grayscale. */ unsigned int i; *formatP = PGM_TYPE; @@ -314,8 +314,8 @@ dumpX11Cmap(unsigned int const nColors, unsigned int i; for (i = 0; i < nColors; ++i) - pm_message("Color %u r/g/b = %u/%u/%u", i, - x11colors[i].red, x11colors[i].green, + pm_message("Color %u r/g/b = %u/%u/%u", i, + x11colors[i].red, x11colors[i].green, x11colors[i].blue); } @@ -323,11 +323,11 @@ dumpX11Cmap(unsigned int const nColors, static void readX11Colormap(FILE * const file, - unsigned int const nColors, + unsigned int const nColors, bool const byteSwap, bool const cmapDump, X11XColor** const x11colorsP) { - + X11XColor * x11colors; int rc; @@ -362,7 +362,7 @@ colormapAllGray(const X11XColor* const x11colors, bool grayscale; grayscale = TRUE; /* initial assumption */ - for (i = 0; i < ncolors; ++i) + for (i = 0; i < ncolors; ++i) if (x11colors[i].red != x11colors[i].green || x11colors[i].green != x11colors[i].blue ) grayscale = FALSE; @@ -383,7 +383,7 @@ dumpX11Header(X11WDFileHeader * const h11P) { X11WDFileHeader * h11FixedP; fixH11ByteOrder(h11P, &h11FixedP); - + switch(h11FixedP->pixmap_format) { case XYBitmap: formatDesc = "XY bit map"; break; case XYPixmap: formatDesc = "XY pix map"; break; @@ -421,12 +421,12 @@ dumpX11Header(X11WDFileHeader * const h11P) { pm_message("X offset: %u", h11FixedP->xoffset); pm_message("byte order: %s (%u)", byteOrderDesc, h11FixedP->byte_order); pm_message("bitmap unit: %u", h11FixedP->bitmap_unit); - pm_message("bit order: %s (%u)", + pm_message("bit order: %s (%u)", bitOrderDesc, h11FixedP->bitmap_bit_order); pm_message("bitmap pad: %u", h11FixedP->bitmap_pad); pm_message("bits per pixel: %u", h11FixedP->bits_per_pixel); pm_message("bytes per line: %u", h11FixedP->bytes_per_line); - pm_message("visual class: %s (%u)", + pm_message("visual class: %s (%u)", visualClassDesc, h11FixedP->visual_class); pm_message("red mask: %08x", h11FixedP->red_mask); pm_message("green mask: %08x", h11FixedP->green_mask); @@ -517,18 +517,18 @@ computeComponentMasks(X11WDFileHeader * const h11P, static void -processX11Header(X11WDFileHeader * const h11P, +processX11Header(X11WDFileHeader * const h11P, FILE * const fileP, bool const cmapDump, - int * const colsP, - int * const rowsP, - unsigned int * const padrightP, - xelval * const maxvalP, - enum visualclass * const visualclassP, - int * const formatP, - xel ** const colorsP, - int * const bits_per_pixelP, - int * const bits_per_itemP, + int * const colsP, + int * const rowsP, + unsigned int * const padrightP, + xelval * const maxvalP, + enum visualclass * const visualclassP, + int * const formatP, + xel ** const colorsP, + int * const bits_per_pixelP, + int * const bits_per_itemP, struct compMask * const compMaskP, enum byteorder * const byte_orderP, enum byteorder * const bit_orderP) { @@ -538,12 +538,12 @@ processX11Header(X11WDFileHeader * const h11P, bool grayscale; bool const byte_swap = (h11P->file_version != X11WD_FILE_VERSION); X11WDFileHeader * h11FixedP; - + fixH11ByteOrder(h11P, &h11FixedP); if (byte_swap && verbose) pm_message("Header is different endianness from this machine."); - + for (i = 0; i < h11FixedP->header_size - sizeof(*h11FixedP); ++i) if (getc(fileP) == EOF) pm_error("couldn't read rest of X11 XWD file header"); @@ -649,7 +649,7 @@ processX11Header(X11WDFileHeader * const h11P, from a truecolor 32 bit window on a Hummingbird Exceed X server on Win32, and it had bitmap_unit = 8 and bitmap_pad = 32. - But Björn Eriksson in October 2003 had an xwd file from a 24 + But Bjorn Eriksson in October 2003 had an xwd file from a 24 bit-per-pixel direct color window that had bitmap_unit = 32 and bitmap_pad = 8. This was made by Xwd in Red Hat Xfree86 4.3.0-2. @@ -687,21 +687,21 @@ processX11Header(X11WDFileHeader * const h11P, computeComponentMasks(h11FixedP, compMaskP); free(h11FixedP); -} +} static void -getinit(FILE * const ifP, - int * const colsP, - int * const rowsP, - unsigned int * const padrightP, - xelval * const maxvalP, - enum visualclass * const visualclassP, - int * const formatP, +getinit(FILE * const ifP, + int * const colsP, + int * const rowsP, + unsigned int * const padrightP, + xelval * const maxvalP, + enum visualclass * const visualclassP, + int * const formatP, xel ** const colorsP, - int * const bits_per_pixelP, - int * const bits_per_itemP, + int * const bits_per_pixelP, + int * const bits_per_itemP, struct compMask * const compMaskP, enum byteorder * const byte_orderP, enum byteorder * const bit_orderP, @@ -729,13 +729,13 @@ getinit(FILE * const ifP, if ( sizeof(*h10P) > sizeof(*h11P) ) pm_error("ARGH! On this machine, X10 headers are larger than " "X11 headers!\n You will have to re-write xwdtopnm." ); - + /* We read an X10 header's worth of data from the file, then look at it to see if it looks like an X10 header. If so we process the X10 header. If not, but it looks like the beginning of an X11 header, we read more bytes so we have an X11 header's worth of data, then process the X11 header. Otherwise, we raise an - error. + error. */ rc = fread(&header[0], sizeof(*h10P), 1, ifP); @@ -744,23 +744,23 @@ getinit(FILE * const ifP, if (h10P->file_version == X10WD_FILE_VERSION || pm_bs_long(h10P->file_version) == X10WD_FILE_VERSION) { - + if (verbose) pm_message("Input is X10"); - processX10Header(h10P, ifP, colsP, rowsP, padrightP, maxvalP, - visualclassP, formatP, - colorsP, bits_per_pixelP, bits_per_itemP, + processX10Header(h10P, ifP, colsP, rowsP, padrightP, maxvalP, + visualclassP, formatP, + colorsP, bits_per_pixelP, bits_per_itemP, compMaskP, byte_orderP, bit_orderP); } else if (h11P->file_version == X11WD_FILE_VERSION || pm_bs_long(h11P->file_version) == X11WD_FILE_VERSION) { - + int rc; if (verbose) pm_message("Input is X11"); /* Read the balance of the X11 header */ - rc = fread(&header[sizeof(*h10P)], + rc = fread(&header[sizeof(*h10P)], sizeof(*h11P) - sizeof(*h10P), 1, ifP); if (rc != 1) pm_error("couldn't read end of X11 XWD file header"); @@ -769,9 +769,9 @@ getinit(FILE * const ifP, dumpX11Header(h11P); processX11Header(h11P, ifP, cmapDump, - colsP, rowsP, padrightP, maxvalP, - visualclassP, formatP, - colorsP, bits_per_pixelP, bits_per_itemP, + colsP, rowsP, padrightP, maxvalP, + visualclassP, formatP, + colorsP, bits_per_pixelP, bits_per_itemP, compMaskP, byte_orderP, bit_orderP); } else pm_error("unknown XWD file version: %u", h11P->file_version); @@ -786,7 +786,7 @@ getinit(FILE * const ifP, #define DEBUG_PIXEL_2 \ if (pixel_count < 4) \ - pm_message("item: %.8lx", row_controlP->item.l); + pm_message("item: %.8lx", row_controlP->item.l); #define DEBUG_PIXEL_3 \ @@ -876,10 +876,10 @@ static void pixelReader_init(pixelReader * const pixelReaderP, FILE * const fileP, int const bitsPerPixel, - int const bitsPerItem, + int const bitsPerItem, enum byteorder const byteOrder, enum byteorder const bitOrder) { - + pixelReaderP->fileP = fileP; pixelReaderP->bitsPerPixel = bitsPerPixel; pixelReaderP->bitsPerItem = bitsPerItem; @@ -887,7 +887,7 @@ pixelReader_init(pixelReader * const pixelReaderP, pixelReaderP->bitOrder = bitOrder; pixelReaderP->nBitsLeft = 0; -} +} @@ -950,10 +950,10 @@ readItem(pixelReader * const rdrP) { rdrP->nBitsLeft = 16; } break; - + case 32: { long item32; - + switch (rdrP->byteOrder) { case MSBFirst: pm_readbiglong(rdrP->fileP, &item32); @@ -979,7 +979,7 @@ static unsigned long const lsbmask[] = { of a bit string. -----------------------------------------------------------------------------*/ 0x00000000, - 0x00000001, 0x00000003, 0x00000007, 0x0000000f, + 0x00000001, 0x00000003, 0x00000007, 0x0000000f, 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff, @@ -1002,7 +1002,7 @@ pixelReader_getbits(pixelReader * const rdrP, bits from the right end. The number of bits presently in the accumulator is rdrP->bitsPerPixel - nBitsStillNeeded . */ - + unsigned int nBitsStillNeeded; /* How many bits we still need to add to 'pixel', as we build it up to the @@ -1030,7 +1030,7 @@ pixelReader_getbits(pixelReader * const rdrP, /* The actual bits we take, in the 'nBitsToTake' low bits */ assert(nBitsToTake <= 32); - + if (rdrP->bitOrder == MSBFirst) { unsigned int const nBitsToLeave = rdrP->nBitsLeft - nBitsToTake; @@ -1039,7 +1039,7 @@ pixelReader_getbits(pixelReader * const rdrP, } else { bitsToTake = rdrP->itemBuffer & bitsToTakeMask; rdrP->itemBuffer >>= nBitsToTake; - } + } /* Shift the bits into the right end of the accumulator */ pixel <<= nBitsToTake; pixel |= bitsToTake; @@ -1064,7 +1064,7 @@ pixelReader_getpix(pixelReader * const rdrP) { We return an integer. It's the integer that the pixel represents as pure binary cipher, with the first bit the most significant bit. - + The basic unit of storage in the input file is an "item." An item can be 1, 2, or 4 bytes, and 'bits_per_item' tells us which. Each item can have its bytes stored in forward or reverse order, and @@ -1103,18 +1103,18 @@ pixelReader_getpix(pixelReader * const rdrP) { static void -reportInfo(int const cols, - int const rows, - unsigned int const padright, - xelval const maxval, +reportInfo(int const cols, + int const rows, + unsigned int const padright, + xelval const maxval, enum visualclass const visualclass, - int const format, + int const format, int const bits_per_pixel, - int const bits_per_item, + int const bits_per_item, struct compMask const compMask, - enum byteorder const byte_order, + enum byteorder const byte_order, enum byteorder const bit_order) { - + const char *visualclass_name; const char *byte_order_name; const char *bit_order_name; @@ -1140,7 +1140,7 @@ reportInfo(int const cols, pm_message("%d rows of %d columns with maxval %d", rows, cols, maxval); pm_message("padright=%u bits. visualclass = %s. format=%d (%c%c)", - padright, visualclass_name, + padright, visualclass_name, format, format/256, format%256); pm_message("bits_per_pixel=%d; bits_per_item=%d", bits_per_pixel, bits_per_item); @@ -1174,12 +1174,12 @@ warn16Bit(xelval const maxval) { -static void +static void convertRowSimpleIndex(pixelReader * const pixelReaderP, int const cols, const xel * const colors, xel * const xelrow) { - + unsigned int col; for (col = 0; col < cols; ++col) xelrow[col] = colors[pixelReader_getpix(pixelReaderP)]; @@ -1193,7 +1193,7 @@ convertRowDirect(pixelReader * const pixelReaderP, const xel * const colors, struct compMask const compMask, xel * const xelrow) { - + unsigned int col; for (col = 0; col < cols; ++col) { @@ -1204,11 +1204,11 @@ convertRowDirect(pixelReader * const pixelReaderP, unsigned int red_index, grn_index, blu_index; /* These are indices into the color map, unpacked from 'pixel'. */ - + pixel = pixelReader_getpix(pixelReaderP); red_index = (pixel & compMask.red) >> zero_bits(compMask.red); - grn_index = (pixel & compMask.grn) >> zero_bits(compMask.grn); + grn_index = (pixel & compMask.grn) >> zero_bits(compMask.grn); blu_index = (pixel & compMask.blu) >> zero_bits(compMask.blu); PPM_ASSIGN(xelrow[col], @@ -1263,12 +1263,12 @@ convertRowTrueColor(pixelReader * const pixelReaderP, static void convertRow(pixelReader * const pixelReaderP, FILE * const ofP, - unsigned int const padright, - int const cols, + unsigned int const padright, + int const cols, xelval const maxval, - int const format, + int const format, struct compMask const compMask, - const xel* const colors, + const xel* const colors, enum visualclass const visualclass) { /*---------------------------------------------------------------------------- Read a row from the XWD pixel input stream 'pixelReaderP' and write @@ -1290,20 +1290,20 @@ convertRow(pixelReader * const pixelReaderP, case PseudoColor: convertRowSimpleIndex(pixelReaderP, cols, colors, xelrow); break; - case DirectColor: + case DirectColor: convertRowDirect(pixelReaderP, cols, colors, compMask, xelrow); - + break; - case TrueColor: + case TrueColor: convertRowTrueColor(pixelReaderP, cols, maxval, colors, compMask, xelrow); break; - + default: pm_error("unknown visual class"); } pixelReader_getbits(pixelReaderP, padright); - + pnm_writepnmrow(ofP, xelrow, cols, maxval, format, 0); pnm_freerow(xelrow); } @@ -1321,11 +1321,11 @@ reportOutputType(int const format) { case PGM_TYPE: pm_message("writing PGM file"); break; - + case PPM_TYPE: pm_message("writing PPM file"); break; - + default: pm_error("shouldn't happen"); } @@ -1358,19 +1358,19 @@ main(int argc, char *argv[]) { debug = cmdline.debug; verbose = cmdline.verbose; - if (cmdline.inputFilename != NULL) + if (cmdline.inputFilename != NULL) ifP = pm_openr(cmdline.inputFilename); else ifP = stdin; - getinit(ifP, &cols, &rows, &padright, &maxval, &visualclass, &format, - &colors, &bitsPerPixel, &bitsPerItem, + getinit(ifP, &cols, &rows, &padright, &maxval, &visualclass, &format, + &colors, &bitsPerPixel, &bitsPerItem, &compMask, &byteOrder, &bitOrder, cmdline.headerdump, cmdline.cmapdump); warn16Bit(maxval); - - if (verbose) + + if (verbose) reportInfo(cols, rows, padright, maxval, visualclass, format, bitsPerPixel, bitsPerItem, compMask, byteOrder, bitOrder); @@ -1389,17 +1389,17 @@ main(int argc, char *argv[]) { } pixelReader_term(&pixelReader); - + pm_close(ifP); pm_close(stdout); - + return 0; } /* - This used to be the way we parsed a direct/true color pixel. I'm + This used to be the way we parsed a direct/true color pixel. I'm keeping it here in case we find out some application needs it this way. There doesn't seem to be any reason to do this hard-coded stuff when @@ -1411,7 +1411,7 @@ main(int argc, char *argv[]) { this whole switch thing. -Bryan 00.03.01 switch (bits_per_pixel) { - + case 16: PPM_ASSIGN( *xP, ( ( ul & red_mask ) >> 0 ), diff --git a/converter/pbm/mdatopbm.c b/converter/pbm/mdatopbm.c index d8e06572..461b3f80 100644 --- a/converter/pbm/mdatopbm.c +++ b/converter/pbm/mdatopbm.c @@ -36,7 +36,7 @@ static bit **data; /* PBM image */ static mdbyte *mdrow; /* MDA row after decompression (MD3 only) */ static int bInvert = 0; /* Invert image? */ static int bScale = 0; /* Scale image? */ -static int bAscii = 0; /* Ouput ASCII PBM? */ +static int bAscii = 0; /* Output ASCII PBM? */ static int nInRows, nInCols; /* Height, width of input (rows x bytes) */ static int nOutCols, nOutRows; /* Height, width of output (rows x bytes) */ diff --git a/converter/pbm/pbmtogem.c b/converter/pbm/pbmtogem.c index 9eab0416..4fd30e92 100644 --- a/converter/pbm/pbmtogem.c +++ b/converter/pbm/pbmtogem.c @@ -26,7 +26,7 @@ * changed header length to count words to conform with Atari ST documentation * removed rounding of the imagewidth to the next word boundary * removed arbitrary limit to imagewidth -* changed pattern length to 1 to simplify locating of compressable parts +* changed pattern length to 1 to simplify locating of compressible parts * in real world images * add solid run and pattern run compression * diff --git a/converter/pbm/pbmtogo.c b/converter/pbm/pbmtogo.c index 23b2ee9a..4f84f391 100644 --- a/converter/pbm/pbmtogo.c +++ b/converter/pbm/pbmtogo.c @@ -1,29 +1,29 @@ /* pbmtogo.c - read a PBM image and produce a GraphOn terminal raster file -** +** ** Rev 1.1 was based on pbmtolj.c ** ** Bo Thide', Swedish Institute of Space Physics, bt@irfu.se -** +** ** ** $Log: pbmtogo.c,v $ * Revision 1.5 89/11/25 00:24:12 00:24:12 root (Bo Thide) * Bug found: The byte after 64 repeated bytes sometimes lost. Fixed. - * + * * Revision 1.4 89/11/24 14:56:04 14:56:04 root (Bo Thide) * Fixed the command line parsing since pbmtogo now always uses 2D * compression. Added a few comments to the source. - * + * * Revision 1.3 89/11/24 13:43:43 13:43:43 root (Bo Thide) * Added capability for > 63 repeated bytes and > 62 repeated lines in * the 2D compression scheme. - * + * * Revision 1.2 89/11/15 01:04:47 01:04:47 root (Bo Thide) * First version that works reasonably well with GraphOn 2D runlength * encoding/compression. - * + * * Revision 1.1 89/11/02 23:25:25 23:25:25 root (Bo Thide) * Initial revision - * + * ** ** Copyright (C) 1988, 1989 by Jef Poskanzer, Michael Haberler, and Bo Thide'. ** @@ -44,10 +44,10 @@ #define GRAPHON_WIDTH 1056 /* GraphOn has 1056 bit wide raster lines */ #define GRAPHON_WIDTH_BYTES (GRAPHON_WIDTH / 8) -#define REPEAT_CURRENT_LINE_MASK 0x00 -#define SKIP_AND_PLOT_MASK 0x40 -#define REPEAT_PLOT_MASK 0x80 -#define PLOT_ARBITRARY_DATA_MASK 0xc0 +#define REPEAT_CURRENT_LINE_MASK 0x00 +#define SKIP_AND_PLOT_MASK 0x40 +#define REPEAT_PLOT_MASK 0x80 +#define PLOT_ARBITRARY_DATA_MASK 0xc0 #define MAX_REPEAT 64 static unsigned char * scanlineptr; @@ -167,7 +167,7 @@ main(int argc, buffer[i] = oldscanline[i] = 0; putinit(); - /* Start donwloading screen raster */ + /* Start downloading screen raster */ printf("\033P0;1;0;4;1;%d;%d;1!R1/", rows, rucols); linerepeat = 63; /* 63 means "Start new picture" */ @@ -183,32 +183,32 @@ main(int argc, putbit(0); assert(bytesperrow <= GRAPHON_WIDTH_BYTES); - + /* XOR data from the new scan line with data from old scan line */ for (i = 0; i < bytesperrow; i++) diff[i] = oldscanline[i]^newscanline[i]; - + /* ** If the difference map is different from current internal buffer, - ** encode the difference and put it in the output buffer. + ** encode the difference and put it in the output buffer. ** Else, increase the counter for the current buffer by one. */ - + if ((memcmp(buffer, diff, bytesperrow) != 0) || (row == 0)) { - /* + /* **Since the data in the buffer has changed, send the **scan line repeat count to cause the old line(s) to **be plotted on the screen, copy the new data into - **the internal buffer, and reset the counters. + **the internal buffer, and reset the counters. */ - + putchar(linerepeat); for (i = 0; i < bytesperrow; ++i) buffer[i] = diff[i]; nbyte = 0; /* Internal buffer byte counter */ nout = 0; /* Output buffer byte counter */ - - /* Run length encode the new internal buffr (= difference map) */ + + /* Run length encode the new internal buffer (= difference map) */ while (TRUE) { ucount = 0; /* Unique items counter */ do /* Find unique patterns */ @@ -217,16 +217,16 @@ main(int argc, ucount++; } while (nbyte < bytesperrow && (olditem != buffer[nbyte]) && (ucount < MIN(bytesperrow, MAX_REPEAT))); - + if ((ucount != MAX_REPEAT) && (nbyte != bytesperrow)) { /* Back up to the last truly unique pattern */ ucount--; nbyte--; } - if (ucount > 0) { + if (ucount > 0) { /* Output the unique patterns */ - outbuffer[nout++] = + outbuffer[nout++] = (ucount-1) | PLOT_ARBITRARY_DATA_MASK; for (i = nbyte-ucount; i < nbyte; i++) outbuffer[nout++] = buffer[i]; @@ -235,12 +235,12 @@ main(int argc, /* ** If we already are at the end of the current scan ** line, skip the rest of the encoding and start - ** with a new scan line. + ** with a new scan line. */ if (nbyte >= bytesperrow) goto nextrow; - + ecount = 0; /* Equal items counter */ do /* Find equal patterns */ { @@ -248,25 +248,25 @@ main(int argc, ecount++; } while (nbyte < bytesperrow && (olditem == buffer[nbyte]) && (ecount < MIN(bytesperrow, MAX_REPEAT))); - + if (ecount > 1) { /* More than 1 equal pattern */ if (olditem == '\0') { /* White patterns */ if (nbyte >= bytesperrow-1) { /* No more valid data ahead */ - outbuffer[nout++] = + outbuffer[nout++] = (ecount-2) | SKIP_AND_PLOT_MASK; outbuffer[nout++] = buffer[nbyte-1]; - } - else { + } + else { /* More valid data ahead */ - outbuffer[nout++] = + outbuffer[nout++] = (ecount-1) | SKIP_AND_PLOT_MASK; outbuffer[nout++] = buffer[nbyte++]; - } + } } - else { + else { /* Non-white patterns */ outbuffer[nout++] = (ecount-1) | REPEAT_PLOT_MASK; outbuffer[nout++] = olditem; @@ -274,11 +274,11 @@ main(int argc, } /* if (ecount > 1) */ else nbyte--; /* No equal items found */ - + if (nbyte >= bytesperrow) goto nextrow; } /* while (TRUE) */ - + nextrow: printf("%d/", nout+1); /* Total bytes to xfer = nout+1 */ fflush(stdout); @@ -298,7 +298,7 @@ main(int argc, linerepeat = 0; } } - + /* Now we are ready for a new scan line */ for (i = 0; i < bytesperrow; ++i) oldscanline[i] = newscanline[i]; diff --git a/converter/pbm/pbmtoibm23xx.c b/converter/pbm/pbmtoibm23xx.c index 183d5419..3f1f9679 100644 --- a/converter/pbm/pbmtoibm23xx.c +++ b/converter/pbm/pbmtoibm23xx.c @@ -18,7 +18,7 @@ */ /* - * This prgram is primarily based on the description of Brothers PPDS + * This program is primarily based on the description of Brothers PPDS * emulation (see * http://www.brother.de/download/send_file.cfm?file_name=guide_ibmpro.pdf). * However, there are some differences. Their document states that @@ -39,7 +39,7 @@ * normally achieve in y. But the printer is able to do line feeds in * terms of 1/240", so the trick to print in higher resolutions is to * print in several interleaved passes, and do a line feed of 1/240" - * or 1/120" inbetween. + * or 1/120" in between. */ #include @@ -131,7 +131,7 @@ process_handle(FILE * const fh, int cols, rows, format; /* iteration variables */ unsigned int x, y; - unsigned int bitline; /* pixel line within a sigle printing line */ + unsigned int bitline; /* pixel line within a single printing line */ unsigned int pass; /* here we build the to-be-printed data */ unsigned char *output; /* for reading one row from the file */ diff --git a/converter/pbm/pbmtomacp.c b/converter/pbm/pbmtomacp.c index e02f5559..4897e6d0 100644 --- a/converter/pbm/pbmtomacp.c +++ b/converter/pbm/pbmtomacp.c @@ -18,7 +18,7 @@ /* - Implemention notes + Implementation notes Header size is 512 bytes. There is no MacBinary header. diff --git a/converter/pbm/pbmtopk.c b/converter/pbm/pbmtopk.c index 2f05d449..3f54254c 100644 --- a/converter/pbm/pbmtopk.c +++ b/converter/pbm/pbmtopk.c @@ -1,8 +1,8 @@ /* pbmtopk, adapted from "pxtopk.c by tomas rokicki" by AJCD 1/8/90 - + References (retrieved May 31 2015): - Packed (PK) Font File Format + Packed (PK) Font File Format https://www.tug.org/TUGboat/tb06-3/tb13pk.pdf Tex Font Metric Files (TFM) @@ -148,7 +148,7 @@ compute_checksum() temp_width:=memory[char_wd[c]]; if design_units<>unity then temp_width:=round((temp_width/design_units)*1048576.0); - temp_width:=temp_width + (c+4)*@'20000000; + temp_width:=temp_width + (c+4)*@'20000000; {this should be positive} c0:=(c0+c0+temp_width) mod 255; c1:=(c1+c1+temp_width) mod 253; @@ -173,12 +173,12 @@ compute_checksum() static byte -add_tfmtable(int * const table, - int * const count, - int const value, - int const max_count, +add_tfmtable(int * const table, + int * const count, + int const value, + int const max_count, const char * const name) { - + integer i; for (i = 0; i < *count; i++) /* search for value in tfm table */ if (table[i] == value) return (byte)i; @@ -194,8 +194,8 @@ add_tfmtable(int * const table, /* add a suffix to a filename in an allocated space */ -static void -pbmtopk_add_suffix(char * const name, +static void +pbmtopk_add_suffix(char * const name, const char * const suffix) { char *slash = strrchr(name, '/'); @@ -208,7 +208,7 @@ pbmtopk_add_suffix(char * const name, /* initialize the PK parameters */ -static void +static void initialize_pk(void) { integer i ; pm_message("This is PBMtoPK, version 2.4") ; @@ -225,13 +225,13 @@ initialize_pk(void) { /* write a single byte to the PK file */ -static void +static void pbmtopk_pkbyte(integer const b_in) { integer b; b = b_in; /* initial value */ - if (b < 0) + if (b < 0) b += 256 ; putc(b, pkfile) ; pbmtopk_pkloc++ ; @@ -240,13 +240,13 @@ pbmtopk_pkbyte(integer const b_in) { /* write two bytes to the PK file */ -static void +static void pkhalfword(integer const a_in) { integer a; a = a_in; - if (a < 0) + if (a < 0) a += 65536 ; pbmtopk_pkbyte(a >> 8) ; pbmtopk_pkbyte(a & 255) ; @@ -255,7 +255,7 @@ pkhalfword(integer const a_in) { /* write three bytes to the PK file */ -static void +static void pkthreebytes(integer const a) { pbmtopk_pkbyte((a>>16) & 255) ; @@ -266,7 +266,7 @@ pkthreebytes(integer const a) { /* write four bytes to the PK file */ -static void +static void pkword(integer const a) { pbmtopk_pkbyte((a>>24) & 255) ; pbmtopk_pkbyte((a>>16) & 255) ; @@ -277,7 +277,7 @@ pkword(integer const a) { /* write a nibble to the PK file */ -static void +static void pknyb(integer const a) { if (bitweight == 16) { @@ -292,15 +292,15 @@ pknyb(integer const a) { /* write preamble to PK file */ -static void +static void writepreamble(void) { integer i ; const char * const comment = "PBMtoPK 2.4 output" ; - + pbmtopk_pkbyte(247) ; /* PRE command */ pbmtopk_pkbyte(89) ; /* PK file type */ pbmtopk_pkbyte(strlen(comment)) ; /* output comment */ - for (i = 0 ; i < strlen(comment); i++) + for (i = 0 ; i < strlen(comment); i++) pbmtopk_pkbyte(xord[(int)comment[i]]) ; pkword(designsize) ; /* write designsize */ pkword(checksum) ; /* write checksum; calculate if possible */ @@ -311,7 +311,7 @@ writepreamble(void) { /* write postamble to PK file, padded to word length */ -static void +static void writepostamble(void) { pbmtopk_pkbyte(245) ; /* POST command */ while (pbmtopk_pkloc % 4) @@ -322,7 +322,7 @@ writepostamble(void) { /* write a byte to the TFM file */ -static void +static void tfmbyte(integer const b_in) { integer b; @@ -335,9 +335,9 @@ tfmbyte(integer const b_in) { /* write a half word to the TFM file */ -static void +static void tfmhalfword(integer const a_in) { - + integer a; a = a_in; @@ -350,7 +350,7 @@ tfmhalfword(integer const a_in) { /* write a word to the TFM file */ -static void +static void tfmword(integer const a) { tfmbyte((a>>24) & 255) ; tfmbyte((a>>16) & 255) ; @@ -361,12 +361,12 @@ tfmword(integer const a) { /* write the whole TFM file for the font */ -static void +static void writetfmfile(void) { integer totallength ; integer headersize = 17; integer i ; - + if (largestch - smallestch < 0) { largestch = 0; smallestch = 1; @@ -406,23 +406,23 @@ writetfmfile(void) { /* header */ tfmword(checksum) ; /* write checksum */ tfmword(designsize) ; /* write designsize */ - if (strlen(codingscheme) > 39) + if (strlen(codingscheme) > 39) tfmbyte(39) ; /* write coding scheme len */ - else + else tfmbyte(strlen(codingscheme)) ; for (i = 0; i < 39; i++) /* write coding scheme */ - if + if (*codingscheme) tfmbyte(xord[(int)(*codingscheme++)]) ; else tfmbyte(0) ; - if (strlen(familyname) > 19) + if (strlen(familyname) > 19) tfmbyte(19) ; /* write family length */ - else + else tfmbyte(strlen(familyname)) ; for (i = 0; i < 19; i++) /* write family */ - if (*familyname) + if (*familyname) tfmbyte(xord[(int)(*familyname++)]) ; - else + else tfmbyte(0) ; /* char_info */ for (car = smallestch; car <= largestch; car++) @@ -441,7 +441,7 @@ writetfmfile(void) { for (i = 0; i < numdepth; i++) tfmword(depthtab[i]) ; /* italic correction table */ for (i = 0; i < numitalic; i++) tfmword(italictab[i]) ; - /* no lig_kern, kern, or exten tables */ + /* no lig_kern, kern, or extent tables */ /* fontdimen table */ for (i = 0; i < numparam; i++) if (i && !fixrange(parameters[i])) @@ -456,11 +456,11 @@ writetfmfile(void) { /* read a character from a PBM file */ static void readcharacter(void) { FILE *fp; - + fp = pm_openr(filename[car]); bitmap = pbm_readpbm(fp, &width, &height) ; pm_close(fp) ; - + if ((charflags[car] & HORZESC) == 0) horzesc[car] = width ; if ((charflags[car] & VERTESC) == 0) vertesc[car] = 0; if ((charflags[car] & XOFFSET) == 0) xoffset[car] = 0; @@ -470,10 +470,10 @@ static void readcharacter(void) { if ((charflags[car] & TFMHEIGHT) == 0) hgtindex[car] = add_tfmheight(fixword(designunits(yoffset[car]+1))); if ((charflags[car] & TFMDEPTH) == 0) - depindex[car] = + depindex[car] = add_tfmdepth(fixword(designunits(height-1-yoffset[car]))); if ((charflags[car] & TFMITALIC) == 0) italindex[car] = 0; - + if (car < smallestch) smallestch = car; if (car > largestch) largestch = car; if (width > emwidth) emwidth = width ; @@ -482,14 +482,14 @@ static void readcharacter(void) { /* test if two rows of the PBM are the same */ -static int -equal(const bit * const row1, +static int +equal(const bit * const row1, const bit * const row2) { integer i ; - + for (i = 0; i < width; i++) - if (row1[i] != row2[i]) + if (row1[i] != row2[i]) return (0) ; return(1) ; @@ -497,7 +497,7 @@ equal(const bit * const row1, -static void +static void shipcharacter(void) { integer compsize ; @@ -526,13 +526,13 @@ shipcharacter(void) { integer max2 ; integer predpkloc ; integer buff ; - + integer tfwid = widthtab[tfmindex[car]] ; integer hesc = horzesc[car] ; integer vesc = vertesc[car] ; integer xoff = xoffset[car] ; integer yoff = yoffset[car] ; - + MALLOCARRAY(repeatptr, height + 1); MALLOCARRAY(bitcounts, height * width); if (repeatptr == NULL || bitcounts == NULL) @@ -781,8 +781,8 @@ shipcharacter(void) { } if (predpkloc != pbmtopk_pkloc) pm_error("bad predicted character length: character %d", car); - pbm_freerow(zerorow); - pbm_freerow(onesrow); + pbm_freerow(zerorow); + pbm_freerow(onesrow); free((char *)repeatptr); free((char *)bitcounts); } @@ -790,7 +790,7 @@ shipcharacter(void) { /* check that character is in valid range */ -static void +static void checkchar(void) { if (car < 0 || car >= MAXPKCHAR) pm_error("character must be in range 0 to %d", MAXPKCHAR-1) ; @@ -799,16 +799,16 @@ checkchar(void) { /* read character information from an option file */ -static void +static void optionfile(const char * const name) { FILE *fp ; char buffer[MAXOPTLINE] ; - + fp = pm_openr(name); while (!feof(fp)) { char *here = buffer; - + if (fgets(buffer, MAXOPTLINE, fp) == NULL) break ; while (ISSPACE(*here)) here++ ; if (*here && *here == '=') { @@ -817,7 +817,7 @@ optionfile(const char * const name) { } else if (*here && *here != '%' && *here != '#') { char str[NAMELENGTH] ; integer i, n; - + checkchar() ; if (sscanf(here, "%s%n", str, &n) != 1) pm_error("bad option file line %s", buffer) ; @@ -881,26 +881,26 @@ main(int argc, char *argv[]) { pbm_init(&argc, argv); initialize_pk() ; - + if (--argc < 1) pm_usage(usage) ; ++argv; if(strlen(*argv) + 4 > NAMELENGTH) pm_error("pkname is too long"); strcpy(pkname, *argv) ; pbmtopk_add_suffix(pkname, ".pk") ; - + if (--argc < 1) pm_usage(usage); ++argv; if(strlen(*argv) + 4 > NAMELENGTH) pm_error("tfmname is too long"); strcpy(tfmname, *argv) ; pbmtopk_add_suffix(tfmname, ".tfm") ; - + if (--argc < 1) pm_usage(usage) ; resolution = atoi(*++argv) ; if (resolution < 1 || resolution > 32767) pm_error("unlikely resolution %d dpi", resolution); - + car = flags = hesc = vesc = xoff = yoff = tfwid = 0; while (++argv, --argc) { if (argv[0][0] == '-' && argv[0][1]) { @@ -922,7 +922,7 @@ main(int argc, char *argv[]) { case 's': designsize = fixword(atof(p)); if (designsize < 1048576) - pm_error("design size %f out of range", + pm_error("design size %f out of range", unfixword(designsize)); case 'h': hesc = atoi(p) ; @@ -1009,3 +1009,5 @@ main(int argc, char *argv[]) { return 0; } + + diff --git a/converter/pbm/pbmtoppa/README.REDHAT b/converter/pbm/pbmtoppa/README.REDHAT index 3586aea2..e7b30490 100644 --- a/converter/pbm/pbmtoppa/README.REDHAT +++ b/converter/pbm/pbmtoppa/README.REDHAT @@ -17,7 +17,7 @@ StartEntry: DeskJet720C It does does not support color printing. \ IMPORTANT! Insert \ "- | pbm2ppa -" \ - in the "Extra GS Otions" field.\ + in the "Extra GS Options" field.\ } Resolution: {600} {600} {} EndEntry diff --git a/converter/pbm/pbmtoppa/ppa.c b/converter/pbm/pbmtoppa/ppa.c index aa30d684..69e7bb79 100644 --- a/converter/pbm/pbmtoppa/ppa.c +++ b/converter/pbm/pbmtoppa/ppa.c @@ -207,7 +207,7 @@ void ppa_init_job(ppa_stat* prn) scp3_put (prn->fptr, 0x018f, sizeof(init3), 7, 2, 4, init3); break; default: - fprintf(stderr,"ppa_init_job(): unknown printer verson\n"); + fprintf(stderr,"ppa_init_job(): unknown printer version\n"); } } @@ -238,7 +238,7 @@ void ppa_init_page(ppa_stat* prn) scp3_put (prn->fptr, 0x0183, sizeof(pageA), 5, 1, 0, pageA); break; default: - fprintf(stderr,"ppa_init_page(): unknown printer verson\n"); + fprintf(stderr,"ppa_init_page(): unknown printer version\n"); } } @@ -260,7 +260,7 @@ void ppa_load_page(ppa_stat* prn) scp3_put (prn->fptr, 0x0181, sizeof(loadC), 7, 1, 0, loadC); break; default: - fprintf(stderr,"ppa_load_page(): unknown printer verson\n"); + fprintf(stderr,"ppa_load_page(): unknown printer version\n"); } } @@ -282,7 +282,7 @@ void ppa_eject_page(ppa_stat* prn) scp3_put (prn->fptr, 0x0181, sizeof(loadC), 7, 1, 0, loadC); break; default: - fprintf(stderr,"ppa_eject_page(): unknown printer verson\n"); + fprintf(stderr,"ppa_eject_page(): unknown printer version\n"); } } @@ -440,7 +440,7 @@ void ppa_print_sweep(ppa_stat* prn,ppa_sweep_data* data) MF=1; break; default: - fprintf(stderr,"ppa_print_sweep(): unknown printer verson\n"); + fprintf(stderr,"ppa_print_sweep(): unknown printer version\n"); return; } diff --git a/converter/pbm/pbmtoptx.c b/converter/pbm/pbmtoptx.c index c0fb0f80..69f1707a 100644 --- a/converter/pbm/pbmtoptx.c +++ b/converter/pbm/pbmtoptx.c @@ -12,10 +12,10 @@ #include "pbm.h" -/* Follwing is obtained by reversing bit order (MFS-LFS) and adding 64. */ +/* Following is obtained by reversing bit order (MFS-LFS) and adding 64. */ /* Note the two escape sequences: \\ and \x7f . */ -static unsigned char const ptxchar[64] = +static unsigned char const ptxchar[64] = "@`PpHhXxDdTtLl\\|BbRrJjZzFfVvNn^~AaQqIiYyEeUuMm]}CcSsKk[{GgWwOo_\x7f"; @@ -32,7 +32,7 @@ putBitrow(const bit * const bitrow, unsigned int const byteCnt = (itemCnt * 6) / 8; bit const byteCur = bitrow[byteCnt]; bit const byteNext = bitrow[byteCnt + 1]; - + unsigned int item; switch (itemCnt % 4) { @@ -62,7 +62,7 @@ main(int argc, const char ** argv) { ifP = stdin; else { ifP = pm_openr(argv[1]); - + if (argc-1 > 1) pm_error("Too many arguments. The only possible argument is " "the input fil name"); @@ -82,9 +82,8 @@ main(int argc, const char ** argv) { pbm_freerow_packed(bitrow); pm_close(ifP); - + return 0; } - diff --git a/converter/pgm/rawtopgm.c b/converter/pgm/rawtopgm.c index 2e5fbb7d..f34815a7 100644 --- a/converter/pgm/rawtopgm.c +++ b/converter/pgm/rawtopgm.c @@ -107,7 +107,7 @@ parse_command_line(int argc, char ** argv, pm_error("Program takes zero, one, two, or three arguments. You " "specified %d", argc-1); - if (cmdlineP->bpp != 1 && cmdlineP->bpp != 2) + if (cmdlineP->bpp != 1 && cmdlineP->bpp != 2) pm_error("Bytes per pixel (-bpp) must be 1 or 2. You specified %d.", cmdlineP->bpp); @@ -125,7 +125,7 @@ parse_command_line(int argc, char ** argv, pm_error("If you specify -rowskip, you must also give the image " "dimensions."); if (cmdlineP->rowskip && cmdlineP->bottomfirst) - pm_error("You canot specify both -rowskip and -bottomfirst. This is " + pm_error("You cannot specify both -rowskip and -bottomfirst. This is " "a limitation of this program."); } @@ -137,9 +137,9 @@ compute_image_size(const struct cmdline_info cmdline, const long nread, int * const rows_p, int * const cols_p) { if (cmdline.autosize) { - int sqrt_trunc = + int sqrt_trunc = (int) sqrt((double) (nread-cmdline.headerskip)); - if (sqrt_trunc*sqrt_trunc+cmdline.headerskip != nread) + if (sqrt_trunc*sqrt_trunc+cmdline.headerskip != nread) pm_error( "You must specify the dimensions of the image unless " "it is a quadratic image. This one is not quadratic: " "The number of " @@ -178,7 +178,7 @@ read_from_file(FILE *ifp, const int bpp, const int row, const int col, input stream is 'bpp' bytes per pixel (1 or 2). In the case of two bytes, if 'littleendian', assume least significant byte is first. Otherwise, assume MSB first. - + In error messages, say this is Column 'col', Row 'row'. Exit program if error. -----------------------------------------------------------------------------*/ @@ -194,7 +194,7 @@ read_from_file(FILE *ifp, const int bpp, const int row, const int col, } else { short val; int rc; - rc = littleendian ? + rc = littleendian ? pm_readlittleshort(ifp, &val) : pm_readbigshort(ifp, &val); if (rc != 0) pm_error( "EOF / read error at Row %d Column %d", @@ -220,7 +220,7 @@ main(int argc, char *argv[] ) { as if the pixels are one byte each. pixels_2 is the array as if they are two bytes each. */ - unsigned char *pixels_1; + unsigned char *pixels_1; unsigned short *pixels_2; long nread; int row; @@ -269,7 +269,7 @@ main(int argc, char *argv[] ) { else grayrow[col] = pixels_2[rowpos+col]; } else { - grayrow[col] = read_from_file(ifp, cmdline.bpp, + grayrow[col] = read_from_file(ifp, cmdline.bpp, row, col, cmdline.littleendian); } @@ -283,7 +283,7 @@ main(int argc, char *argv[] ) { } pgm_writepgmrow( stdout, grayrow, cols, maxval, 0 ); } - + if (buf) free(buf); pm_close( ifp ); @@ -291,3 +291,6 @@ main(int argc, char *argv[] ) { exit( 0 ); } + + + diff --git a/converter/pgm/st4topgm.c b/converter/pgm/st4topgm.c index 8e4660a3..90be6b72 100644 --- a/converter/pgm/st4topgm.c +++ b/converter/pgm/st4topgm.c @@ -149,7 +149,7 @@ readFooter(FILE * const ifP, 109 10 Calibration factor 119 73 Reserved - Note tha the footer is the same length as a raster row. + Note that the footer is the same length as a raster row. */ bytesReadCt = fread(buffer, 1, sizeof(buffer), ifP); diff --git a/converter/ppm/ilbm.h b/converter/ppm/ilbm.h index dbe47758..c0fac7d2 100644 --- a/converter/ppm/ilbm.h +++ b/converter/ppm/ilbm.h @@ -25,8 +25,8 @@ typedef struct { #define mskHasTransparentColor 2 #define mskLasso 3 /* can't handle this */ #define mskMAXKNOWN mskLasso -static const char * mskNAME[] = { - "none", "mask plane", "transparent color", "lasso" +static const char * mskNAME[] = { + "none", "mask plane", "transparent color", "lasso" }; #define cmpNone 0 @@ -147,98 +147,98 @@ typedef unsigned long IFF_ID; #define MAKE_ID(a, b, c, d) \ ((IFF_ID)(a)<<24 | (IFF_ID)(b)<<16 | (IFF_ID)(c)<<8 | (IFF_ID)(d)) -#define ID_FORM MAKE_ID('F', 'O', 'R', 'M') +#define ID_FORM MAKE_ID('F', 'O', 'R', 'M') /* EA IFF 85 group identifier */ -#define ID_CAT MAKE_ID('C', 'A', 'T', ' ') +#define ID_CAT MAKE_ID('C', 'A', 'T', ' ') /* EA IFF 85 group identifier */ -#define ID_LIST MAKE_ID('L', 'I', 'S', 'T') +#define ID_LIST MAKE_ID('L', 'I', 'S', 'T') /* EA IFF 85 group identifier */ -#define ID_PROP MAKE_ID('P', 'R', 'O', 'P') +#define ID_PROP MAKE_ID('P', 'R', 'O', 'P') /* EA IFF 85 group identifier */ -#define ID_END MAKE_ID('E', 'N', 'D', ' ') +#define ID_END MAKE_ID('E', 'N', 'D', ' ') /* unofficial END-of-FORM identifier (see Amiga RKM Devices Ed.3 page 376) */ -#define ID_ILBM MAKE_ID('I', 'L', 'B', 'M') +#define ID_ILBM MAKE_ID('I', 'L', 'B', 'M') /* EA IFF 85 raster bitmap form */ -#define ID_DEEP MAKE_ID('D', 'E', 'E', 'P') +#define ID_DEEP MAKE_ID('D', 'E', 'E', 'P') /* Chunky pixel image files (Used in TV Paint) */ -#define ID_RGB8 MAKE_ID('R', 'G', 'B', '8') +#define ID_RGB8 MAKE_ID('R', 'G', 'B', '8') /* RGB image forms, Turbo Silver (Impulse) */ -#define ID_RGBN MAKE_ID('R', 'G', 'B', 'N') +#define ID_RGBN MAKE_ID('R', 'G', 'B', 'N') /* RGB image forms, Turbo Silver (Impulse) */ -#define ID_PBM MAKE_ID('P', 'B', 'M', ' ') +#define ID_PBM MAKE_ID('P', 'B', 'M', ' ') /* 256-color chunky format (DPaint 2 ?) */ -#define ID_ACBM MAKE_ID('A', 'C', 'B', 'M') +#define ID_ACBM MAKE_ID('A', 'C', 'B', 'M') /* Amiga Contiguous Bitmap (AmigaBasic) */ /* generic */ -#define ID_FVER MAKE_ID('F', 'V', 'E', 'R') +#define ID_FVER MAKE_ID('F', 'V', 'E', 'R') /* AmigaOS version string */ -#define ID_JUNK MAKE_ID('J', 'U', 'N', 'K') +#define ID_JUNK MAKE_ID('J', 'U', 'N', 'K') /* always ignore this chunk */ -#define ID_ANNO MAKE_ID('A', 'N', 'N', 'O') +#define ID_ANNO MAKE_ID('A', 'N', 'N', 'O') /* EA IFF 85 Generic Annotation chunk */ -#define ID_AUTH MAKE_ID('A', 'U', 'T', 'H') +#define ID_AUTH MAKE_ID('A', 'U', 'T', 'H') /* EA IFF 85 Generic Author chunk */ -#define ID_CHRS MAKE_ID('C', 'H', 'R', 'S') +#define ID_CHRS MAKE_ID('C', 'H', 'R', 'S') /* EA IFF 85 Generic character string chunk */ -#define ID_NAME MAKE_ID('N', 'A', 'M', 'E') +#define ID_NAME MAKE_ID('N', 'A', 'M', 'E') /* EA IFF 85 Generic Name of art, music, etc. chunk */ -#define ID_TEXT MAKE_ID('T', 'E', 'X', 'T') +#define ID_TEXT MAKE_ID('T', 'E', 'X', 'T') /* EA IFF 85 Generic unformatted ASCII text chunk */ -#define ID_copy MAKE_ID('(', 'c', ')', ' ') +#define ID_copy MAKE_ID('(', 'c', ')', ' ') /* EA IFF 85 Generic Copyright text chunk */ /* ILBM chunks */ -#define ID_BMHD MAKE_ID('B', 'M', 'H', 'D') +#define ID_BMHD MAKE_ID('B', 'M', 'H', 'D') /* ILBM BitmapHeader */ -#define ID_CMAP MAKE_ID('C', 'M', 'A', 'P') +#define ID_CMAP MAKE_ID('C', 'M', 'A', 'P') /* ILBM 8bit RGB colormap */ -#define ID_GRAB MAKE_ID('G', 'R', 'A', 'B') - /* ILBM "hotspot" coordiantes */ -#define ID_DEST MAKE_ID('D', 'E', 'S', 'T') +#define ID_GRAB MAKE_ID('G', 'R', 'A', 'B') + /* ILBM "hotspot" coordinates */ +#define ID_DEST MAKE_ID('D', 'E', 'S', 'T') /* ILBM destination image info */ -#define ID_SPRT MAKE_ID('S', 'P', 'R', 'T') +#define ID_SPRT MAKE_ID('S', 'P', 'R', 'T') /* ILBM sprite identifier */ -#define ID_CAMG MAKE_ID('C', 'A', 'M', 'G') +#define ID_CAMG MAKE_ID('C', 'A', 'M', 'G') /* Amiga viewportmodes */ -#define ID_BODY MAKE_ID('B', 'O', 'D', 'Y') +#define ID_BODY MAKE_ID('B', 'O', 'D', 'Y') /* ILBM image data */ -#define ID_CRNG MAKE_ID('C', 'R', 'N', 'G') +#define ID_CRNG MAKE_ID('C', 'R', 'N', 'G') /* color cycling */ -#define ID_CCRT MAKE_ID('C', 'C', 'R', 'T') +#define ID_CCRT MAKE_ID('C', 'C', 'R', 'T') /* color cycling */ -#define ID_CLUT MAKE_ID('C', 'L', 'U', 'T') +#define ID_CLUT MAKE_ID('C', 'L', 'U', 'T') /* Color Lookup Table chunk */ -#define ID_DPI MAKE_ID('D', 'P', 'I', ' ') +#define ID_DPI MAKE_ID('D', 'P', 'I', ' ') /* Dots per inch chunk */ -#define ID_DPPV MAKE_ID('D', 'P', 'P', 'V') +#define ID_DPPV MAKE_ID('D', 'P', 'P', 'V') /* DPaint perspective chunk (EA) */ -#define ID_DRNG MAKE_ID('D', 'R', 'N', 'G') +#define ID_DRNG MAKE_ID('D', 'R', 'N', 'G') /* DPaint IV enhanced color cycle chunk (EA) */ -#define ID_EPSF MAKE_ID('E', 'P', 'S', 'F') +#define ID_EPSF MAKE_ID('E', 'P', 'S', 'F') /* Encapsulated Postscript chunk */ -#define ID_CMYK MAKE_ID('C', 'M', 'Y', 'K') +#define ID_CMYK MAKE_ID('C', 'M', 'Y', 'K') /* Cyan, Magenta, Yellow, & Black color map (Soft-Logik) */ -#define ID_CNAM MAKE_ID('C', 'N', 'A', 'M') +#define ID_CNAM MAKE_ID('C', 'N', 'A', 'M') /* Color naming chunk (Soft-Logik) */ -#define ID_PCHG MAKE_ID('P', 'C', 'H', 'G') +#define ID_PCHG MAKE_ID('P', 'C', 'H', 'G') /* Line by line palette control information (Sebastiano Vigna) */ -#define ID_PRVW MAKE_ID('P', 'R', 'V', 'W') +#define ID_PRVW MAKE_ID('P', 'R', 'V', 'W') /* A mini duplicate ILBM used for preview (Gary Bonham) */ -#define ID_XBMI MAKE_ID('X', 'B', 'M', 'I') +#define ID_XBMI MAKE_ID('X', 'B', 'M', 'I') /* eXtended BitMap Information (Soft-Logik) */ -#define ID_CTBL MAKE_ID('C', 'T', 'B', 'L') +#define ID_CTBL MAKE_ID('C', 'T', 'B', 'L') /* Newtek Dynamic Ham color chunk */ -#define ID_DYCP MAKE_ID('D', 'Y', 'C', 'P') +#define ID_DYCP MAKE_ID('D', 'Y', 'C', 'P') /* Newtek Dynamic Ham chunk */ -#define ID_SHAM MAKE_ID('S', 'H', 'A', 'M') +#define ID_SHAM MAKE_ID('S', 'H', 'A', 'M') /* Sliced HAM color chunk */ -#define ID_ABIT MAKE_ID('A', 'B', 'I', 'T') +#define ID_ABIT MAKE_ID('A', 'B', 'I', 'T') /* ACBM body chunk */ -#define ID_DCOL MAKE_ID('D', 'C', 'O', 'L') +#define ID_DCOL MAKE_ID('D', 'C', 'O', 'L') /* unofficial direct color */ #define ID_DPPS MAKE_ID('D', 'P', 'P', 'S') /* ? */ diff --git a/converter/ppm/ilbmtoppm.c b/converter/ppm/ilbmtoppm.c index 92d4d6f2..b9b89862 100644 --- a/converter/ppm/ilbmtoppm.c +++ b/converter/ppm/ilbmtoppm.c @@ -1597,8 +1597,8 @@ rgbn_to_ppm(FILE * const ifP, Multipalette chunk reader Currently there are three multipalette formats: - SHAM - sliced HAM (obselete) - CTBL - dynamic HAM/Hires (obselete) + SHAM - sliced HAM (obsolete) + CTBL - dynamic HAM/Hires (obsolete) PCHG - palette change There is no official documentation available for SHAM and CTBL, so this is mostly guesswork from other sources and hexdumps of pictures... diff --git a/converter/ppm/picttoppm.c b/converter/ppm/picttoppm.c index b8fb8642..9cf570e6 100644 --- a/converter/ppm/picttoppm.c +++ b/converter/ppm/picttoppm.c @@ -186,9 +186,9 @@ allocateRaster(struct raster * const rasterP, multiple of 16, because we've seen many images in which the PICT raster does contain that much padding on the right. I don't know why; I could understand a multiple of 8, since in 1 bpp image, the smallest unit - expressable in PICT is 8 pixels. But why 16? The images we saw came + expressible in PICT is 8 pixels. But why 16? The images we saw came from Adobe Illustrator 10 in March 2007, supplied by - Guillermo Gómez Valcárcel. + Guillermo Gomez Valcarcel. -----------------------------------------------------------------------------*/ unsigned int const allocWidth = ROUNDUP(width, 16); @@ -2473,10 +2473,6 @@ interpretOneRasterBlock(unsigned char * const block, -static unsigned int const maxPixelBytesPerBlock = 1024; - - - static void interpretCompressedLine(unsigned char * const linebuf, unsigned int const linelen, diff --git a/converter/ppm/pjtoppm.c b/converter/ppm/pjtoppm.c index b8b94f74..ffb01d0c 100644 --- a/converter/ppm/pjtoppm.c +++ b/converter/ppm/pjtoppm.c @@ -143,7 +143,7 @@ main(int argc, const char ** argv) { switch (c) { case 'M': /* transmission mode */ if (val != 0 && val != 1) - pm_error("unimplemented trasmission mode %d", val); + pm_error("unimplemented transmission mode %d", val); mode = val; break; case 'V': /* send plane */ diff --git a/converter/ppm/ppmtoarbtxt.c b/converter/ppm/ppmtoarbtxt.c index 6d4ed04e..6d4c6eac 100644 --- a/converter/ppm/ppmtoarbtxt.c +++ b/converter/ppm/ppmtoarbtxt.c @@ -1079,7 +1079,7 @@ readSkeletonFile(const char * const filename, int rc; rc = getc(sklfileP); if (rc == EOF) { - /* Not a replacement sequence, just an escape caharacter + /* Not a replacement sequence, just an escape character at the end of the file. */ Buffer_add(&buffer, escape); diff --git a/converter/ppm/ppmtobmp.c b/converter/ppm/ppmtobmp.c index f89cec8d..41cee482 100644 --- a/converter/ppm/ppmtobmp.c +++ b/converter/ppm/ppmtobmp.c @@ -138,7 +138,7 @@ parseCommandLine(int argc, const char ** argv, cmdlineP->inputFilename = pm_strdup(argv[1]); else pm_error("Too many arguments. The only argument accepted " - "is the input file specificaton"); + "is the input file specification"); free(option_def); } diff --git a/converter/ppm/ppmtomitsu.c b/converter/ppm/ppmtomitsu.c index 5b0b3245..50b790d6 100644 --- a/converter/ppm/ppmtomitsu.c +++ b/converter/ppm/ppmtomitsu.c @@ -705,7 +705,7 @@ main(int argc, char * argv[]) { for (row = 0; row < rows; ++row) ppm_readppmrow(ifP, pixels[row], cols, maxval, format); - /* first check wether we can use the lut transfer */ + /* first check whether we can use the lut transfer */ table = ppm_computecolorhist(pixels, cols, rows, MAXLUTCOL+1, &nColor); diff --git a/converter/ppm/ppmtompeg/LOGIC b/converter/ppm/ppmtompeg/LOGIC index 8c19dc8d..b346d597 100644 --- a/converter/ppm/ppmtompeg/LOGIC +++ b/converter/ppm/ppmtompeg/LOGIC @@ -45,7 +45,7 @@ is ready. When an encoder server finishes an assignment, it connects to the master server TCP listen port and tells the master it is done, and receives over -the same connetion its next assignment. If there is no more work to do, +the same connection its next assignment. If there is no more work to do, the master server instead tells the encoder server just to terminate. When the master server has told every encoder server to terminate, it diff --git a/converter/ppm/ppmtompeg/Makefile b/converter/ppm/ppmtompeg/Makefile index eeab9727..9ad09c77 100644 --- a/converter/ppm/ppmtompeg/Makefile +++ b/converter/ppm/ppmtompeg/Makefile @@ -124,7 +124,7 @@ profile: LDFLAGS_TARGET = \ PERL = perl # The following stuff is for the Huffman encoding tables. It's commented-out -# because you probably don't want to change this. If you do, then uncommment +# because you probably don't want to change this. If you do, then uncomment # it. # # huff.h: huff.c diff --git a/converter/ppm/ppmtompeg/bsearch.c b/converter/ppm/ppmtompeg/bsearch.c index c618bbd4..b825ef72 100644 --- a/converter/ppm/ppmtompeg/bsearch.c +++ b/converter/ppm/ppmtompeg/bsearch.c @@ -26,7 +26,7 @@ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ -/* +/* * $Header: /n/picasso/project/mpeg/mpeg_dist/mpeg_encode/RCS/bsearch.c,v 1.10 1995/08/07 21:49:01 smoot Exp $ * $Log: bsearch.c,v $ * Revision 1.10 1995/08/07 21:49:01 smoot @@ -37,7 +37,7 @@ * (B frames which are backward P's at the start of a sequence) * * Revision 1.8 1995/03/27 19:17:43 smoot - * killed useless type error messge (int32 defiend as int) + * killed useless type error message (int32 defined as int) * * Revision 1.7 1995/01/19 23:07:20 eyhung * Changed copyrights @@ -194,7 +194,7 @@ FindBestMatchExhaust(const LumBlock * const blockP, /* maybe should try spiral pattern centered around prev motion vector? */ - /* try a spiral pattern */ + /* try a spiral pattern */ for (distance = stepSize; distance <= searchRange; distance += stepSize) { @@ -212,7 +212,7 @@ FindBestMatchExhaust(const LumBlock * const blockP, m.y = my; m.x = mx; diff = LumAddMotionError(currentBlockP, blockP, prev, by, bx, m, bestDiff); - + if (diff < bestDiff) { *motionP = m; bestDiff = diff; @@ -237,7 +237,7 @@ FindBestMatchExhaust(const LumBlock * const blockP, diff = LumAddMotionError(currentBlockP, blockP, prev, by, bx, m, bestDiff); - + if (diff < bestDiff) { *motionP = m; bestDiff = diff; @@ -310,7 +310,7 @@ FindBestMatchTwoLevel(const LumBlock * const blockP, if (VALID_MOTION(*motionP)) { bestDiff = LumAddMotionError(currentBlockP, blockP, prev, by, bx, *motionP, bestSoFar); - + if (bestSoFar < bestDiff) bestDiff = bestSoFar; } else { @@ -323,7 +323,7 @@ FindBestMatchTwoLevel(const LumBlock * const blockP, /* maybe should try spiral pattern centered around prev motion vector? */ - /* try a spiral pattern */ + /* try a spiral pattern */ for ( distance = 2; distance <= searchRange; distance += 2 ) { tempRightMY = MIN(distance, rightMY); tempRightMX = MIN(distance, rightMX); @@ -339,7 +339,7 @@ FindBestMatchTwoLevel(const LumBlock * const blockP, m.y = my; m.x = mx; diff = LumAddMotionError(currentBlockP, blockP, prev, by, bx, m, bestDiff); - + if (diff < bestDiff) { *motionP = m; bestDiff = diff; @@ -361,7 +361,7 @@ FindBestMatchTwoLevel(const LumBlock * const blockP, m.y = my; m.x = mx; diff = LumAddMotionError(currentBlockP, blockP, prev, by, bx, m, bestDiff); - + if (diff < bestDiff) { *motionP = m; bestDiff = diff; @@ -423,7 +423,7 @@ trySpacing(int const spacing, MpegFrame * const prev, int const by, int const bx) { - + int tempRightMY, tempRightMX; int my; int bestDiff; @@ -435,7 +435,7 @@ trySpacing(int const spacing, tempRightMY = MIN(rightMY, center.y + spacing + 1); tempRightMX = MIN(rightMX, center.x + spacing + 1); - + for (my = center.y - spacing; my < tempRightMY; my += spacing) { if (my >= leftMY) { int mx; @@ -446,7 +446,7 @@ trySpacing(int const spacing, m.y = my; m.x = mx; diff = LumAddMotionError(currentBlockP, blockP, prev, by, bx, m, bestDiff); - + if (diff < bestDiff) { /* We have a new best */ newCenter = m; @@ -466,7 +466,7 @@ static void chooseNewSpacing(int const oldSpacing, int const stepSize, int * const newSpacingP) { - + if (stepSize == 2) { /* make sure spacing is even */ if (oldSpacing == 2) *newSpacingP = 0; @@ -530,7 +530,7 @@ FindBestMatchLogarithmic(const LumBlock * const blockP, /* Start at (0,0) */ center.y = center.x = 0; - + while (spacing >= stepSize) { trySpacing(spacing, center, bestDiff, ¢er, &bestDiff, @@ -580,7 +580,7 @@ FindBestMatchSubSample(const LumBlock * const blockP, int const searchRange) { /* too lazy to write the code for this... */ - + return FindBestMatchExhaust(blockP, currentBlockP, prev, by, bx, motionP, bestSoFar, searchRange); @@ -671,9 +671,9 @@ BMotionSearchNoInterp(const LumBlock * const currentBlockP, /* CALL SEARCH PROCEDURE */ switch(psearchAlg) { case PSEARCH_SUBSAMPLE: - *forwardErrP = PSubSampleSearch(currentBlockP, prev, by, bx, + *forwardErrP = PSubSampleSearch(currentBlockP, prev, by, bx, &motionP->fwd,searchRangeB); - *backErrP = PSubSampleSearch(currentBlockP, next, by, bx, + *backErrP = PSubSampleSearch(currentBlockP, next, by, bx, &motionP->bwd, searchRangeB); break; case PSEARCH_EXHAUSTIVE: @@ -690,9 +690,9 @@ BMotionSearchNoInterp(const LumBlock * const currentBlockP, *forwardErrP, searchRangeB); break; case PSEARCH_LOGARITHMIC: - *forwardErrP = PLogarithmicSearch(currentBlockP, prev, by, bx, + *forwardErrP = PLogarithmicSearch(currentBlockP, prev, by, bx, &motionP->fwd, searchRangeB); - *backErrP = PLogarithmicSearch(currentBlockP, next, by, bx, + *backErrP = PLogarithmicSearch(currentBlockP, next, by, bx, &motionP->bwd, searchRangeB); break; case PSEARCH_TWOLEVEL: @@ -731,7 +731,7 @@ BMotionSearchNoInterp(const LumBlock * const currentBlockP, * *fmyP,fmxP,bmyP,bmxP are inputs as well as outputs. We do not update * them if it would make the error worse than the existing values. Otherwise, * we update them to the vectors we find to be best. - * + * *===========================================================================*/ static int BMotionSearchSimple(const LumBlock * const currentBlockP, @@ -750,7 +750,7 @@ BMotionSearchSimple(const LumBlock * const currentBlockP, /* STEP 1 */ BMotionSearchNoInterp(currentBlockP, prev, next, by, bx, motionP, &forwardErr, &backErr, TRUE); - + /* STEP 2 */ ComputeBMotionLumBlock(prev, next, by, bx, MOTION_INTERPOLATE, @@ -799,7 +799,7 @@ BMotionSearchCross2(const LumBlock * const currentBlockP, int const bx, motion * const motionP, int const oldMode) { - + int retval; LumBlock forwardBlock, backBlock; int32 forwardErr, backErr; @@ -816,19 +816,19 @@ BMotionSearchCross2(const LumBlock * const currentBlockP, { /* STEP 2 */ - + struct motion motion; motion.fwd = motionP->fwd; motion.bwd.y = motion.bwd.x = 0; ComputeBMotionLumBlock(prev, next, by, bx, MOTION_FORWARD, motion, &forwardBlock); - + motion.fwd.y = motion.fwd.x = 0; motion.bwd = motionP->bwd; ComputeBMotionLumBlock(prev, next, by, bx, MOTION_BACKWARD, motion, &backBlock); } - /* try a cross-search; total of 4 local searches */ + /* try a cross-search; total of 4 local searches */ newMotion = *motionP; interpErrF = FindBestMatch(&forwardBlock, currentBlockP, @@ -934,11 +934,11 @@ BMotionSearchExhaust(const LumBlock * const currentBlockP, motion, &forwardBlock); newMotion = motion.fwd; - + diff = FindBestMatch(&forwardBlock, currentBlockP, next, by, bx, &newMotion, bestDiff, searchRangeB); - + if (diff < bestDiff) { motionP->fwd = motion.fwd; motionP->bwd = newMotion; @@ -968,7 +968,7 @@ BMotionSearchExhaust(const LumBlock * const currentBlockP, * * PRECONDITIONS: The relevant block in 'current' is valid (it has not * been dct'd). Thus, the data in 'current' can be - * accesed through y_blocks, cr_blocks, and cb_blocks. + * accessed through y_blocks, cr_blocks, and cb_blocks. * This is not the case for the blocks in 'prev' and * 'next.' Therefore, references into 'prev' and 'next' * should be done @@ -1001,7 +1001,7 @@ BMotionSearch(const LumBlock * const currentBlockP, PMotionSearch(currentBlockP, next, by, bx, &motionP->bwd); return MOTION_BACKWARD; } - + /* otherwise simply call the appropriate algorithm, based on user preference */ diff --git a/converter/ppm/ppmtompeg/docs/template.param b/converter/ppm/ppmtompeg/docs/template.param index 78ad5300..fb837428 100644 --- a/converter/ppm/ppmtompeg/docs/template.param +++ b/converter/ppm/ppmtompeg/docs/template.param @@ -138,7 +138,7 @@ BQSCALE 25 # this must be ORIGINAL or DECODED REFERENCE_FRAME ORIGINAL -# for parallel parameters see parallel.param in the exmaples subdirectory +# for parallel parameters see parallel.param in the examples subdirectory # if you want constant bit-rate mode, specify it as follows (number is bits/sec): BIT_RATE 1000000 diff --git a/converter/ppm/ppmtompeg/examples/payam.param b/converter/ppm/ppmtompeg/examples/payam.param index ce886914..e9287a89 100644 --- a/converter/ppm/ppmtompeg/examples/payam.param +++ b/converter/ppm/ppmtompeg/examples/payam.param @@ -16,7 +16,7 @@ kh*.pnm [1-3] END_INPUT -# motion vector search paramters +# motion vector search parameters # MAD or MSE -- must be upper case ERROR MAD diff --git a/converter/ppm/ppmtompeg/examples/payam18.param b/converter/ppm/ppmtompeg/examples/payam18.param index 7f7b767e..95839e83 100644 --- a/converter/ppm/ppmtompeg/examples/payam18.param +++ b/converter/ppm/ppmtompeg/examples/payam18.param @@ -15,7 +15,7 @@ kh*.pnm [1-39] END_INPUT -# motion vector search paramters +# motion vector search parameters # FULL or HALF -- must be upper case PIXEL HALF diff --git a/converter/ppm/ppmtompeg/examples/template.param b/converter/ppm/ppmtompeg/examples/template.param index 78ad5300..fb837428 100644 --- a/converter/ppm/ppmtompeg/examples/template.param +++ b/converter/ppm/ppmtompeg/examples/template.param @@ -138,7 +138,7 @@ BQSCALE 25 # this must be ORIGINAL or DECODED REFERENCE_FRAME ORIGINAL -# for parallel parameters see parallel.param in the exmaples subdirectory +# for parallel parameters see parallel.param in the examples subdirectory # if you want constant bit-rate mode, specify it as follows (number is bits/sec): BIT_RATE 1000000 diff --git a/converter/ppm/ppmtompeg/frametype.c b/converter/ppm/ppmtompeg/frametype.c index 09afa403..debefcdc 100644 --- a/converter/ppm/ppmtompeg/frametype.c +++ b/converter/ppm/ppmtompeg/frametype.c @@ -13,7 +13,7 @@ * FType_FutureRef returns the number of the future reference frame * * FType_PastRef returns the number of the past reference frame * * * - * 00.12.07 change malloc from frameTable to calloc to fix bug + * 00.12.07 change malloc from frameTable to calloc to fix bug *===========================================================================*/ /* @@ -86,24 +86,24 @@ FType_Type(unsigned int const frameNum) { char retval; - if (use_cache) + if (use_cache) return frameTable[frameNum].typ; - + if (frameNum+1 == numFrames) { /* It's the last frame in the sequence. If the pattern says it's a B, we convert it to I because a B frame makes no sense as the last frame of a sequence. */ - if (patternedType == 'b') + if (patternedType == 'b') retval = 'i'; - else + else retval = patternedType; } else { if (specificsOn) { static int lastI = -1; int newtype; - - if (lastI > frameNum) + + if (lastI > frameNum) lastI = -1; newtype = SpecTypeLookup(frameNum); switch (newtype) { @@ -119,13 +119,13 @@ FType_Type(unsigned int const frameNum) { break; default: if (lastI != -1) { - unsigned int const pretendFrameNumber = + unsigned int const pretendFrameNumber = (frameNum - lastI + firstI) % framePatternLen; retval = framePattern[pretendFrameNumber]; - } else + } else retval = patternedType; } - } else + } else retval = patternedType; } return retval; @@ -180,7 +180,7 @@ FType_PastRef(currFrameNum) } else { index = currFrameNum % framePatternLen; pastIndex = frameTable[index].prev->number; - + return currFrameNum - (((index-pastIndex)+framePatternLen) % framePatternLen); } @@ -227,14 +227,14 @@ SetFramePattern(const char * const pattern) { firstI = -1; for (index = 0; index < len; index++) { switch( SIMPLE_ASCII_UPPER(pattern[index]) ) { - case 'I': + case 'I': buf[index] = 'i'; if (firstI == -1) firstI = index; break; - case 'P': - buf[index] = 'p'; + case 'P': + buf[index] = 'p'; break; - case 'B': + case 'B': buf[index] = 'b'; break; default: @@ -248,7 +248,7 @@ SetFramePattern(const char * const pattern) { framePattern = buf; framePatternLen = len; - + /* Used to ComputeFrameTable(), but now must wait until param parsed. (STDIN or not) */ @@ -259,7 +259,7 @@ SetFramePattern(const char * const pattern) { void ComputeFrameTable(unsigned int const numFramesArg) { /*---------------------------------------------------------------------------- - Compute a table of I, P, B frames to help in determining dependencie + Compute a table of I, P, B frames to help in determining dependency 'numFrames' == 0 means number of frames is not known at this time. -----------------------------------------------------------------------------*/ @@ -339,7 +339,7 @@ ComputeFrameTable(unsigned int const numFramesArg) { break; } } - + /* why? SRS */ frameTable[table_size].number = framePatternLen; ptr = firstB; @@ -362,3 +362,6 @@ ComputeFrameTable(unsigned int const numFramesArg) { if (numFrames) use_cache = TRUE; } + + + diff --git a/converter/ppm/ppmtompeg/jpeg.c b/converter/ppm/ppmtompeg/jpeg.c index 24c9ae2d..4540f6f0 100644 --- a/converter/ppm/ppmtompeg/jpeg.c +++ b/converter/ppm/ppmtompeg/jpeg.c @@ -1,12 +1,12 @@ /*===========================================================================* - * jpeg.c - * - * procedures to deal with JPEG files - * - * EXPORTED PROCEDURES: - * JMovie2JPEG - * ReadJPEG - * + * jpeg.c + * + * procedures to deal with JPEG files + * + * EXPORTED PROCEDURES: + * JMovie2JPEG + * ReadJPEG + * *===========================================================================*/ /* COPYRIGHT INFORMATION IS AT THE END OF THIS FILE */ @@ -20,7 +20,7 @@ /* With the lossless jpeg patch applied to the Jpeg library (ftp://ftp.wizards.dupont.com/pub/ImageMagick/delegates/ljpeg-6b.tar.gz), the name of min_DCT_scaled_size changes to min_codec_data_unit, - for some reason. With this macro, we change it back. + for some reason. With this macro, we change it back. */ #define min_codec_data_unit min_DCT_scaled_size #include @@ -40,7 +40,7 @@ /* make it happier.... */ #undef DCTSIZE2 -/* jcopy_sample_rows() is an internal routine in the JPEG library, not +/* jcopy_sample_rows() is an internal routine in the JPEG library, not meant for use by us. We should figure out what the official interface for this is and use it. The following is copied out of jpegint.h, which is part of the JPEG library source code. @@ -88,7 +88,7 @@ void JMovie2JPEG(const char * const infilename, /* input filename string */ const char * const obase, - /* output filename base string=>obase##.jpg */ + /* output filename base string=>obase##.jpg */ int const start, /* first frame to be extracted */ int const end @@ -126,154 +126,154 @@ JMovie2JPEG(const char * const infilename, for the appending of the jpeg bitstream. It can be made smaller if you have a better idea of its expected size */ - static unsigned char inbuffer[300000] = { - 0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, + static unsigned char inbuffer[300000] = { + 0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, - 0x00, 0x01, 0x00, 0x00, 0xFF, 0xC0, 0x00, 0x11, + 0x00, 0x01, 0x00, 0x00, 0xFF, 0xC0, 0x00, 0x11, 0x08, 0x00, 0xF0, 0x01, 0x40, 0x03, 0x01, 0x21, - 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01, 0xFF, + 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01, 0xFF, 0xDB, 0x00, 0x84, 0x00, 0x10, 0x0B, 0x0C, 0x0E, - 0x0C, 0x0A, 0x10, 0x0E, 0x0D, 0x0E, 0x12, + 0x0C, 0x0A, 0x10, 0x0E, 0x0D, 0x0E, 0x12, 0x11, 0x10, 0x13, 0x18, 0x28, 0x1A, 0x18, 0x16, - 0x16, 0x18, 0x31, 0x23, 0x25, 0x1D, 0x28, 0x3A, + 0x16, 0x18, 0x31, 0x23, 0x25, 0x1D, 0x28, 0x3A, 0x33, 0x3D, 0x3C, 0x39, 0x33, 0x38, 0x37, 0x40, - 0x48, 0x5C, 0x4E, 0x40, 0x44, 0x57, 0x45, 0x37, + 0x48, 0x5C, 0x4E, 0x40, 0x44, 0x57, 0x45, 0x37, 0x38, 0x50, 0x6D, 0x51, 0x57, 0x5F, 0x62, 0x67, - 0x68, 0x67, 0x3E, 0x4D, 0x71, 0x79, 0x70, 0x64, + 0x68, 0x67, 0x3E, 0x4D, 0x71, 0x79, 0x70, 0x64, 0x78, 0x5C, 0x65, 0x67, 0x63, 0x01, 0x11, 0x12, - 0x12, 0x18, 0x15, 0x18, 0x2F, 0x1A, 0x1A, 0x2F, + 0x12, 0x18, 0x15, 0x18, 0x2F, 0x1A, 0x1A, 0x2F, 0x63, 0x42, 0x38, 0x42, 0x63, 0x63, 0x63, 0x63, - 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, - 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, - 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, - 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, - 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, + 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, + 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, + 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, + 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, + 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0xFF, 0xC4, - 0x01, 0xA2, 0x00, 0x00, 0x01, 0x05, 0x01, 0x01, + 0x01, 0xA2, 0x00, 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, + 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, - 0x10, 0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, + 0x10, 0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03, 0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, - 0x7D, 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, + 0x7D, 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, - 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xA1, + 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xA1, 0x08, 0x23, 0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1, - 0xF0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, + 0xF0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0A, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x25, 0x26, - 0x27, 0x28, 0x29, 0x2A, 0x34, 0x35, 0x36, 0x37, + 0x27, 0x28, 0x29, 0x2A, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, - 0x48, 0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, + 0x48, 0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, - 0x68, 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, + 0x68, 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x83, 0x84, 0x85, 0x86, 0x87, - 0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, + 0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, - 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, + 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, - 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, + 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, - 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, + 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, - 0xF7, 0xF8, 0xF9, 0xFA, 0x01, 0x00, 0x03, 0x01, + 0xF7, 0xF8, 0xF9, 0xFA, 0x01, 0x00, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, - 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, - 0x0A, 0x0B, 0x11, 0x00, 0x02, 0x01, 0x02, 0x04, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, + 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, + 0x0A, 0x0B, 0x11, 0x00, 0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05, 0x04, 0x04, 0x00, - 0x01, 0x02, 0x77, 0x00, 0x01, 0x02, 0x03, 0x11, + 0x01, 0x02, 0x77, 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, - 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, + 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xA1, 0xB1, 0xC1, 0x09, 0x23, - 0x33, 0x52, 0xF0, 0x15, 0x62, 0x72, 0xD1, + 0x33, 0x52, 0xF0, 0x15, 0x62, 0x72, 0xD1, 0x0A, 0x16, 0x24, 0x34, 0xE1, 0x25, 0xF1, 0x17, - 0x18, 0x19, 0x1A, 0x26, 0x27, 0x28, 0x29, 0x2A, + 0x18, 0x19, 0x1A, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, - 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x53, 0x54, + 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, - 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x73, 0x74, + 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x82, 0x83, - 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x92, + 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, - 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, + 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, - 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, + 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, - 0xD7, 0xD8, 0xD9, 0xDA, 0xE2, 0xE3, 0xE4, 0xE5, + 0xD7, 0xD8, 0xD9, 0xDA, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF2, 0xF3, 0xF4, - 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFF, 0xDA, + 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFF, 0xDA, 0x00, 0x0C, 0x03, 0x01, 0x00, 0x02, 0x11, 0x03, - 0x11, 0x00, 0x3F, 0x00 + 0x11, 0x00, 0x3F, 0x00 }; - + if (start > end) { fprintf(stderr,"bad frame numbers\n"); exit(1); } - + /* open J_Movie */ inFile = fopen(infilename, "rb"); if (inFile == NULL) { perror (infilename); exit(1); } - - /* get file descriptor */ + + /* get file descriptor */ fd = fileno(inFile); - + /* The following lines parse the jpeg_movie header and recover the */ - /* relavant information */ + /* relevant information */ fseek(inFile, 8 * sizeof(char), 0); - + if (fread(&ver_no, sizeof(int), 1, inFile) != 1) { perror("Error in reading version"); exit(1); - } + } if (ver_no != 2) { perror("Unrecognized version - Quantization tables may be wrong\n"); } if (fread(&fps, sizeof(int), 1, inFile) != 1) { perror("Error in reading fps"); exit(1); - } + } if (fread (&no_frames, sizeof(int), 1, inFile) != 1) { perror("Error in reading no_frames"); exit(1); - } + } MALLOCARRAY(inoffsets, no_frames); - + if (fread(&width, sizeof(int), 1, inFile) != 1) { perror("Error in reading width"); exit(1); - } + } /* set image width in JFIF header */ inbuffer[27] = (char)(0xFF & (width >> 8)); inbuffer[28] = (char)(0xFF & width); - + if (fread(&height, sizeof(int), 1, inFile) != 1) { perror("Error in reading height"); exit(1); - } + } /* set image height in JFIF header */ inbuffer[25] = (char)(0xFF & (height >> 8)); inbuffer[26] = (char)(0xFF & height); - + if (fread(&bandwidth, sizeof(int), 1, inFile) != 1) { perror("Error in reading bandwidth"); exit(1); - } - + } + if (fread(&qfactor, sizeof(int), 1, inFile) != 1) { perror("Error in reading qfactor"); exit(1); - } + } /* The default quality factor = 100, therefore, if our quality factor does not equal 100 we must scale the quantization matrices in the JFIF header - */ + */ /* Note values are clipped to a max of 255 */ if (qfactor != 100) { for (Temp = 44; Temp < 108; ++Temp) { @@ -283,13 +283,13 @@ JMovie2JPEG(const char * const infilename, for (Temp = 109; Temp < 173; ++Temp) { temp = (inbuffer[Temp]*qfactor)/100; inbuffer[Temp] = (char)((temp<255) ? temp : 255); - } + } } - + if (fread(&mapsize, sizeof(int), 1, inFile) != 1) { perror("Error in reading mapsize"); exit(1); - } + } if (fread (&image_offset, sizeof(int), 1, inFile) != 1) { perror("Error in reading image offset"); exit(1); @@ -298,32 +298,32 @@ JMovie2JPEG(const char * const infilename, perror("Error in reading audio tracks"); exit(1); } - + fread(junk,sizeof(int),1,inFile); - + if (fread (&audiosize, sizeof(int), 1, inFile) != 1) { perror("Error in reading audiosize"); exit(1); } - + fseek (inFile, image_offset, 0); - + last = MIN(end, no_frames-1); for (i = 0; i < no_frames; ++i) { fread(&(inoffsets[i]), sizeof(int), 1, inFile); } /* Reads in the frame sizes into the array */ - + rewind(inFile); - /* Extract JFIF files from J_Movie */ + /* Extract JFIF files from J_Movie */ for (i = start; i <= last; ++i) { size = inoffsets[i] - inoffsets[i-1]- 5; - lseek(fd, inoffsets[i-1], 0); + lseek(fd, inoffsets[i-1], 0); read(fd, &(op_code), 1); while (op_code != 0xffffffec) { read(fd,junk,audiosize); - read(fd, &(op_code), 1); + read(fd, &(op_code), 1); size = size - audiosize ; } /* To skip the audio bytes in each frame */ read(fd, jpeg_size, 4); @@ -331,7 +331,7 @@ JMovie2JPEG(const char * const infilename, sprintf(ofname, "%s%d.jpg", obase, i); outFile = fopen(ofname, "wb"); fwrite(inbuffer, (size+607), sizeof(char), outFile); - fclose(outFile); + fclose(outFile); } free(inoffsets); fclose(inFile); @@ -413,50 +413,50 @@ ReadJPEG(MpegFrame * const mf, jpeg_stdio_src(&cinfo, fp); } } - + /* specify data source (eg, a file) */ - + jpeg_stdio_src(&cinfo, fp); - + /* read file parameters with jpeg_read_header() */ - - + + (void) jpeg_read_header(&cinfo, TRUE); /* We can ignore the return value from jpeg_read_header since * (a) suspension is not possible with the stdio data source, and * (b) we passed TRUE to reject a tables-only JPEG file as an error. */ - + /* set parameters for decompression */ cinfo.raw_data_out = TRUE; cinfo.out_color_space = JCS_YCbCr; - + /* calculate image output dimensions */ jpeg_calc_output_dimensions(&cinfo); /* the above calculation will set these soon */ /* for now we'll set them ourselves */ - + /* tell mpeg_encode the size of the JPEG Image*/ Fsize_Note(mf->id,(int)(cinfo.image_width),(int)(cinfo.image_height)); - + /* Allocate memory for the raw YCbCr data to occupy*/ Frame_AllocYCC(mf); /*allocate space for mpeg frame*/ - + /* copy pointers to array structure- this make the following code more compact */ orig[0] = mf->orig_y; orig[1] = mf->orig_cb; orig[2] = mf->orig_cr; - + /* Note that we can use the info obtained from jpeg_read_header. */ - + /* Start decompressor */ - + jpeg_start_decompress(&cinfo); - - + + /* JSAMPLEs per row in output buffer */ /* collect component subsample values*/ for (cp=0, compptr = cinfo.comp_info; @@ -470,28 +470,28 @@ ReadJPEG(MpegFrame * const mf, max_h_samp = (temp_hh_samp_factor)/ max_h_samp); - + nrows[cp] = (JDIMENSION)((buffer_height*compptr->v_samp_factor)/ max_v_samp); - + scanarray[cp] = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, ncols[cp], nrows[cp]); } - + /* while (scan lines remain to be read) jpeg_read_scanlines(...); */ - + /* Here we use the library's state variable cinfo.output_scanline as the * loop counter, so that we don't have to keep track ourselves. */ @@ -525,29 +525,29 @@ ReadJPEG(MpegFrame * const mf, } } else pm_error("Invalid subsampling ratio"); - + /* transfer data from jpeg buffer to MPEG frame */ /* calculate the row we wish to output into */ for (ci = 0, compptr = cinfo.comp_info; ci < cinfo.num_components; ++ci, ++compptr) { current_row[ci] =((cinfo.output_scanline - buffer_height)* - (v_samp[ci])/max_v_samp); - + (v_samp[ci])/max_v_samp); + jcopy_sample_rows(scanarray[ci],0,(JSAMPARRAY)(orig[ci]), current_row[ci],nrows[ci],ncols[ci]); } - } - + } + /* Step 7: Finish decompression */ - + (void) jpeg_finish_decompress(&cinfo); /* We can ignore the return value since suspension is not possible * with the stdio data source. */ - + /* Step 8: Release JPEG decompression object */ - + /* ** DO NOT release the cinfo struct if we are reading from stdin, this ** is because the cinfo struct contains the read buffer, and the read @@ -572,7 +572,7 @@ ReadJPEG(MpegFrame * const mf, think that jpeg_destroy can do an error exit, but why assume anything...) */ - + /* At this point you may want to check to see whether any corrupt-data * warnings occurred (test whether jerr.pub.num_warnings is nonzero). * If you prefer to treat corrupt data as a fatal error, override the diff --git a/converter/ppm/ppmtompeg/mheaders.c b/converter/ppm/ppmtompeg/mheaders.c index 4cfe49ac..98e1b063 100644 --- a/converter/ppm/ppmtompeg/mheaders.c +++ b/converter/ppm/ppmtompeg/mheaders.c @@ -39,7 +39,7 @@ * $Header: /n/picasso/project/mpeg/mpeg_dist/mpeg_encode/RCS/mheaders.c,v 1.15 1995/08/07 21:45:19 smoot Exp $ * $Log: mheaders.c,v $ * Revision 1.15 1995/08/07 21:45:19 smoot - * check for illegal MVs (shouldnt ever be called, but....) + * check for illegal MVs (shouldn't ever be called, but....) * fix bug which made us not weite Iframe Qscale changes * warns if writing a size=0 mpeg * @@ -746,7 +746,7 @@ Mhead_GenSequenceHeader(BitBucket * const bbPtr, } Bitio_Write(bbPtr, pratio, 4); - /* Wrtie picture rate, negative values default to 30 fps. */ + /* Write picture rate, negative values default to 30 fps. */ if (pict_rate < 0) { fprintf(stderr, "PROGRAMMER ERROR: pict_rate = %d\n", pict_rate); diff --git a/converter/ppm/ppmtompeg/mpeg.c b/converter/ppm/ppmtompeg/mpeg.c index 33e1a9f9..cb014b32 100644 --- a/converter/ppm/ppmtompeg/mpeg.c +++ b/converter/ppm/ppmtompeg/mpeg.c @@ -91,7 +91,7 @@ static boolean frameCountsUnknown; /*==================* - * GLOBAL VARIABLES * + * GLOBAL VARIABLES * *==================*/ /* important -- don't initialize anything here */ @@ -142,14 +142,14 @@ ShowRemainingTime(boolean const childProcess) { /* nothing */; } else if ( numI + numP + numB == 0 ) { /* no time left */ - } else if ( timeMask != 0 ) { + } else if ( timeMask != 0 ) { /* haven't encoded all types yet */ } else { static int lastTime = 0; float total; time_t nowTime; float secondsPerFrame; - + time(&nowTime); secondsPerFrame = (nowTime-timeStart)/(float)framesOutput; total = secondsPerFrame*(float)(numI+numP+numB); @@ -174,7 +174,7 @@ static void initTCTime(unsigned int const firstFrameNumber) { unsigned int frameNumber; - + tc_hrs = 0; tc_min = 0; tc_sec = 0; tc_pict = 0; tc_extra = 0; for (frameNumber = 0; frameNumber < firstFrameNumber; ++frameNumber) IncrementTCTime(); @@ -201,13 +201,13 @@ IncrementTCTime() { otherwise, it is the number of extra 1/1001 frames we've passed by so far; for example, if fps = 24000/1001, then 24 frames = 24024/24000 - seconds = 1 second + 24/24000 seconds = 1 + 1/1000 seconds; similary, + seconds = 1 second + 24/24000 seconds = 1 + 1/1000 seconds; similarly, if fps = 30000/1001, then 30 frames = 30030/30000 = 1 + 1/1000 seconds and if fps = 60000/1001, then 60 frames = 1 + 1/1000 seconds if fps = 24000/1001, then 1/1000 seconds = 24/1001 frames if fps = 30000/1001, then 1/1000 seconds = 30/1001 frames - if fps = 60000/1001, then 1/1000 seconds = 60/1001 frames + if fps = 60000/1001, then 1/1000 seconds = 60/1001 frames */ totalFramesSent++; @@ -250,7 +250,7 @@ initializeRateControl(bool const wantUnderflowWarning, */ } } - + /*===========================================================================* @@ -294,16 +294,16 @@ finishFrameOutput(MpegFrame * const frameP, boolean const childProcess, boolean const remoteIO) { - if ((referenceFrame == DECODED_FRAME) && + if ((referenceFrame == DECODED_FRAME) && childProcess && NonLocalRefFrame(frameP->id)) { if (remoteIO) SendDecodedFrame(frameP); else WriteDecodedFrame(frameP); - + NotifyDecodeServerReady(frameP->id); } - + if (separateFiles) { if (remoteIO) SendRemoteFrame(frameP->id, bbP); @@ -314,7 +314,7 @@ finishFrameOutput(MpegFrame * const frameP, } } - + static void @@ -324,41 +324,41 @@ outputIFrame(MpegFrame * const frameP, int const realEnd, MpegFrame * const pastRefFrameP, boolean const separateFiles) { - + /* only start a new GOP with I */ /* don't start GOP if only doing frames */ if (!separateFiles && currentGOP >= gopSize) { - boolean const closed = + boolean const closed = (totalFramesSent == frameP->id || pastRefFrameP == NULL); static int num_gop = 0; - + /* first, check to see if closed GOP */ - + /* new GOP */ - if (num_gop != 0 && mult_seq_headers && + if (num_gop != 0 && mult_seq_headers && num_gop % mult_seq_headers == 0) { if (!realQuiet) { - fprintf(stdout, + fprintf(stdout, "Creating new Sequence before GOP %d\n", num_gop); fflush(stdout); } - + Mhead_GenSequenceHeader( bbP, Fsize_x, Fsize_y, /* pratio */ aspectRatio, /* pict_rate */ frameRate, /* bit_rate */ bit_rate, /* buf_size */ buf_size, /* c_param_flag */ 1, - /* iq_matrix */ customQtable, + /* iq_matrix */ customQtable, /* niq_matrix */ customNIQtable, /* ext_data */ NULL, /* ext_data_size */ 0, /* user_data */ NULL, /* user_data_size */ 0); } - + if (!realQuiet) pm_message("Creating new GOP (closed = %s) before frame %d\n", closed ? "YES" : "NO", frameP->id); - + ++num_gop; Mhead_GenGOPHeader(bbP, /* drop_frame_flag */ 0, tc_hrs, tc_min, tc_sec, tc_pict, @@ -371,13 +371,13 @@ outputIFrame(MpegFrame * const frameP, else SetGOPStartTime(pastRefFrameP->id + 1); } - + if (frameP->id >= realStart && frameP->id <= realEnd) GenIFrame(bbP, frameP); - + --numI; timeMask &= 0x6; - + ++currentGOP; IncrementTCTime(); } @@ -396,7 +396,7 @@ outputPFrame(MpegFrame * const frameP, --numP; timeMask &= 0x5; - + ++currentGOP; IncrementTCTime(); } @@ -464,7 +464,7 @@ getBFrame(int const frameNum, *bFramePP = bFrameP; } else { /* As the frame input is serial, we can't read the B frame now. - Rather, Caller has already read it and chained it to + Rather, Caller has already read it and chained it to the previous reference frame. So we get that copy now. */ *bFramePP = pastRefFrameP->next; @@ -510,15 +510,15 @@ processBFrames(MpegFrame * const pastRefFrameP, assert(pastRefFrameP != NULL); assert(futureRefFrameP != NULL); - - for (frameNum = MAX(realStart, firstBFrameNum); - frameNum < MIN(realEnd, futureRefFrameP->id); + + for (frameNum = MAX(realStart, firstBFrameNum); + frameNum < MIN(realEnd, futureRefFrameP->id); ++frameNum) { MpegFrame * bFrame; BitBucket * bbP; - getBFrame(frameNum, inputSourceP, pastRefFrameP, childProcess, + getBFrame(frameNum, inputSourceP, pastRefFrameP, childProcess, remoteIO, &bFrame, IOtimeP, framesReadP); @@ -554,7 +554,7 @@ processBFrames(MpegFrame * const pastRefFrameP, static void -processRefFrame(MpegFrame * const frameP, +processRefFrame(MpegFrame * const frameP, BitBucket * const wholeStreamBbP, int const realStart, int const realEnd, @@ -574,18 +574,18 @@ processRefFrame(MpegFrame * const frameP, -----------------------------------------------------------------------------*/ if (frameP->id >= realStart && frameP->id <= realEnd) { bool const separateFiles = (wholeStreamBbP == NULL); - + BitBucket * bbP; - + if (separateFiles) bbP = bitioNew(outputFileName, frameP->id, remoteIO); else bbP = wholeStreamBbP; - + /* first, output this reference frame */ switch (frameP->type) { case TYPE_IFRAME: - outputIFrame(frameP, bbP, realStart, realEnd, pastRefFrameP, + outputIFrame(frameP, bbP, realStart, realEnd, pastRefFrameP, separateFiles); break; case TYPE_PFRAME: @@ -595,10 +595,10 @@ processRefFrame(MpegFrame * const frameP, default: pm_error("INTERNAL ERROR: non-reference frame passed to " "ProcessRefFrame()"); - } - + } + ++(*framesOutputP); - + finishFrameOutput(frameP, bbP, separateFiles, referenceFrame, childProcess, remoteIO); } @@ -620,7 +620,7 @@ countFrames(unsigned int const firstFrame, -----------------------------------------------------------------------------*/ unsigned int numI, numP, numB; unsigned int timeMask; - + numI = 0; numP = 0; numB = 0; timeMask = 0; if (stdinUsed) { @@ -663,7 +663,7 @@ readAndSaveFrame(struct inputSource * const inputSourceP, type 'frameType'. Increment *framesReadP. - + Add the time it took to read it, in seconds, to *iotimeP. Iff we can't read because we hit end of file, return @@ -672,11 +672,11 @@ readAndSaveFrame(struct inputSource * const inputSourceP, /* This really should be part of ReadNthFrame. The frame should be chained to the input object, not the past reference frame. */ - + MpegFrame * p; MpegFrame * frameP; time_t ioTimeStart, ioTimeEnd; - + time(&ioTimeStart); frameP = Frame_New(frameNumber, frameType); @@ -687,15 +687,15 @@ readAndSaveFrame(struct inputSource * const inputSourceP, Frame_Free(frameP); else { ++(*framesReadP); - + time(&ioTimeEnd); *ioTimeP += (ioTimeEnd - ioTimeStart); - /* Add the B frame to the end of the queue of B-frames + /* Add the B frame to the end of the queue of B-frames for later encoding. */ assert(pastRefFrameP != NULL); - + p = pastRefFrameP; while (p->next != NULL) p = p->next; @@ -726,7 +726,7 @@ doFirstFrameStuff(enum frameContext const context, -----------------------------------------------------------------------------*/ *inputFrameBitsP = 24 * Fsize_x * Fsize_y; SetBlocksPerSlice(); - + if (context == CONTEXT_WHOLESTREAM) { int32 const bitstreamMode = getRateMode(); char * userData; @@ -742,11 +742,11 @@ doFirstFrameStuff(enum frameContext const context, bit_rate = -1; buf_size = -1; } - + if (strlen(userDataFileName) != 0) { struct stat statbuf; FILE *fp; - + stat(userDataFileName,&statbuf); userDataSize = statbuf.st_size; userData = malloc(userDataSize); @@ -771,7 +771,7 @@ doFirstFrameStuff(enum frameContext const context, } else { /* Put in our UserData Header */ const char * userDataString; time_t now; - + time(&now); pm_asprintf(&userDataString,"MPEG stream encoded by UCB Encoder " "(mpeg_encode) v%s on %s.", @@ -782,11 +782,11 @@ doFirstFrameStuff(enum frameContext const context, } Mhead_GenSequenceHeader(bbP, Fsize_x, Fsize_y, /* pratio */ aspectRatio, - /* pict_rate */ frameRate, + /* pict_rate */ frameRate, /* bit_rate */ bit_rate, /* buf_size */ buf_size, /*c_param_flag */ 1, - /* iq_matrix */ qtable, + /* iq_matrix */ qtable, /* niq_matrix */ niqtable, /* ext_data */ NULL, /* ext_data_size */ 0, @@ -844,9 +844,9 @@ getPreviousFrame(unsigned int const frameStart, separateConversion, slaveConversion, inputConversion, frameP, &endOfStream); assert(!endOfStream); /* Because Stdin causes failure above */ - } + } ++(*framesReadP); - + time(&ioTimeEnd); *ioTimeP += (ioTimeEnd-ioTimeStart); @@ -858,7 +858,7 @@ getPreviousFrame(unsigned int const frameStart, static void computeFrameRange(unsigned int const frameStart, unsigned int const frameEnd, - enum frameContext const context, + enum frameContext const context, struct inputSource * const inputSourceP, unsigned int * const firstFrameP, unsigned int * const lastFrameP) { @@ -881,13 +881,13 @@ computeFrameRange(unsigned int const frameStart, *firstFrameP = frameStart; /* if last frame is B, need to read in P or I frame after it */ - if ((FType_Type(frameEnd) == 'b') && + if ((FType_Type(frameEnd) == 'b') && (frameEnd != inputSourceP->numInputFiles-1)) { /* can't find the next reference frame interactively */ if (inputSourceP->stdinUsed) pm_error("Cannot encode frames from Standard Input " "when last frame is a B-frame."); - + *lastFrameP = FType_FutureRef(frameEnd); } else *lastFrameP = frameEnd; @@ -930,11 +930,11 @@ getFrame(MpegFrame ** const framePP, time_t ioTimeStart, ioTimeEnd; MpegFrame * frameP; bool endOfStream; - + time(&ioTimeStart); frameP = Frame_New(frameNumber, frameType); - + if ((referenceFrame == DECODED_FRAME) && ((frameNumber < realStart) || (frameNumber > realEnd)) ) { WaitForDecodedFrame(frameNumber); @@ -952,13 +952,13 @@ getFrame(MpegFrame ** const framePP, ReadNthFrame(inputSourceP, frameNumber, remoteIO, childProcess, separateConversion, slaveConversion, inputConversion, frameP, &endOfStream); - + if (endOfStream) { Frame_Free(frameP); *framePP = NULL; } else { ++(*framesReadP); - + time(&ioTimeEnd); *ioTimeP += (ioTimeEnd - ioTimeStart); @@ -988,9 +988,9 @@ handleBitRate(unsigned int const realEnd, static void doAFrame(unsigned int const frameNumber, struct inputSource * const inputSourceP, - enum frameContext const context, - unsigned int const frameStart, - unsigned int const frameEnd, + enum frameContext const context, + unsigned int const frameStart, + unsigned int const frameEnd, unsigned int const realStart, unsigned int const realEnd, bool const childProcess, @@ -1017,7 +1017,7 @@ doAFrame(unsigned int const frameNumber, output each frame to its own individual file instead. -----------------------------------------------------------------------------*/ char const frameType = FType_Type(frameNumber); - + *endOfStreamP = FALSE; /* initial assumption */ if (frameType == 'b') { @@ -1026,44 +1026,44 @@ doAFrame(unsigned int const frameNumber, just read it later. */ *newPastRefFramePP = pastRefFrameP; - if (inputSourceP->stdinUsed) + if (inputSourceP->stdinUsed) readAndSaveFrame(inputSourceP, frameNumber, frameType, inputConversion, pastRefFrameP, framesReadP, &IOtime, endOfStreamP); } else { MpegFrame * frameP; - + getFrame(&frameP, inputSourceP, frameNumber, frameType, realStart, realEnd, referenceFrame, childProcess, remoteIO, separateConversion, slaveConversion, inputConversion, framesReadP, &IOtime); - + if (frameP) { *endOfStreamP = FALSE; if (!*firstFrameDoneP) { doFirstFrameStuff(context, userDataFileName, wholeStreamBbP, Fsize_x, Fsize_y, aspectRatio, - frameRate, qtable, niqtable, + frameRate, qtable, niqtable, inputFrameBitsP); - + *firstFrameDoneP = TRUE; } processRefFrame(frameP, wholeStreamBbP, frameStart, frameEnd, - pastRefFrameP, childProcess, outputFileName, + pastRefFrameP, childProcess, outputFileName, framesReadP, framesOutputP); - + if (pastRefFrameP) { processBFrames(pastRefFrameP, frameP, realStart, realEnd, - inputSourceP, remoteIO, childProcess, + inputSourceP, remoteIO, childProcess, &IOtime, wholeStreamBbP, outputFileName, framesReadP, framesOutputP, ¤tGOP); } if (pastRefFrameP != NULL) Frame_Free(pastRefFrameP); - + *newPastRefFramePP = frameP; } else *endOfStreamP = TRUE; @@ -1074,13 +1074,13 @@ doAFrame(unsigned int const frameNumber, void GenMPEGStream(struct inputSource * const inputSourceP, - enum frameContext const context, - unsigned int const frameStart, - unsigned int const frameEnd, - int32 const qtable[], - int32 const niqtable[], + enum frameContext const context, + unsigned int const frameStart, + unsigned int const frameEnd, + int32 const qtable[], + int32 const niqtable[], bool const childProcess, - FILE * const ofP, + FILE * const ofP, const char * const outputFileName, bool const wantVbvUnderflowWarning, bool const wantVbvOverflowWarning, @@ -1129,7 +1129,7 @@ GenMPEGStream(struct inputSource * const inputSourceP, "(%u frames)", frameEnd, inputSourceP->numInputFiles); if (context == CONTEXT_WHOLESTREAM && - !inputSourceP->stdinUsed && + !inputSourceP->stdinUsed && FType_Type(inputSourceP->numInputFiles-1) == 'b') pm_message("WARNING: " "One or more B-frames at end will not be encoded. " @@ -1188,27 +1188,27 @@ GenMPEGStream(struct inputSource * const inputSourceP, frameNumber <= lastFrame && !endOfStream; ++frameNumber) { - doAFrame(frameNumber, inputSourceP, context, + doAFrame(frameNumber, inputSourceP, context, frameStart, frameEnd, realStart, realEnd, childProcess, outputFileName, pastRefFrameP, &pastRefFrameP, &framesRead, &framesOutput, &firstFrameDone, streamBbP, inputFrameBitsP, &endOfStream); } - + if (pastRefFrameP != NULL) Frame_Free(pastRefFrameP); - + /* SEQUENCE END CODE */ if (context == CONTEXT_WHOLESTREAM) Mhead_GenSequenceEnder(streamBbP); - + if (streamBbP) numBits = streamBbP->cumulativeBits; else { /* What should the correct value be? Most likely 1. "numBits" is - used below, so we need to make sure it's properly initialized - to somthing (anything). + used below, so we need to make sure it's properly initialized + to something (anything). */ numBits = 1; } @@ -1272,9 +1272,9 @@ SetGOPSize(size) * *===========================================================================*/ void -PrintStartStats(time_t const startTime, +PrintStartStats(time_t const startTime, bool const specificFrames, - unsigned int const firstFrame, + unsigned int const firstFrame, unsigned int const lastFrame, struct inputSource * const inputSourceP) { @@ -1296,7 +1296,7 @@ PrintStartStats(time_t const startTime, fprintf(stdout, "\n\n"); } } - + for (i = 0; i < 2; ++i) { if ( ( i == 0 ) && (! realQuiet) ) { fpointer = stdout; @@ -1322,15 +1322,15 @@ PrintStartStats(time_t const startTime, fprintf(fpointer, "INPUT FROM FILES:\n"); GetNthInputFileName(inputSourceP, 0, &inputFileName); - fprintf(fpointer, "FIRST FILE: %s/%s\n", + fprintf(fpointer, "FIRST FILE: %s/%s\n", currentPath, inputFileName); pm_strfree(inputFileName); - GetNthInputFileName(inputSourceP, inputSourceP->numInputFiles-1, + GetNthInputFileName(inputSourceP, inputSourceP->numInputFiles-1, &inputFileName); - fprintf(fpointer, "LAST FILE: %s/%s\n", + fprintf(fpointer, "LAST FILE: %s/%s\n", currentPath, inputFileName); pm_strfree(inputFileName); - } + } fprintf(fpointer, "OUTPUT: %s\n", outputFileName); if (resizeFrame) @@ -1341,15 +1341,15 @@ PrintStartStats(time_t const startTime, fprintf(fpointer, "SLICES PER FRAME: %d\n", slicesPerFrame); if (searchRangeP==searchRangeB) fprintf(fpointer, "RANGE: +/-%d\n", searchRangeP/2); - else fprintf(fpointer, "RANGES: +/-%d %d\n", + else fprintf(fpointer, "RANGES: +/-%d %d\n", searchRangeP/2,searchRangeB/2); - fprintf(fpointer, "PIXEL SEARCH: %s\n", + fprintf(fpointer, "PIXEL SEARCH: %s\n", pixelFullSearch ? "FULL" : "HALF"); fprintf(fpointer, "PSEARCH: %s\n", PSearchName()); fprintf(fpointer, "BSEARCH: %s\n", BSearchName()); - fprintf(fpointer, "QSCALE: %d %d %d\n", qscaleI, + fprintf(fpointer, "QSCALE: %d %d %d\n", qscaleI, GetPQScale(), GetBQScale()); - if (specificsOn) + if (specificsOn) fprintf(fpointer, "(Except as modified by Specifics file)\n"); if ( referenceFrame == DECODED_FRAME ) { fprintf(fpointer, "REFERENCE FRAME: DECODED\n"); @@ -1386,22 +1386,22 @@ NonLocalRefFrame(int const id) { boolean retval; int const lastIPid = FType_PastRef(id); - + /* might be accessed by B-frame */ - + if (lastIPid+1 < realStart) retval = TRUE; else { unsigned int const nextIPid = FType_FutureRef(id); - + /* if B-frame is out of range, then current frame can be - ref'd by it + ref'd by it */ - + /* might be accessed by B-frame */ if (nextIPid > realEnd+1) retval = TRUE; - + /* might be accessed by P-frame */ if ((nextIPid > realEnd) && (FType_Type(nextIPid) == 'p')) retval = TRUE; @@ -1410,7 +1410,7 @@ NonLocalRefFrame(int const id) { } - + /*===========================================================================* * * SetFrameRate @@ -1508,9 +1508,9 @@ ComputeDHMSTime(someTime, timeText) void -ComputeGOPFrames(int const whichGOP, - unsigned int * const firstFrameP, - unsigned int * const lastFrameP, +ComputeGOPFrames(int const whichGOP, + unsigned int * const firstFrameP, + unsigned int * const lastFrameP, unsigned int const numFrames) { /*---------------------------------------------------------------------------- Figure out which frames are in GOP number 'whichGOP'. @@ -1537,7 +1537,7 @@ ComputeGOPFrames(int const whichGOP, if (gopNum == whichGOP) { foundGop = TRUE; firstFrame = frameNum; - } + } /* go past one gop */ /* must go past at least one frame */ @@ -1551,7 +1551,7 @@ ComputeGOPFrames(int const whichGOP, ++frameNum; ++passedB; } - } while ((frameNum < numFrames) && + } while ((frameNum < numFrames) && ((FType_Type(frameNum) != 'i') || (currGOP < gopSize))); currGOP -= gopSize; @@ -1583,7 +1583,7 @@ doEndStats(FILE * const fpointer, fprintf(fpointer, "TIME COMPLETED: %s", ctime(&endTime)); fprintf(fpointer, "%s\n\n", timeText); - + ShowIFrameSummary(inputFrameBits, totalBits, fpointer); ShowPFrameSummary(inputFrameBits, totalBits, fpointer); ShowBFrameSummary(inputFrameBits, totalBits, fpointer); @@ -1595,7 +1595,7 @@ doEndStats(FILE * const fpointer, if (diffTime > 0) { fprintf(fpointer, "Total Frames Per Sec Elapsed: %f (%ld mps)\n", (float)framesOutput/(float)diffTime, - (long)((float)framesOutput * + (long)((float)framesOutput * (float)inputFrameBits / (256.0*24.0*(float)diffTime))); } else { @@ -1613,7 +1613,7 @@ doEndStats(FILE * const fpointer, frameRateRounded, frameRateRounded*totalBits/framesOutput); fprintf(fpointer, "MPEG file created in : %s\n", outputFileName); fprintf(fpointer, "\n\n"); - + if ( computeMVHist ) { ShowPMVHistogram(fpointer); ShowBBMVHistogram(fpointer); @@ -1637,7 +1637,7 @@ doEndStats(FILE * const fpointer, void PrintEndStats(time_t const startTime, time_t const endTime, - unsigned int const inputFrameBits, + unsigned int const inputFrameBits, unsigned int const totalBits) { float totalCPU; @@ -1652,7 +1652,7 @@ PrintEndStats(time_t const startTime, doEndStats(stdout, startTime, endTime, inputFrameBits, totalBits, totalCPU); } - + if (statFile) { doEndStats(statFile, startTime, endTime, inputFrameBits, totalBits, totalCPU); @@ -1664,7 +1664,7 @@ PrintEndStats(time_t const startTime, void -ReadDecodedRefFrame(MpegFrame * const frameP, +ReadDecodedRefFrame(MpegFrame * const frameP, unsigned int const frameNumber) { FILE *fpointer; @@ -1689,7 +1689,7 @@ ReadDecodedRefFrame(MpegFrame * const frameP, }} Frame_AllocDecoded(frameP, TRUE); - + for ( y = 0; y < height; y++ ) { size_t bytesRead; @@ -1697,7 +1697,7 @@ ReadDecodedRefFrame(MpegFrame * const frameP, if (bytesRead != width) pm_error("Could not read enough bytes from '%s;", fileName); } - + for (y = 0; y < (height >> 1); y++) { /* U */ size_t const bytesToRead = width/2; size_t bytesRead; @@ -1706,7 +1706,7 @@ ReadDecodedRefFrame(MpegFrame * const frameP, if (bytesRead != bytesToRead) pm_message("Could not read enough bytes from '%s'", fileName); } - + for (y = 0; y < (height >> 1); y++) { /* V */ size_t const bytesToRead = width/2; size_t bytesRead; @@ -1723,7 +1723,7 @@ static void OpenBitRateFile() { bitRateFile = fopen(bitRateFileName, "w"); if ( bitRateFile == NULL ) { - pm_message("ERROR: Could not open bit rate file: '%s'", + pm_message("ERROR: Could not open bit rate file: '%s'", bitRateFileName); showBitRatePerFrame = FALSE; } @@ -1735,3 +1735,6 @@ static void CloseBitRateFile() { fclose(bitRateFile); } + + + diff --git a/converter/ppm/ppmtompeg/opts.c b/converter/ppm/ppmtompeg/opts.c index 841efdab..c9c94cd6 100644 --- a/converter/ppm/ppmtompeg/opts.c +++ b/converter/ppm/ppmtompeg/opts.c @@ -13,17 +13,17 @@ /* * Copyright (c) 1995 The Regents of the University of California. * All rights reserved. - * + * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose, without fee, and without written agreement is * hereby granted, provided that the above copyright notice and the following * two paragraphs appear in all copies of this software. - * + * * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * + * * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS @@ -122,7 +122,7 @@ SkipSpacesTabs(const char * const start) { * SIDE EFFECTS: sets collect_quant and collect_quant_fp * *===========================================================================*/ -static void +static void SetupCollectQuantStats(const char * const charPtr) { char fname[256]; @@ -166,17 +166,17 @@ SetupCollectQuantStats(const char * const charPtr) * SIDE EFFECTS: sets kill_dim, kill_dim_break, kill_dim_end * *===========================================================================*/ -static void +static void SetupKillDimAreas(const char * const charPtr) { int items_scanned; kill_dim = TRUE; - items_scanned = sscanf(charPtr, "%d %d %f", + items_scanned = sscanf(charPtr, "%d %d %f", &kill_dim_break, &kill_dim_end, &kill_dim_slope); if (items_scanned != 3) { kill_dim_slope = 0.25; - items_scanned = sscanf(charPtr, "%d %d", + items_scanned = sscanf(charPtr, "%d %d", &kill_dim_break, &kill_dim_end); if (items_scanned != 2) { /* Use defaults */ @@ -205,10 +205,10 @@ SetupKillDimAreas(const char * const charPtr) * * RETURNS: nothing * - * SIDE EFFECTS: sets squash_max_differences SquashMaxLum SquashMaxChr + * SIDE EFFECTS: sets squash_max_differences SquashMaxLum SquashMaxChr * *===========================================================================*/ -static void +static void SetupSquashSmall(const char * const charPtr) { squash_small_differences = TRUE; @@ -232,7 +232,7 @@ SetupSquashSmall(const char * const charPtr) * can change LocalDCTRateScale, LocalDCTDistortScale * *===========================================================================*/ -static void +static void SetupLocalDCT(const char * const charPtr) { int num_scales=0; @@ -262,7 +262,7 @@ SetupLocalDCT(const char * const charPtr) * SIDE EFFECTS: sets DoLaplace, L1, L2, and Lambdas * *===========================================================================*/ -static void +static void SetupLaplace() { int i; @@ -328,18 +328,18 @@ SetupWriteDistortions(const char * const charPtr) default: fprintf(stderr, "Unknown TUNE parameter setting format %s\n", cp); }} -} +} /*=====================* * EXPORTED PROCEDURES * *=====================*/ -void +void CalcLambdas(void) { int i,j,n; double var; - + n = LaplaceNum; for (i = 0; i < 3; i++) { for (j = 0; j < 64; j++) { @@ -378,11 +378,11 @@ Mpost_UnQuantZigBlockLaplace(in, out, qscale, iblock) /* qtable[0] must be 8 */ out[0][0] = (int16)(in[0] * 8); - + for ( index = 1; index < DCTSIZE_SQ; index++ ) { position = ZAG[index]; level = in[index]; - + if (level == 0) { ((int16 *)out)[position] = 0; continue; @@ -413,7 +413,7 @@ Mpost_UnQuantZigBlockLaplace(in, out, qscale, iblock) } } -int +int mse(Block blk1, Block blk2) { register int index, error, tmp; @@ -447,7 +447,7 @@ void Tune_Init() { int i; - /* Just check for each, and do whats needed */ + /* Just check for each, and do what's needed */ if (collect_quant) { if (!pureDCT) { pureDCT = TRUE; @@ -456,14 +456,14 @@ void Tune_Init() } fprintf(collect_quant_fp, "# %s\n", outputFileName); fprintf(collect_quant_fp, "#"); - for (i=0; i<64; i++) + for (i=0; i<64; i++) fprintf(collect_quant_fp, " %d", qtable[i]); fprintf(collect_quant_fp, "\n#"); - for (i=0; i<64; i++) + for (i=0; i<64; i++) fprintf(collect_quant_fp, " %d", niqtable[i]); - fprintf(collect_quant_fp, "\n# %d %d %d\n\n", + fprintf(collect_quant_fp, "\n# %d %d %d\n\n", GetIQScale(), GetPQScale(), GetBQScale()); - + } if (DoLaplace) { @@ -475,7 +475,7 @@ void Tune_Init() decodeRefFrames = TRUE; printSNR = TRUE; } - + } /*===========================================================================* @@ -492,7 +492,7 @@ void Tune_Init() void ParseTuneParam(const char * const charPtr) { switch (ASCII_TOUPPER(*charPtr)) { - case 'B': + case 'B': if (1 != sscanf(charPtr+2, "%d", &block_bound)) { fprintf(stderr, "Invalid tuning parameter (b) in parameter file.\n"); } diff --git a/converter/ppm/ppmtompeg/parallel.c b/converter/ppm/ppmtompeg/parallel.c index e3bcec1a..0fe635ed 100644 --- a/converter/ppm/ppmtompeg/parallel.c +++ b/converter/ppm/ppmtompeg/parallel.c @@ -1,8 +1,8 @@ /*===========================================================================* - * parallel.c - * - * Procedures to make encoder run in parallel - * + * parallel.c + * + * Procedures to make encoder run in parallel + * *===========================================================================*/ /* COPYRIGHT INFORMATION IS AT THE END OF THIS FILE */ @@ -13,8 +13,8 @@ *==============*/ #define _XOPEN_SOURCE 500 /* Make sure stdio.h contains pclose() */ -/* _ALL_SOURCE is needed on AIX to make the C library include the - socket services (e.g. define struct sockaddr) +/* _ALL_SOURCE is needed on AIX to make the C library include the + socket services (e.g. define struct sockaddr) Note that AIX standards.h actually sets feature declaration macros such as _XOPEN_SOURCE, unless they are already set. @@ -93,7 +93,8 @@ struct scheduler { * CONSTANTS * *==================*/ -#define TERMINATE_PID_SIGNAL SIGTERM /* signal used to terminate forked childs */ +#define TERMINATE_PID_SIGNAL SIGTERM + /* signal used to terminate forked children */ #ifndef MAXARGS #define MAXARGS 1024 /* Max Number of arguments in safe_fork command */ #endif @@ -187,8 +188,8 @@ errorExit(const char format[], ...) { static void -TransmitPortNum(const char * const hostName, - int const portNum, +TransmitPortNum(const char * const hostName, + int const portNum, int const newPortNum) { /*---------------------------------------------------------------------------- Transmit the port number 'newPortNum' to the master on port 'portNum' @@ -196,15 +197,15 @@ TransmitPortNum(const char * const hostName, -----------------------------------------------------------------------------*/ int clientSocket; const char * error; - + ConnectToSocket(hostName, portNum, &hostEntry, &clientSocket, &error); - + if (error) errorExit("Can't connect in order to transmit port number. %s", error); WriteInt(clientSocket, newPortNum); - + close(clientSocket); } @@ -215,19 +216,19 @@ readYUVDecoded(int const socketFd, unsigned int const Fsize_x, unsigned int const Fsize_y, MpegFrame * const frameP) { - + unsigned int y; - + for (y = 0; y < Fsize_y; ++y) /* Y */ - ReadBytes(socketFd, + ReadBytes(socketFd, (unsigned char *)frameP->decoded_y[y], Fsize_x); - + for (y = 0; y < (Fsize_y >> 1); ++y) /* U */ - ReadBytes(socketFd, + ReadBytes(socketFd, (unsigned char *)frameP->decoded_cb[y], (Fsize_x >> 1)); - + for (y = 0; y < (Fsize_y >> 1); ++y) /* V */ - ReadBytes(socketFd, + ReadBytes(socketFd, (unsigned char *)frameP->decoded_cr[y], (Fsize_x >> 1)); } @@ -238,19 +239,19 @@ writeYUVDecoded(int const socketFd, unsigned int const Fsize_x, unsigned int const Fsize_y, MpegFrame * const frameP) { - + unsigned int y; - + for (y = 0; y < Fsize_y; ++y) /* Y */ - WriteBytes(socketFd, + WriteBytes(socketFd, (unsigned char *)frameP->decoded_y[y], Fsize_x); - + for (y = 0; y < (Fsize_y >> 1); ++y) /* U */ - WriteBytes(socketFd, + WriteBytes(socketFd, (unsigned char *)frameP->decoded_cb[y], (Fsize_x >> 1)); - + for (y = 0; y < (Fsize_y >> 1); ++y) /* V */ - WriteBytes(socketFd, + WriteBytes(socketFd, (unsigned char *)frameP->decoded_cr[y], (Fsize_x >> 1)); } @@ -261,19 +262,19 @@ writeYUVOrig(int const socketFd, unsigned int const Fsize_x, unsigned int const Fsize_y, MpegFrame * const frameP) { - + unsigned int y; - + for (y = 0; y < Fsize_y; ++y) /* Y */ - WriteBytes(socketFd, + WriteBytes(socketFd, (unsigned char *)frameP->orig_y[y], Fsize_x); - + for (y = 0; y < (Fsize_y >> 1); ++y) /* U */ - WriteBytes(socketFd, + WriteBytes(socketFd, (unsigned char *)frameP->orig_cb[y], (Fsize_x >> 1)); - + for (y = 0; y < (Fsize_y >> 1); ++y) /* V */ - WriteBytes(socketFd, + WriteBytes(socketFd, (unsigned char *)frameP->orig_cr[y], (Fsize_x >> 1)); } @@ -284,19 +285,19 @@ readYUVOrig(int const socketFd, unsigned int const Fsize_x, unsigned int const Fsize_y, MpegFrame * const frameP) { - + unsigned int y; - + for (y = 0; y < Fsize_y; ++y) /* Y */ - ReadBytes(socketFd, + ReadBytes(socketFd, (unsigned char *)frameP->orig_y[y], Fsize_x); - + for (y = 0; y < (Fsize_y >> 1); ++y) /* U */ - ReadBytes(socketFd, + ReadBytes(socketFd, (unsigned char *)frameP->orig_cb[y], (Fsize_x >> 1)); - + for (y = 0; y < (Fsize_y >> 1); ++y) /* V */ - ReadBytes(socketFd, + ReadBytes(socketFd, (unsigned char *)frameP->orig_cr[y], (Fsize_x >> 1)); } @@ -340,20 +341,20 @@ NotifyDecodeServerReady(int const id) { int clientSocket; time_t tempTimeStart, tempTimeEnd; const char * error; - + time(&tempTimeStart); - + ConnectToSocket(IOhostName, decodePortNumber, &hostEntry, &clientSocket, &error); - + if (error) errorExit("CHILD: Can't connect to decode server to tell it a frame " "is ready. %s", error); - + WriteInt(clientSocket, id); - + close(clientSocket); - + time(&tempTimeEnd); IOtime += (tempTimeEnd-tempTimeStart); } @@ -461,23 +462,23 @@ SendDecodedFrame(MpegFrame * const frameP) { Send frame *frameP to the decode server. -----------------------------------------------------------------------------*/ int const negativeTwo = -2; - + int clientSocket; const char * error; - + /* send to IOServer */ ConnectToSocket(IOhostName, ioPortNumber, &hostEntry, &clientSocket, &error); if (error) errorExit("CHILD: Can't connect to decode server to " "give it a decoded frame. %s", error); - + WriteInt(clientSocket, negativeTwo); - + WriteInt(clientSocket, frameP->id); writeYUVDecoded(clientSocket, Fsize_x, Fsize_y, frameP); - + close(clientSocket); } @@ -490,11 +491,11 @@ SendDecodedFrame(MpegFrame * const frameP) { * * RETURNS: nothing * - * SIDE EFFECTS: + * SIDE EFFECTS: * *===========================================================================*/ void -GetRemoteDecodedRefFrame(MpegFrame * const frameP, +GetRemoteDecodedRefFrame(MpegFrame * const frameP, int const frameNumber) { /*---------------------------------------------------------------------------- Get decoded frame number 'frameNumber' *frameP from the decode server. @@ -551,7 +552,7 @@ static void cleanup_fork( dummy ) /* try to kill all child processes */ #endif if (kill(ClientPid[i], TERMINATE_PID_SIGNAL)) { - fprintf(stderr, "cleanup_fork: killed PID=%d failed (errno %d)\n", + fprintf(stderr, "cleanup_fork: killed PID=%d failed (errno %d)\n", ClientPid[i], errno); } } @@ -574,24 +575,24 @@ static int safe_fork(command) /* fork child process and remember its PID * static int init=0; char *argis[MAXARGS]; register int i=1; - + if (!(argis[0] = strtok(command, " \t"))) return(0); /* tokenize */ while ((argis[i] = strtok(NULL, " \t")) && i < MAXARGS) ++i; argis[i] = NULL; - + #ifdef DEBUG_FORK - {register int i=0; + {register int i=0; fprintf(stderr, "Command %s becomes:\n", command); while(argis[i]) {fprintf(stderr, "--%s--\n", argis[i]); ++i;} } #endif - + if (!init) { /* register clean-up routine */ signal (SIGQUIT, cleanup_fork); signal (SIGTERM, cleanup_fork); signal (SIGINT , cleanup_fork); init=1; } - + if (-1 == (ClientPid[current_max_forked_pid] = fork()) ) { perror("safe_fork: fork failed "); return(-1); @@ -682,25 +683,25 @@ decodedFrameToDisk(int const otherSock) { MpegFrame * frameP; ReadInt(otherSock, &frameNumber); - + if (debugSockets) { - fprintf(stdout, "INPUT SERVER: GETTING DECODED FRAME %d\n", + fprintf(stdout, "INPUT SERVER: GETTING DECODED FRAME %d\n", frameNumber); fflush(stdout); } /* should read frame from socket, then write to disk */ frameP = Frame_New(frameNumber, 'i'); - + Frame_AllocDecoded(frameP, TRUE); - + readYUVDecoded(otherSock, Fsize_x, Fsize_y, frameP); /* now output to disk */ WriteDecodedFrame(frameP); Frame_Free(frameP); -} +} @@ -708,12 +709,12 @@ static void decodedFrameFromDisk(int const otherSock) { /* request for decoded frame from disk */ - + int frameNumber; MpegFrame * frameP; ReadInt(otherSock, &frameNumber); - + if (debugSockets) { fprintf(stdout, "INPUT SERVER: READING DECODED FRAME %d " "from DISK\n", frameNumber); @@ -722,15 +723,15 @@ decodedFrameFromDisk(int const otherSock) { /* should read frame from disk, then write to socket */ frameP = Frame_New(frameNumber, 'i'); - + Frame_AllocDecoded(frameP, TRUE); - + ReadDecodedRefFrame(frameP, frameNumber); - + writeYUVDecoded(otherSock, Fsize_x, Fsize_y, frameP); - + Frame_Free(frameP); -} +} @@ -762,10 +763,10 @@ routeFromSocketToDisk(int const otherSock, MALLOCARRAY_NOFAIL(bigBuffer, bigBufferSize); } - + /* now read in the bytes */ ReadBytes(otherSock, bigBuffer, numBytes); - + /* open file to output this stuff to */ pm_asprintf(&fileName, "%s.frame.%d", outputFileName, frameNumber); filePtr = fopen(fileName, "wb"); @@ -777,9 +778,9 @@ routeFromSocketToDisk(int const otherSock, /* now write the bytes here */ fwrite(bigBuffer, sizeof(char), numBytes, filePtr); - + fclose(filePtr); - + if (debugSockets) { fprintf(stdout, "====I/O SERVER: WROTE FRAME %d to disk\n", frameNumber); @@ -788,7 +789,7 @@ routeFromSocketToDisk(int const otherSock, *bigBufferP = bigBuffer; *bigBufferSizeP = bigBufferSize; -} +} @@ -803,7 +804,7 @@ readConvertWriteToSocket(struct inputSource * const inputSourceP, the "base format" result to socket 'otherSock'. -----------------------------------------------------------------------------*/ FILE * convertedFileP; - + convertedFileP = ReadIOConvert(inputSourceP, frameNumber); if (convertedFileP) { bool eof; @@ -811,21 +812,21 @@ readConvertWriteToSocket(struct inputSource * const inputSourceP, while (!eof) { unsigned char buffer[1024]; unsigned int numBytes; - + numBytes = fread(buffer, 1, sizeof(buffer), convertedFileP); - + if (numBytes > 0) { WriteInt(otherSock, numBytes); WriteBytes(otherSock, buffer, numBytes); } else eof = TRUE; } - + if (strcmp(ioConversion, "*") == 0 ) fclose(convertedFileP); else pclose(convertedFileP); - + *endOfStreamP = FALSE; } else *endOfStreamP = TRUE; @@ -848,13 +849,13 @@ readWriteYuvToSocket(struct inputSource * const inputSourceP, MpegFrame * frameP; frameP = Frame_New(frameNumber, 'i'); - + ReadFrame(frameP, inputSourceP, frameNumber, inputConversion, endOfStreamP); - + if (!*endOfStreamP) { writeYUVOrig(otherSock, Fsize_x, Fsize_y, frameP); - + { /* Make sure we don't leave until other processor read everything @@ -907,7 +908,7 @@ processNextConnection(int const serverSocket, int otherSock; int command; const char * error; - + AcceptConnection(serverSocket, &otherSock, &error); if (error) errorExit("I/O SERVER: Failed to accept next connection. %s", error); @@ -948,12 +949,12 @@ processNextConnection(int const serverSocket, } close(otherSock); } - + void IoServer(struct inputSource * const inputSourceP, - const char * const parallelHostName, + const char * const parallelHostName, int const portNum) { /*---------------------------------------------------------------------------- Execute an I/O server. @@ -979,7 +980,7 @@ IoServer(struct inputSource * const inputSourceP, bigBufferSize = 0; /* Start with no buffer */ bigBuffer = NULL; - + /* once we get IO port num, should transmit it to parallel server */ CreateListeningSocket(&serverSocket, &ioPortNum, &error); @@ -1043,12 +1044,12 @@ SendRemoteFrame(int const frameNumber, BitBucket * const bb) { WriteInt(clientSocket, negativeFour); WriteInt(clientSocket, frameNumber); - + if (frameNumber != -1) { /* send number of bytes */ - + WriteInt(clientSocket, (bb->totalbits+7)>>3); - + /* now send the bytes themselves */ Bitio_WriteToSocket(bb, clientSocket); } @@ -1062,11 +1063,11 @@ SendRemoteFrame(int const frameNumber, BitBucket * const bb) { void -GetRemoteFrame(MpegFrame * const frameP, +GetRemoteFrame(MpegFrame * const frameP, int const frameNumber) { /*---------------------------------------------------------------------------- Get a frame from the I/O server. - + This is intended for use by a child. -----------------------------------------------------------------------------*/ int clientSocket; @@ -1084,7 +1085,7 @@ GetRemoteFrame(MpegFrame * const frameP, &clientSocket, &error); if (error) - errorExit("CHILD: Can't connect to I/O server to get a frame. %s", + errorExit("CHILD: Can't connect to I/O server to get a frame. %s", error); WriteInt(clientSocket, frameNumber); @@ -1104,7 +1105,7 @@ GetRemoteFrame(MpegFrame * const frameP, if (numBytes > sizeof(buffer)) errorExit("Invalid message received: numBytes = %d, " - "which is greater than %u", + "which is greater than %u", numBytes, (unsigned)sizeof(numBytes)); ReadBytes(clientSocket, buffer, numBytes); @@ -1162,9 +1163,9 @@ getAndProcessACombineConnection(int const outputServerSocket) { if (error) errorExit("COMBINE SERVER: " "Failed to accept next connection. %s", error); - + ReadInt(otherSock, &command); - + if (command == -2) { /* this is notification from non-remote process that a frame is done. @@ -1173,7 +1174,7 @@ getAndProcessACombineConnection(int const outputServerSocket) { ReadInt(otherSock, &frameStart); ReadInt(otherSock, &frameEnd); - + machineDebug("COMBINE_SERVER: Frames %d - %d done", frameStart, frameEnd); { @@ -1199,7 +1200,7 @@ openInputFile(const char * const fileName, FILE * inputFileP; unsigned int attempts; - + inputFileP = NULL; attempts = 0; @@ -1207,14 +1208,14 @@ openInputFile(const char * const fileName, inputFileP = fopen(fileName, "rb"); if (inputFileP == NULL) { pm_message("ERROR Couldn't read frame file '%s' errno = %d (%s)" - "attempt %d", + "attempt %d", fileName, errno, strerror(errno), attempts); pm_sleep(1000); } ++attempts; } if (inputFileP == NULL) - pm_error("Unable to open file '%s' after %d attempts.", + pm_error("Unable to open file '%s' after %d attempts.", fileName, attempts); *inputFilePP = inputFileP; @@ -1239,7 +1240,7 @@ waitForOutputFile(void * const inputHandle, const char * fileName; while (!frameDone[frameNumber]) { - machineDebug("COMBINE_SERVER: Waiting for frame %u done", + machineDebug("COMBINE_SERVER: Waiting for frame %u done", frameNumber); getAndProcessACombineConnection(outputServerSocket); @@ -1274,8 +1275,8 @@ unlinkFile(void * const inputHandle, void -CombineServer(int const numFrames, - const char * const masterHostName, +CombineServer(int const numFrames, + const char * const masterHostName, int const masterPortNum, const char * const outputFileName) { /*---------------------------------------------------------------------------- @@ -1287,17 +1288,17 @@ CombineServer(int const numFrames, FILE * ofP; const char * error; struct combineControl combineControl; - + /* once we get Combine port num, should transmit it to parallel server */ - + CreateListeningSocket(&outputServerSocket, &combinePortNum, &error); if (error) errorExit("Unable to create socket on which to listen. %s", error); machineDebug("COMBINE SERVER: LISTENING ON PORT %d", combinePortNum); - + TransmitPortNum(masterHostName, masterPortNum, combinePortNum); - + MALLOCARRAY_NOFAIL(frameDone, numFrames); { unsigned int i; @@ -1305,16 +1306,16 @@ CombineServer(int const numFrames, frameDone[i] = FALSE; } ofP = pm_openw(outputFileName); - + combineControl.numFrames = numFrames; FramesToMPEG(ofP, &combineControl, &waitForOutputFile, &unlinkFile); machineDebug("COMBINE SERVER: Shutting down"); - + /* tell Master server we are done */ TransmitPortNum(masterHostName, masterPortNum, combinePortNum); - + close(outputServerSocket); fclose(ofP); @@ -1340,18 +1341,18 @@ startCombineServer(const char * const encoderName, int otherSock; const char * error; - pm_snprintf(command, sizeof(command), + pm_snprintf(command, sizeof(command), "%s %s -max_machines %d -output_server %s %d %d %s", - encoderName, + encoderName, debugMachines ? "-debug_machines" : "", - numMachines, masterHostName, masterPortNum, + numMachines, masterHostName, masterPortNum, numInputFiles, paramFileName); - + machineDebug("MASTER: Starting combine server with shell command '%s'", command); safe_fork(command); - + machineDebug("MASTER: Listening for connection back from " "new Combine server"); @@ -1382,9 +1383,9 @@ startDecodeServer(const char * const encoderName, int otherSock; const char * error; - pm_snprintf(command, sizeof(command), + pm_snprintf(command, sizeof(command), "%s %s -max_machines %d -decode_server %s %d %d %s", - encoder_name, + encoder_name, debugMachines ? "-debug_machines" : "", numMachines, masterHostName, masterPortNum, numInputFiles, paramFileName); @@ -1404,9 +1405,9 @@ startDecodeServer(const char * const encoderName, "decode server. %s", error); ReadInt(otherSock, decodePortNumP); - + close(otherSock); - + machineDebug("MASTER: Decode port number = %d", *decodePortNumP); } @@ -1420,11 +1421,11 @@ startIoServer(const char * const encoderName, int const masterSocket, const char * const paramFileName, int * const ioPortNumP) { - + char command[1024]; int otherSock; const char * error; - + sprintf(command, "%s -max_machines %d -io_server %s %d %s", encoderName, numChildren, masterHostName, masterPortNum, paramFileName); @@ -1433,7 +1434,7 @@ startIoServer(const char * const encoderName, command); safe_fork(command); - + machineDebug("MASTER: Listening for connection back from " "new I/O server"); @@ -1442,14 +1443,14 @@ startIoServer(const char * const encoderName, errorExit("MASTER SERVER: " "Failed to accept connection back from the new " "I/O server. %s", error); - + ReadInt(otherSock, ioPortNumP); close(otherSock); - + machineDebug("MASTER: I/O port number = %d", *ioPortNumP); -} - - +} + + static void extendToEndOfPattern(unsigned int * const nFramesP, @@ -1458,7 +1459,7 @@ extendToEndOfPattern(unsigned int * const nFramesP, unsigned int const numFramesInStream) { assert(framePatternLen >= 1); - + while (startFrame + *nFramesP < numFramesInStream && (startFrame + *nFramesP) % framePatternLen != 0) ++(*nFramesP); @@ -1478,7 +1479,7 @@ allocateInitialFrames(struct scheduler * const schedulerP, /*---------------------------------------------------------------------------- Choose which frames, to hand out to the new child numbered 'childNum'. -----------------------------------------------------------------------------*/ - unsigned int const framesPerChild = + unsigned int const framesPerChild = MAX(1, ((schedulerP->numFramesInJob - schedulerP->nextFrame) / (schedulerP->numMachines - childNum))); @@ -1507,7 +1508,7 @@ allocateInitialFrames(struct scheduler * const schedulerP, static float taperedGoalTime(struct childState const childState[], unsigned int const remainingFrameCount) { - + float goalTime; float allChildrenFPS; float remainingJobTime; @@ -1515,9 +1516,9 @@ taperedGoalTime(struct childState const childState[], float sum; int numMachinesToEstimate; unsigned int childNum; - + /* frames left = lastFrameInStream - startFrame + 1 */ - for (childNum = 0, sum = 0.0, numMachinesToEstimate = 0; + for (childNum = 0, sum = 0.0, numMachinesToEstimate = 0; childNum < numMachines; ++childNum) { if (!childState[childNum].finished) { if (childState[childNum].fps < 0.0 ) @@ -1526,12 +1527,12 @@ taperedGoalTime(struct childState const childState[], sum += childState[childNum].fps; } } - + allChildrenFPS = (float)numMachines * (sum/(float)(numMachines-numMachinesToEstimate)); - + remainingJobTime = (float)remainingFrameCount/allChildrenFPS; - + goalTime = MAX(5.0, remainingJobTime/2); return goalTime; @@ -1575,23 +1576,23 @@ allocateMoreFrames(struct scheduler * const schedulerP, if (!goalTimeSpecified) { goalTime = taperedGoalTime(childState, - schedulerP->numFramesInJob - + schedulerP->numFramesInJob - schedulerP->nextFrame); - + pm_message("MASTER: ASSIGNING %s %.2f seconds of work", machineName[childNum], goalTime); } else goalTime = goalTimeArg; - + if (childState[childNum].numSeconds != 0) - avgFps = (float)childState[childNum].numFrames / + avgFps = (float)childState[childNum].numFrames / childState[childNum].numSeconds; else avgFps = 0.1; /* arbitrary small value */ nFrames = MAX(1u, (unsigned int)(goalTime * avgFps + 0.5)); - - nFrames = MIN(nFrames, + + nFrames = MIN(nFrames, schedulerP->numFramesInJob - schedulerP->nextFrame); if (forceIalign) @@ -1648,7 +1649,7 @@ startChildren(struct scheduler * const schedulerP, MALLOCARRAY_NOFAIL(childState, schedulerP->numMachines); childrenLeftCurrentIoServer = 0; /* No current I/O server yet */ - + numIoServers = 0; /* None created yet */ for (childNum = 0; childNum < schedulerP->numMachines; ++childNum) { @@ -1669,17 +1670,17 @@ startChildren(struct scheduler * const schedulerP, machineName[childNum]); } else { childState[childNum].finished = FALSE; - + if (remote[childNum]) { if (childrenLeftCurrentIoServer == 0) { - startIoServer(encoderName, schedulerP->numMachines, + startIoServer(encoderName, schedulerP->numMachines, masterHostName, masterPortNum, masterSocket, paramFileName, &ioPortNum[numIoServers++]); - + childrenLeftCurrentIoServer = SOMAXCONN; } --childrenLeftCurrentIoServer; - } + } pm_snprintf(command, sizeof(command), "%s %s -l %s %s " "%s %s -child %s %d %d %d %d %d %d " @@ -1689,22 +1690,22 @@ startChildren(struct scheduler * const schedulerP, beNice ? "nice" : "", executable[childNum], debugMachines ? "-debug_machines" : "", - masterHostName, masterPortNum, + masterHostName, masterPortNum, remote[childNum] ? ioPortNum[numIoServers-1] : 0, combinePortNum, decodePortNum, childNum, remote[childNum] ? 1 : 0, startFrame, startFrame + nFrames - 1, - remote[childNum] ? + remote[childNum] ? remoteParamFile[childNum] : paramFileName ); - + machineDebug("MASTER: Starting child server " "with shell command '%s'", command); safe_fork(command); machineDebug("MASTER: Frames %d-%d assigned to new child %s", - startFrame, startFrame + nFrames - 1, + startFrame, startFrame + nFrames - 1, machineName[childNum]); } childState[childNum].startFrame = startFrame; @@ -1720,7 +1721,7 @@ startChildren(struct scheduler * const schedulerP, static void noteFrameDone(const char * const combineHostName, int const combinePortNum, - unsigned int const frameStart, + unsigned int const frameStart, unsigned int const frameEnd) { /*---------------------------------------------------------------------------- Tell the Combine server that frames 'frameStart' through 'frameEnd' @@ -1738,7 +1739,7 @@ noteFrameDone(const char * const combineHostName, ConnectToSocket(combineHostName, combinePortNum, &hostEntP, &clientSocket, &error); - + if (error) errorExit("MASTER: Can't connect to Combine server to tell it frames " "are done. %s", error); @@ -1775,7 +1776,7 @@ feedTheChildren(struct scheduler * const schedulerP, As children finish assignments, inform the combine server at 'combineHostName':'combinePortNum' of such. - Note that the children got initial assigments when they were created. + Note that the children got initial assignments when they were created. So the first thing we do is wait for them to finish those. -----------------------------------------------------------------------------*/ unsigned int numFinished; @@ -1808,7 +1809,7 @@ feedTheChildren(struct scheduler * const schedulerP, ReadInt(otherSock, &seconds); csP = &childState[childNum]; - + csP->numSeconds += seconds; csP->fps = (float)csP->numFrames / (float)csP->numSeconds; @@ -1818,7 +1819,7 @@ feedTheChildren(struct scheduler * const schedulerP, framesPerSecond = (float)csP->lastNumFrames * 2.0; machineDebug("MASTER: Child %s FINISHED ASSIGNMENT. " - "%f frames per second", + "%f frames per second", machineName[childNum], framesPerSecond); noteFrameDone(combineHostName, combinePortNum, csP->startFrame, @@ -1855,7 +1856,7 @@ feedTheChildren(struct scheduler * const schedulerP, close(otherSock); machineDebug("MASTER: %d/%d DONE; %d ARE ASSIGNED", - framesDone, schedulerP->numFramesInJob, + framesDone, schedulerP->numFramesInJob, schedulerP->nextFrame - framesDone); } } @@ -1898,7 +1899,7 @@ waitForCombineServerToTerminate(int const masterSocket) { } close(otherSock); } - + static void @@ -1932,46 +1933,46 @@ printFinalStats(FILE * const statfileP, (unsigned int)(startUpEnd - startUpBegin)); fprintf(fileP, "SHUT DOWN TIME: %u seconds\n", (unsigned int)(shutDownEnd - shutDownBegin)); - - fprintf(fileP, + + fprintf(fileP, "%14.14s %8.8s %8.8s %12.12s %9.9s\n", "MACHINE", "Frames", "Seconds", "Frames/Sec", "Self Time"); - fprintf(fileP, + fprintf(fileP, "%14.14s %8.8s %8.8s %12.12s %9.9s\n", "--------------", "--------", "--------", "------------", "---------"); totalFPS = 0.0; for (childNum = 0; childNum < numChildren; ++childNum) { - float const localFPS = + float const localFPS = (float)childState[childNum].numFrames / childState[childNum].numSeconds; fprintf(fileP, "%14.14s %8u %8u %12.4f %8u\n", - machineName[childNum], - childState[childNum].numFrames, + machineName[childNum], + childState[childNum].numFrames, childState[childNum].numSeconds, - localFPS, + localFPS, (unsigned int)((float)numFrames/localFPS)); totalFPS += localFPS; } - fprintf(fileP, + fprintf(fileP, "%14.14s %8.8s %8.8s %12.12s %9.9s\n", "--------------", "--------", "--------", "------------", "---------"); - fprintf(fileP, "%14s %8.8s %8u %12.4f\n", - "OPTIMAL", "", + fprintf(fileP, "%14s %8.8s %8u %12.4f\n", + "OPTIMAL", "", (unsigned int)((float)numFrames/totalFPS), totalFPS); - + { unsigned int const diffTime = shutDownEnd - startUpBegin; - - fprintf(fileP, "%14s %8.8s %8u %12.4f\n", - "ACTUAL", "", diffTime, + + fprintf(fileP, "%14s %8.8s %8u %12.4f\n", + "ACTUAL", "", diffTime, (float)numFrames / diffTime); } fprintf(fileP, "\n\n"); @@ -1983,7 +1984,7 @@ printFinalStats(FILE * const statfileP, void MasterServer(struct inputSource * const inputSourceP, - const char * const paramFileName, + const char * const paramFileName, const char * const outputFileName) { /*---------------------------------------------------------------------------- Execute the master server function. @@ -2025,21 +2026,21 @@ MasterServer(struct inputSource * const inputSourceP, fprintf(stdout, "---MASTER USING PORT %d\n", portNum); startCombineServer(encoder_name, numMachines, hostName, portNum, - inputSourceP->numInputFiles, - paramFileName, masterSocket, + inputSourceP->numInputFiles, + paramFileName, masterSocket, &combinePortNum); if (referenceFrame == DECODED_FRAME) startDecodeServer(encoder_name, numMachines, hostName, portNum, - inputSourceP->numInputFiles, + inputSourceP->numInputFiles, paramFileName, masterSocket, &decodePortNum); startChildren(&scheduler, encoder_name, hostName, portNum, paramFileName, parallelPerfect, forceIalign, - framePatternLen, parallelTestFrames, + framePatternLen, parallelTestFrames, niceProcesses, - masterSocket, combinePortNum, decodePortNum, + masterSocket, combinePortNum, decodePortNum, ioPortNum, &numIoServers, &childState); @@ -2076,10 +2077,10 @@ MasterServer(struct inputSource * const inputSourceP, void -NotifyMasterDone(const char * const masterHostName, - int const masterPortNum, +NotifyMasterDone(const char * const masterHostName, + int const masterPortNum, int const childNum, - unsigned int const seconds, + unsigned int const seconds, boolean * const moreWorkToDoP, int * const nextFrameStartP, int * const nextFrameEndP) { @@ -2098,11 +2099,11 @@ NotifyMasterDone(const char * const masterHostName, time_t tempTimeStart, tempTimeEnd; const char * error; - machineDebug("CHILD: NOTIFYING MASTER Machine %d assignment complete", + machineDebug("CHILD: NOTIFYING MASTER Machine %d assignment complete", childNum); time(&tempTimeStart); - + ConnectToSocket(masterHostName, masterPortNum, &hostEntry, &clientSocket, &error); if (error) @@ -2132,9 +2133,9 @@ NotifyMasterDone(const char * const masterHostName, void -DecodeServer(int const numInputFiles, - const char * const decodeFileName, - const char * const masterHostName, +DecodeServer(int const numInputFiles, + const char * const decodeFileName, + const char * const masterHostName, int const masterPortNum) { /*---------------------------------------------------------------------------- Execute the decode server. @@ -2220,7 +2221,7 @@ DecodeServer(int const numInputFiles, } } else { frameDone[frameReady] = TRUE; - + machineDebug("DECODE SERVER: FRAME %d READY", frameReady); if ( waitMachine[frameReady] ) { @@ -2233,7 +2234,7 @@ DecodeServer(int const numInputFiles, &clientSocket, &error); if (error) errorExit("DECODE SERVER: " - "Can't connect to child machine. %s", + "Can't connect to child machine. %s", error); close(clientSocket); waitPtr = waitList[waitPtr]-1; @@ -2243,7 +2244,7 @@ DecodeServer(int const numInputFiles, close(otherSock); } - + machineDebug("DECODE SERVER: Shutting down"); /* tell Master server we are done */ diff --git a/converter/ppm/ppmtompeg/param.c b/converter/ppm/ppmtompeg/param.c index 87fdfa6b..84104dcb 100644 --- a/converter/ppm/ppmtompeg/param.c +++ b/converter/ppm/ppmtompeg/param.c @@ -1,8 +1,8 @@ /*===========================================================================* - * param.c - * - * Procedures to read in parameter file - * + * param.c + * + * Procedures to read in parameter file + * *===========================================================================*/ /* COPYRIGHT INFORMATION IS AT THE END OF THIS FILE */ @@ -10,9 +10,9 @@ #define _DEFAULT_SOURCE 1 /* New name for SVID & BSD source defines */ #define _XOPEN_SOURCE 500 - /* This makes sure popen() is in stdio.h. In GNU libc 2.1.3, + /* This makes sure popen() is in stdio.h. In GNU libc 2.1.3, _POSIX_C_SOURCE = 2 is sufficient, but on AIX 4.3, the higher level - _XOPEN_SOURCE is required. 2000.09.09 + _XOPEN_SOURCE is required. 2000.09.09 This also makes sure strdup() is in string.h. */ @@ -125,11 +125,6 @@ int mult_seq_headers = 0; /* 0 for none, N for header/N GOPs */ extern char currentPath[MAXPATHLEN]; -static const char * const optionText[LAST_OPTION+1] = { - "GOP_SIZE", "PATTERN", "PIXEL", "PQSCALE", - "OUTPUT", "RANGE", "PSEARCH_ALG", "IQSCALE", "INPUT_DIR", - "INPUT_CONVERT", "INPUT", "BQSCALE", "BASE_FILE_FORMAT", - "SLICES_PER_FRAME", "BSEARCH_ALG", "REFERENCE_FRAME"}; static bool optionSeen[NUM_OPTIONS+1]; /* optionSeen[x] means we have seen option x in the parameter file we've been reading. @@ -250,7 +245,7 @@ ReadMachineNames(FILE * const fpointer) * * GetFrameRate * - * take a character string with the input frame rate + * take a character string with the input frame rate * and return the correct frame rate code for use in the Sequence header * * RETURNS: frame rate code as per MPEG-I spec @@ -292,7 +287,7 @@ mergeInputSource(struct inputSource * const baseSourceP, unsigned int i; baseSourceP->ifArraySize += addedSourceP->numInputFileEntries; - REALLOCARRAY_NOFAIL(baseSourceP->inputFileEntries, + REALLOCARRAY_NOFAIL(baseSourceP->inputFileEntries, baseSourceP->ifArraySize); for (i = 0; i < addedSourceP->numInputFileEntries; ++i) baseSourceP->inputFileEntries[baseSourceP->numInputFileEntries++] = @@ -303,7 +298,7 @@ mergeInputSource(struct inputSource * const baseSourceP, /* Forward declaration for recursively called function */ static void -ReadInputFileNames(FILE * const fpointer, +ReadInputFileNames(FILE * const fpointer, const char * const endInput, struct inputSource * const inputSourceP); @@ -353,11 +348,11 @@ expandBackTickLine(const char * const input, static void -ReadInputFileNames(FILE * const fpointer, +ReadInputFileNames(FILE * const fpointer, const char * const endInput, struct inputSource * const inputSourceP) { /*---------------------------------------------------------------------------- - Read a list of input file names from the parameter file. Add + Read a list of input file names from the parameter file. Add the information to *inputSourceP. If inputSourceP == NULL, read off the list, but ignore it. @@ -382,7 +377,7 @@ ReadInputFileNames(FILE * const fpointer, else { if (strncmp(input, endInput, strlen(endInput)) == 0) endStatementRead = TRUE; - else if ((input[0] == '#') || (input[0] == '\n')) { + else if ((input[0] == '#') || (input[0] == '\n')) { /* It's a comment or blank line. Ignore it */ } else if (input[0] == '`' ) { expandBackTickLine(input, inputSourceP); @@ -403,7 +398,7 @@ static void initOptionSeen(void) { unsigned int index; - + for (index = FIRST_OPTION; index < NUM_OPTIONS; ++index) optionSeen[index] = FALSE; } @@ -475,7 +470,7 @@ verifyNoMissingCombineFramesOption(void) { static void verifyNoMissingOption(int const function) { /*---------------------------------------------------------------------------- - Verify that the parameter file contains every option it is supposed to. + Verify that the parameter file contains every option it is supposed to. Abort program if not. -----------------------------------------------------------------------------*/ switch(function) { @@ -513,7 +508,7 @@ processIqtable(FILE * const fpointer) { &qtable[row*8+2], &qtable[row*8+3], &qtable[row*8+4], &qtable[row*8+5], &qtable[row*8+6], &qtable[row*8+7])) { - pm_error("Line %d of IQTABLE doesn't have 8 elements!", + pm_error("Line %d of IQTABLE doesn't have 8 elements!", row); } for (col = 0; col < 8; ++col) { @@ -526,7 +521,7 @@ processIqtable(FILE * const fpointer) { } } } - + if (qtable[0] != 8) { pm_message("Warning: IQTable Element 1,1 reset to 8, " "since it must be 8."); @@ -591,15 +586,15 @@ removeTrailingWhite(const char * const rawLine, pm_error("Unable to get memory to process parameter file"); p = buffer + strlen(buffer) - 1; /* Point to last character */ - + /* Position p to just before the trailing white space (might be one character before beginning of string!) */ while (p >= buffer && isspace(*p)) --p; - + ++p; /* Move to first trailing whitespace character */ - + *p = '\0'; /* Chop off all the trailing whitespace */ *editedLineP = buffer; @@ -620,7 +615,7 @@ readNiqTable(FILE * const fpointer) { &niqtable[row*8+2], &niqtable[row*8+3], &niqtable[row*8+4], &niqtable[row*8+5], &niqtable[row*8+6], &niqtable[row*8+7])) { - pm_error("Line %d of NIQTABLE doesn't have 8 elements!", + pm_error("Line %d of NIQTABLE doesn't have 8 elements!", row); } for ( col = 0; col < 8; col++ ) { @@ -673,7 +668,7 @@ processParamLine(char const input[], optionSeen[OPTION_ASPECT_RATIO] = TRUE; } break; - + case 'B': if (strneq(input, "BQSCALE", 7)) { SetBQScale(atoi(SkipSpacesTabs(&input[7]))); @@ -692,7 +687,7 @@ processParamLine(char const input[], optionSeen[OPTION_BIT_RATE] = TRUE; } else if (strneq(input, "BUFFER_SIZE", 11)) { setBufferSize(SkipSpacesTabs(&input[11])); - optionSeen[OPTION_BUFFER_SIZE] = TRUE; + optionSeen[OPTION_BUFFER_SIZE] = TRUE; } break; @@ -715,8 +710,8 @@ processParamLine(char const input[], strcpy(currentFramePath, arg); } else if (strneq(input, "FRAME_INPUT", 11)) { - ReadInputFileNames(fpointer, "FRAME_END_INPUT", - frameInputSourceP->stdinUsed ? + ReadInputFileNames(fpointer, "FRAME_END_INPUT", + frameInputSourceP->stdinUsed ? NULL : frameInputSourceP); optionSeen[OPTION_FRAME_INPUT] = TRUE; } else if (strneq(input, "FORCE_I_ALIGN", 13)) { @@ -724,7 +719,7 @@ processParamLine(char const input[], } else if (strneq(input, "FORCE_ENCODE_LAST_FRAME", 23)) { /* NO-OP. We used to drop trailing B frames by default and you needed this option to change the last frame to I so you could - encode all the frames. Now we just do that all the time. + encode all the frames. Now we just do that all the time. Why wouldn't we? */ } else if (strneq(input, "FRAME_RATE", 10)) { @@ -735,7 +730,7 @@ processParamLine(char const input[], optionSeen[OPTION_FRAME_RATE] = TRUE; } break; - + case 'G': if (strneq(input, "GOP_SIZE", 8)) { SetGOPSize(atoi(SkipSpacesTabs(&input[8]))); @@ -747,8 +742,8 @@ processParamLine(char const input[], strcpy(currentGOPPath, arg); } else if (strneq(input, "GOP_INPUT", 9)) { - ReadInputFileNames(fpointer, "GOP_END_INPUT", - gopInputSourceP->stdinUsed ? + ReadInputFileNames(fpointer, "GOP_END_INPUT", + gopInputSourceP->stdinUsed ? NULL : gopInputSourceP); optionSeen[OPTION_GOP_INPUT] = TRUE; } else if (strneq(input, "GAMMA", 5)) { @@ -757,7 +752,7 @@ processParamLine(char const input[], optionSeen[OPTION_GAMMA] = TRUE; } break; - + case 'I': if (strneq(input, "IQSCALE", 7)) { SetIQScale(atoi(SkipSpacesTabs(&input[7]))); @@ -772,7 +767,7 @@ processParamLine(char const input[], strcpy(inputConversion, SkipSpacesTabs(&input[13])); optionSeen[OPTION_INPUT_CONVERT] = TRUE; } else if (streq(input, "INPUT")) { - ReadInputFileNames(fpointer, "END_INPUT", + ReadInputFileNames(fpointer, "END_INPUT", inputSourceP->stdinUsed ? NULL : inputSourceP); optionSeen[OPTION_INPUT] = TRUE; @@ -790,7 +785,7 @@ processParamLine(char const input[], if (strneq(input, "KEEP_TEMP_FILES", 15)) keepTempFiles = TRUE; break; - + case 'N': if (strneq(input, "NIQTABLE", 8)) { readNiqTable(fpointer); @@ -806,11 +801,11 @@ processParamLine(char const input[], strcpy(outputFileName, arg); else sprintf(outputFileName, "%s.gop.%d", arg, whichGOP); - + optionSeen[OPTION_OUTPUT] = TRUE; } break; - + case 'P': if (strneq(input, "PATTERN", 7)) { SetFramePattern(SkipSpacesTabs(&input[7])); @@ -840,7 +835,7 @@ processParamLine(char const input[], optionSeen[OPTION_PARALLEL] = TRUE; } break; - + case 'R': if (strneq(input, "RANGE", 5)) { processRanges(SkipSpacesTabs(&input[5])); @@ -898,14 +893,14 @@ processParamLine(char const input[], optionSeen[OPTION_USER_DATA] = TRUE; } break; - + case 'W': if (strneq(input, "WARN_UNDERFLOW", 14)) paramP->warnUnderflow = TRUE; if (strneq(input, "WARN_OVERFLOW", 13)) paramP->warnOverflow = TRUE; break; - + case 'Y': if (strneq(input, "YUV_SIZE", 8)) { const char * const arg = SkipSpacesTabs(&input[8]); @@ -932,7 +927,7 @@ processParamLine(char const input[], void -ReadParamFile(const char * const fileName, +ReadParamFile(const char * const fileName, majorProgramFunction const function, struct params * const paramP) { /*---------------------------------------------------------------------------- @@ -1012,7 +1007,7 @@ ReadParamFile(const char * const fileName, if (yuvUsed) { if (!optionSeen[OPTION_YUV_SIZE]) pm_error("YUV format used but YUV_SIZE not given"); - + if (!optionSeen[OPTION_YUV_FORMAT]) { strcpy (yuvConversion, "EYUV"); pm_message("WARNING: YUV format not specified; " @@ -1029,7 +1024,7 @@ ReadParamFile(const char * const fileName, if (optionSeen[OPTION_IO_CONVERT] != optionSeen[OPTION_SLAVE_CONVERT]) pm_error("Must have either both IO_SERVER_CONVERT and SLAVE_CONVERT " "or neither"); - + if (optionSeen[OPTION_DEFS_SPECIFICS] && !optionSeen[OPTION_SPECIFICS]) pm_error("Does not make sense to define Specifics file options, " "but no specifics file!"); diff --git a/converter/ppm/ppmtompeg/parse_huff.pl b/converter/ppm/ppmtompeg/parse_huff.pl index 1fc6466c..633e5877 100644 --- a/converter/ppm/ppmtompeg/parse_huff.pl +++ b/converter/ppm/ppmtompeg/parse_huff.pl @@ -51,7 +51,7 @@ # composed of 1, 0, space, and 's'. Spaces are ignored, and # s corresponds to the sign bit. In the output of this program, # We'll completely right-shift the data, with a 0 for the sign -# bit. The encoder will make appropriate changes before outputing. +# bit. The encoder will make appropriate changes before outputting. open(HUFFC, "> huff.c") || die "Can't write huff.c: $!\n"; diff --git a/converter/ppm/ppmtompeg/psearch.c b/converter/ppm/ppmtompeg/psearch.c index 3cca1241..e350137e 100644 --- a/converter/ppm/ppmtompeg/psearch.c +++ b/converter/ppm/ppmtompeg/psearch.c @@ -58,7 +58,7 @@ int psearchAlg; * * PRECONDITIONS: The relevant block in 'current' is valid (it has not * been dct'd). Thus, the data in 'current' can be - * accesed through y_blocks, cr_blocks, and cb_blocks. + * accessed through y_blocks, cr_blocks, and cb_blocks. * This is not the case for the blocks in 'prev.' * Therefore, references into 'prev' should be done * through the struct items ref_y, ref_cr, ref_cb diff --git a/converter/ppm/ppmtompeg/psocket.c b/converter/ppm/ppmtompeg/psocket.c index 6a50dc27..aac61022 100644 --- a/converter/ppm/ppmtompeg/psocket.c +++ b/converter/ppm/ppmtompeg/psocket.c @@ -10,15 +10,15 @@ ============================================================================*/ #define _XOPEN_SOURCE 500 /* Make sure stdio.h contains pclose() */ -/* _ALL_SOURCE is needed on AIX to make the C library include the - socket services (e.g. define struct sockaddr) +/* _ALL_SOURCE is needed on AIX to make the C library include the + socket services (e.g. define struct sockaddr) Note that AIX standards.h actually sets feature declaration macros such as _XOPEN_SOURCE, unless they are already set. */ #define _ALL_SOURCE #define __EXTENSIONS__ - /* __EXTENSIONS__ is for a broken Sun C library (uname SunOS kosh 5.8 + /* __EXTENSIONS__ is for a broken Sun C library (uname SunOS kosh 5.8 generic_108528-16 sun4u sparc). When you define _XOPEN_SOURCE, it's vnode.h and resource.h fail to define some data types that they need (e.g. timestruct_t). But with __EXTENSIONS__, they declare the @@ -126,8 +126,8 @@ unmarshallInt(unsigned char const buffer[], static void -safeRead(int const fd, - unsigned char * const buf, +safeRead(int const fd, + unsigned char * const buf, unsigned int const nbyte) { /*---------------------------------------------------------------------------- Safely read from file 'fd'. Keep reading until we get @@ -144,7 +144,7 @@ safeRead(int const fd, errorExit("read (of %u bytes (total %u) ) returned " "errno %d (%s)", nbyte-numRead, nbyte, errno, strerror(errno)); - else + else numRead += result; } } @@ -203,8 +203,8 @@ marshallInt(int const value, static void -safeWrite(int const fd, - unsigned char * const buf, +safeWrite(int const fd, + unsigned char * const buf, unsigned int const nbyte) { /*---------------------------------------------------------------------------- Safely write to file 'fd'. Keep writing until we write 'nbyte' @@ -217,7 +217,7 @@ safeWrite(int const fd, while (numWritten < nbyte) { int const result = write(fd, &buf[numWritten], nbyte-numWritten); - if (result == -1) + if (result == -1) errorExit("write (of %u bytes (total %u) ) returned " "errno %d (%s)", nbyte-numWritten, nbyte, errno, strerror(errno)); @@ -251,8 +251,8 @@ WriteInt(int const socketFd, void -ConnectToSocket(const char * const machineName, - int const portNum, +ConnectToSocket(const char * const machineName, + int const portNum, struct hostent ** const hostEnt, int * const socketFdP, const char ** const errorP) { @@ -266,7 +266,7 @@ ConnectToSocket(const char * const machineName, **hostEnt. -----------------------------------------------------------------------------*/ int rc; - + *errorP = NULL; /* initial value */ if ((*hostEnt) == NULL) { @@ -277,15 +277,15 @@ ConnectToSocket(const char * const machineName, if (!*errorP) { rc = socket(AF_INET, SOCK_STREAM, 0); if (rc < 0) - pm_asprintf(errorP, "socket() failed with errno %d (%s)", + pm_asprintf(errorP, "socket() failed with errno %d (%s)", errno, strerror(errno)); else { int const socketFd = rc; - + int rc; unsigned short tempShort; struct sockaddr_in nameEntry; - + nameEntry.sin_family = AF_INET; memset((void *) nameEntry.sin_zero, 0, 8); memcpy((void *) &(nameEntry.sin_addr.s_addr), @@ -293,12 +293,12 @@ ConnectToSocket(const char * const machineName, (size_t) (*hostEnt)->h_length); tempShort = portNum; nameEntry.sin_port = htons(tempShort); - + rc = connect(socketFd, (struct sockaddr *) &nameEntry, sizeof(struct sockaddr)); - + if (rc != 0) - pm_asprintf(errorP, + pm_asprintf(errorP, "connect() to host '%s', port %d failed with " "errno %d (%s)", machineName, portNum, errno, strerror(errno)); @@ -317,7 +317,7 @@ ConnectToSocket(const char * const machineName, static bool portInUseErrno(int const testErrno) { /*---------------------------------------------------------------------------- - Return TRUE iff 'testErrno' is what a bind() would return if one requestd + Return TRUE iff 'testErrno' is what a bind() would return if one requested a port number that is unavailable (but other port numbers might be). -----------------------------------------------------------------------------*/ bool retval; @@ -340,19 +340,19 @@ static void bindToUnusedPort(int const socketFd, unsigned short * const portNumP, const char ** const errorP) { - + bool foundPort; unsigned short trialPortNum; *errorP = NULL; /* initial value */ - for (foundPort = FALSE, trialPortNum = 2048; - !foundPort && trialPortNum < 16384 && !*errorP; + for (foundPort = FALSE, trialPortNum = 2048; + !foundPort && trialPortNum < 16384 && !*errorP; ++trialPortNum) { - + struct sockaddr_in nameEntry; int rc; - + memset((char *) &nameEntry, 0, sizeof(nameEntry)); nameEntry.sin_family = AF_INET; nameEntry.sin_port = htons(trialPortNum); @@ -365,10 +365,10 @@ bindToUnusedPort(int const socketFd, *portNumP = trialPortNum; } else if (!portInUseErrno(errno)) pm_asprintf(errorP, "bind() of TCP port number %hu failed " - "with errno %d (%s)", + "with errno %d (%s)", trialPortNum, errno, strerror(errno)); } - + if (!*errorP && !foundPort) pm_asprintf(errorP, "Unable to find a free port. Every TCP port " "in the range 2048-16383 is in use"); @@ -389,7 +389,7 @@ CreateListeningSocket(int * const socketP, partner can connect). -----------------------------------------------------------------------------*/ int rc; - + rc = socket(AF_INET, SOCK_STREAM, 0); if (rc < 0) pm_asprintf(errorP, @@ -415,7 +415,7 @@ CreateListeningSocket(int * const socketP, rc = listen(socketFd, SOMAXCONN); if (rc != 0) pm_asprintf(errorP, "Unable to listen on TCP socket. " - "listen() fails with errno %d (%s)", + "listen() fails with errno %d (%s)", errno, strerror(errno)); } if (*errorP) @@ -433,11 +433,11 @@ AcceptConnection(int const listenSocketFd, struct sockaddr otherSocket; socklenx_t otherSize; /* This is an ugly dual-meaning variable. As input to accept(), - it is the storage size of 'otherSocket'. As output, it is the + it is the storage size of 'otherSocket'. As output, it is the data length of 'otherSocket'. */ int rc; - + otherSize = sizeof(otherSocket); rc = accept(listenSocketFd, &otherSocket, &otherSize); @@ -450,3 +450,6 @@ AcceptConnection(int const listenSocketFd, *errorP = NULL; } } + + + diff --git a/converter/ppm/ppmtompeg/rate.c b/converter/ppm/ppmtompeg/rate.c index 6ec330cf..3fa41102 100644 --- a/converter/ppm/ppmtompeg/rate.c +++ b/converter/ppm/ppmtompeg/rate.c @@ -1,6 +1,6 @@ /*============================================================================* * rate.c * - * * + * * * Procedures concerned with rate control * * * * EXPORTED PROCEDURES: * @@ -75,7 +75,7 @@ #define MAX_BIT_RATE 104857600 /* 18 digit number in units of 400 */ #define MAX_BUFFER_SIZE 16760832 /* 10 digit number in units of 16k */ -#define DEFAULT_BUFFER_SIZE 327680 /* maximun for "constrained" bitstream */ +#define DEFAULT_BUFFER_SIZE 327680 /* maximum for "constrained" bitstream */ #define DEFAULT_VBV_FULLNESS 3 /* wait till 1/3 full */ #define DEFAULT_PICT_RATE_CODE 5 /* code for 30 Frames/sec */ #define DEFAULT_PICT_RATE 30 /* 30 frames per second */ @@ -92,7 +92,7 @@ static bool wantVbvUnderflowWarning; static bool wantVbvOverflowWarning; /* Variables for the VBV buffer defined in MPEG specs */ -static unsigned int VBV_remainingDelay; +static unsigned int VBV_remainingDelay; /* delay in units of 1/90000 seconds */ static int32 VBV_buffer = 0; /* fullness of the theoretical VBV buffer */ static int32 bufferFillRate = 0; /* constant rate at which buffer filled */ @@ -104,7 +104,7 @@ static int Xi, Xp, Xb; /* Global complexity measure */ static int Si, Sp, Sb; /* Total # bits for last pict of type (Overhead?) */ static float Qi, Qp, Qb; /* avg quantizaton for last picture of type */ - + /* Target bit allocations for each type of picture*/ int Ti, Tp, Tb; @@ -175,24 +175,6 @@ static int Qscale; /* Clipped, truncated quantization value */ static FILE *RC_FILE; #endif -static const char * const Frame_header1 = -" Fm # Bit GOP V "; -static const char * const Frame_header2 = -" # type MBs Alloc left Ni Np Nb N_act buff Q_rc Qscale"; -static const char * const Frame_header3 = -"---- - ---- ------ ------- -- -- -- ----- ------ ---- ----"; -static const char * const Frame_trailer1 = -" avg virt % GOP % VBV"; -static const char * const Frame_trailer2 = -" Sx Qx Xx act N_act buffer alloc left left buf delay"; -static const char * const Frame_trailer3 = -"------ --.-- ------- --- --.-- ------- --- ------- --- ------- ------"; - -static const char * const MB_header1 = -"MB# #bits Q mqt Dj Q_j actj N_act totbits b/MB %alloc %done"; -static const char * const MB_header2 = -"--- ----- -- --- ------ --- ----- --.-- ------ ---- --- ---"; - static char rc_buffer[101]; /* EXTERNAL Variables */ @@ -211,8 +193,8 @@ void checkSpatialActivity (Block blk0, Block blk1, Block blk2, Block blk3); void incNumBlocks (int num); void calculateVBVDelay (int num); int BlockExperiments (int16 *OrigBlock, int16 *NewBlock, int control); - - + + static void analyzePattern(const char * const framePattern, @@ -226,10 +208,10 @@ analyzePattern(const char * const framePattern, unsigned int i; /* Initialize Pattern info */ - *gop_xP = framePatternLen; + *gop_xP = framePatternLen; for (i = 0, *gop_iP = 0, *gop_pP = 0, *gop_bP = 0, *errorP = NULL; - i < framePatternLen && !*errorP; + i < framePatternLen && !*errorP; ++i) { switch(framePattern[i]) { case 'i': ++*gop_iP; break; @@ -241,7 +223,7 @@ analyzePattern(const char * const framePattern, } assert(*gop_xP == *gop_iP + *gop_pP + *gop_bP); } - + /*===========================================================================* @@ -252,7 +234,7 @@ analyzePattern(const char * const framePattern, * * RETURNS: nothing * - * SIDE EFFECTS: many global variables + * SIDE EFFECTS: many global variables * * NOTES: Get rid of the redundant pattern stuff!! *===========================================================================*/ @@ -266,7 +248,7 @@ initRateControl(bool const wantUnderflowWarning, wantVbvOverflowWarning = wantOverflowWarning; DBG_PRINT(("Initializing Allocation Data\n")); - + #ifdef RC_STATS_FILE RC_FILE = fopen("RC_STATS_FILE", "w"); if ( RC_FILE == NULL) { @@ -278,7 +260,7 @@ initRateControl(bool const wantUnderflowWarning, #endif VBV_remainingDelay = 0; - + analyzePattern(framePattern, framePatternLen, &GOP_X, &GOP_I, &GOP_P, &GOP_B, &error); @@ -291,46 +273,46 @@ initRateControl(bool const wantUnderflowWarning, } - /* Initializing GOP bit allocation */ + /* Initializing GOP bit allocation */ rc_R = 0; rc_G = (bit_rate * GOP_X/frameRateRounded); - + /* Initialize the "global complexity measures" */ Xi = (160 * bit_rate/115); Xp = (60 * bit_rate/115); Xb = (42 * bit_rate/115); - + /* Initialize MB counters */ rc_totalMBBits= rc_bitsThisMB= rc_totalFrameBits=rc_totalOverheadBits = 0; rc_numBlocks = rc_totalQuant = 0; - + /* init virtual buffers */ reactionParameter = (2 * bit_rate / frameRateRounded); d0_i = (10 * reactionParameter / 31); d0_p = (Kp * d0_i); d0_b = (Kb * d0_i); - + lastFrameVirtBuf = d0_i; /* start with I Frame */ rc_Q = lastFrameVirtBuf * 31 / reactionParameter; - + /* init spatial activity measures */ avg_act = 400; /* Suggested initial value */ N_act = 1; - + mquant = rc_Q * N_act; - + frameDelayIncrement = (90000 / frameRateRounded); /* num of "delay" units per frame */ - bufferFillRate = bit_rate / frameRateRounded; + bufferFillRate = bit_rate / frameRateRounded; /* VBV buf fills at constant rate */ VBV_buffer = buffer_size; DBG_PRINT(("VBV- delay: %d, fill rate: %d, delay/Frame: %d units, " "buffer size: %d\n", - VBV_remainginDelay, bufferFillRate, frameDelayIncrement, + VBV_remainginDelay, bufferFillRate, frameDelayIncrement, buffer_size)); - + result = initGOPRateControl(); - + return result; } @@ -343,21 +325,21 @@ initRateControl(bool const wantUnderflowWarning, * * RETURNS: nothing * - * SIDE EFFECTS: many global variables + * SIDE EFFECTS: many global variables * *===========================================================================*/ int initGOPRateControl() { DBG_PRINT(("Initializing new GOP\n")); - + Nx = GOP_X; Ni = GOP_I; Np = GOP_P; Nb = GOP_B; - + rc_R += rc_G; - + DBG_PRINT(("bufsize: %d, bitrate: %d, pictrate: %d, GOP bits: %d\n", buffer_size, bit_rate, frameRateRounded, rc_R)); DBG_PRINT(("Xi: %d, Xp: %d, Xb: %d Nx: %d, Ni: %d, Np: %d, Nb: %d\n", @@ -389,20 +371,20 @@ targetRateControl(MpegFrame * const frame) { float tempX, tempY, tempZ; int result; int frameType; - + minimumBits = (bit_rate / (8 * frameRateRounded)); - + /* Check if new GOP */ if (Nx == 0) { initGOPRateControl(); } - + if (MB_cnt < 0) {MB_cnt = determineMBCount();} - + switch (frame->type) { case TYPE_IFRAME: frameType = 'I'; - + tempX = ( (Np * Ki * Xp) / (Xi * Kp) ); tempY = ( (Nb * Ki * Xb) / (Xi*Kb) ); tempZ = Ni + tempX + tempY; @@ -411,7 +393,7 @@ targetRateControl(MpegFrame * const frame) { current_Tx = Ti = result; lastFrameVirtBuf = d0_i; break; - + case TYPE_PFRAME: frameType = 'P'; tempX = ( (Ni * Kp * Xi) / (Ki * Xp) ); @@ -422,7 +404,7 @@ targetRateControl(MpegFrame * const frame) { current_Tx = Tp = result; lastFrameVirtBuf = d0_p; break; - + case TYPE_BFRAME: frameType = 'B'; tempX = ( (Ni * Kb * Xi) / (Ki * Xb) ); @@ -433,17 +415,17 @@ targetRateControl(MpegFrame * const frame) { current_Tx = Tb = result; lastFrameVirtBuf = d0_b; break; - + default: frameType = 'X'; } - + N_act = 1; rc_Q = lastFrameVirtBuf * 31 / reactionParameter; mquant = rc_Q * N_act; Qscale = (mquant > 31 ? 31 : mquant); Qscale = (Qscale < 1 ? 1 : Qscale); - + #ifdef HEINOUS_DEBUG_MODE { const char * strPtr; @@ -459,15 +441,15 @@ targetRateControl(MpegFrame * const frame) { /* Print Frame info */ sprintf(rc_buffer, "%4d %1c %4d %6d %7d " "%2d %2d %2d %2.2f %6d %4d %3d", - frame->id,frameType,MB_cnt,current_Tx,rc_R,Ni,Np,Nb, + frame->id,frameType,MB_cnt,current_Tx,rc_R,Ni,Np,Nb, N_act, lastFrameVirtBuf, rc_Q, Qscale); - + #ifdef RC_STATS_FILE fprintf(RC_FILE,"%s\n", rc_buffer); fflush(RC_FILE); #endif DBG_PRINT(("%s\n",rc_buffer)); - + /* Print headers for Macroblock info */ if (RC_MB_SAMPLE_RATE) { #ifdef HEINOUS_DEBUG_MODE @@ -483,7 +465,7 @@ targetRateControl(MpegFrame * const frame) { -static void +static void updateVBVBuffer(int const frameBits) { /*---------------------------------------------------------------------------- Update the VBV buffer after each frame. This theoretical buffer is @@ -532,11 +514,11 @@ updateRateControl(int const type) { pctAllocUsed = (totalBits *100 / current_Tx); rc_R -= totalBits; pctGOPUsed = (rc_R *100/ rc_G); - + avg_act = (total_act_j / MB_cnt); - + updateVBVBuffer(totalBits); - + switch (type) { case TYPE_IFRAME: Ti = current_Tx; @@ -563,9 +545,9 @@ updateRateControl(int const type) { Xb = frameComplexity; break; } - + #ifdef HEINOUS_DEBUG_MODE - { + { /* Print Frame info */ const char * strPtr; strPtr = Frame_trailer1; @@ -575,26 +557,26 @@ updateRateControl(int const type) { strPtr = Frame_trailer3; DBG_PRINT(("%s\n",strPtr)); } -#endif +#endif sprintf(rc_buffer, "%6d %2.2f %6d %3d %2.2f %7d " "%3d %7d %3d %6d %6d", - totalBits, avgQuant, frameComplexity, avg_act, N_act, - currentVirtBuf, pctAllocUsed, rc_R, pctGOPUsed, + totalBits, avgQuant, frameComplexity, avg_act, N_act, + currentVirtBuf, pctAllocUsed, rc_R, pctGOPUsed, VBV_buffer, VBV_remainingDelay); #ifdef RC_STATS_FILE fprintf(RC_FILE,"%s\n", rc_buffer); fflush(RC_FILE); #endif DBG_PRINT(("%s\n",rc_buffer)); - + Nx--; rc_totalMBBits= rc_bitsThisMB= rc_totalFrameBits=rc_totalOverheadBits = 0; rc_numBlocks = rc_totalQuant = total_act_j = currentVirtBuf = 0; - + DBG_PRINT(("GOP now has %d bits remaining (%3d%%) for %d frames .. , " - "Ni= %d, Np= %d, Nb= %d\n", + "Ni= %d, Np= %d, Nb= %d\n", rc_R, (rc_R*100/rc_G), (Ni+Np+Nb), Ni, Np, Nb)); - + } @@ -622,21 +604,21 @@ int type; int pctUsed, pctDone; int bitsThisMB; int bitsPerMB; - + bitsThisMB = rc_bitsThisMB; totalBits = rc_totalFrameBits; - bitsPerMB = (totalBits / rc_numBlocks); - pctDone = (rc_numBlocks * 100/ MB_cnt); + bitsPerMB = (totalBits / rc_numBlocks); + pctDone = (rc_numBlocks * 100/ MB_cnt); pctUsed = (totalBits *100/current_Tx); - + sprintf(rc_buffer, "%3d %5d %2d %3d %6d %3d %6d %2.2f %6d %4d %3d %3d\n", - (rc_numBlocks - 1), bitsThisMB, Qscale, mquant, currentVirtBuf, + (rc_numBlocks - 1), bitsThisMB, Qscale, mquant, currentVirtBuf, rc_Q, act_j, N_act, totalBits, bitsPerMB, pctUsed, pctDone); #ifdef RC_STATS_FILE fprintf(RC_FILE, "%s", rc_buffer); fflush(RC_FILE); #endif - + if ( (RC_MB_SAMPLE_RATE) && ((rc_numBlocks -1) % RC_MB_SAMPLE_RATE)) { DBG_PRINT(("%s\n", rc_buffer)); } else { @@ -695,7 +677,7 @@ void incMacroBlockBits(num) * * RETURNS: new Qscale * - * SIDE EFFECTS: + * SIDE EFFECTS: * *===========================================================================*/ int needQScaleChange(oldQScale, blk0, blk1, blk2, blk3) @@ -705,19 +687,19 @@ int needQScaleChange(oldQScale, blk0, blk1, blk2, blk3) Block blk2; Block blk3; { - + /* One more MacroBlock seen */ rc_numBlocks++; /* this notes each block num in MB */ - + checkBufferFullness(oldQScale); - + checkSpatialActivity(blk0, blk1, blk2, blk3); - + mquant = rc_Q * N_act; Qscale = (mquant > 31 ? 31 : mquant); Qscale = (Qscale < 1 ? 1 : Qscale); rc_totalQuant += Qscale; - + if (oldQScale == Qscale) return -1; else @@ -727,7 +709,7 @@ int needQScaleChange(oldQScale, blk0, blk1, blk2, blk3) /*===========================================================================* * - * determineMBCount() + * determineMBCount() * * Determines number of Macro Blocks in frame from the frame sizes * passed. @@ -741,7 +723,7 @@ int determineMBCount () { int y,x; - + x = (Fsize_x +15)/16; y = (Fsize_y +15)/16; return (x * y); @@ -769,11 +751,11 @@ void checkBufferFullness (oldQScale) int oldQScale; { int temp; - + temp = lastFrameVirtBuf + rc_totalFrameBits; temp -= (current_Tx * rc_numBlocks / MB_cnt); currentVirtBuf = temp; - + rc_Q = (currentVirtBuf * 31 / reactionParameter); return; } @@ -783,8 +765,8 @@ void checkBufferFullness (oldQScale) * * void checkSpatialActivity() * - * Calcualtes the spatial activity for the four luminance blocks of the - * macroblock. Along with the normalized reference quantization parameter + * Calculates the spatial activity for the four luminance blocks of the + * macroblock. Along with the normalized reference quantization parameter * (rc_Q) , it determines the quantization factor for the next macroblock. * * RETURNS: nothing @@ -801,19 +783,19 @@ void checkSpatialActivity(blk0, blk1, blk2, blk3) Block blk3; { int temp; - int16 *blkArray[4]; + int16 *blkArray[4]; int16 *curBlock; int16 *blk_ptr; int var[4]; int i, j; - - + + blkArray[0] = (int16 *) blk0; blkArray[1] = (int16 *) blk1; blkArray[2] = (int16 *) blk2; blkArray[3] = (int16 *) blk3; - - + + for (i =0; i < 4; i++) { /* Compute the activity in each block */ curBlock = blkArray[i]; blk_ptr = curBlock; @@ -821,14 +803,14 @@ void checkSpatialActivity(blk0, blk1, blk2, blk3) /* Find the mean pixel value */ for (j=0; j < DCTSIZE_SQ; j ++) { P_mean += *(blk_ptr++); - /* P_mean += curBlock[j]; + /* P_mean += curBlock[j]; if (curBlock[j] != *(blk_ptr++)) { printf("ARRAY ERROR: block %d\n", j); } */ } P_mean /= DCTSIZE_SQ; - + /* Now find the variance */ curBlock = blkArray[i]; blk_ptr = curBlock; @@ -839,25 +821,25 @@ void checkSpatialActivity(blk0, blk1, blk2, blk3) printf("ARRAY ERROR: block %d\n", j); } temp = curBlock[j] - P_mean; -#endif +#endif temp = *(blk_ptr++) - P_mean; var[i] += (temp * temp); } var[i] /= DCTSIZE_SQ; } - + /* Choose the minimum variance from the 4 blocks and use as the activity */ var_sblk = var[0]; for (i=1; i < 4; i++) { var_sblk = (var_sblk < var[i] ? var_sblk : var[i]); } - - + + act_j = 1 + var_sblk; total_act_j += act_j; temp = (2 * act_j + avg_act); N_act = ( (float) temp / (float) (act_j + 2*avg_act) ); - + return; } @@ -900,7 +882,7 @@ int getRateMode() void setBitRate (const char * const charPtr) { int rate, rnd; - + rate = atoi(charPtr); if (rate > 0) { RateControlMode = FIXED_RATE; @@ -915,7 +897,7 @@ void setBitRate (const char * const charPtr) rate = (rate > MAX_BIT_RATE ? MAX_BIT_RATE : rate); bit_rate = rate; DBG_PRINT(("Bit rate is: %d\n", bit_rate)); -} +} @@ -957,7 +939,7 @@ int getBitRate () void setBufferSize (const char * const charPtr) { int size; - + size = atoi(charPtr); size = (size > MAX_BUFFER_SIZE ? MAX_BUFFER_SIZE : size); if (size > 0) { diff --git a/converter/ppm/ppmtopcx.c b/converter/ppm/ppmtopcx.c index fa68edc5..76f06290 100644 --- a/converter/ppm/ppmtopcx.c +++ b/converter/ppm/ppmtopcx.c @@ -12,7 +12,7 @@ ** ** 11/Dec/94: first version ** 12/Dec/94: added handling of "packed" format (16 colors or less) -** +** ** ZSoft PCX File Format Technical Reference Manual ** http://bespin.org/~qz/pc-gpe/pcx.txt ** http://web.archive.org/web/20100206055706/http://www.qzx.com/pc-gpe/pcx.txt @@ -74,7 +74,7 @@ parseCommandLine(int argc, char ** argv, struct cmdlineInfo * const cmdlineP) { /*---------------------------------------------------------------------------- parse program command line described in Unix standard form by argc - and argv. Return the information in the options as *cmdlineP. + and argv. Return the information in the options as *cmdlineP. If command line is internally inconsistent (invalid options, etc.), issue error message to stderr and abort program. @@ -94,15 +94,15 @@ parseCommandLine(int argc, char ** argv, MALLOCARRAY(option_def, 100); option_def_index = 0; /* incremented by OPTENT3 */ - OPTENT3(0, "24bit", OPT_FLAG, NULL, + OPTENT3(0, "24bit", OPT_FLAG, NULL, &cmdlineP->truecolor, 0); - OPTENT3(0, "8bit", OPT_FLAG, NULL, + OPTENT3(0, "8bit", OPT_FLAG, NULL, &cmdlineP->use_8_bit, 0); - OPTENT3(0, "planes", OPT_UINT, &cmdlineP->planes, + OPTENT3(0, "planes", OPT_UINT, &cmdlineP->planes, &planesSpec, 0); - OPTENT3(0, "packed", OPT_FLAG, NULL, + OPTENT3(0, "packed", OPT_FLAG, NULL, &cmdlineP->packed, 0); - OPTENT3(0, "verbose", OPT_FLAG, NULL, + OPTENT3(0, "verbose", OPT_FLAG, NULL, &cmdlineP->verbose, 0); OPTENT3(0, "stdpalette", OPT_FLAG, NULL, &cmdlineP->stdpalette, 0); @@ -144,14 +144,14 @@ parseCommandLine(int argc, char ** argv, if (cmdlineP->use_8_bit) pm_error("-planes is meaningless with -8bit"); } - + if (paletteSpec && cmdlineP->stdpalette) pm_error("You can't specify both -palette and -stdpalette"); if (!paletteSpec) cmdlineP->palette = NULL; - if (cmdlineP->use_8_bit && cmdlineP->truecolor) + if (cmdlineP->use_8_bit && cmdlineP->truecolor) pm_error("You cannot specify both -8bit and -truecolor"); if (argc-1 < 1) @@ -172,11 +172,11 @@ parseCommandLine(int argc, char ** argv, * Write out a two-byte little-endian word to the PCX file */ static void -Putword(int const w, +Putword(int const w, FILE * const fp) { int rc; - + rc = pm_writelittleshort(fp, w); if (rc != 0) @@ -189,7 +189,7 @@ Putword(int const w, * Write out a byte to the PCX file */ static void -Putbyte(int const b, +Putbyte(int const b, FILE * const fp) { int rc; @@ -201,13 +201,10 @@ Putbyte(int const b, -static const unsigned char bitmask[] = {1, 2, 4, 8, 16, 32, 64, 128}; - - static void -extractPlane(unsigned char * const rawrow, - int const cols, - unsigned char * const buf, +extractPlane(unsigned char * const rawrow, + int const cols, + unsigned char * const buf, int const plane) { /*---------------------------------------------------------------------------- From the image row 'rawrow', which is an array of 'cols' palette indices @@ -223,7 +220,7 @@ extractPlane(unsigned char * const rawrow, int cbit; /* Significance of bit representing current column in output */ unsigned char *cp; /* Ptr to next output byte to fill */ unsigned char byteUnderConstruction; - + cp = buf; /* initial value */ cbit = 7; @@ -250,9 +247,9 @@ extractPlane(unsigned char * const rawrow, static void -PackBits(unsigned char * const rawrow, - int const width, - unsigned char * const buf, +PackBits(unsigned char * const rawrow, + int const width, + unsigned char * const buf, int const bits) { int x, i, shift; @@ -273,13 +270,13 @@ PackBits(unsigned char * const rawrow, static void -write_header(FILE * const fp, - int const cols, - int const rows, - int const BitsPerPixel, - int const Planes, +write_header(FILE * const fp, + int const cols, + int const rows, + int const BitsPerPixel, + int const Planes, struct pcxCmapEntry const cmap16[], - unsigned int const xPos, + unsigned int const xPos, unsigned int const yPos) { int i, BytesPerLine; @@ -288,7 +285,7 @@ write_header(FILE * const fp, Putbyte(0x05, fp); /* PC Paintbrush version */ Putbyte(0x01, fp); /* .PCX run length encoding */ Putbyte(BitsPerPixel, fp); /* bits per pixel */ - + Putword(xPos, fp); /* x1 - image left */ Putword(yPos, fp); /* y1 - image top */ Putword(xPos+cols-1, fp); /* x2 - image right */ @@ -330,8 +327,8 @@ write_header(FILE * const fp, static void -PCXEncode(FILE * const fp, - const unsigned char * const buf, +PCXEncode(FILE * const fp, + const unsigned char * const buf, int const Size) { const unsigned char * const end = buf + Size; @@ -377,10 +374,10 @@ indexOfColor(colorhash_table const cht, -----------------------------------------------------------------------------*/ int const rc = ppm_lookupcolor(cht, &color); - + if (rc < 0) pm_error("Image contains color which is not " - "in the palette: %u/%u/%u", + "in the palette: %u/%u/%u", PPM_GETR(color), PPM_GETG(color), PPM_GETB(color)); return rc; @@ -389,12 +386,12 @@ indexOfColor(colorhash_table const cht, static void -ppmTo16ColorPcx(pixel ** const pixels, - int const cols, - int const rows, - struct pcxCmapEntry const pcxcmap[], - int const colors, - colorhash_table const cht, +ppmTo16ColorPcx(pixel ** const pixels, + int const cols, + int const rows, + struct pcxCmapEntry const pcxcmap[], + int const colors, + colorhash_table const cht, bool const packbits, unsigned int const planesRequested, unsigned int const xPos, @@ -429,7 +426,7 @@ ppmTo16ColorPcx(pixel ** const pixels, MALLOCARRAY_NOFAIL(indexRow, cols); MALLOCARRAY_NOFAIL(planesrow, BytesPerLine); - write_header(stdout, cols, rows, BitsPerPixel, Planes, pcxcmap, + write_header(stdout, cols, rows, BitsPerPixel, Planes, pcxcmap, xPos, yPos); for (row = 0; row < rows; ++row) { int col; @@ -454,13 +451,13 @@ ppmTo16ColorPcx(pixel ** const pixels, static void -ppmTo256ColorPcx(pixel ** const pixels, - int const cols, - int const rows, - struct pcxCmapEntry const pcxcmap[], - int const colors, +ppmTo256ColorPcx(pixel ** const pixels, + int const cols, + int const rows, + struct pcxCmapEntry const pcxcmap[], + int const colors, colorhash_table const cht, - unsigned int const xPos, + unsigned int const xPos, unsigned int const yPos) { int row; @@ -489,11 +486,11 @@ ppmTo256ColorPcx(pixel ** const pixels, static void -ppmToTruecolorPcx(pixel ** const pixels, - int const cols, - int const rows, +ppmToTruecolorPcx(pixel ** const pixels, + int const cols, + int const rows, pixval const maxval, - unsigned int const xPos, + unsigned int const xPos, unsigned int const yPos) { unsigned char *redrow, *greenrow, *bluerow; @@ -530,7 +527,7 @@ ppmToTruecolorPcx(pixel ** const pixels, -static const struct pcxCmapEntry +static const struct pcxCmapEntry stdPalette[] = { { 0, 0, 0 }, { 0, 0, 170 }, @@ -565,7 +562,7 @@ putPcxColorInHash(colorhash_table const cht, int rc; PPM_DEPTH(ppmColor, newPcxColor, PCX_MAXVAL, maxval); - + rc = ppm_lookupcolor(cht, &ppmColor); if (rc == -1) @@ -577,8 +574,8 @@ putPcxColorInHash(colorhash_table const cht, 'maxval' is less than PCX_MAXVAL), and two distinct colors in the standard palette are indistinguishable at subject image color resolution. - - So we have to figure out wether color 'newPcxColor' or + + So we have to figure out whether color 'newPcxColor' or 'existingPcxColor' is a better match for 'ppmColor'. */ @@ -588,8 +585,8 @@ putPcxColorInHash(colorhash_table const cht, pixel existingPcxColor; PPM_DEPTH(idealPcxColor, ppmColor, maxval, PCX_MAXVAL); - - PPM_ASSIGN(existingPcxColor, + + PPM_ASSIGN(existingPcxColor, stdPalette[existingColorIndex].r, stdPalette[existingColorIndex].g, stdPalette[existingColorIndex].b); @@ -619,7 +616,7 @@ generateStandardPalette(struct pcxCmapEntry ** const pcxcmapP, colorhash_table cht; MALLOCARRAY_NOFAIL(pcxcmap, MAXCOLORS); - + *pcxcmapP = pcxcmap; cht = ppm_alloccolorhash(); @@ -629,8 +626,8 @@ generateStandardPalette(struct pcxCmapEntry ** const pcxcmapP, /* The color of this colormap entry, in PCX resolution */ pcxcmap[colorIndex] = stdPalette[colorIndex]; - - PPM_ASSIGN(pcxColor, + + PPM_ASSIGN(pcxColor, stdPalette[colorIndex].r, stdPalette[colorIndex].g, stdPalette[colorIndex].b); @@ -651,27 +648,27 @@ generateStandardPalette(struct pcxCmapEntry ** const pcxcmapP, *chtP = cht; *colorsP = stdPaletteSize; } - + static void readPpmPalette(const char * const paletteFileName, - pixel (* const ppmPaletteP)[], + pixel (* const ppmPaletteP)[], unsigned int * const paletteSizeP) { FILE * pfP; pixel ** pixels; int cols, rows; pixval maxval; - + pfP = pm_openr(paletteFileName); pixels = ppm_readppm(pfP, &cols, &rows, &maxval); pm_close(pfP); - + *paletteSizeP = rows * cols; - if (*paletteSizeP > MAXCOLORS) + if (*paletteSizeP > MAXCOLORS) pm_error("ordered palette image contains %d pixels. Maximum is %d", *paletteSizeP, MAXCOLORS); @@ -681,12 +678,12 @@ readPpmPalette(const char * const paletteFileName, j = 0; /* initial value */ for (row = 0; row < rows; ++row) { int col; - for (col = 0; col < cols; ++col) + for (col = 0; col < cols; ++col) (*ppmPaletteP)[j++] = pixels[row][col]; } } ppm_freearray(pixels, rows); -} +} @@ -706,7 +703,7 @@ readPaletteFromFile(struct pcxCmapEntry ** const pcxcmapP, readPpmPalette(paletteFileName, &ppmPalette, &paletteSize); MALLOCARRAY_NOFAIL(pcxcmap, MAXCOLORS); - + *pcxcmapP = pcxcmap; cht = ppm_alloccolorhash(); @@ -716,8 +713,8 @@ readPaletteFromFile(struct pcxCmapEntry ** const pcxcmapP, /* The color of this colormap entry, in PCX resolution */ pcxcmap[colorIndex] = pcxCmapEntryFromPixel(ppmPalette[colorIndex]); - - PPM_ASSIGN(pcxColor, + + PPM_ASSIGN(pcxColor, ppmPalette[colorIndex].r, ppmPalette[colorIndex].g, ppmPalette[colorIndex].b); @@ -728,7 +725,7 @@ readPaletteFromFile(struct pcxCmapEntry ** const pcxcmapP, *chtP = cht; *colorsP = paletteSize; } - + static void @@ -748,7 +745,7 @@ moveBlackToIndex0(colorhist_vector const chv, for (i = 0; i < colors; ++i) if (PPM_EQUAL(chv[i].color, blackPixel)) blackPresent = TRUE; - + if (blackPresent) { /* We use a trick here. ppm_addtocolorhist() always adds to the beginning of the table and if the color is already elsewhere in @@ -780,10 +777,10 @@ makePcxColormapFromImage(pixel ** const pixels, *pcxcmapP. Also return a lookup hash to relate a color in the image to the - appropriate index in *pcxcmapP. Return that in newly malloc'ed + appropriate index in *pcxcmapP. Return that in newly malloc'ed storage as *chtP. - Iff there are too many colors to do that (i.e. more than 256), + Iff there are too many colors to do that (i.e. more than 256), return *tooManyColorsP == TRUE. -----------------------------------------------------------------------------*/ int colors; @@ -801,7 +798,7 @@ makePcxColormapFromImage(pixel ** const pixels, *tooManyColorsP = FALSE; pm_message("%d colors found", colors); - + moveBlackToIndex0(chv, colors); MALLOCARRAY_NOFAIL(pcxcmap, MAXCOLORS); @@ -835,12 +832,12 @@ makePcxColormapFromImage(pixel ** const pixels, -static void -ppmToPalettePcx(pixel ** const pixels, - int const cols, +static void +ppmToPalettePcx(pixel ** const pixels, + int const cols, int const rows, pixval const maxval, - unsigned int const xPos, + unsigned int const xPos, unsigned int const yPos, struct pcxCmapEntry const pcxcmap[], colorhash_table const cht, @@ -848,10 +845,10 @@ ppmToPalettePcx(pixel ** const pixels, bool const packbits, unsigned int const planes, bool const use_8_bit) { - + /* convert image */ if( colors <= 16 && !use_8_bit ) - ppmTo16ColorPcx(pixels, cols, rows, pcxcmap, colors, cht, + ppmTo16ColorPcx(pixels, cols, rows, pcxcmap, colors, cht, packbits, planes, xPos, yPos); else ppmTo256ColorPcx(pixels, cols, rows, pcxcmap, colors, cht, @@ -889,14 +886,14 @@ main(int argc, char *argv[]) { generateStandardPalette(&pcxcmap, maxval, &cht, &colors); } else if (cmdline.palette) { truecolor = FALSE; - readPaletteFromFile(&pcxcmap, cmdline.palette, maxval, + readPaletteFromFile(&pcxcmap, cmdline.palette, maxval, &cht, &colors); } else { bool tooManyColors; makePcxColormapFromImage(pixels, cols, rows, maxval, &pcxcmap, &cht, &colors, &tooManyColors); - + if (tooManyColors) { pm_message("too many colors - writing a 24bit PCX file"); pm_message("if you want a non-24bit file, " @@ -908,16 +905,19 @@ main(int argc, char *argv[]) { } if (truecolor) - ppmToTruecolorPcx(pixels, cols, rows, maxval, + ppmToTruecolorPcx(pixels, cols, rows, maxval, cmdline.xpos, cmdline.ypos); else { - ppmToPalettePcx(pixels, cols, rows, maxval, + ppmToPalettePcx(pixels, cols, rows, maxval, cmdline.xpos, cmdline.ypos, - pcxcmap, cht, colors, cmdline.packed, + pcxcmap, cht, colors, cmdline.packed, cmdline.planes, cmdline.use_8_bit); - + ppm_freecolorhash(cht); free(pcxcmap); } return 0; } + + + diff --git a/converter/ppm/ppmtospu.c b/converter/ppm/ppmtospu.c index b558c1fe..a6acbaa0 100644 --- a/converter/ppm/ppmtospu.c +++ b/converter/ppm/ppmtospu.c @@ -292,7 +292,7 @@ computePalette(struct PixelType * const pixelType) { /* Uses popularity algorithm */ - /* Count the occurences of each color */ + /* Count the occurrences of each color */ for (i = 0; i < 512; ++i) hist[i] = 0; diff --git a/converter/ppm/sldtoppm.c b/converter/ppm/sldtoppm.c index 2dc049f8..2fef0233 100644 --- a/converter/ppm/sldtoppm.c +++ b/converter/ppm/sldtoppm.c @@ -600,7 +600,7 @@ slider(slvecfn slvec, curcolor = cw & 0xFF; break; - default: /* Co-ordinates */ + default: /* Coordinates */ lx = vec.f.x = cw; ly = vec.f.y = sli(); vec.t.x = sli(); diff --git a/converter/ppm/xim.h b/converter/ppm/xim.h index 27556b30..ff21203f 100644 --- a/converter/ppm/xim.h +++ b/converter/ppm/xim.h @@ -6,7 +6,7 @@ ** Taken from the X.V11R4 version of XimHeader.h: ** ** Author: Philip R. Thompson -** Address: phils@athena.mit.edu, 9-526 +** Address: phils@athena.mit.edu, 9-526 ** Note: size of header should be 1024 (1K) bytes. ** $Header: /mit/phils/X/RCS/XimHeader.h,v 1.7 89/11/09 17:26:54 phils Exp Locker: phils $ ** $Date: 89/11/09 17:26:54 $ @@ -24,7 +24,7 @@ typedef struct ImageHeader { char file_version[8]; /* header version */ char header_size[8]; /* Size of file header in bytes */ char image_width[8]; /* Width of the raster image */ - char image_height[8]; /* Height of the raster imgage */ + char image_height[8]; /* Height of the raster image */ char num_colors[8]; /* Actual number of entries in c_map */ char num_channels[3]; /* 0 or 1 = pixmap, 3 = RG&B buffers */ char bytes_per_line[5]; /* bytes per scanline */ @@ -81,7 +81,7 @@ typedef struct XimImage { typedef struct XimAsciiHeader { char file_version[4]; /* header version */ char header_size[8]; /* Size of file header (fixed part only) */ - char image_height[8]; /* Height of the raster imgage in pixels */ + char image_height[8]; /* Height of the raster image in pixels */ char image_width[8]; /* Width of the raster image in pixels */ char bytes_line[8]; /* Actual # of bytes separating scanlines */ char bits_channel[4]; /* Bits per channel (usually 1 or 8) */ @@ -111,7 +111,7 @@ typedef struct XimAsciiHeader { /* Note: * - All data is in char's in order to maintain easily portability -* across machines, and some human readibility. +* across machines, and some human readability. * - Images may be stored as pixmaps (8 bits/pixel) or as separate * red, green, blue channel data (24+ bits/pixel). * - An alpha channel is optional and is found after every num_channels diff --git a/converter/ppm/ximtoppm.c b/converter/ppm/ximtoppm.c index 75faac69..96209425 100644 --- a/converter/ppm/ximtoppm.c +++ b/converter/ppm/ximtoppm.c @@ -50,7 +50,7 @@ parseCommandLine(int argc, char ** argv, unsigned int alphaoutSpec; option_def_index = 0; /* incremented by OPTENT3 */ - OPTENT3(0, "alphaout", OPT_STRING, + OPTENT3(0, "alphaout", OPT_STRING, &cmdlineP->alpha_filename, &alphaoutSpec, 0); opt.opt_table = option_def; @@ -67,21 +67,21 @@ parseCommandLine(int argc, char ** argv, cmdlineP->input_filename = "-"; /* he wants stdin */ else if (argc - 1 == 1) cmdlineP->input_filename = strdup(argv[1]); - else + else pm_error("Too many arguments. The only argument accepted " "is the input file specification"); - if (cmdlineP->alpha_filename && + if (cmdlineP->alpha_filename && streq(cmdlineP->alpha_filename, "-")) cmdlineP->alpha_stdout = TRUE; - else + else cmdlineP->alpha_stdout = FALSE; } /* The subroutines are excerpted and slightly modified from the - X.V11R4 version of xim_io.c. + X.V11R4 version of xim_io.c. */ static int @@ -143,7 +143,7 @@ ReadXimHeader(FILE * const in_fp, header->width = atoi(a_head.image_width); strncpy(header->program, a_head.program,strlen(a_head.program)); } - /* Do double checking for bakwards compatibility */ + /* Do double checking for backwards compatibility */ if (header->npics == 0) header->npics = 1; if (header->bits_channel == 0) @@ -153,7 +153,7 @@ ReadXimHeader(FILE * const in_fp, header->bits_channel = 8; } if ((int)header->bytes_per_line == 0) - header->bytes_per_line = + header->bytes_per_line = (header->bits_channel == 1 && header->nchannels == 1) ? (header->width + 7) / 8 : header->width; @@ -209,7 +209,7 @@ ReadImageChannel(FILE * const infp, } marker += i; } - /* return to the beginning of the next image's bufffer */ + /* return to the beginning of the next image's buffer */ if (fseek(infp, marker, 0) == -1) { pm_message("ReadImageChannel: can't fseek to location in image buffer" ); return(0); @@ -294,7 +294,7 @@ ReadXimImage(FILE * const in_fp, * Author: Philip Thompson * $Date: 89/11/01 10:14:23 $ * $Revision: 1.14 $ -* Purpose: General xim libray of utililities +* Purpose: General xim library of utililities * Copyright (c) 1988 Philip R. Thompson * Computer Resource Laboratory (CRL) * Dept. of Architecture and Planning @@ -356,21 +356,21 @@ main(int argc, ppm_init(&argc, argv); parseCommandLine(argc, argv, &cmdline); - + ifP = pm_openr(cmdline.input_filename); - + if (cmdline.alpha_stdout) alpha_file = stdout; - else if (cmdline.alpha_filename == NULL) + else if (cmdline.alpha_filename == NULL) alpha_file = NULL; else alpha_file = pm_openw(cmdline.alpha_filename); - - if (cmdline.alpha_stdout) + + if (cmdline.alpha_stdout) imageout_file = NULL; else imageout_file = stdout; - + success = ReadXim(ifP, &xim); if (!success) pm_error("can't read Xim file"); @@ -397,7 +397,7 @@ main(int argc, "unknown Xim file type, nchannels == %d, bits_channel == %d", xim.nchannels, xim.bits_channel); - if (imageout_file) + if (imageout_file) ppm_writeppminit(imageout_file, cols, rows, maxval, 0); if (alpha_file) pgm_writepgminit(alpha_file, cols, rows, maxval, 0); @@ -409,8 +409,8 @@ main(int argc, if (mapped) { byte * const ximrow = xim.data + row * xim.bytes_per_line; unsigned int col; - - for (col = 0; col < cols; ++col) + + for (col = 0; col < cols; ++col) pixelrow[col] = colormap[ximrow[col]]; alpharow[col] = 0; } else { @@ -426,11 +426,11 @@ main(int argc, redrow[col], grnrow[col], blurow[col]); if (xim.nchannels > 3) alpharow[col] = othrow[col]; - else + else alpharow[col] = 0; } } - if (imageout_file) + if (imageout_file) ppm_writeppmrow(imageout_file, pixelrow, cols, maxval, 0); if (alpha_file) pgm_writepgmrow(alpha_file, alpharow, cols, maxval, 0); @@ -443,3 +443,6 @@ main(int argc, return 0; } + + + diff --git a/converter/ppm/xpmtoppm.README b/converter/ppm/xpmtoppm.README index b5e254fa..0a32113c 100644 --- a/converter/ppm/xpmtoppm.README +++ b/converter/ppm/xpmtoppm.README @@ -49,7 +49,7 @@ xpmtoppm.c: - Now understands multword X11 color names - Now reads multiple color keys. Takes the color - of the hightest available key. Lines no longer need + of the highest available key. Lines no longer need to begin with key 'c'. - expanded line buffer to from 500 to 2048 for bigger files diff --git a/converter/ppm/xpmtoppm.c b/converter/ppm/xpmtoppm.c index 46101a09..0c9abcc0 100644 --- a/converter/ppm/xpmtoppm.c +++ b/converter/ppm/xpmtoppm.c @@ -544,7 +544,7 @@ interpretXpm3ColorTableLine(char const line[], addToColorMap(hashP, colorName, curbuf, isTransparent); highkey = curkey; } - /* intialize state to process this new key */ + /* initialize state to process this new key */ curkey = key; curbuf[0] = '\0'; isTransparent = FALSE; @@ -1074,7 +1074,7 @@ main(int argc, char *argv[]) { ** - Now understands multiword X11 color names ** ** - Now reads multiple color keys. Takes the color -** of the hightest available key. Lines no longer need +** of the highest available key. Lines no longer need ** to begin with key 'c'. ** ** - expanded line buffer to from 500 to 2048 for bigger files diff --git a/doc/COPYRIGHT.PATENT b/doc/COPYRIGHT.PATENT index 24b1583a..dd1d91e6 100644 --- a/doc/COPYRIGHT.PATENT +++ b/doc/COPYRIGHT.PATENT @@ -35,6 +35,6 @@ maintainer's knowledge." Netpbm may practice valid patents, which would mean that you owe someone -royalties if you use the code. This is a miniscule risk, though. +royalties if you use the code. This is a minuscule risk, though. What is known about patents related to Netpbm is in the file 'doc/patent_summary' in the Netpbm source tree. diff --git a/doc/HISTORY b/doc/HISTORY index 6b9905ac..019beaa1 100644 --- a/doc/HISTORY +++ b/doc/HISTORY @@ -4,7 +4,18 @@ Netpbm. CHANGE HISTORY -------------- -20.03.22 BJH Release 10.89.03 +20.03.26 BJH Release 10.90.00 + + pamundice: Add -listfile. + + pamditherbw: Remove restriction to 2^18 pixels width and height + for -hilbert . + + pamundice: Add error and warning messages for insane file name + pattern. + + pamcut: Improve error messages for legacy command line + arguments. pbmtopgm: Fix incorrect output when convolution area is not square. Always broken. pbmtopgm was in primordial Netpbm, @@ -15,20 +26,28 @@ CHANGE HISTORY 1991. pnmshear: Fix arithmetic overflow with shear angle near +/- 90 - degrees. + degrees. Always broken; pnmshear was in primordial Netpbm, + ca. 1989. + + pnmshear: Fix shearing direction for angles larger than 90 + degrees. Always broken; pnmshear was in primordial Netpbm, + ca. 1989. + + pamditherbw: Fix bug: issue error message instead of just + ignoring one of the options when you specify -hilbert and + another halftone option. + + pamdice: Fix junk output when -width or -height not specified. pamdice: Fix crash when -width or -height is zero. pamdice: Fix incorrect file names when -outstem contains "%s", etc. -20.02.14 BJH Release 10.89.02 - - libnetpbm: pm_getline: ? + pgmnoise: Correct error messages for invalid height, width + arguments. -20.01.15 BJH Release 10.89.01 - - pamdice: Fix junk output when -width or -height not specified. + pnmquantall: remove accidentally published debugging trace. libnetpbm: pm_getline, xvminitoppm, pamtris : Fix bug: crash when reading empty line. @@ -36,6 +55,12 @@ CHANGE HISTORY libnetpbm: pm_read_unknown_size, rawtopgm, zeisstopnm: crash when out of memory + Build: make deb: don't include empty Recommends; newer dpkg-deb + won't accept it. + + Install: Use e.g. "10.90.00" for version in pkg-config and + config file, intead of e.g. "Netpbm 10.90.00". + 19.12.29 BJH Release 10.89.00 pnmpad: Add -reportonly. @@ -825,7 +850,7 @@ CHANGE HISTORY pnmtopng: Add -srgbintent. pamstereogram: Add -xbegin. Change default to render from - center outwards intead of from right to left, thus making the + center outwards instead of from right to left, thus making the center of the image the crispest part. Thanks Scott Pakin (scott+pbm@pakin.org). @@ -977,7 +1002,7 @@ CHANGE HISTORY color map nor a local one. pgmmorphconv: fix bug: always produces PGM Plain format. Always - present (progam was added to Netpbm in Release 10.0 (June 2002)). + present (program was added to Netpbm in Release 10.0 (June 2002)). pamtilt: fix bug: unconditional crash. Broken in Netpbm 10.63 (June 2013). @@ -1473,7 +1498,7 @@ CHANGE HISTORY libpam, pamcomp: fix bug: treats tuple type GRAYSCALE_ALPHA like GRAYSCALE on 32-bit machine. Actually, looks only at first 4 - characters (8 characters on machine with 64 bit addressess) of + characters (8 characters on machine with 64 bit addresses) of the tuple type. Broken since Netpbm 10.56 (September 2011). pngtopam -alphapam with grayscale input: fix bug: generates @@ -1888,7 +1913,7 @@ CHANGE HISTORY anytopnm: recognize "PC bitmap" in 'file' response as BMP. (in addition to existing "PC bitmap data"). - libnetpbm, various PBM programs: Use SSE insted of MMX. Thanks + libnetpbm, various PBM programs: Use SSE instead of MMX. Thanks Akira F Urushibata . pbmtext/libpbmfont: Fix wild pointer; probably asymptomatic. @@ -5532,7 +5557,7 @@ CHANGE HISTORY ppmdither: fix bug with input maxval != 255. Make output maxval the LCM of the requested numbers of primary levels. - xwdtopnm: works with files where there aren't an integeral + xwdtopnm: works with files where there aren't an integral number of pixels per storage unit (e.g. 24 bits per pixel) Add some missing pXm_init() diff --git a/doc/INSTALL b/doc/INSTALL index 3c3bfcbd..c20d372e 100644 --- a/doc/INSTALL +++ b/doc/INSTALL @@ -210,7 +210,7 @@ to in _mingw.h. This is the trick other C libraries use. (A user proposed that this change be distributed in _mingw.h, in April 2017 on -the mingw-users mailing list, but the maintainer was opposed to accomodating +the mingw-users mailing list, but the maintainer was opposed to accommodating programs written for the older standards). If you cannot change _mingw.h, you can alternatively change Netpbm. Find all diff --git a/editor/pamaltsat.c b/editor/pamaltsat.c index 6d9b91e0..3bff55bd 100644 --- a/editor/pamaltsat.c +++ b/editor/pamaltsat.c @@ -160,7 +160,7 @@ typedef double (binsearchFunc)(double const x, /* The binary-search function. Returns such from [, ] that monotonically increasing function func(x, data) equals within - precision . is an arbitary parameter to . */ + precision . is an arbitrary parameter to . */ static double binsearch(binsearchFunc func, const void * const dataP, @@ -299,7 +299,7 @@ typedef struct { TupleD * tupsatP; /* saturated color */ double * intRatioP; - /* ratio of orignal and saturated intensities */ + /* ratio of original and saturated intensities */ } MaxLogSatInfo; @@ -346,7 +346,7 @@ getMaxLogSat(LinSampleInfo * const siP, /* Discarding return value (maximum saturation) because upon completion of binsearch() info.tupsatP will contain the saturated color. The target value of maximum channel intensity is decreased by PREC in order to avoid - overlow. */ + overflow. */ binsearch(binsearchMaxLogSat, &info, PREC, 1.0, upperLimit, 1.0 - PREC); } @@ -399,11 +399,11 @@ saturateSpectrum(LinSampleInfo * const siP, else { double const km1 = (1.0 - siP->intensity)/(siP->maxval - siP->intensity); - /* Maximum saturation factor that keeps maximum layer intesity + /* Maximum saturation factor that keeps maximum layer intensity within range */ double const km2 = siP->intensity/(siP->intensity - sample[siP->minl]); - /* Maximum saturation factor that keeps minimum layer intesity + /* Maximum saturation factor that keeps minimum layer intensity within range */ diff --git a/editor/pamcut.c b/editor/pamcut.c index db5b5b3d..1fc9d9b2 100644 --- a/editor/pamcut.c +++ b/editor/pamcut.c @@ -17,6 +17,7 @@ #include "pam.h" #include "shhopt.h" #include "mallocvar.h" +#include "nstring.h" #define UNSPEC INT_MAX /* UNSPEC is the value we use for an argument that is not specified @@ -35,10 +36,10 @@ typedef struct { If LOCTYPE_NONE: Meaningless - If LOCTYPE_FROMFAR: Number of colums from the far edge of the image + If LOCTYPE_FROMFAR: Number of columns from the far edge of the image (right or bottom). Last column/row is 1. - If LOCTYPE_FROMNEAR: Number of colums from the near edge of the + If LOCTYPE_FROMNEAR: Number of columns from the near edge of the image (left or top). First column/row is 0. */ } Location; @@ -78,6 +79,73 @@ struct CmdlineInfo { +static void +parseLegacyLocationArgs(const char ** const argv, + struct CmdlineInfo * const cmdlineP) { + + int leftArg, topArg, widthArg, heightArg; + + { + const char * error; + pm_string_to_int(argv[1], &leftArg, &error); + if (error) + pm_error("Invalid number for left column argument. %s", error); + } + { + const char * error; + pm_string_to_int(argv[2], &topArg, &error); + if (error) + pm_error("Invalid number for top row argument. %s", error); + } + { + const char * error; + pm_string_to_int(argv[3], &widthArg, &error); + if (error) + pm_error("Invalid number for width argument. %s", error); + } + { + const char * error; + pm_string_to_int(argv[4], &heightArg, &error); + if (error) + pm_error("Invalid number for height argument. %s", error); + } + + if (leftArg < 0) { + cmdlineP->leftLoc.locType = LOCTYPE_FROMFAR; + cmdlineP->leftLoc.n = -leftArg; + } else { + cmdlineP->leftLoc.locType = LOCTYPE_FROMNEAR; + cmdlineP->leftLoc.n = leftArg; + } + if (topArg < 0) { + cmdlineP->topLoc.locType = LOCTYPE_FROMFAR; + cmdlineP->topLoc.n = -topArg; + } else { + cmdlineP->topLoc.locType = LOCTYPE_FROMNEAR; + cmdlineP->topLoc.n = topArg; + } + if (widthArg > 0) { + cmdlineP->width = widthArg; + cmdlineP->widthSpec = 1; + cmdlineP->rghtLoc.locType = LOCTYPE_NONE; + } else { + cmdlineP->widthSpec = 0; + cmdlineP->rghtLoc.locType = LOCTYPE_FROMFAR; + cmdlineP->rghtLoc.n = -(widthArg - 1); + } + if (heightArg > 0) { + cmdlineP->height = heightArg; + cmdlineP->heightSpec = 1; + cmdlineP->botLoc.locType = LOCTYPE_NONE; + } else { + cmdlineP->heightSpec = 0; + cmdlineP->botLoc.locType = LOCTYPE_FROMFAR; + cmdlineP->botLoc.n = -(heightArg - 1); + } +} + + + static void parseCommandLine(int argc, const char ** const argv, struct CmdlineInfo * const cmdlineP) { @@ -156,51 +224,9 @@ parseCommandLine(int argc, const char ** const argv, break; } - if (haveLegacyLocationArgs) { - int leftArg, topArg, widthArg, heightArg; - - if (sscanf(argv[1], "%d", &leftArg) != 1) - pm_error("Invalid number for left column argument"); - if (sscanf(argv[2], "%d", &topArg) != 1) - pm_error("Invalid number for right column argument"); - if (sscanf(argv[3], "%d", &widthArg) != 1) - pm_error("Invalid number for width argument"); - if (sscanf(argv[4], "%d", &heightArg) != 1) - pm_error("Invalid number for height argument"); - - if (leftArg < 0) { - cmdlineP->leftLoc.locType = LOCTYPE_FROMFAR; - cmdlineP->leftLoc.n = -leftArg; - } else { - cmdlineP->leftLoc.locType = LOCTYPE_FROMNEAR; - cmdlineP->leftLoc.n = leftArg; - } - if (topArg < 0) { - cmdlineP->topLoc.locType = LOCTYPE_FROMFAR; - cmdlineP->topLoc.n = -topArg; - } else { - cmdlineP->topLoc.locType = LOCTYPE_FROMNEAR; - cmdlineP->topLoc.n = topArg; - } - if (widthArg > 0) { - cmdlineP->width = widthArg; - cmdlineP->widthSpec = 1; - cmdlineP->rghtLoc.locType = LOCTYPE_NONE; - } else { - cmdlineP->widthSpec = 0; - cmdlineP->rghtLoc.locType = LOCTYPE_FROMFAR; - cmdlineP->rghtLoc.n = -(widthArg - 1); - } - if (heightArg > 0) { - cmdlineP->height = heightArg; - cmdlineP->heightSpec = 1; - cmdlineP->botLoc.locType = LOCTYPE_NONE; - } else { - cmdlineP->heightSpec = 0; - cmdlineP->botLoc.locType = LOCTYPE_FROMFAR; - cmdlineP->botLoc.n = -(heightArg - 1); - } - } else { + if (haveLegacyLocationArgs) + parseLegacyLocationArgs(argv, cmdlineP); + else { if (leftSpec && cropleftSpec) pm_error("You cannot specify both -left and -cropleft"); if (leftSpec) { diff --git a/editor/pamdice.c b/editor/pamdice.c index 32881129..9063c4bd 100644 --- a/editor/pamdice.c +++ b/editor/pamdice.c @@ -17,34 +17,30 @@ #include "nstring.h" #include "mallocvar.h" -#define MAXFILENAMELEN 80 - /* Maximum number of characters we accept in filenames */ - -struct cmdlineInfo { +struct CmdlineInfo { /* All the information the user supplied in the command line, in a form easy for the program to use. */ const char * inputFileName; /* '-' if stdin */ - const char * outstem; - /* null-terminated string, max MAXFILENAMELEN-10 characters */ + const char * outstem; unsigned int sliceVertically; /* boolean */ unsigned int sliceHorizontally; /* boolean */ unsigned int width; /* Meaningless if !sliceVertically */ unsigned int height; /* Meaningless if !sliceHorizontally */ - unsigned int hoverlap; + unsigned int hoverlap; /* Meaningless if !sliceVertically. Guaranteed < width */ - unsigned int voverlap; + unsigned int voverlap; /* Meaningless if !sliceHorizontally. Guaranteed < height */ unsigned int verbose; }; static void -parseCommandLine(int argc, char ** argv, - struct cmdlineInfo * const cmdlineP ) { +parseCommandLine(int argc, const char ** argv, + struct CmdlineInfo * const cmdlineP) { /*---------------------------------------------------------------------------- parse program command line described in Unix standard form by argc - and argv. Return the information in the options as *cmdlineP. + and argv. Return the information in the options as *cmdlineP. If command line is internally inconsistent (invalid options, etc.), issue error message to stderr and abort program. @@ -52,18 +48,18 @@ parseCommandLine(int argc, char ** argv, Note that the strings we return are stored in the storage that was passed to us as the argv array. We also trash *argv. -----------------------------------------------------------------------------*/ - optEntry *option_def; + optEntry * option_def; /* Instructions to pm_optParseOptions3 on how to parse our options. */ optStruct3 opt; - + unsigned int outstemSpec, hoverlapSpec, voverlapSpec; unsigned int option_def_index; MALLOCARRAY_NOFAIL(option_def, 100); option_def_index = 0; /* incremented by OPTENT3 */ - OPTENT3(0, "width", OPT_UINT, &cmdlineP->width, + OPTENT3(0, "width", OPT_UINT, &cmdlineP->width, &cmdlineP->sliceVertically, 0); OPTENT3(0, "height", OPT_UINT, &cmdlineP->height, &cmdlineP->sliceHorizontally, 0); @@ -80,7 +76,7 @@ parseCommandLine(int argc, char ** argv, opt.short_allowed = FALSE; /* We have no short (old-fashioned) options */ opt.allowNegNum = FALSE; /* We have no parms that are negative numbers */ - pm_optParseOptions3( &argc, argv, opt, sizeof(opt), 0 ); + pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0); /* Uses and sets argc, argv, and some of *cmdline_p and others. */ if (cmdlineP->sliceVertically) { @@ -114,9 +110,11 @@ parseCommandLine(int argc, char ** argv, cmdlineP->inputFileName = "-"; else if (argc-1 == 1) cmdlineP->inputFileName = argv[1]; - else - pm_error("Progam takes at most 1 parameter: the file specification. " + else + pm_error("Program takes at most 1 parameter: the file specification. " "You specified %u", argc-1); + + free(option_def); } @@ -133,7 +131,7 @@ divup(unsigned int const dividend, static void -computeSliceGeometry(struct cmdlineInfo const cmdline, +computeSliceGeometry(struct CmdlineInfo const cmdline, struct pam const inpam, bool const verbose, unsigned int * const nHorizSliceP, @@ -146,20 +144,30 @@ computeSliceGeometry(struct cmdlineInfo const cmdline, /*---------------------------------------------------------------------------- Compute the geometry of the slices, both common slices and possibly smaller remainder slices at the top and right. + + We return the following. + + *nHorizSliceP is the number of horizontal slices. *sliceHeightP is the + height of every slice except possibly the bottom one. *bottomSliceHeightP + is the height of the bottom slice. + + *nVertSliceP is the number of vertical slices. *sliceWidthP is the width + of every slice except possibly the rightmost one. *rightSliceWidthP is the + width of the rightmost slice. -----------------------------------------------------------------------------*/ if (cmdline.sliceHorizontally) { if (cmdline.height >= inpam.height) *nHorizSliceP = 1; else - *nHorizSliceP = 1 + divup(inpam.height - cmdline.height, + *nHorizSliceP = 1 + divup(inpam.height - cmdline.height, cmdline.height - cmdline.voverlap); *sliceHeightP = cmdline.height; - *bottomSliceHeightP = - inpam.height - (*nHorizSliceP-1) * (cmdline.height - cmdline.voverlap); + *bottomSliceHeightP = inpam.height - + (*nHorizSliceP-1) * (cmdline.height - cmdline.voverlap); } else { - *nHorizSliceP = 1; - *sliceHeightP = inpam.height; + *nHorizSliceP = 1; + *sliceHeightP = inpam.height; *bottomSliceHeightP = inpam.height; } @@ -167,14 +175,14 @@ computeSliceGeometry(struct cmdlineInfo const cmdline, if (cmdline.width >= inpam.width) *nVertSliceP = 1; else - *nVertSliceP = 1 + divup(inpam.width - cmdline.width, + *nVertSliceP = 1 + divup(inpam.width - cmdline.width, cmdline.width - cmdline.hoverlap); *sliceWidthP = cmdline.width; - *rightSliceWidthP = - inpam.width - (*nVertSliceP-1) * (cmdline.width - cmdline.hoverlap); + *rightSliceWidthP = inpam.width - + (*nVertSliceP-1) * (cmdline.width - cmdline.hoverlap); } else { - *nVertSliceP = 1; - *sliceWidthP = inpam.width; + *nVertSliceP = 1; + *sliceWidthP = inpam.width; *rightSliceWidthP = inpam.width; } @@ -185,7 +193,7 @@ computeSliceGeometry(struct cmdlineInfo const cmdline, *nVertSliceP, *nHorizSliceP, *sliceWidthP, *sliceHeightP); if (*rightSliceWidthP != *sliceWidthP) - pm_message("Right vertical slice is only %u wide", + pm_message("Right vertical slice is only %u wide", *rightSliceWidthP); if (*bottomSliceHeightP != *sliceHeightP) pm_message("Bottom horizontal slice is only %u high", @@ -212,7 +220,7 @@ ndigits(unsigned int const arg) { static void -computeOutputFilenameFormat(int const format, +computeOutputFilenameFormat(int const format, unsigned int const nHorizSlice, unsigned int const nVertSlice, const char ** const filenameFormatP) { @@ -226,7 +234,7 @@ computeOutputFilenameFormat(int const format, case PAM_TYPE: filenameSuffix = "pam"; break; default: filenameSuffix = ""; break; } - + pm_asprintf(filenameFormatP, "%%s_%%0%uu_%%0%uu.%s", ndigits(nHorizSlice), ndigits(nVertSlice), filenameSuffix); @@ -237,16 +245,16 @@ computeOutputFilenameFormat(int const format, static void -openOutStreams(struct pam const inpam, - struct pam outpam[], - unsigned int const horizSlice, +openOutStreams(struct pam const inpam, + struct pam * const outpam, + unsigned int const horizSlice, unsigned int const nHorizSlice, unsigned int const nVertSlice, - unsigned int const sliceHeight, + unsigned int const sliceHeight, unsigned int const sliceWidth, unsigned int const rightSliceWidth, unsigned int const hOverlap, - char const outstem[]) { + const char * const outstem) { /*---------------------------------------------------------------------------- Open the output files for a single horizontal slice (there's one file for each vertical slice) and write the Netpbm headers to them. Also @@ -268,34 +276,37 @@ openOutStreams(struct pam const inpam, else { outpam[vertSlice] = inpam; outpam[vertSlice].file = pm_openw(filename); - - outpam[vertSlice].width = + + outpam[vertSlice].width = vertSlice < nVertSlice-1 ? sliceWidth : rightSliceWidth; - + outpam[vertSlice].height = sliceHeight; - + pnm_writepaminit(&outpam[vertSlice]); pm_strfree(filename); } - } + } pm_strfree(filenameFormat); } static void -closeOutFiles(struct pam pam[], unsigned int const nVertSlice) { +closeOutFiles(struct pam * const pam, + unsigned int const nVertSlice) { unsigned int vertSlice; - + for (vertSlice = 0; vertSlice < nVertSlice; ++vertSlice) pm_close(pam[vertSlice].file); } + + static void -sliceRow(tuple inputRow[], - struct pam outpam[], +sliceRow(tuple * const inputRow, + struct pam * const outpam, unsigned int const nVertSlice, unsigned int const hOverlap) { /*---------------------------------------------------------------------------- @@ -306,14 +317,15 @@ sliceRow(tuple inputRow[], 'hOverlap', which is meaningful only when nVertSlice is greater than 1, is the amount by which slices overlap each other. -----------------------------------------------------------------------------*/ - tuple * outputRow; - unsigned int vertSlice; unsigned int const sliceWidth = outpam[0].width; - unsigned int const stride = + unsigned int const stride = nVertSlice > 1 ? sliceWidth - hOverlap : sliceWidth; - for (vertSlice = 0, outputRow = inputRow; - vertSlice < nVertSlice; + tuple * outputRow; + unsigned int vertSlice; + + for (vertSlice = 0, outputRow = inputRow; + vertSlice < nVertSlice; outputRow += stride, ++vertSlice) { pnm_writepamrow(&outpam[vertSlice], outputRow); } @@ -331,15 +343,15 @@ sliceRow(tuple inputRow[], struct inputWindow { unsigned int windowSize; unsigned int firstRowInWindow; - struct pam pam; - tuple ** rows; + struct pam pam; + tuple ** rows; }; static void initInput(struct inputWindow * const inputWindowP, struct pam * const pamP, unsigned int const windowSize) { - + struct pam allocPam; /* Just for allocating the window array */ unsigned int i; @@ -348,7 +360,7 @@ initInput(struct inputWindow * const inputWindowP, allocPam = *pamP; allocPam.height = windowSize; - + inputWindowP->rows = pnm_allocpamarray(&allocPam); inputWindowP->firstRowInWindow = 0; @@ -369,6 +381,8 @@ termInputWindow(struct inputWindow * const inputWindowP) { pnm_freepamarray(inputWindowP->rows, &freePam); } + + static tuple * getInputRow(struct inputWindow * const inputWindowP, unsigned int const row) { @@ -391,7 +405,7 @@ getInputRow(struct inputWindow * const inputWindowP, /* Read in the new last row in the window */ inputWindowP->rows[i] = oldRow0; /* Reuse the memory */ pnm_readpamrow(&inputWindowP->pam, inputWindowP->rows[i]); - } + } return inputWindowP->rows[row - inputWindowP->firstRowInWindow]; } @@ -418,10 +432,10 @@ allocOutpam(unsigned int const nVertSlice, int -main(int argc, char ** argv) { +main(int argc, const char ** argv) { - struct cmdlineInfo cmdline; - FILE *ifP; + struct CmdlineInfo cmdline; + FILE * ifP; struct pam inpam; unsigned int horizSlice; /* Number of the current horizontal slice. Slices are numbered @@ -431,7 +445,7 @@ main(int argc, char ** argv) { /* Width in pam columns of each vertical slice, except the rightmost slice, which may be narrower. If we aren't slicing vertically, that means one slice, i.e. the slice width - is the image width. + is the image width. */ unsigned int rightSliceWidth; /* Width in pam columns of the rightmost vertical slice. */ @@ -439,23 +453,23 @@ main(int argc, char ** argv) { /* Height in pam rows of each horizontal slice, except the bottom slice, which may be shorter. If we aren't slicing horizontally, that means one slice, i.e. the slice height - is the image height. + is the image height. */ unsigned int bottomSliceHeight; /* Height in pam rows of the bottom horizontal slice. */ unsigned int nHorizSlice; unsigned int nVertSlice; struct inputWindow inputWindow; - + struct pam * outpam; - /* malloc'ed. outpam[x] is the pam structure that controls + /* malloc'ed array. outpam[x] is the pam structure that controls the current horizontal slice of vertical slice x. */ - pnm_init(&argc, argv); - + pm_proginit(&argc, argv); + parseCommandLine(argc, argv, &cmdline); - + ifP = pm_openr(cmdline.inputFileName); pnm_readpaminit(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type)); @@ -465,28 +479,29 @@ main(int argc, char ** argv) { &nVertSlice, &sliceWidth, &rightSliceWidth); allocOutpam(nVertSlice, &outpam); - - initInput(&inputWindow, &inpam, + + initInput(&inputWindow, &inpam, nHorizSlice > 1 ? cmdline.voverlap + 1 : 1); for (horizSlice = 0; horizSlice < nHorizSlice; ++horizSlice) { - unsigned int const thisSliceFirstRow = + unsigned int const thisSliceFirstRow = horizSlice > 0 ? horizSlice * (sliceHeight - cmdline.voverlap) : 0; /* Note that 'cmdline.voverlap' is not defined when there is only one horizontal slice */ - unsigned int const thisSliceHeight = + unsigned int const thisSliceHeight = horizSlice < nHorizSlice-1 ? sliceHeight : bottomSliceHeight; unsigned int row; - openOutStreams(inpam, outpam, horizSlice, nHorizSlice, nVertSlice, + openOutStreams(inpam, outpam, horizSlice, nHorizSlice, nVertSlice, thisSliceHeight, sliceWidth, rightSliceWidth, cmdline.hoverlap, cmdline.outstem); for (row = 0; row < thisSliceHeight; ++row) { tuple * const inputRow = getInputRow(&inputWindow, thisSliceFirstRow + row); + sliceRow(inputRow, outpam, nVertSlice, cmdline.hoverlap); } closeOutFiles(outpam, nVertSlice); @@ -500,3 +515,6 @@ main(int argc, char ** argv) { return 0; } + + + diff --git a/editor/pamditherbw.c b/editor/pamditherbw.c index 4b192e6e..ae91a26f 100644 --- a/editor/pamditherbw.c +++ b/editor/pamditherbw.c @@ -42,7 +42,7 @@ struct cmdlineInfo { enum halftone halftone; unsigned int clumpSize; /* Defined only for halftone == QT_HILBERT */ - unsigned int clusterRadius; + unsigned int clusterRadius; /* Defined only for halftone == QT_CLUSTER */ float threshval; unsigned int randomseed; @@ -85,9 +85,9 @@ parseCommandLine(int argc, char ** argv, OPTENT3(0, "c4", OPT_FLAG, NULL, &cluster4Opt, 0); OPTENT3(0, "cluster8", OPT_FLAG, NULL, &cluster8Opt, 0); OPTENT3(0, "c8", OPT_FLAG, NULL, &cluster8Opt, 0); - OPTENT3(0, "value", OPT_FLOAT, &cmdlineP->threshval, + OPTENT3(0, "value", OPT_FLOAT, &cmdlineP->threshval, &valueSpec, 0); - OPTENT3(0, "clump", OPT_UINT, &cmdlineP->clumpSize, + OPTENT3(0, "clump", OPT_UINT, &cmdlineP->clumpSize, &clumpSpec, 0); OPTENT3(0, "randomseed", OPT_UINT, &cmdlineP->randomseed, &cmdlineP->randomseedSpec, 0); @@ -101,10 +101,10 @@ parseCommandLine(int argc, char ** argv, free(option_def); - if (floydOpt + atkinsonOpt + thresholdOpt + hilbertOpt + dither8Opt + + if (floydOpt + atkinsonOpt + thresholdOpt + hilbertOpt + dither8Opt + cluster3Opt + cluster4Opt + cluster8Opt == 0) cmdlineP->halftone = QT_FS; - else if (floydOpt + atkinsonOpt + thresholdOpt + dither8Opt + + else if (floydOpt + atkinsonOpt + thresholdOpt + hilbertOpt + dither8Opt + cluster3Opt + cluster4Opt + cluster8Opt > 1) pm_error("Cannot specify more than one halftoning type"); else { @@ -135,7 +135,7 @@ parseCommandLine(int argc, char ** argv, } else if (cluster8Opt) { cmdlineP->halftone = QT_CLUSTER; cmdlineP->clusterRadius = 8; - } else + } else pm_error("INTERNAL ERROR. No halftone option"); } @@ -190,152 +190,211 @@ makeOutputPam(unsigned int const width, /* Hilbert curve tracer */ -#define MAXORD 18 +typedef struct { + unsigned int x; + unsigned int y; +} Point; + -struct Hil { - int order; - int ord; + +typedef struct { + bool firstPointDone; + unsigned int order; + unsigned int ord; + /* Meaningful only when 'firstPointDone' is true */ int turn; int dx; int dy; int x; int y; - int stage[MAXORD]; - int width; - int height; -}; + int stage[sizeof(unsigned int)*8]; + /* One entry for every bit in the height or width, each of which + is an unsigned int + */ + unsigned int width; + unsigned int height; +} Hilbert; -static void -initHilbert(int const w, - int const h, - struct Hil * const hilP) { +static void +hilbert_init(Hilbert * const hilP, + unsigned int const width, + unsigned int const height) { /*---------------------------------------------------------------------------- - Initialize the Hilbert curve tracer + Initialize the Hilbert curve tracer -----------------------------------------------------------------------------*/ - int big, ber; - hilP->width = w; - hilP->height = h; - big = w > h ? w : h; - for (ber = 2, hilP->order = 1; ber < big; ber <<= 1, hilP->order++); - if (hilP->order > MAXORD) - pm_error("Sorry, hilbert order is too large"); - hilP->ord = hilP->order; - hilP->order--; + unsigned int const maxDim = MAX(width, height); + + unsigned int order; + + hilP->width = width; + hilP->height = height; + { + unsigned int ber; + for (ber = 2, order = 0; ber < maxDim; ber <<= 1, ++order); + } + assert(order + 1 <= ARRAY_SIZE(hilP->stage)); + hilP->order = order; + hilP->firstPointDone = false; } -static bool -hilbert(int * const px, - int * const py, - struct Hil * const hilP) { -/*---------------------------------------------------------------------------- - Return non-zero if got another point ------------------------------------------------------------------------------*/ - int temp; - if (hilP->ord > hilP->order) { - /* have to do first point */ - - hilP->ord--; - hilP->stage[hilP->ord] = 0; - hilP->turn = -1; - hilP->dy = 1; - hilP->dx = hilP->x = hilP->y = 0; - *px = *py = 0; - return true; - } +static void +hilbert_doFirstPoint(Hilbert * const hilbertP, + bool * const gotPointP, + Point * const pointP) { + + hilbertP->ord = hilbertP->order; + hilbertP->stage[hilbertP->ord] = 0; + hilbertP->turn = -1; + hilbertP->dy = 1; + hilbertP->dx = hilbertP->x = hilbertP->y = 0; + hilbertP->firstPointDone = true; + + pointP->x = 0; pointP->y = 0; + *gotPointP = true; +} + + + +static void +hilbert_advanceStateMachine(Hilbert * const hilbertP, + bool * const gotPointP, + Point * const pointP) { - /* Operate the state machine */ for(;;) { - switch (hilP->stage[hilP->ord]) { - case 0: - hilP->turn = -hilP->turn; - temp = hilP->dy; - hilP->dy = -hilP->turn * hilP->dx; - hilP->dx = hilP->turn * temp; - if (hilP->ord > 0) { - hilP->stage[hilP->ord] = 1; - hilP->ord--; - hilP->stage[hilP->ord]=0; + switch (hilbertP->stage[hilbertP->ord]) { + case 0: { + int const origDy = hilbertP->dy; + + hilbertP->turn = -hilbertP->turn; + hilbertP->dy = -hilbertP->turn * hilbertP->dx; + hilbertP->dx = hilbertP->turn * origDy; + if (hilbertP->ord > 0) { + hilbertP->stage[hilbertP->ord] = 1; + --hilbertP->ord; + hilbertP->stage[hilbertP->ord]=0; continue; } - case 1: - hilP->x += hilP->dx; - hilP->y += hilP->dy; - if (hilP->x < hilP->width && hilP->y < hilP->height) { - hilP->stage[hilP->ord] = 2; - *px = hilP->x; - *py = hilP->y; - return true; + } + case 1: { + hilbertP->x += hilbertP->dx; + hilbertP->y += hilbertP->dy; + if (hilbertP->x < hilbertP->width && + hilbertP->y < hilbertP->height) { + + hilbertP->stage[hilbertP->ord] = 2; + + pointP->x = hilbertP->x; + pointP->y = hilbertP->y; + *gotPointP = true; + return; } - case 2: - hilP->turn = -hilP->turn; - temp = hilP->dy; - hilP->dy = -hilP->turn * hilP->dx; - hilP->dx = hilP->turn * temp; - if (hilP->ord > 0) { + } + case 2: { + int const origDy = hilbertP->dy; + + hilbertP->turn = -hilbertP->turn; + hilbertP->dy = -hilbertP->turn * hilbertP->dx; + hilbertP->dx = hilbertP->turn * origDy; + if (hilbertP->ord > 0) { /* recurse */ - hilP->stage[hilP->ord] = 3; - hilP->ord--; - hilP->stage[hilP->ord]=0; + hilbertP->stage[hilbertP->ord] = 3; + --hilbertP->ord; + hilbertP->stage[hilbertP->ord]=0; continue; } - case 3: - hilP->x += hilP->dx; - hilP->y += hilP->dy; - if (hilP->x < hilP->width && hilP->y < hilP->height) { - hilP->stage[hilP->ord] = 4; - *px = hilP->x; - *py = hilP->y; - return true; + } + case 3: { + hilbertP->x += hilbertP->dx; + hilbertP->y += hilbertP->dy; + if (hilbertP->x < hilbertP->width && + hilbertP->y < hilbertP->height) { + + hilbertP->stage[hilbertP->ord] = 4; + + pointP->x = hilbertP->x; + pointP->y = hilbertP->y; + *gotPointP = true; + return; } - case 4: - if (hilP->ord > 0) { + } + case 4: { + if (hilbertP->ord > 0) { /* recurse */ - hilP->stage[hilP->ord] = 5; - hilP->ord--; - hilP->stage[hilP->ord]=0; + hilbertP->stage[hilbertP->ord] = 5; + --hilbertP->ord; + hilbertP->stage[hilbertP->ord]=0; continue; } - case 5: - temp = hilP->dy; - hilP->dy = -hilP->turn * hilP->dx; - hilP->dx = hilP->turn * temp; - hilP->turn = -hilP->turn; - hilP->x += hilP->dx; - hilP->y += hilP->dy; - if (hilP->x < hilP->width && hilP->y < hilP->height) { - hilP->stage[hilP->ord] = 6; - *px = hilP->x; - *py = hilP->y; - return true; + } + case 5: { + int const origDy = hilbertP->dy; + + hilbertP->dy = -hilbertP->turn * hilbertP->dx; + hilbertP->dx = hilbertP->turn * origDy; + hilbertP->turn = -hilbertP->turn; + hilbertP->x += hilbertP->dx; + hilbertP->y += hilbertP->dy; + if (hilbertP->x < hilbertP->width && + hilbertP->y < hilbertP->height) { + + hilbertP->stage[hilbertP->ord] = 6; + + pointP->x = hilbertP->x; + pointP->y = hilbertP->y; + *gotPointP = true; + return; } - case 6: - if (hilP->ord > 0) { + } + case 6: { + if (hilbertP->ord > 0) { /* recurse */ - hilP->stage[hilP->ord] = 7; - hilP->ord--; - hilP->stage[hilP->ord]=0; + hilbertP->stage[hilbertP->ord] = 7; + --hilbertP->ord; + hilbertP->stage[hilbertP->ord]=0; continue; } - case 7: - temp = hilP->dy; - hilP->dy = -hilP->turn * hilP->dx; - hilP->dx = hilP->turn * temp; - hilP->turn = -hilP->turn; + } + case 7: { + int const origDy = hilbertP->dy; + + hilbertP->dy = -hilbertP->turn * hilbertP->dx; + hilbertP->dx = hilbertP->turn * origDy; + hilbertP->turn = -hilbertP->turn; /* Return from a recursion */ - if (hilP->ord < hilP->order) - hilP->ord++; - else - return false; + if (hilbertP->ord < hilbertP->order) + ++hilbertP->ord; + else { + *gotPointP = false; + return; + } + } } } } -static void +static void +hilbert_trace(Hilbert * const hilbertP, + bool * const gotPointP, + Point * const pointP) { +/*---------------------------------------------------------------------------- + ... + Return *gotPointP true iff we got another point +-----------------------------------------------------------------------------*/ + if (!hilbertP->firstPointDone) { + hilbert_doFirstPoint(hilbertP, gotPointP, pointP); + } else { + hilbert_advanceStateMachine(hilbertP, gotPointP, pointP); + } +} + + + +static void doHilbert(FILE * const ifP, unsigned int const clumpSize) { /*---------------------------------------------------------------------------- @@ -356,10 +415,10 @@ doHilbert(FILE * const ifP, tuple ** grays; tuple ** bits; - struct Hil hil; + Hilbert hilbert; int end; - int *x,*y; + Point * point; int sum; grays = pnm_readpam(ifP, &graypam, PAM_STRUCT_SIZE(tuple_type)); @@ -368,11 +427,11 @@ doHilbert(FILE * const ifP, bits = pnm_allocpamarray(&bitpam); - MALLOCARRAY(x, clumpSize); - MALLOCARRAY(y, clumpSize); - if (x == NULL || y == NULL) - pm_error("out of memory"); - initHilbert(graypam.width, graypam.height, &hil); + MALLOCARRAY(point, clumpSize); + if (!point) + pm_error("Unable to get memory for clump of %u points", clumpSize); + + hilbert_init(&hilbert, graypam.width, graypam.height); sum = 0; end = clumpSize; @@ -380,19 +439,20 @@ doHilbert(FILE * const ifP, while (end == clumpSize) { unsigned int i; /* compute the next cluster co-ordinates along hilbert path */ - for (i = 0; i < end; i++) { + for (i = 0; i < end; ++i) { bool gotPoint; - gotPoint = hilbert(&x[i], &y[i], &hil); + hilbert_trace(&hilbert, &gotPoint, &point[i]); if (!gotPoint) end = i; /* we reached the end */ } /* sum levels */ - for (i = 0; i < end; i++) - sum += grays[y[i]][x[i]][0]; + for (i = 0; i < end; ++i) + sum += grays[point[i].y][point[i].x][0]; /* dither half and half along path */ - for (i = 0; i < end; i++) { - unsigned int const row = y[i]; - unsigned int const col = x[i]; + for (i = 0; i < end; ++i) { + unsigned int const row = point[i].y; + unsigned int const col = point[i].x; + if (sum >= graypam.maxval) { bits[row][col][0] = 1; sum -= graypam.maxval; @@ -400,7 +460,7 @@ doHilbert(FILE * const ifP, bits[row][col][0] = 0; } } - free(x); free(y); + free(point); pnm_writepam(&bitpam, bits); pnm_freepamarray(bits, &bitpam); @@ -412,7 +472,7 @@ doHilbert(FILE * const ifP, struct converter { void (*convertRow)(struct converter * const converterP, unsigned int const row, - tuplen grayrow[], + tuplen grayrow[], tuple bitrow[]); void (*destroy)(struct converter * const converterP); unsigned int cols; @@ -423,11 +483,11 @@ struct converter { struct fsState { float * thiserr; - /* thiserr[N] is the power from previous pixels to include in + /* thiserr[N] is the power from previous pixels to include in future column N of the current row. */ float * nexterr; - /* nexterr[N] is the power from previous pixels to include in + /* nexterr[N] is the power from previous pixels to include in future column N of the next row. */ bool fs_forward; @@ -455,7 +515,7 @@ fsConvertRow(struct converter * const converterP, unsigned int limitcol; unsigned int col; - + for (col = 0; col < converterP->cols + 2; ++col) nexterr[col] = 0.0; @@ -494,18 +554,18 @@ fsConvertRow(struct converter * const converterP, nexterr[col ] += (accum * 3) / 16; nexterr[col + 1] += (accum * 5) / 16; nexterr[col + 2] += (accum * 1) / 16; - + ++col; } else { thiserr[col ] += (accum * 7) / 16; nexterr[col + 2] += (accum * 3) / 16; nexterr[col + 1] += (accum * 5) / 16; nexterr[col ] += (accum * 1) / 16; - + --col; } } while (col != limitcol); - + stateP->thiserr = nexterr; stateP->nexterr = thiserr; stateP->fs_forward = ! stateP->fs_forward; @@ -584,7 +644,7 @@ struct atkinsonState { static void moveAtkinsonErrorWindowDown(struct converter * const converterP) { - + struct atkinsonState * const stateP = converterP->stateP; float * const oldError0 = stateP->error[0]; @@ -628,7 +688,7 @@ atkinsonConvertRow(struct converter * const converterP, accum -= stateP->white; } else bitrow[col] = blackTuple; - + /* Forward to future output pixels 3/4 of the power from current input pixel and the power forwarded from previous input pixels to the current pixel, less any power we put into the @@ -642,7 +702,7 @@ atkinsonConvertRow(struct converter * const converterP, error[1][col+1] += accum/8; error[2][col ] += accum/8; } - + moveAtkinsonErrorWindowDown(converterP); } @@ -670,7 +730,7 @@ createAtkinsonConverter(struct pam * const graypamP, struct atkinsonState * stateP; struct converter converter; unsigned int relRow; - + converter.cols = graypamP->width; converter.convertRow = &atkinsonConvertRow; converter.destroy = &atkinsonDestroy; @@ -710,7 +770,7 @@ threshConvertRow(struct converter * const converterP, unsigned int const row, tuplen grayrow[], tuple bitrow[]) { - + struct threshState * const stateP = converterP->stateP; unsigned int col; @@ -740,7 +800,7 @@ createThreshConverter(struct pam * const graypamP, converter.cols = graypamP->width; converter.convertRow = &threshConvertRow; converter.destroy = &threshDestroy; - + stateP->threshval = threshFraction; converter.stateP = stateP; @@ -768,7 +828,7 @@ clusterConvertRow(struct converter * const converterP, unsigned int col; for (col = 0; col < converterP->cols; ++col) { - float const threshold = + float const threshold = stateP->clusterMatrix[row % diameter][col % diameter]; bitrow[col] = grayrow[col][0] > threshold ? whiteTuple : blackTuple; @@ -789,7 +849,7 @@ clusterDestroy(struct converter * const converterP) { free(stateP->clusterMatrix[row]); free(stateP->clusterMatrix); - + free(stateP); } @@ -799,14 +859,14 @@ static struct converter createClusterConverter(struct pam * const graypamP, enum ditherType const ditherType, unsigned int const radius) { - + /* TODO: We create a floating point normalized, gamma-adjusted - dither matrix from the old integer dither matrices that were + dither matrix from the old integer dither matrices that were developed for use with integer arithmetic. We really should just change the literal values in dither.h instead of computing the matrix from the integer literal values here. */ - + int const clusterNormalizer = radius * radius * 2; unsigned int const diameter = 2 * radius; @@ -827,16 +887,16 @@ createClusterConverter(struct pam * const graypamP, unsigned int col; MALLOCARRAY_NOFAIL(stateP->clusterMatrix[row], diameter); - + for (col = 0; col < diameter; ++col) { switch (ditherType) { - case DT_REGULAR: + case DT_REGULAR: switch (radius) { - case 8: - stateP->clusterMatrix[row][col] = + case 8: + stateP->clusterMatrix[row][col] = pm_gamma709((float)dither8[row][col] / 256); break; - default: + default: pm_error("INTERNAL ERROR: invalid radius"); } break; @@ -849,13 +909,13 @@ createClusterConverter(struct pam * const graypamP, default: pm_error("INTERNAL ERROR: invalid radius"); } - stateP->clusterMatrix[row][col] = + stateP->clusterMatrix[row][col] = pm_gamma709((float)val / clusterNormalizer); } break; } } - } + } converter.stateP = stateP; @@ -891,7 +951,7 @@ main(int argc, char *argv[]) { pnm_readpaminit(ifP, &graypam, PAM_STRUCT_SIZE(tuple_type)); bitpam = makeOutputPam(graypam.width, graypam.height); - + pnm_writepaminit(&bitpam); switch (cmdline.halftone) { @@ -904,15 +964,15 @@ main(int argc, char *argv[]) { case QT_THRESH: converter = createThreshConverter(&graypam, cmdline.threshval); break; - case QT_DITHER8: - converter = createClusterConverter(&graypam, DT_REGULAR, 8); + case QT_DITHER8: + converter = createClusterConverter(&graypam, DT_REGULAR, 8); break; - case QT_CLUSTER: - converter = createClusterConverter(&graypam, - DT_CLUSTER, + case QT_CLUSTER: + converter = createClusterConverter(&graypam, + DT_CLUSTER, cmdline.clusterRadius); break; - case QT_HILBERT: + case QT_HILBERT: pm_error("INTERNAL ERROR: halftone is QT_HILBERT where it " "shouldn't be."); break; @@ -925,7 +985,7 @@ main(int argc, char *argv[]) { pnm_readpamrown(&graypam, grayrow); converter.convertRow(&converter, row, grayrow, bitrow); - + pnm_writepamrow(&bitpam, bitrow); } free(bitrow); diff --git a/editor/pamlevels.c b/editor/pamlevels.c index fbbb2c0b..a282751a 100644 --- a/editor/pamlevels.c +++ b/editor/pamlevels.c @@ -482,7 +482,7 @@ pamlevels(CmdlineInfo const cmdline) { static void freeCmdLineInfo(CmdlineInfo cmdline) { /*---------------------------------------------------------------------------- - Free any memory that has been dynamically allcoated in . + Free any memory that has been dynamically allocated in . -----------------------------------------------------------------------------*/ TransSet * const xxP = &cmdline.xlats; diff --git a/editor/pamperspective.c b/editor/pamperspective.c index a206b57f..a8b1cf8f 100644 --- a/editor/pamperspective.c +++ b/editor/pamperspective.c @@ -804,7 +804,7 @@ static void determine_world_parallelogram (world_data *const world, yw_lr = world->yi_lr * zw_lr; /* Now we introduce the margin. There are several ways the margin can be - defined. margin_spec keeps track of wether one of them has yet been + defined. margin_spec keeps track of whether one of them has yet been used. As long as margin_spec==FALSE, the variables top_margin to bottom_margin are not initialized! */ diff --git a/editor/pamthreshold.c b/editor/pamthreshold.c index 8d28bc4a..809d76d9 100644 --- a/editor/pamthreshold.c +++ b/editor/pamthreshold.c @@ -73,7 +73,7 @@ initRange(struct range * const rangeP) { rangeP->max = 0.0; } - + static void addToRange(struct range * const rangeP, @@ -89,7 +89,7 @@ static float spread(struct range const range) { assert(range.max >= range.min); - + return range.max - range.min; } @@ -120,12 +120,12 @@ parseGeometry(const char * const wxl, static void -parseCommandLine(int argc, +parseCommandLine(int argc, char ** argv, struct cmdlineInfo *cmdlineP ) { /*---------------------------------------------------------------------------- Parse program command line described in Unix standard form by argc - and argv. Return the information in the options as *cmdlineP. + and argv. Return the information in the options as *cmdlineP. If command line is internally inconsistent (invalid options, etc.), issue error message to stderr and abort program. @@ -145,7 +145,7 @@ parseCommandLine(int argc, MALLOCARRAY_NOFAIL(option_def, 100); /* define the options */ - OPTENT3(0, "simple", OPT_FLAG, NULL, + OPTENT3(0, "simple", OPT_FLAG, NULL, &cmdlineP->simple, 0); OPTENT3(0, "local", OPT_STRING, &localOpt, &localSpec, 0); @@ -155,7 +155,7 @@ parseCommandLine(int argc, &thresholdSpec, 0); OPTENT3(0, "contrast", OPT_FLOAT, &cmdlineP->contrast, &contrastSpec, 0); - OPTENT3(0, "verbose", OPT_FLAG, NULL, + OPTENT3(0, "verbose", OPT_FLAG, NULL, &cmdlineP->verbose, 0); /* set the defaults */ @@ -216,8 +216,8 @@ parseCommandLine(int argc, cmdlineP->inputFileName = "-"; else if (argc-1 == 1) cmdlineP->inputFileName = argv[1]; - else - pm_error("Progam takes at most 1 parameter: the file name. " + else + pm_error("Program takes at most 1 parameter: the file name. " "You specified %d", argc-1); } @@ -389,7 +389,7 @@ computeGlobalThreshold(struct pam * const inpamP, of the "k-means clustering algorithm." The article claims it's proven to converge, by the way. - We have an interation limit just as a safety net. + We have an iteration limit just as a safety net. This code originally implemented a rather different algorithm, while nonetheless carrying the comment that it implemented the @@ -524,7 +524,7 @@ thresholdLocalRow(struct pam * const inpamP, getLocalThreshold(inrows, inpamP->width, col, localWidth, windowHeight, cmdline.threshold, minSpread, globalThreshold, &threshold); - + thresholdPixel(outpamP, inrow[col], outrow[col], threshold); } } @@ -569,12 +569,12 @@ thresholdLocal(struct pam * const inpamP, unsigned int oddLocalWidth; unsigned int oddLocalHeight; unsigned int i; - + /* use a subimage with odd width and height to have a middle pixel */ if (cmdline.width % 2 == 0) oddLocalWidth = cmdline.width + 1; - else + else oddLocalWidth = cmdline.width; if (cmdline.height % 2 == 0) oddLocalHeight = cmdline.height + 1; @@ -616,7 +616,7 @@ thresholdLocal(struct pam * const inpamP, outpamP, outrow); pnm_writepamrow(outpamP, outrow); - + /* read next image line if available and necessary */ if (row + windowHeight / 2 >= nextRowToRead && nextRowToRead < inpamP->height) @@ -655,7 +655,7 @@ thresholdIterative(struct pam * const inpamP, int main(int argc, char **argv) { - FILE * ifP; + FILE * ifP; struct cmdlineInfo cmdline; struct pam inpam, outpam; int eof; /* No more images in input stream */ @@ -711,3 +711,6 @@ main(int argc, char **argv) { return 0; } + + + diff --git a/editor/pamundice.c b/editor/pamundice.c index dbe0a8df..60360f17 100644 --- a/editor/pamundice.c +++ b/editor/pamundice.c @@ -18,30 +18,28 @@ #include "nstring.h" #include "mallocvar.h" -#define MAXFILENAMELEN 80 - /* Maximum number of characters we accept in filenames */ - -struct cmdlineInfo { +struct CmdlineInfo { /* All the information the user supplied in the command line, in a form easy for the program to use. */ const char * inputFilePattern; - /* null-terminated string, max MAXFILENAMELEN-10 characters */ unsigned int across; unsigned int down; - unsigned int hoverlap; - unsigned int voverlap; + unsigned int hoverlap; + unsigned int voverlap; + const char * listfile; + unsigned int listfileSpec; unsigned int verbose; }; static void -parseCommandLine(int argc, char ** argv, - struct cmdlineInfo * const cmdlineP ) { +parseCommandLine(int argc, const char ** argv, + struct CmdlineInfo * const cmdlineP ) { /*---------------------------------------------------------------------------- parse program command line described in Unix standard form by argc - and argv. Return the information in the options as *cmdlineP. + and argv. Return the information in the options as *cmdlineP. If command line is internally inconsistent (invalid options, etc.), issue error message to stderr and abort program. @@ -53,7 +51,7 @@ parseCommandLine(int argc, char ** argv, /* Instructions to pm_optParseOptions3 on how to parse our options. */ optStruct3 opt; - + unsigned int acrossSpec, downSpec; unsigned int hoverlapSpec, voverlapSpec; unsigned int option_def_index; @@ -69,6 +67,8 @@ parseCommandLine(int argc, char ** argv, &hoverlapSpec, 0); OPTENT3(0, "voverlap", OPT_UINT, &cmdlineP->voverlap, &voverlapSpec, 0); + OPTENT3(0, "listfile", OPT_STRING, &cmdlineP->listfile, + &cmdlineP->listfileSpec, 0); OPTENT3(0, "verbose", OPT_FLAG, NULL, &cmdlineP->verbose, 0); @@ -76,13 +76,19 @@ parseCommandLine(int argc, char ** argv, opt.short_allowed = FALSE; /* We have no short (old-fashioned) options */ opt.allowNegNum = FALSE; /* We have no parms that are negative numbers */ - pm_optParseOptions3( &argc, argv, opt, sizeof(opt), 0 ); + pm_optParseOptions3( &argc, (char **)argv, opt, sizeof(opt), 0 ); /* Uses and sets argc, argv, and some of *cmdline_p and others. */ - if (!acrossSpec) + if (acrossSpec) { + if (cmdlineP->across == 0) + pm_error ("-across value must be positive"); + } else cmdlineP->across = 1; - - if (!downSpec) + + if (downSpec) { + if (cmdlineP->down == 0) + pm_error ("-down value must be positive"); + } else cmdlineP->down = 1; if (!hoverlapSpec) @@ -91,16 +97,23 @@ parseCommandLine(int argc, char ** argv, if (!voverlapSpec) cmdlineP->voverlap = 0; - if (argc-1 < 1) - pm_error("You must specify one argument: the input file name " - "pattern (e.g. 'myimage%%2a%%2d.pnm')"); - else { - cmdlineP->inputFilePattern = argv[1]; - - if (argc-1 > 1) - pm_error("Progam takes at most one parameter: input file name. " - "You specified %u", argc-1); + if (cmdlineP->listfileSpec) { + if (argc-1 > 0) + pm_error("Program takes no parameters when -listfile is " + "specified. You specified %u", argc-1); + else + cmdlineP->inputFilePattern = NULL; + } else { + if (argc-1 < 1) + pm_error("You must specify one argument, the input file name " + "pattern (e.g. 'myimage%%2a%%2d.pnm'), or -listfile"); + else if (argc-1 > 1) + pm_error("Program takes at most one parameter: " + "the input file name pattern. You specified %u", argc-1); + else + cmdlineP->inputFilePattern = argv[1]; } + free(option_def); } @@ -128,7 +141,7 @@ buffer_init(struct buffer * const bufferP) { static void buffer_term(struct buffer * const bufferP) { - + free(bufferP->string); } @@ -184,7 +197,7 @@ getPrecision(const char * const pattern, inCursor = startInCursor; /* Start right after the '%' */ precision = 0; - + while (isdigit(pattern[inCursor])) { precision = 10 * precision + digitValue(pattern[inCursor]); ++inCursor; @@ -202,13 +215,24 @@ getPrecision(const char * const pattern, +typedef struct { + /* Context of % substitutions as we progress through a file name pattern */ + bool downSub; + /* There has been a %d (down) substitution */ + bool acrossSub; + /* There has been a %a (across) substitution */ +} SubstContext; + + + static void doSubstitution(const char * const pattern, unsigned int const startInCursor, unsigned int const rank, unsigned int const file, struct buffer * const bufferP, - unsigned int * const newInCursorP) { + unsigned int * const newInCursorP, + SubstContext * const substContextP) { unsigned int inCursor; @@ -219,7 +243,7 @@ doSubstitution(const char * const pattern, ++inCursor; } else { unsigned int precision; - + getPrecision(pattern, inCursor, &precision, &inCursor); if (pattern[inCursor] == '\0') @@ -232,16 +256,28 @@ doSubstitution(const char * const pattern, switch (pattern[inCursor]) { case 'a': - pm_asprintf(&substString, "%0*u", precision, file); - pm_asprintf(&desc, "file (across)"); + if (substContextP->acrossSub) + pm_error("Format specifier 'a' appears more than " + "once in input file pattern '%s'", pattern); + else { + pm_asprintf(&substString, "%0*u", precision, file); + pm_asprintf(&desc, "file (across)"); + substContextP->acrossSub = true; + } break; case 'd': - pm_asprintf(&substString, "%0*u", precision, rank); - pm_asprintf(&desc, "rank (down)"); + if (substContextP->downSub) + pm_error("Format specifier 'd' appears more than " + "once in input file pattern '%s'", pattern); + else { + pm_asprintf(&substString, "%0*u", precision, rank); + pm_asprintf(&desc, "rank (down)"); + substContextP->downSub = true; + } break; default: pm_error("Unknown format specifier '%c' in input file " - "pattern '%s'. Recognized format specifier s are " + "pattern '%s'. Recognized format specifiers are " "'%%a' (across) and '%%d (down)'", pattern[inCursor], pattern); } @@ -252,7 +288,7 @@ doSubstitution(const char * const pattern, desc, (unsigned)strlen(substString), precision); else buffer_addString(bufferP, substString); - + pm_strfree(desc); pm_strfree(substString); @@ -268,25 +304,32 @@ static void computeInputFileName(const char * const pattern, unsigned int const rank, unsigned int const file, - const char ** const fileNameP) { + const char ** const fileNameP, + bool * const rankFileIndependentP) { struct buffer buffer; unsigned int inCursor; + SubstContext substContext; buffer_init(&buffer); inCursor = 0; + substContext.downSub = 0; + substContext.acrossSub = 0; while (pattern[inCursor] != '\0') { if (pattern[inCursor] == '%') { ++inCursor; - doSubstitution(pattern, inCursor, rank, file, &buffer, &inCursor); + doSubstitution(pattern, inCursor, rank, file, &buffer, &inCursor, + &substContext); } else buffer_addChar(&buffer, pattern[inCursor++]); } + *rankFileIndependentP = !substContext.downSub && !substContext.acrossSub; + pm_asprintf(fileNameP, "%s", buffer.string); buffer_term(&buffer); @@ -295,8 +338,127 @@ computeInputFileName(const char * const pattern, + +static void +createInFileListFmFile(const char * const listFile, + unsigned int const nRank, + unsigned int const nFile, + const char *** const inputFileListP) { + + FILE * const lfP = pm_openr(listFile); + unsigned int const fileCt = nRank * nFile; + + const char ** inputFileList; + unsigned int fileSeq; + + MALLOCARRAY_NOFAIL(inputFileList, nRank * nFile); + + for (fileSeq = 0; fileSeq < fileCt; ) { + int eof; + size_t lineLen; + char * buf = NULL; /* initial value */ + size_t bufferSz = 0; /* initial value */ + + pm_getline(lfP, &buf, &bufferSz, &eof, &lineLen); + + if (eof) + pm_error("Premature EOF reading list file. " + "Read %u files. Should be %u.", fileSeq, fileCt); + else if (lineLen > 0) { + inputFileList[fileSeq] = buf; + ++fileSeq; + } + } + pm_close(lfP); + + *inputFileListP = inputFileList; + +} + + + +static void +createInFileListFmPattern(const char * const pattern, + unsigned int const nRank, + unsigned int const nFile, + const char *** const inputFileListP) { + + const char ** inputFileList; + unsigned int rank, file; + bool warnedSingleFile; + + MALLOCARRAY_NOFAIL(inputFileList, nRank * nFile); + + for (rank = 0, warnedSingleFile = false; rank < nRank ; ++rank) { + for (file = 0; file < nFile ; ++file) { + const unsigned int idx = rank * nFile + file; + + bool fileNmIsRankFileIndependent; + + computeInputFileName(pattern, rank, file, &inputFileList[idx], + &fileNmIsRankFileIndependent); + + if (fileNmIsRankFileIndependent && !warnedSingleFile) { + pm_message("Warning: No grid location (%%a/%%d) specified " + "in input file pattern '%s'. " + "Input is single file", pattern); + warnedSingleFile = true; + } + } + } + *inputFileListP = inputFileList; +} + + + +static void +destroyInFileList(const char ** const inputFileList, + unsigned int const nRank, + unsigned int const nFile) { + + unsigned int const fileCt = nRank * nFile; + + unsigned int fileSeq; + + for (fileSeq = 0; fileSeq < fileCt; ++fileSeq) + pm_strfree(inputFileList[fileSeq]); + + free(inputFileList); +} + + + +typedef struct { + unsigned int nRank; /* Number of images in the vertical direction */ + unsigned int nFile; /* Number of images in the horizontal direction */ + unsigned int hoverlap; /* horizontal overlap */ + unsigned int voverlap; /* vertical overlap */ + const char ** list; /* List (1-dimensional array) of filenames */ + /* Row-major, top to bottom, left to right */ +} InputFiles; + + + +static const char * +inputFileName(InputFiles const inputFiles, + unsigned int const rank, + unsigned int const file) { +/*---------------------------------------------------------------------------- + A selected entry from "inputFiles.list" based on "rank" and "file". + + Currently we assume that the list is a one-dimensional represetation + of an array, row-major, top to bottom and left to right in each row. +----------------------------------------------------------------------------*/ + assert(rank < inputFiles.nRank); + assert(file < inputFiles.nFile); + + return inputFiles.list[rank * inputFiles.nFile + file]; +} + + + static void -getCommonInfo(const char * const inputFilePattern, +getCommonInfo(InputFiles const inputFiles, int * const formatP, unsigned int * const depthP, sample * const maxvalP, @@ -306,16 +468,12 @@ getCommonInfo(const char * const inputFilePattern, among all input images and the output image. I.e. everything except width and height. -----------------------------------------------------------------------------*/ - const char * fileName; - /* Name of top left input image */ FILE * ifP; /* Top left input image stream */ struct pam inpam00; /* Description of top left input image */ - computeInputFileName(inputFilePattern, 0, 0, &fileName); - - ifP = pm_openr(fileName); + ifP = pm_openr(inputFileName(inputFiles, 0, 0)); pnm_readpaminit(ifP, &inpam00, PAM_STRUCT_SIZE(tuple_type)); @@ -325,40 +483,19 @@ getCommonInfo(const char * const inputFilePattern, strcpy(tupleType, inpam00.tuple_type); pm_close(ifP); - - pm_strfree(fileName); } -static FILE * -openInputImage(const char * const inputFilePattern, - unsigned int const rank, - unsigned int const file) { - - FILE * retval; - const char * fileName; - - computeInputFileName(inputFilePattern, rank, file, &fileName); - - retval = pm_openr(fileName); - - pm_strfree(fileName); - - return retval; -} - - - static void -getImageInfo(const char * const inputFilePattern, +getImageInfo(InputFiles const inputFiles, unsigned int const rank, unsigned int const file, struct pam * const pamP) { FILE * ifP; - ifP = openInputImage(inputFilePattern, rank, file); + ifP = pm_openr(inputFileName(inputFiles, rank, file)); pnm_readpaminit(ifP, pamP, PAM_STRUCT_SIZE(tuple_type)); @@ -369,76 +506,70 @@ getImageInfo(const char * const inputFilePattern, static void -getOutputWidth(const char * const inputFilePattern, - unsigned int const nFile, - unsigned int const hoverlap, - int * const widthP) { +getOutputWidth(InputFiles const inputFiles, + int * const widthP) { /*---------------------------------------------------------------------------- - Get the output width by adding up the widths of all 'nFile' images of - the top rank, and allowing for overlap of 'hoverlap' pixels. + Get the output width by adding up the widths of all 'inputFiles.nFile' + images of the top rank, and allowing for overlap of 'inputFiles.hoverlap' + pixels. -----------------------------------------------------------------------------*/ - unsigned int totalWidth; + double totalWidth; unsigned int file; - for (file = 0, totalWidth = 0; file < nFile; ++file) { + for (file = 0, totalWidth = 0; file < inputFiles.nFile; ++file) { struct pam inpam; - getImageInfo(inputFilePattern, 0, file, &inpam); + getImageInfo(inputFiles, 0, file, &inpam); - if (inpam.width < hoverlap) + if (inpam.width < inputFiles.hoverlap) pm_error("Rank 0, file %u image has width %u, " "which is less than the horizontal overlap of %u pixels", - file, inpam.width, hoverlap); + file, inpam.width, inputFiles.hoverlap); else { totalWidth += inpam.width; - if (file < nFile-1) - totalWidth -= hoverlap; + if (file < inputFiles.nFile-1) + totalWidth -= inputFiles.hoverlap; } } - *widthP = totalWidth; + *widthP = (int) totalWidth; } static void -getOutputHeight(const char * const inputFilePattern, - unsigned int const nRank, - unsigned int const voverlap, - int * const heightP) { +getOutputHeight(InputFiles const inputFiles, + int * const heightP) { /*---------------------------------------------------------------------------- - Get the output height by adding up the widths of all 'nRank' images of - the left file, and allowing for overlap of 'voverlap' pixels. + Get the output height by adding up the widths of all 'inputFiles.nRank' + images of the left file, and allowing for overlap of 'inputFiles.voverlap' + pixels. -----------------------------------------------------------------------------*/ - unsigned int totalHeight; + double totalHeight; unsigned int rank; - for (rank = 0, totalHeight = 0; rank < nRank; ++rank) { + for (rank = 0, totalHeight = 0; rank < inputFiles.nRank; ++rank) { struct pam inpam; - getImageInfo(inputFilePattern, rank, 0, &inpam); + getImageInfo(inputFiles, rank, 0, &inpam); - if (inpam.height < voverlap) + if (inpam.height < inputFiles.voverlap) pm_error("Rank %u, file 0 image has height %u, " "which is less than the vertical overlap of %u pixels", - rank, inpam.height, voverlap); - + rank, inpam.height, inputFiles.voverlap); + totalHeight += inpam.height; - - if (rank < nRank-1) - totalHeight -= voverlap; + + if (rank < inputFiles.nRank-1) + totalHeight -= inputFiles.voverlap; } - *heightP = totalHeight; + *heightP = (int) totalHeight; } static void -initOutpam(const char * const inputFilePattern, - unsigned int const nFile, - unsigned int const nRank, - unsigned int const hoverlap, - unsigned int const voverlap, +initOutpam(InputFiles const inputFiles, FILE * const ofP, bool const verbose, struct pam * const outpamP) { @@ -447,10 +578,10 @@ initOutpam(const char * const inputFilePattern, *outpamP. Do this by examining the top rank and left file of the input images, - which are in files named by 'inputFilePattern', 'nFile', and 'nRank'. + which are in 'inputFiles.list'. - In computing dimensions, assume 'hoverlap' pixels of horizontal - overlap and 'voverlap' pixels of vertical overlap. + In computing dimensions, assume 'inputFiles.hoverlap' pixels of horizontal + overlap and 'inputFiles.voverlap' pixels of vertical overlap. We overlook any inconsistencies among the images. E.g. if two images have different depths, we just return one of them. If two images in @@ -459,23 +590,23 @@ initOutpam(const char * const inputFilePattern, Therefore, Caller must check all the input images to make sure they are consistent with the information we return. -----------------------------------------------------------------------------*/ - assert(nFile >= 1); - assert(nRank >= 1); + assert(inputFiles.nFile >= 1); + assert(inputFiles.nRank >= 1); outpamP->size = sizeof(*outpamP); outpamP->len = PAM_STRUCT_SIZE(tuple_type); outpamP->file = ofP; outpamP->plainformat = 0; - - getCommonInfo(inputFilePattern, &outpamP->format, &outpamP->depth, + + getCommonInfo(inputFiles, &outpamP->format, &outpamP->depth, &outpamP->maxval, outpamP->tuple_type); - getOutputWidth(inputFilePattern, nFile, hoverlap, &outpamP->width); + getOutputWidth(inputFiles, &outpamP->width); - getOutputHeight(inputFilePattern, nRank, voverlap, &outpamP->height); + getOutputHeight(inputFiles, &outpamP->height); if (verbose) { - pm_message("Output width = %u pixels", outpamP->width); + pm_message("Output width = %u pixels", outpamP->width); pm_message("Output height = %u pixels", outpamP->height); } } @@ -485,53 +616,50 @@ initOutpam(const char * const inputFilePattern, static void openInStreams(struct pam inpam[], unsigned int const rank, - unsigned int const fileCount, - char const inputFilePattern[]) { + InputFiles const inputFiles) { /*---------------------------------------------------------------------------- Open the input files for a single horizontal slice (there's one file for each vertical slice) and read the Netpbm headers from them. Return the pam structures to describe each as inpam[]. - Open the files for horizontal slice number 'rank', assuming there are - 'fileCount' vertical slices (so open 'fileCount' files). Use - inputFilePattern[] with each rank and file number to compute the name of - each file. + Open the files for horizontal slice number 'rank', as described by + 'inputFiles'. -----------------------------------------------------------------------------*/ unsigned int file; - for (file = 0; file < fileCount; ++file) { - FILE * const ifP = openInputImage(inputFilePattern, rank, file); + for (file = 0; file < inputFiles.nFile; ++file) { + FILE * const ifP = pm_openr(inputFileName(inputFiles, rank, file)); pnm_readpaminit(ifP, &inpam[file], PAM_STRUCT_SIZE(tuple_type)); - } + } } static void closeInFiles(struct pam pam[], - unsigned int const fileCount) { + unsigned int const fileCt) { /*---------------------------------------------------------------------------- - Close the 'fileCount' input file streams represented by pam[]. + Close the 'fileCt' input file streams represented by pam[]. -----------------------------------------------------------------------------*/ - unsigned int file; - - for (file = 0; file < fileCount; ++file) - pm_close(pam[file].file); + unsigned int fileSeq; + + for (fileSeq = 0; fileSeq < fileCt; ++fileSeq) + pm_close(pam[fileSeq].file); } static void -assembleRow(tuple outputRow[], - struct pam inpam[], - unsigned int const fileCount, +assembleRow(tuple outputRow[], + struct pam inpam[], + unsigned int const fileCt, unsigned int const hOverlap) { /*---------------------------------------------------------------------------- - Assemble the row outputRow[] from the 'fileCount' input files + Assemble the row outputRow[] from the 'fileCt' input files described out inpam[]. - 'hOverlap', which is meaningful only when fileCount is greater than 1, + 'hOverlap', which is meaningful only when 'fileCt' is greater than 1, is the amount by which files overlap each other. We assume every input image is at least that wide. @@ -539,19 +667,17 @@ assembleRow(tuple outputRow[], entire assembly. -----------------------------------------------------------------------------*/ tuple * inputRow; - unsigned int file; + unsigned int fileSeq; - for (file = 0, inputRow = &outputRow[0]; - file < fileCount; - ++file) { + for (fileSeq = 0, inputRow = &outputRow[0]; fileSeq < fileCt; ++fileSeq) { - unsigned int const overlap = file == fileCount - 1 ? 0 : hOverlap; + unsigned int const overlap = fileSeq == fileCt - 1 ? 0 : hOverlap; - assert(hOverlap <= inpam[file].width); + assert(hOverlap <= inpam[fileSeq].width); - pnm_readpamrow(&inpam[file], inputRow); + pnm_readpamrow(&inpam[fileSeq], inputRow); - inputRow += inpam[file].width - overlap; + inputRow += inpam[fileSeq].width - overlap; } } @@ -574,6 +700,7 @@ allocInpam(unsigned int const rankCount, + static void verifyRankFileAttributes(struct pam * const inpam, unsigned int const nFile, @@ -622,7 +749,7 @@ verifyRankFileAttributes(struct pam * const inpam, rank, file, inpamP->height, inpam[0].height); else { totalWidth += inpamP->width; - + if (file < nFile-1) totalWidth -= hoverlap; } @@ -637,11 +764,7 @@ verifyRankFileAttributes(struct pam * const inpam, static void assembleTiles(struct pam * const outpamP, - const char * const inputFilePattern, - unsigned int const nFile, - unsigned int const nRank, - unsigned int const hoverlap, - unsigned int const voverlap, + InputFiles const inputFiles, struct pam inpam[], tuple * const tuplerow) { @@ -649,12 +772,17 @@ assembleTiles(struct pam * const outpamP, /* Number of the current rank (horizontal slice). Ranks are numbered sequentially starting at 0. */ - + + unsigned int const nRank = inputFiles.nRank; + unsigned int const nFile = inputFiles.nFile; + unsigned int const hoverlap = inputFiles.hoverlap; + unsigned int const voverlap = inputFiles.voverlap; + for (rank = 0; rank < nRank; ++rank) { unsigned int row; unsigned int rankHeight; - openInStreams(inpam, rank, nFile, inputFilePattern); + openInStreams(inpam, rank, inputFiles); verifyRankFileAttributes(inpam, nFile, outpamP, hoverlap, rank); @@ -672,36 +800,47 @@ assembleTiles(struct pam * const outpamP, int -main(int argc, char ** argv) { +main(int argc, const char ** argv) { - struct cmdlineInfo cmdline; + struct CmdlineInfo cmdline; + InputFiles inputFiles; struct pam outpam; struct pam * inpam; /* malloc'ed. inpam[x] is the pam structure that controls the - current rank of file x. + current rank of file x. */ tuple * tuplerow; - pnm_init(&argc, argv); - + pm_proginit(&argc, argv); + parseCommandLine(argc, argv, &cmdline); - + allocInpam(cmdline.across, &inpam); - initOutpam(cmdline.inputFilePattern, cmdline.across, cmdline.down, - cmdline.hoverlap, cmdline.voverlap, stdout, cmdline.verbose, - &outpam); - + if (cmdline.listfileSpec) + createInFileListFmFile(cmdline.listfile, + cmdline.down, cmdline.across, + &inputFiles.list); + else + createInFileListFmPattern(cmdline.inputFilePattern, + cmdline.down, cmdline.across, + &inputFiles.list); + + inputFiles.nFile = cmdline.across; + inputFiles.nRank = cmdline.down; + inputFiles.hoverlap = cmdline.hoverlap; + inputFiles.voverlap = cmdline.voverlap; + + initOutpam(inputFiles, stdout, cmdline.verbose, &outpam); + tuplerow = pnm_allocpamrow(&outpam); pnm_writepaminit(&outpam); - assembleTiles(&outpam, - cmdline.inputFilePattern, cmdline.across, cmdline.down, - cmdline.hoverlap, cmdline.voverlap, inpam, tuplerow); + assembleTiles(&outpam, inputFiles, inpam, tuplerow); pnm_freepamrow(tuplerow); - + destroyInFileList(inputFiles.list, inputFiles.nRank, inputFiles.nFile); free(inpam); return 0; diff --git a/editor/pgmmedian.c b/editor/pgmmedian.c index 4648af68..cdd94629 100644 --- a/editor/pgmmedian.c +++ b/editor/pgmmedian.c @@ -1,4 +1,4 @@ -/* +/* ** Version 1.0 September 28, 1996 ** ** Copyright (C) 1996 by Mike Burns @@ -15,11 +15,11 @@ /* References ** ---------- -** The select k'th value implementation is based on Algorithm 489 by +** The select k'th value implementation is based on Algorithm 489 by ** Robert W. Floyd from the "Collected Algorithms from ACM" Volume II. ** ** The histogram sort is based is described in the paper "A Fast Two- -** Dimensional Median Filtering Algorithm" in "IEEE Transactions on +** Dimensional Median Filtering Algorithm" in "IEEE Transactions on ** Acoustics, Speech, and Signal Processing" Vol. ASSP-27, No. 1, February ** 1979. The algorithm I more closely followed is found in "Digital ** Image Processing Algorithms" by Ioannis Pitas. @@ -189,12 +189,11 @@ selectMedian(FILE * const ifP, unsigned int const numValues = crows * ccols; unsigned int col; - gray * garray; - /* Array of the currenty gray values */ + gray * garray; /* Array of the currently gray values */ int * parray; int * subcol; gray ** rowptr; - + garray = pgm_allocrow(numValues); MALLOCARRAY(rowptr, crows); @@ -212,7 +211,7 @@ selectMedian(FILE * const ifP, int crow; int rownum, irow, temprow; unsigned int col; - + pgm_readpgmrow(ifP, grays[row % crows], cols, maxval, format); /* Rotate pointers to rows, so rows can be accessed in order. */ @@ -334,7 +333,7 @@ histogramSortMedian(FILE * const ifP, for (mdn = 0; ltmdn <= median; ++mdn) ltmdn += hist[mdn]; --mdn; - if (ltmdn > median) + if (ltmdn > median) ltmdn -= hist[mdn]; grayrow[col] = mdn; @@ -374,7 +373,7 @@ histogramSortMedian(FILE * const ifP, ++mdn; } --mdn; - if (ltmdn > median) + if (ltmdn > median) ltmdn -= hist[mdn]; } grayrow[col] = mdn; @@ -410,7 +409,7 @@ main(int argc, pgm_init(&argc, argv); parseCommandLine(argc, argv, &cmdline); - + ifP = pm_openr(cmdline.inputFileName); ccolso2 = cmdline.width / 2; @@ -446,7 +445,7 @@ main(int argc, case SELECT_MEDIAN: selectMedian(ifP, cmdline.width, cmdline.height, cols, rows, median); break; - + case HISTOGRAM_SORT_MEDIAN: histogramSortMedian(ifP, cmdline.width, cmdline.height, cols, rows, median); @@ -454,7 +453,7 @@ main(int argc, case MEDIAN_UNSPECIFIED: pm_error("INTERNAL ERROR: median unspecified"); } - + pm_close(ifP); pm_close(stdout); @@ -463,3 +462,6 @@ main(int argc, return 0; } + + + diff --git a/editor/pnmcat.c b/editor/pnmcat.c index a26dcf3e..565ecceb 100644 --- a/editor/pnmcat.c +++ b/editor/pnmcat.c @@ -358,9 +358,9 @@ getPbmImageInfo(struct imgInfo const img[], case JUST_MAX: img2[i].padtop = newrows - img[i].rows; break; case JUST_CENTER: img2[i].padtop = (newrows - img[i].rows) / 2; break; } - + img2[i].offset = (i == 0) ? 0 : img2[i-1].offset + img[i-1].cols; - + if (img[i].rows == newrows) /* no padding */ img2[i].proberow = NULL; else { /* determine pad color for image i */ @@ -414,13 +414,13 @@ concatenateLeftRightPbm(FILE * const ofP, unsigned int const newcols, unsigned int const newrows, enum justification const justification, - struct imgInfo const img[], + struct imgInfo const img[], enum backcolor const backcolor) { unsigned char * const outrow = pbm_allocrow_packed(newcols); /* We use just one outrow. All padding and image data (with the - exeption of following img2.proberow) goes directly into this - packed PBM row. + exception of following img2.proberow) goes directly into this + packed PBM row. */ struct imgInfoPbm2 * img2; @@ -496,7 +496,7 @@ concatenateTopBottomPbm(FILE * const ofP, unsigned int i; unsigned int row, startRow; - + outrow[pbm_packed_bytes(newcols)-1] = 0x00; switch (backcolor){ @@ -525,7 +525,7 @@ concatenateTopBottomPbm(FILE * const ofP, bit bgBit; startRow = 1; - + pbm_readpbmrow_bitoffset(img[i].ifP, outrow, img[i].cols, img[i].format, padleft); @@ -544,23 +544,23 @@ concatenateTopBottomPbm(FILE * const ofP, if (backChange || (i > 0 && img[i-1].cols > img[i].cols)) { unsigned int const padright = newcols - padleft - img[i].cols; - + if (padleft > 0) padFillBitrow(outrow, background, padleft, 0); - - if (padright > 0) + + if (padright > 0) padFillBitrow(outrow, background, padright, padleft + img[i].cols); - + } } - + if (startRow == 1) /* Top row already read for auto background color determination. Write it out. */ pbm_writepbmrow_packed(ofP, outrow, newcols, 0); - + for (row = startRow; row < img[i].rows; ++row) { pbm_readpbmrow_bitoffset(img[i].ifP, outrow, img[i].cols, img[i].format, padleft); @@ -685,7 +685,7 @@ concatenateLeftRightGen(FILE * const ofP, unsigned int col; for (col = 0; col < img[i].cols; ++col) img2[i].inrow[col] = img2[i].xelrow[col]; - + free(img2[i].xelrow); } else if (row >= img2[i].padtop && row < img2[i].padtop + img[i].rows) { @@ -745,7 +745,7 @@ concatenateTopBottomGen(FILE * const ofP, startRow = 0; backChange = FALSE; inrow = newxelrow; - } else { /* Calculate left padding amount */ + } else { /* Calculate left padding amount */ switch (justification) { case JUST_MIN: padleft = 0; break; case JUST_MAX: padleft = newcols - img[i].cols; break; @@ -869,3 +869,6 @@ main(int argc, return 0; } + + + diff --git a/editor/pnmconvol.c b/editor/pnmconvol.c index b1d8e025..fcd52bea 100644 --- a/editor/pnmconvol.c +++ b/editor/pnmconvol.c @@ -1314,7 +1314,7 @@ computeInitialColumnSums(struct pam * const pamP, sample ** const convColumnSum) { /*---------------------------------------------------------------------------- Add up the sum of each column of window[][], whose rows are described - by *inpamP. The window's height is that of tthe convolution kernel + by *inpamP. The window's height is that of the convolution kernel *convKernelP. Return it as convColumnSum[][]. @@ -1854,7 +1854,7 @@ convolveHorizontalRowPlane(struct pam * const pamP, pamP->maxval); } else if (col == ccolso2) { unsigned int const leftcol = 0; - /* Window is up againt left edge of image */ + /* Window is up against left edge of image */ { unsigned int ccol; @@ -2019,7 +2019,7 @@ convolveVerticalRowPlane(struct pam * const pamP, if (col == ccolso2) { unsigned int const leftcol = 0; - /* Convolution window is againt left edge of image */ + /* Convolution window is against left edge of image */ unsigned int ccol; diff --git a/editor/pnmcrop.c b/editor/pnmcrop.c index 6ef1c280..5e74190f 100644 --- a/editor/pnmcrop.c +++ b/editor/pnmcrop.c @@ -1136,7 +1136,7 @@ extremeCrops(struct CmdlineInfo const cmdline, pm_message("Input image has no distinction between " "border and content"); - /* We can't just pick a representive pixel, say top-left corner. + /* We can't just pick a representative pixel, say top-left corner. If -top and/or -bottom was specified but not -left and -right, the output should be one row, not a single pixel. diff --git a/editor/pnmgamma.c b/editor/pnmgamma.c index b357b0d8..1fdf20eb 100644 --- a/editor/pnmgamma.c +++ b/editor/pnmgamma.c @@ -602,7 +602,7 @@ createGammaTables(enum transferFunction const transferFunction, if (*rtableP == NULL || *gtableP == NULL || *btableP == NULL) pm_error("Can't get memory to make gamma transfer tables"); - /* Build the gamma corection tables. */ + /* Build the gamma correction tables. */ switch (transferFunction) { case XF_BT709RAMP: { buildBt709Gamma(*rtableP, maxval, newMaxval, rgamma); diff --git a/editor/pnmnlfilt.c b/editor/pnmnlfilt.c index f55a67bd..bcb3680d 100644 --- a/editor/pnmnlfilt.c +++ b/editor/pnmnlfilt.c @@ -59,9 +59,9 @@ struct cmdlineInfo { }; -static void -parseCommandLine(int argc, - char ** argv, +static void +parseCommandLine(int argc, + char ** argv, struct cmdlineInfo * const cmdlineP) { if (argc-1 < 2) @@ -75,9 +75,9 @@ parseCommandLine(int argc, if (sscanf( argv[2], "%lf", &cmdlineP->radius ) != 1) pm_error("Invalid radius (2nd) argument '%s'. " - "Must be a decimal number", + "Must be a decimal number", argv[2]); - + if ((cmdlineP->alpha > -0.1 && cmdlineP->alpha < 0.0) || (cmdlineP->alpha > 0.5 && cmdlineP->alpha < 1.0)) pm_error( "Alpha must be in range 0.0 <= alpha <= 0.5 " @@ -118,11 +118,11 @@ parseCommandLine(int argc, this value. */ -#define MXIVAL PPM_MAXMAXVAL +#define MXIVAL PPM_MAXMAXVAL -xelval omaxval; +xelval omaxval; /* global so that pixel processing code can get at it quickly */ -int noisevariance; +int noisevariance; /* global so that pixel processing code can get at it quickly */ /* @@ -157,7 +157,7 @@ static xelval maxval; /* round and scale floating point to scaled integer */ #define ROUNDSCALE(x) ((int)(((x) * (double)SCALE) + 0.5)) /* round and un-scale scaled integer value */ -#define RUNSCALE(x) (((x) + (1 << (SCALEB-1))) >> SCALEB) +#define RUNSCALE(x) (((x) + (1 << (SCALEB-1))) >> SCALEB) /* rounded un-scale */ #define UNSCALE(x) ((x) >> SCALEB) @@ -194,9 +194,9 @@ int AVEDIV[7 * NOCSVAL]; /* divide by 7 to give average value */ int SQUARE[2 * NOCSVAL]; /* scaled square lookup table */ /* ************************************************** * - Hexagon intersecting square area functions - Compute the area of the intersection of a triangle - and a rectangle + Hexagon intersecting square area functions + Compute the area of the intersection of a triangle + and a rectangle ************************************************** */ /* Triangle orientation is per geometric axes (not graphical axies) */ @@ -210,7 +210,7 @@ int SQUARE[2 * NOCSVAL]; /* scaled square lookup table */ #define SWAPI(a,b) (t = a, a = -b, b = -t) -static double +static double triang_area(double rx0, double ry0, double rx1, double ry1, double tx0, double ty0, double tx1, double ty1, int tt) { @@ -250,7 +250,7 @@ triang_area(double rx0, double ry0, double rx1, double ry1, a = tx0 - b * ty0; d = (ty1 - ty0)/(tx1 - tx0); c = ty0 - d * tx0; - + /* compute top or right intersection */ tt = 0; ly1 = ry1; @@ -278,7 +278,7 @@ triang_area(double rx0, double ry0, double rx1, double ry1, return (rx1 - rx0) * (ry1 - ry0); tt |= 2; /* bottom intersection */ } - + if (tt == 0) { /* top and left intersection */ /* rectangle minus triangle */ @@ -293,7 +293,7 @@ triang_area(double rx0, double ry0, double rx1, double ry1, return ((rx1 - lx1) * (ry1 - ry0)) + (0.5 * (lx1 - lx0) * (ry1 - ry0)); } else { - /* tt == 3 */ + /* tt == 3 */ /* right and bottom intersection */ /* triangle */ return (0.5 * (rx1 - lx0) * (ly1 - ry0)); @@ -303,7 +303,7 @@ triang_area(double rx0, double ry0, double rx1, double ry1, static double -rectang_area(double rx0, double ry0, double rx1, double ry1, +rectang_area(double rx0, double ry0, double rx1, double ry1, double tx0, double ty0, double tx1, double ty1) { /* Compute rectangle area */ /* rx0,ry0,rx1,ry1: rectangle boundaries */ @@ -326,7 +326,7 @@ rectang_area(double rx0, double ry0, double rx1, double ry1, -static double +static double hex_area(double sx, double sy, double hx, double hy, double d) { /* compute the area of overlap of a hexagon diameter d, */ /* centered at hx,hy, with a unit square of center sx,sy. */ @@ -384,7 +384,7 @@ setupSquare(void) { for (i=0; i < (2 * NOCSVAL); ++i) { /* compute square and rescale by (val >> (2 * SCALEB + 2)) table */ - int const val = CSCTOSC(i - NOCSVAL); + int const val = CSCTOSC(i - NOCSVAL); /* NOCSVAL offset to cope with -ve input values */ SQUARE[i] = (val * val) >> (2 * SCALEB + 2); } @@ -414,7 +414,7 @@ setup1(double const alpha, *mmeanscaleP = *meanscaleP = maxscale/noinmean; if (alpha == 0.0) { - /* mean filter */ + /* mean filter */ *alpharangeP = 0; *alphafractionP = 0.0; /* not used */ } else if (alpha < (1.0/6.0)) { @@ -438,9 +438,9 @@ setup1(double const alpha, double const noinmean = 7.0; *alpharangeP = 5; /* edge enhancement function */ *mmeanscaleP = *meanscaleP = maxscale; /* compute scaled hex values */ - *alphafractionP = 1.0/noinmean; + *alphafractionP = 1.0/noinmean; /* Set up 1:1 division lookup - not used */ - *noisevarianceP = sqr(alphaNormalized * omaxval) / 8.0; + *noisevarianceP = sqr(alphaNormalized * omaxval) / 8.0; /* estimate of noise variance */ } else if (alpha >= -0.9 && alpha <= -0.1) { /* edge enhancement function */ @@ -449,7 +449,7 @@ setup1(double const alpha, *alpharangeP = 4; /* edge enhancement function */ *meanscaleP = maxscale * (-posAlpha/((1.0 - posAlpha) * 7.0)); /* mean of 7 and scaled by -posAlpha/(1-posAlpha) */ - *mmeanscaleP = maxscale * (1.0/(1.0 - posAlpha) + *meanscaleP); + *mmeanscaleP = maxscale * (1.0/(1.0 - posAlpha) + *meanscaleP); /* middle pixel has 1/(1-posAlpha) as well */ *alphafractionP = 0.0; /* not used */ } else { @@ -481,18 +481,18 @@ setupPixelWeightingTables(double const radius, double const mmeanscale) { /* Setup pixel weighting tables - note we pre-compute mean - division here too. + division here too. */ - double const hexhoff = radius/2; + double const hexhoff = radius/2; /* horizontal offset of vertical hex centers */ - double const hexvoff = 3.0 * radius/sqrt(12.0); + double const hexvoff = 3.0 * radius/sqrt(12.0); /* vertical offset of vertical hex centers */ double const tabscale = meanscale / (radius * hexvoff); double const mtabscale = mmeanscale / (radius * hexvoff); /* scale tables to normalize by hexagon area, and number of - hexes used in mean + hexes used in mean */ double const v0 = hex_area(0.0, 0.0, hexhoff, hexvoff, radius) * tabscale; @@ -538,7 +538,7 @@ setupPixelWeightingTables(double const radius, /* Table initialization function - return alpha range */ -static int +static int atfilt_setup(double const alpha, double const radius, double const maxscale) { @@ -546,7 +546,7 @@ atfilt_setup(double const alpha, int alpharange; /* alpha range value 0 - 5 */ double meanscale; /* scale for finding mean */ double mmeanscale; /* scale for finding mean - midle hex */ - double alphafraction; + double alphafraction; /* fraction of next largest/smallest to subtract from sum */ setup1(alpha, radius, maxscale, @@ -562,7 +562,7 @@ atfilt_setup(double const alpha, -static int +static int atfilt0(int * p) { /* Core pixel processing function - hand it 3x3 pixels and return result. */ /* Mean filter */ @@ -586,7 +586,7 @@ atfilt0(int * p) { else if (xx < small) \ small = xx; } -static int +static int atfilt1(int * p) { /* Mean of 5 - 7 middle values */ /* 'p' is 9 pixel values from 3x3 neighbors */ @@ -635,7 +635,7 @@ atfilt1(int * p) { } -static int +static int atfilt2(int *p) { /* Mean of 3 - 5 middle values */ /* 'p' is 9 pixel values from 3x3 neighbors */ @@ -708,10 +708,10 @@ atfilt2(int *p) { small2 = xx; \ }} -static int +static int atfilt3(int *p) { /* Mean of 1 - 3 middle values. If only 1 value, then this is a median - filter. + filter. */ /* 'p' is pixel values from 3x3 neighbors */ int h0,h1,h2,h3,h4,h5,h6; /* hexagon values 2 3 */ @@ -737,12 +737,12 @@ atfilt3(int *p) { CHECK(h5); CHECK(h6); /* Compute mean of middle 1-3 values */ - return UNSCALE(h0 -big0 -big1 -small0 -small1 + return UNSCALE(h0 -big0 -big1 -small0 -small1 -ALFRAC[(big2 + small2)>>SCALEB]); } #undef CHECK -static int +static int atfilt4(int *p) { /* Edge enhancement */ /* notice we use the global omaxval */ @@ -765,7 +765,7 @@ atfilt4(int *p) { return hav; } -static int +static int atfilt5(int *p) { /* Optimal estimation - do smoothing in inverse proportion */ /* to the local variance. */ @@ -786,19 +786,19 @@ atfilt5(int *p) { h6 = V0[p[0]] + V1[p[7]] + V2[p[8]] + V3[p[1]]; mean = h0 + h1 + h2 + h3 + h4 + h5 + h6; mean = AVEDIV[SCTOCSC(mean)]; /* compute scaled mean by dividing by 7 */ - temp = (h1 - mean); variance = SQUARE[NOCSVAL + SCTOCSC(temp)]; + temp = (h1 - mean); variance = SQUARE[NOCSVAL + SCTOCSC(temp)]; /* compute scaled variance */ - temp = (h2 - mean); variance += SQUARE[NOCSVAL + SCTOCSC(temp)]; + temp = (h2 - mean); variance += SQUARE[NOCSVAL + SCTOCSC(temp)]; /* and rescale to keep */ - temp = (h3 - mean); variance += SQUARE[NOCSVAL + SCTOCSC(temp)]; + temp = (h3 - mean); variance += SQUARE[NOCSVAL + SCTOCSC(temp)]; /* within 32 bit limits */ temp = (h4 - mean); variance += SQUARE[NOCSVAL + SCTOCSC(temp)]; temp = (h5 - mean); variance += SQUARE[NOCSVAL + SCTOCSC(temp)]; temp = (h6 - mean); variance += SQUARE[NOCSVAL + SCTOCSC(temp)]; - temp = (h0 - mean); variance += SQUARE[NOCSVAL + SCTOCSC(temp)]; + temp = (h0 - mean); variance += SQUARE[NOCSVAL + SCTOCSC(temp)]; /* (temp = h0 - mean) */ if (variance != 0) /* avoid possible divide by 0 */ - temp = mean + (variance * temp) / (variance + noisevariance); + temp = mean + (variance * temp) / (variance + noisevariance); /* optimal estimate */ else temp = h0; if (temp < 0) @@ -811,17 +811,17 @@ atfilt5(int *p) { -static void +static void do_one_frame(FILE * const ifP) { pnm_writepnminit( stdout, cols, rows, omaxval, oformat, 0 ); - + if ( PNM_FORMAT_TYPE(oformat) == PPM_TYPE ) { int pr[9],pg[9],pb[9]; /* 3x3 neighbor pixel values */ int r,g,b; for ( row = 0; row < rows; row++ ) { - int po,no; /* offsets for left and right colums in 3x3 */ + int po,no; /* offsets for left and right columns in 3x3 */ xel *ip0, *ip1, *ip2, *op; if (row == 0) { @@ -897,14 +897,14 @@ do_one_frame(FILE * const ifP) { promote = ( PNM_FORMAT_TYPE(format) != PNM_FORMAT_TYPE(oformat) ); for ( row = 0; row < rows; row++ ) { - int po,no; /* offsets for left and right colums in 3x3 */ + int po,no; /* offsets for left and right columns in 3x3 */ xel *ip0, *ip1, *ip2, *op; if (row == 0) { irow0 = irow1; pnm_readpnmrow( ifP, irow1, cols, maxval, format ); if ( promote ) - pnm_promoteformatrow( irow1, cols, maxval, + pnm_promoteformatrow( irow1, cols, maxval, format, maxval, oformat ); } if (row == (rows-1)) @@ -912,7 +912,7 @@ do_one_frame(FILE * const ifP) { else { pnm_readpnmrow( ifP, irow2, cols, maxval, format ); if ( promote ) - pnm_promoteformatrow( irow2, cols, maxval, + pnm_promoteformatrow( irow2, cols, maxval, format, maxval, oformat ); } @@ -955,7 +955,7 @@ do_one_frame(FILE * const ifP) { static void -verifySame(unsigned int const imageSeq, +verifySame(unsigned int const imageSeq, int const imageCols, int const imageRows, xelval const imageMaxval, int const imageFormat, int const cols, int const rows, @@ -1000,16 +1000,16 @@ main(int argc, char *argv[]) { ifP = pm_openr(cmdline.inputFileName); pnm_readpnminit(ifP, &cols, &rows, &maxval, &format); - - if (maxval > MXIVAL) + + if (maxval > MXIVAL) pm_error("The maxval of the input image (%d) is too large.\n" - "This program's limit is %d.", + "This program's limit is %d.", maxval, MXIVAL); - + oformat = PNM_FORMAT_TYPE(format); /* force output to max precision without forcing new 2-byte format */ omaxval = MIN(maxval, PPM_MAXMAXVAL); - + atfunc = atfuncs[atfilt_setup(cmdline.alpha, cmdline.radius, (double)omaxval/(double)maxval)]; @@ -1038,7 +1038,7 @@ main(int argc, char *argv[]) { int imageFormat; ++imageSeq; - pnm_readpnminit(ifP, &imageCols, &imageRows, + pnm_readpnminit(ifP, &imageCols, &imageRows, &imageMaxval, &imageFormat); verifySame(imageSeq, imageCols, imageRows, imageMaxval, imageFormat, @@ -1054,3 +1054,6 @@ main(int argc, char *argv[]) { return 0; } + + + diff --git a/editor/pnmnorm.c b/editor/pnmnorm.c index 2f9a6b20..e0fe0e35 100644 --- a/editor/pnmnorm.c +++ b/editor/pnmnorm.c @@ -274,7 +274,8 @@ minimumValue(const unsigned int * const hist, foundOne = true; else { if (i == highest) - pm_error("INTERNAL ERROR in '%s'. No pixels", __FUNCTION__); + pm_error("INTERNAL ERROR in function 'minimumValue'. " + "No pixels"); else ++i; } @@ -296,7 +297,8 @@ maximumValue(const unsigned int * const hist, foundOne = true; else { if (i == 0) - pm_error("INTERNAL ERROR in '%s'. No pixels", __FUNCTION__); + pm_error("INTERNAL ERROR in function 'maximumValue'. " + "No pixels"); else --i; } diff --git a/editor/pnmquantall b/editor/pnmquantall index d268227d..aea6cc84 100755 --- a/editor/pnmquantall +++ b/editor/pnmquantall @@ -205,7 +205,6 @@ if (!defined($colorMapFh)) { if (!$progError) { makeColorMap(\@fileNames, $newColorCt, $colorMapFileName, \$progError); } -print ("got color map\n"); if (!$progError) { remapFiles(\@fileNames, $colorMapFileName, $ext, \$progError); } diff --git a/editor/pnmshear.c b/editor/pnmshear.c index c705c261..45d74c6f 100644 --- a/editor/pnmshear.c +++ b/editor/pnmshear.c @@ -54,7 +54,7 @@ parseCommandLine(int argc, const char ** argv, OPTENT3(0, "noantialias", OPT_FLAG, NULL, &cmdlineP->noantialias, 0); OPTENT3(0, "background", OPT_STRING, &cmdlineP->background, &backgroundSpec, 0); - + opt.opt_table = option_def; opt.short_allowed = FALSE; opt.allowNegNum = TRUE; @@ -106,21 +106,21 @@ makeNewXel(xel * const outputXelP, switch (PNM_FORMAT_TYPE(format)) { case PPM_TYPE: PPM_ASSIGN(*outputXelP, - (fracnew0 * PPM_GETR(prevXel) - + omfracnew0 * PPM_GETR(curXel) + (fracnew0 * PPM_GETR(prevXel) + + omfracnew0 * PPM_GETR(curXel) + HALFSCALE) / SCALE, - (fracnew0 * PPM_GETG(prevXel) - + omfracnew0 * PPM_GETG(curXel) + (fracnew0 * PPM_GETG(prevXel) + + omfracnew0 * PPM_GETG(curXel) + HALFSCALE) / SCALE, - (fracnew0 * PPM_GETB(prevXel) - + omfracnew0 * PPM_GETB(curXel) + (fracnew0 * PPM_GETB(prevXel) + + omfracnew0 * PPM_GETB(curXel) + HALFSCALE) / SCALE ); break; - + default: PNM_ASSIGN1(*outputXelP, - (fracnew0 * PNM_GET1(prevXel) - + omfracnew0 * PNM_GET1(curXel) + (fracnew0 * PNM_GET1(prevXel) + + omfracnew0 * PNM_GET1(curXel) + HALFSCALE) / SCALE ); break; } @@ -130,9 +130,9 @@ makeNewXel(xel * const outputXelP, static void shearRow(xel * const xelrow, - unsigned int const cols, + unsigned int const cols, xel * const newxelrow, - unsigned int const newcols, + unsigned int const newcols, double const shearCols, int const format, xel const bgxel, @@ -140,7 +140,7 @@ shearRow(xel * const xelrow, /*---------------------------------------------------------------------------- Shear the row 'xelrow' by 'shearCols' columns, and return the result as 'newxelrow'. They are 'cols' and 'newcols' columns wide, respectively. - + Fill in the part of the output row that doesn't contain image data with 'bgxel'. @@ -152,14 +152,14 @@ shearRow(xel * const xelrow, unsigned int const intShearCols = (unsigned int) shearCols; assert(shearCols >= 0.0); - + if (antialias) { const long fracnew0 = (shearCols - intShearCols) * SCALE; const long omfracnew0 = SCALE - fracnew0; unsigned int col; xel prevXel; - + for (col = 0; col < newcols; ++col) newxelrow[col] = bgxel; @@ -170,7 +170,7 @@ shearRow(xel * const xelrow, format); prevXel = xelrow[col]; } - if (fracnew0 > 0) + if (fracnew0 > 0) /* Need to add a column for what's left over */ makeNewXel(&newxelrow[intShearCols + cols], bgxel, prevXel, fracnew0, omfracnew0, format); @@ -197,7 +197,7 @@ backgroundColor(const char * const backgroundColorName, if (backgroundColorName) { retval = pnm_parsecolorxel(backgroundColorName, maxval, format); - } else + } else retval = pnm_backgroundxelrow(topRow, cols, maxval, format); return retval; @@ -212,10 +212,13 @@ main(int argc, const char * argv[]) { xel * xelrow; xel * newxelrow; xel bgxel; - int rows, cols, format; - int newformat, newcols; - int row; - xelval maxval, newmaxval; + int rows, cols; + int format; + unsigned int newcols; + int newformat; + unsigned int row; + xelval maxval; + xelval newmaxval; double shearfac; double newcolsD; @@ -230,6 +233,16 @@ main(int argc, const char * argv[]) { pnm_readpnminit(ifP, &cols, &rows, &maxval, &format); xelrow = pnm_allocrow(cols); + shearfac = tan(cmdline.angle); + + newcolsD = (double) rows * fabs(shearfac) + cols + 0.999999; + if (newcolsD > INT_MAX-2) + pm_error("angle is too close to +/-90 degrees; " + "output image too wide for computation"); + else + newcols = (unsigned int) newcolsD; + + /* Promote PBM files to PGM. */ if (!cmdline.noantialias && PNM_FORMAT_TYPE(format) == PBM_TYPE) { newformat = PGM_TYPE; @@ -241,18 +254,9 @@ main(int argc, const char * argv[]) { newmaxval = maxval; } - shearfac = fabs(tan(cmdline.angle)); - - newcolsD = (double) rows * shearfac + cols + 0.999999; - if (newcolsD > INT_MAX-2) - pm_error("angle is too close to +/-90 degrees; " - "output image too wide for computation"); - else - newcols = (int) newcolsD; - pnm_writepnminit(stdout, newcols, rows, newmaxval, newformat, 0); newxelrow = pnm_allocrow(newcols); - + for (row = 0; row < rows; ++row) { double shearCols; @@ -262,17 +266,17 @@ main(int argc, const char * argv[]) { bgxel = backgroundColor(cmdline.background, xelrow, cols, newmaxval, format); - if (cmdline.angle > 0.0) + if (shearfac > 0.0) shearCols = row * shearfac; else - shearCols = (rows - row) * shearfac; + shearCols = (rows - row) * -shearfac; - shearRow(xelrow, cols, newxelrow, newcols, + shearRow(xelrow, cols, newxelrow, newcols, shearCols, format, bgxel, !cmdline.noantialias); pnm_writepnmrow(stdout, newxelrow, newcols, newmaxval, newformat, 0); } - + pm_close(ifP); pm_close(stdout); diff --git a/editor/pnmstitch.c b/editor/pnmstitch.c index eae5e1b9..4c4c708a 100644 --- a/editor/pnmstitch.c +++ b/editor/pnmstitch.c @@ -20,7 +20,7 @@ * otherwise) arising in any way out of the use of this software, even if * advised of the possibility of such damage. * - * Any restrictions or encumberances added to this source code or derivitives, + * Any restrictions or encumberances added to this source code or derivatives, * is prohibited. * * Name: pnmstitch.c @@ -1116,7 +1116,7 @@ OutputAlloc(Output * const me, static void StraightThroughDeAlloc(Output * me) { - /* Trick the proper freeing of resouces on the Output Image */ + /* Trick the proper freeing of resources on the Output Image */ me->image->pam.height = 1; OutputDeAlloc(me); } /* StraightThroughDeAlloc() - end */ @@ -1131,7 +1131,7 @@ StraightThroughAlloc(Output * const me, if (OutputAlloc(me, file, width, height, prototype) == FALSE) { StraightThroughDeAlloc(me); } - /* Trick the proper allocation of resouces on the Output Image */ + /* Trick the proper allocation of resources on the Output Image */ me->image->pam.height = 1; me->image->tuple = pnm_allocpamarray(&me->image->pam); if (me->image->tuple == (tuple **)NULL) { diff --git a/editor/ppmshadow b/editor/ppmshadow index ae6b1b0f..c07c03b0 100755 --- a/editor/ppmshadow +++ b/editor/ppmshadow @@ -89,7 +89,7 @@ sub imageDimensions($) { sub backgroundColor($) { my ($fileName) = @_; #----------------------------------------------------------------------------- -# Return the color of the backround of the image in the file named $fileName. +# Return the color of the background of the image in the file named $fileName. #----------------------------------------------------------------------------- # We call the color of the top left pixel the background color. diff --git a/editor/specialty/pampaintspill.c b/editor/specialty/pampaintspill.c index eb1888f7..c7994723 100644 --- a/editor/specialty/pampaintspill.c +++ b/editor/specialty/pampaintspill.c @@ -281,7 +281,7 @@ euclideanDistanceSqr(const struct coords * const p0, unsigned int const width, unsigned int const height) { /*---------------------------------------------------------------------------- - Return the square of the Euclidian distance between p0 and p1. + Return the square of the Euclidean distance between p0 and p1. -----------------------------------------------------------------------------*/ double const deltax = (double) (int) (p1->x - p0->x); double const deltay = (double) (int) (p1->y - p0->y); @@ -299,7 +299,7 @@ euclideanDistanceTorusSqr(const struct coords * const p0, unsigned int const width, unsigned int const height) { /*---------------------------------------------------------------------------- - Return the square of the Euclidian distance between p0 and p1, assuming + Return the square of the Euclidean distance between p0 and p1, assuming it's a toroidal surface on which the top row curves around to meet the bottom and the left column to the right. -----------------------------------------------------------------------------*/ diff --git a/editor/specialty/pampop9.c b/editor/specialty/pampop9.c index d6c61e4f..b92c7d6b 100644 --- a/editor/specialty/pampop9.c +++ b/editor/specialty/pampop9.c @@ -25,9 +25,6 @@ #include "pam.h" -static const char * const copyright = - "(c) Robert Tinsley 2003 (http://www.thepoacher.net/contact)"; - static const char *usagestr = "pnmfile|- xtiles ytiles xdelta ydelta"; int main(int argc, char *argv[]) diff --git a/editor/specialty/pgmabel.c b/editor/specialty/pgmabel.c index 1a6e481f..aa748f88 100644 --- a/editor/specialty/pgmabel.c +++ b/editor/specialty/pgmabel.c @@ -44,7 +44,7 @@ static const char* const version="$VER: pgmabel 1.009 (24 Jan 2002)"; #include "pgm.h" #ifndef PID2 /* PI/2 (on AMIGA always defined) */ -#define PID2 1.57079632679489661923 +#define PID2 1.57079632679489661923 #endif @@ -59,7 +59,7 @@ static double *aldl, *ardl; /* pointer for weighting factors */ ** xr <- array of the calculated elements of the row ** adl <- pre-calculated surface coefficient for each segment */ -static double +static double Sum ( int n, double *xr, int N, double *adl) { int k; @@ -79,7 +79,7 @@ Sum ( int n, double *xr, int N, double *adl) ** R, N <- indizes of the coefficient ** r <- radial position of the center of the surface */ -static double +static double dr ( int R, double r, int N) { double a; @@ -95,7 +95,7 @@ dr ( int R, double r, int N) ** N <- width of the array ** adl <- array with pre-calculated weighting factors */ -static void +static void abel ( float *y, int N, double *adl) { register int n; @@ -127,7 +127,7 @@ abel ( float *y, int N, double *adl) /* ---------------------------------------------------------------------------- ** printing a help message if Option -h(elp) is chosen */ -static void +static void help() { pm_message("-----------------------------------------------------------------"); @@ -143,7 +143,7 @@ help() pm_message("| verbose : output of useful data |"); pm_message("| pgmfile : Name of a pgmfile (optional) |"); pm_message("| |"); - pm_message("| for further information please contact the manpage |"); + pm_message("| for further information please contact the manpage |"); pm_message("-----------------------------------------------------------------"); pm_message("%s",version); /* telling the version */ exit(-1); /* retur-code for no result */ @@ -268,11 +268,11 @@ int main( argc, argv ) } for (col = 0; col < (cols-midcol); ++col) /* factors for right side */ { - for (tc = 0; tc < (cols-midcol); ++tc) + for (tc = 0; tc < (cols-midcol); ++tc) ardl[col*(cols-midcol)+tc] = dr(col,tc+0.5,cols-midcol); } - /* abel-transformation for each row splitted in right and left side */ + /* abel-transformation for each row split into right and left side */ for ( row = 0; row < rows ; ++row ) { pgm_readpgmrow( ifp, grayorig, cols, maxval, format ); @@ -309,3 +309,5 @@ int main( argc, argv ) exit( 0 ); /* end of procedure */ } + + diff --git a/generator/pamtris/boundaries.c b/generator/pamtris/boundaries.c index 7045cbc7..cfcc4c1d 100644 --- a/generator/pamtris/boundaries.c +++ b/generator/pamtris/boundaries.c @@ -120,7 +120,7 @@ gen_triangle_boundaries(Xy const xy, } if (xy._[0][1] == xy._[1][1] && xy._[1][1] == xy._[2][1]) { - /* Triangle is degenarate: its visual representation consists only of + /* Triangle is degenerate: its visual representation consists only of a horizontal straight line. */ diff --git a/generator/pamtris/framebuffer.c b/generator/pamtris/framebuffer.c index 93263c91..5665e9a4 100644 --- a/generator/pamtris/framebuffer.c +++ b/generator/pamtris/framebuffer.c @@ -164,7 +164,7 @@ realloc_image_buffer(int32_t const new_maxval, function "process_next_command", which is the only function that calls this one. - If the function suceeds, the image buffer is left in cleared state. The + If the function succeeds, the image buffer is left in cleared state. The Z-Buffer, however, is not touched at all. If the new depth is equal to the previous one, no actual reallocation is @@ -313,7 +313,7 @@ draw_span(uint32_t const base, unsigned int l; /* The following statements will only have any effect if the depth - test, performed above, has suceeded. I. e. if the depth test fails, + test, performed above, has succeeded. I. e. if the depth test fails, no changes will be made on the frame buffer; otherwise, the frame buffer will be updated with the new values. */ diff --git a/generator/pbmtext.c b/generator/pbmtext.c index 6304c7d4..e52a296e 100644 --- a/generator/pbmtext.c +++ b/generator/pbmtext.c @@ -610,7 +610,7 @@ getCharsWithinWidth(PM_WCHAR const line[], if (currentWidth > targetWidth) { if (cursor == 1) pm_error("-width value too small " - "to accomodate single character"); + "to accommodate single character"); else *charCountP = cursor - 1; } else @@ -991,7 +991,7 @@ getText(PM_WCHAR const cmdlineText[], if (!buf) pm_error("Unable to allocate memory for up to %u characters of " "text", MAXLINECHARS); - buf[lineBufTerm] = L'\1'; /* Initalize to non-zero value */ + buf[lineBufTerm] = L'\1'; /* Initialize to non-zero value */ /* to detect input overrun */ maxlines = 50; /* initial value */ diff --git a/generator/pgmnoise.c b/generator/pgmnoise.c index 40d0e189..e3e4eca6 100644 --- a/generator/pgmnoise.c +++ b/generator/pgmnoise.c @@ -3,11 +3,12 @@ Frank Neumann, October 1993 *********************************************************************/ +#include #include "pm_c_util.h" #include "mallocvar.h" +#include "nstring.h" #include "shhopt.h" #include "pgm.h" -#include @@ -68,16 +69,24 @@ parseCommandLine(int argc, const char ** const argv, "Arguments are width and height of image, in pixels", argc-1); else { - int const width = atoi(argv[1]); - int const height = atoi(argv[2]); - - if (width <= 0) - pm_error("Width must be positive, not %d", width); + const char * error; /* error message of pm_string_to_uint */ + unsigned int width, height; + + pm_string_to_uint(argv[1], &width, &error); + if (error) + pm_error("Width argument is not an unsigned integer. %s", + error); + else if (width == 0) + pm_error("Width argument is zero; must be positive"); else cmdlineP->width = width; - if (height <= 0) - pm_error("Height must be positive, not %d", width); + pm_string_to_uint(argv[2], &height, &error); + if (error) + pm_error("Height argument is not an unsigned integer. %s ", + error); + else if (height == 0) + pm_error("Height argument is zero; must be positive"); else cmdlineP->height = height; } @@ -139,7 +148,7 @@ pgmnoise(FILE * const ofP, /* If maxval is 2^n-1, we draw exactly n bits from the pool. Otherwise call rand() and determine gray value by modulo. - In the latter case, there is a miniscule skew toward 0 (=black) + In the latter case, there is a minuscule skew toward 0 (=black) because smaller numbers are produced more frequently by modulo. Thus we employ the pool method only when it is certain that no skew will ensue. diff --git a/generator/ppmforge.c b/generator/ppmforge.c index fe80f529..8fec9fee 100644 --- a/generator/ppmforge.c +++ b/generator/ppmforge.c @@ -49,7 +49,7 @@ static double const hugeVal = 1e50; #define Real(v, x, y) v[1 + (((x) * meshsize) + (y)) * 2] #define Imag(v, x, y) v[2 + (((x) * meshsize) + (y)) * 2] -/* Co-ordinate indices within arrays. */ +/* Coordinate indices within arrays. */ typedef struct { double x; @@ -71,7 +71,7 @@ static int meshsize = 256; /* FFT mesh size */ static double inclangle, hourangle; /* Star position relative to planet */ static bool inclspec = FALSE; /* No inclination specified yet */ static bool hourspec = FALSE; /* No hour specified yet */ -static double icelevel; /* Ice cap theshold */ +static double icelevel; /* Ice cap threshold */ static double glaciers; /* Glacier level */ static int starfraction; /* Star fraction */ static int starcolor; /* Star color saturation */ diff --git a/lib/libpamcolor.c b/lib/libpamcolor.c index e1a24c66..718df89f 100644 --- a/lib/libpamcolor.c +++ b/lib/libpamcolor.c @@ -177,15 +177,15 @@ parseInteger(const char * const colorname, if (r > maxval) pm_error("Red value in color specification '%s' is %u, " - "whcih is invalid because the specified maxval is %u", + "which is invalid because the specified maxval is %u", colorname, r, maxval); if (g > maxval) pm_error("Green value in color specification '%s' is %u, " - "whcih is invalid because the specified maxval is %u", + "which is invalid because the specified maxval is %u", colorname, g, maxval); if (b > maxval) pm_error("Blue value in color specification '%s' is %u, " - "whcih is invalid because the specified maxval is %u", + "which is invalid because the specified maxval is %u", colorname, b, maxval); color[PAM_RED_PLANE] = (float)r/maxval; diff --git a/lib/libpamd.c b/lib/libpamd.c index 952150b4..2b9eb693 100644 --- a/lib/libpamd.c +++ b/lib/libpamd.c @@ -1,4 +1,4 @@ -/* +/* ** ** This library module contains the pamdraw routines. ** @@ -12,7 +12,7 @@ ** copyright notice and this permission notice appear in supporting ** documentation. This software is provided "as is" without express or ** implied warranty. -** +** ** The character drawing routines are by John Walker ** Copyright (C) 1994 by John Walker, kelvin@fourmilab.ch */ @@ -89,7 +89,7 @@ pointIsWithinBounds(pamd_point const p, return (p.x >= 0 && p.x < cols && p.y >= 0 && p.y < rows); } - + static pamd_point vectorSum(pamd_point const a, @@ -106,7 +106,7 @@ static long int const DDA_SCALE = 8192; /* Several factors govern the limit of x, y coordination values. - The limit must be representable as (signed) int for coordinates to + The limit must be representable as (signed) int for coordinates to be carried in struct penpos (immediately above). The following calculation, done with long ints, must not overflow: @@ -116,7 +116,7 @@ static long int const DDA_SCALE = 8192; dy = (y1 - y0) * DDA_SCALE / abs(x1 - x0); Overflow conditions for pamd_text are rather complicated, for commands - come from an external PPMD font file. See comments below. + come from an external PPMD font file. See comments below. */ @@ -145,11 +145,11 @@ pamd_validatePoint(pamd_point const p) { static void drawPoint(pamd_drawproc drawproc, const void * const clientdata, - tuple ** const tuples, - int const cols, - int const rows, - int const depth, - sample const maxval, + tuple ** const tuples, + int const cols, + int const rows, + int const depth, + sample const maxval, pamd_point const p) { /*---------------------------------------------------------------------------- Draw a single point, assuming that it is within the bounds of the @@ -171,16 +171,16 @@ drawPoint(pamd_drawproc drawproc, void -pamd_point_drawproc(tuple ** const tuples, - unsigned int const cols, - unsigned int const rows, - unsigned int const depth, - sample const maxval, +pamd_point_drawproc(tuple ** const tuples, + unsigned int const cols, + unsigned int const rows, + unsigned int const depth, + sample const maxval, pamd_point const p, const void * const clientdata) { unsigned int i; - + if ((p.x >= 0) && (p.x < cols) && (p.y >= 0) && (p.y < rows)) for (i = 0; i < depth; ++i) tuples[p.y][p.x][i] = (sample) *((tuple *) clientdata + i); @@ -216,15 +216,15 @@ findRectangleIntersection(struct rectangle const rect1, void -pamd_filledrectangle(tuple ** const tuples, - int const cols, - int const rows, - int const depth, - sample const maxval, - int const left, - int const top, - int const width, - int const height, +pamd_filledrectangle(tuple ** const tuples, + int const cols, + int const rows, + int const depth, + sample const maxval, + int const left, + int const top, + int const width, + int const height, pamd_drawproc drawProc, const void * const clientdata) { @@ -390,16 +390,16 @@ clipEnd1(pamd_point const p0, at 0. -----------------------------------------------------------------------------*/ pamd_point c1; - /* The current clipped location of p1; we clip it multile times + /* The current clipped location of p1; we clip it multiple times to get the final location. */ /* p0 is in the frame: */ assert(p0.x >= 0 && p0.x < cols); assert(p0.y >= 0 && p0.y < rows); - + /* Clip End 1 of the line horizontally */ c1 = p1; /* initial value */ - + if (c1.x < 0) { /* We know the line isn't vertical, since End 0 is in the frame and End 1 is left of frame. @@ -413,7 +413,7 @@ clipEnd1(pamd_point const p0, c1.y = c1.y + (p0.y - c1.y) * (cols - 1 - c1.x) / (p0.x - c1.x); c1.x = cols - 1; } - + /* Clip End 1 of the line vertically */ if (c1.y < 0) { /* We know the line isn't horizontal, since End 0 is in the frame @@ -477,11 +477,11 @@ clipLine(pamd_point const p0, static void drawShallowLine(pamd_drawproc drawProc, const void * const clientdata, - tuple ** const tuples, - int const cols, - int const rows, - int const depth, - sample const maxval, + tuple ** const tuples, + int const cols, + int const rows, + int const depth, + sample const maxval, pamd_point const p0, pamd_point const p1) { /*---------------------------------------------------------------------------- @@ -526,11 +526,11 @@ drawShallowLine(pamd_drawproc drawProc, static void drawSteepLine(pamd_drawproc drawProc, const void * const clientdata, - tuple ** const tuples, - int const cols, - int const rows, + tuple ** const tuples, + int const cols, + int const rows, int const depth, - sample const maxval, + sample const maxval, pamd_point const p0, pamd_point const p1) { /*---------------------------------------------------------------------------- @@ -574,11 +574,11 @@ drawSteepLine(pamd_drawproc drawProc, void -pamd_line(tuple ** const tuples, - int const cols, - int const rows, - int const depth, - sample const maxval, +pamd_line(tuple ** const tuples, + int const cols, + int const rows, + int const depth, + sample const maxval, pamd_point const p0, pamd_point const p1, pamd_drawproc drawProc, @@ -639,11 +639,11 @@ distanceFromLine(pamd_point const p, void -pamd_spline3(tuple ** const tuples, - int const cols, - int const rows, - int const depth, - sample const maxval, +pamd_spline3(tuple ** const tuples, + int const cols, + int const rows, + int const depth, + sample const maxval, pamd_point const p0, pamd_point const ctl, pamd_point const p1, @@ -679,11 +679,11 @@ pamd_spline3(tuple ** const tuples, void -pamd_polyspline(tuple ** const tuples, - unsigned int const cols, - unsigned int const rows, - unsigned int const depth, - sample const maxval, +pamd_polyspline(tuple ** const tuples, + unsigned int const cols, + unsigned int const rows, + unsigned int const depth, + sample const maxval, pamd_point const p0, unsigned int const nc, pamd_point * const c, @@ -692,7 +692,7 @@ pamd_polyspline(tuple ** const tuples, const void * const clientdata) { pamd_point p; - + unsigned int i; assert(nc > 0); @@ -713,11 +713,11 @@ pamd_polyspline(tuple ** const tuples, void -pamd_spline4(tuple ** const tuples, - unsigned int const cols, - unsigned int const rows, - unsigned int const depth, - sample const maxval, +pamd_spline4(tuple ** const tuples, + unsigned int const cols, + unsigned int const rows, + unsigned int const depth, + sample const maxval, pamd_point const endPt0, pamd_point const endPt1, pamd_point const ctlPt0, @@ -739,13 +739,13 @@ pamd_spline4(tuple ** const tuples, void -pamd_circle(tuple ** const tuples, - unsigned int const cols, - unsigned int const rows, - unsigned int const depth, - sample const maxval, +pamd_circle(tuple ** const tuples, + unsigned int const cols, + unsigned int const rows, + unsigned int const depth, + sample const maxval, pamd_point const center, - unsigned int const radius, + unsigned int const radius, pamd_drawproc drawProc, const void * const clientData) { /*---------------------------------------------------------------------------- @@ -755,7 +755,7 @@ pamd_circle(tuple ** const tuples, it might maintain state that is affected by imaginary points outside the image. - Initial point is 3 o'clock. + Initial point is 3 o'clock. -----------------------------------------------------------------------------*/ if (radius >= DDA_SCALE) pm_error("Error drawing circle. Radius %d is too large.", radius); @@ -869,11 +869,11 @@ pamd_fill_create(void) { stateP->curedge = 0; fillObjP->stateP = stateP; - + /* Turn off line clipping. */ /* UGGH! We must eliminate this global variable */ oldclip = pamd_setlineclip(0); - + return fillObjP; } @@ -969,11 +969,11 @@ continueSegment(struct fillState * const stateP, */ void -pamd_fill_drawproc(tuple ** const tuples, - unsigned int const cols, - unsigned int const rows, - unsigned int const depth, - sample const maxval, +pamd_fill_drawproc(tuple ** const tuples, + unsigned int const cols, + unsigned int const rows, + unsigned int const depth, + sample const maxval, pamd_point const p, const void * const clientdata) { @@ -1029,7 +1029,7 @@ yxCompare(const void * const c1Arg, pamd_point const p2 = c2P->point; int retval; - + if (p1.y > p2.y) retval = 1; else if (p1.y < p2.y) @@ -1047,15 +1047,15 @@ yxCompare(const void * const c1Arg, void -pamd_fill(tuple ** const tuples, - int const cols, - int const rows, - int const depth, - sample const maxval, +pamd_fill(tuple ** const tuples, + int const cols, + int const rows, + int const depth, + sample const maxval, struct fillobj * const fillObjP, pamd_drawproc drawProc, const void * const clientdata) { - + struct fillState * const fh = fillObjP->stateP; int pedge; @@ -1222,7 +1222,7 @@ icos(int const deg) { times the cosine -----------------------------------------------------------------------------*/ return isin(deg + 90); -} +} @@ -1294,7 +1294,7 @@ textPosFromFontPos(pamd_point const fontPos, /* Position relative to the top left of the whole text box, assuming the text box is horizontal and has font scale. */ - + pamd_point const ps = makePoint((pl.x * (int)height) / Scalef, (pl.y * (int)height) / Scalef); /* Same as above, but with the text box its actual size */ @@ -1344,7 +1344,7 @@ drawGlyph(const struct ppmd_glyph * const glyphP, text box, in the coordinate system of the canvas. 'rotcos' and 'rotsin' tell how that text box is rotated with respect to the horizontal on the canvas. - + 'height' is the height in canvas tuples of a glyph. This is a scale factor to convert font coordinates to canvas coordinates. -----------------------------------------------------------------------------*/ @@ -1384,7 +1384,7 @@ drawGlyph(const struct ppmd_glyph * const glyphP, glyphOrigin, height, rotcos, rotsin); - + pamd_line(tuples, cols, rows, depth, maxval, p, n, drawProc, clientdata); @@ -1407,15 +1407,15 @@ drawGlyph(const struct ppmd_glyph * const glyphP, void -pamd_text(tuple** const tuples, - int const cols, - int const rows, - int const depth, - sample const maxval, +pamd_text(tuple** const tuples, + int const cols, + int const rows, + int const depth, + sample const maxval, pamd_point const pos, - int const height, - int const angle, - const char * const sArg, + int const height, + int const angle, + const char * const sArg, pamd_drawproc drawProc, const void * const clientdata) { /*---------------------------------------------------------------------------- @@ -1451,7 +1451,7 @@ pamd_text(tuple** const tuples, unsigned int cursorAdvance; - pamd_validatePoint(p); + pamd_validatePoint(p); drawGlyph(glyphP, p, tuples, cols, rows, depth, maxval, height, pos, rotcos, rotsin, @@ -1471,12 +1471,12 @@ pamd_text(tuple** const tuples, static pamd_drawproc extetnsDrawproc; #endif -static void -extentsDrawproc(tuple** const tuples, - unsigned int const cols, +static void +extentsDrawproc(tuple** const tuples, + unsigned int const cols, unsigned int const rows, unsigned int const depth, - sample const maxval, + sample const maxval, pamd_point const p, const void * const clientdata) { /*---------------------------------------------------------------------------- @@ -1492,12 +1492,12 @@ extentsDrawproc(tuple** const tuples, void -pamd_text_box(int const height, - int const angle, - const char * const s, - int * const leftP, - int * const topP, - int * const rightP, +pamd_text_box(int const height, + int const angle, + const char * const s, + int * const leftP, + int * const topP, + int * const rightP, int * const bottomP) { /*---------------------------------------------------------------------------- Calculate extents rectangle for a given piece of text. For most @@ -1511,10 +1511,10 @@ pamd_text_box(int const height, extbottom = -32767; pamd_text(NULL, 32767, 32767, 255, 255, makePoint(1000, 1000), - height, angle, s, + height, angle, s, extentsDrawproc, NULL); - *leftP = extleft - 1000; + *leftP = extleft - 1000; *topP = exttop - 1000; *rightP = extright - 1000; *bottomP = extbottom - 1000; diff --git a/lib/libpammap.c b/lib/libpammap.c index 22224913..569156fe 100644 --- a/lib/libpammap.c +++ b/lib/libpammap.c @@ -64,7 +64,7 @@ pnm_createtuplehash(void) { pm_error("Out of memory allocating tuple hash of size %u", HASH_SIZE); - for (i = 0; i < HASH_SIZE; ++i) + for (i = 0; i < HASH_SIZE; ++i) retval[i] = NULL; return retval; @@ -82,13 +82,13 @@ pnm_destroytuplehash(tuplehash const tuplehash) { for (i = 0; i < HASH_SIZE; ++i) { struct tupleint_list_item * p; struct tupleint_list_item * next; - + /* Walk this chain, freeing each element */ for (p = tuplehash[i]; p; p = next) { next = p->next; free(p); - } + } } /* Free the table of chains */ @@ -98,18 +98,18 @@ pnm_destroytuplehash(tuplehash const tuplehash) { -static struct tupleint_list_item * +static struct tupleint_list_item * allocTupleIntListItem(struct pam * const pamP) { - /* This is complicated by the fact that the last element of a + /* This is complicated by the fact that the last element of a tupleint_list_item is of variable length, because the last element - of _it_ is of variable length + of _it_ is of variable length */ struct tupleint_list_item * retval; - unsigned int const size = - sizeof(*retval) - sizeof(retval->tupleint.tuple) + unsigned int const size = + sizeof(*retval) - sizeof(retval->tupleint.tuple) + pamP->depth * sizeof(sample); retval = (struct tupleint_list_item *) malloc(size); @@ -121,7 +121,7 @@ allocTupleIntListItem(struct pam * const pamP) { void pnm_addtotuplehash(struct pam * const pamP, - tuplehash const tuplehash, + tuplehash const tuplehash, tuple const tupletoadd, int const value, int * const fitsP) { @@ -138,7 +138,7 @@ pnm_addtotuplehash(struct pam * const pamP, *fitsP = FALSE; else { unsigned int const hashvalue = pnm_hashtuple(pamP, tupletoadd); - + *fitsP = TRUE; pnm_assigntuple(pamP, listItemP->tupleint.tuple, tupletoadd); @@ -151,10 +151,10 @@ pnm_addtotuplehash(struct pam * const pamP, void -pnm_lookuptuple(struct pam * const pamP, - const tuplehash tuplehash, - const tuple searchval, - int * const foundP, +pnm_lookuptuple(struct pam * const pamP, + const tuplehash tuplehash, + const tuple searchval, + int * const foundP, int * const retvalP) { /*---------------------------------------------------------------------------- Return as *revtvalP the index of the tuple value 'searchval' in the @@ -183,18 +183,18 @@ pnm_lookuptuple(struct pam * const pamP, static void -addColorOccurrenceToHash(tuple const color, +addColorOccurrenceToHash(tuple const color, tuplehash const tuplefreqhash, struct pam * const pamP, unsigned int const maxsize, unsigned int * const sizeP, bool * const fullP) { - + unsigned int const hashvalue = pnm_hashtuple(pamP, color); - + struct tupleint_list_item *p; - for (p = tuplefreqhash[hashvalue]; + for (p = tuplefreqhash[hashvalue]; p && !pnm_tupleequal(pamP, p->tupleint.tuple, color); p = p->next); @@ -205,7 +205,7 @@ addColorOccurrenceToHash(tuple const color, } else { /* It's not in the hash yet, so add it (if allowed) */ ++(*sizeP); - if (maxsize > 0 && *sizeP > maxsize) + if (maxsize > 0 && *sizeP > maxsize) *fullP = TRUE; else { *fullP = FALSE; @@ -228,7 +228,7 @@ pnm_addtuplefreqoccurrence(struct pam * const pamP, tuplehash const tuplefreqhash, int * const firstOccurrenceP) { /*---------------------------------------------------------------------------- - Tally one more occurence of the tuple value 'value' to the tuple frequencey + Tally one more occurrence of the tuple value 'value' to the tuple frequency hash 'tuplefreqhash', adding the tuple to the hash if it isn't there already. @@ -238,10 +238,10 @@ pnm_addtuplefreqoccurrence(struct pam * const pamP, program. -----------------------------------------------------------------------------*/ unsigned int const hashvalue = pnm_hashtuple(pamP, value); - + struct tupleint_list_item * p; - for (p = tuplefreqhash[hashvalue]; + for (p = tuplefreqhash[hashvalue]; p && !pnm_tupleequal(pamP, p->tupleint.tuple, value); p = p->next); @@ -270,8 +270,8 @@ pnm_addtuplefreqoccurrence(struct pam * const pamP, static void computehashrecoverable(struct pam * const pamP, - tuple ** const tupleArray, - unsigned int const maxsize, + tuple ** const tupleArray, + unsigned int const maxsize, unsigned int const newDepth, sample const newMaxval, unsigned int * const sizeP, @@ -295,20 +295,20 @@ computehashrecoverable(struct pam * const pamP, *tuplefreqhashP = pnm_createtuplehash(); *sizeP = 0; /* initial value */ - + *rowbufferP = pnm_allocpamrow(pamP); - + *colorP = pnm_allocpamtuple(pamP); - + full = FALSE; /* initial value */ - + /* Go through the entire raster, building a hash table of - tuple values. + tuple values. */ for (row = 0; row < pamP->height && !full; ++row) { unsigned int col; const tuple * tuplerow; /* The row of tuples we are processing */ - + if (tupleArray) tuplerow = tupleArray[row]; else { @@ -335,8 +335,8 @@ computehashrecoverable(struct pam * const pamP, static tuplehash computetuplefreqhash(struct pam * const pamP, - tuple ** const tupleArray, - unsigned int const maxsize, + tuple ** const tupleArray, + unsigned int const maxsize, unsigned int const newDepth, sample const newMaxval, unsigned int * const sizeP) { @@ -350,18 +350,18 @@ computetuplefreqhash(struct pam * const pamP, 2) an open PAM file, positioned to the raster. In this case, 'tupleArray' is NULL. *pamP contains the file descriptor. - - We return with the file still open and its position undefined. + + We return with the file still open and its position undefined. In either case, *pamP contains parameters of the tuple array. Return the number of unique tuple values found as *sizeP. - However, if the number of unique tuple values is greater than 'maxsize', + However, if the number of unique tuple values is greater than 'maxsize', return a null return value and *sizeP undefined. The tuple values that index the hash have depth 'newDepth'. We look at - only the first 'newDepth' planes of the input. Caler must ensure that + only the first 'newDepth' planes of the input. Caller must ensure that the input has at least that many planes. The tuple values that index the hash are scaled to a new maxval of @@ -374,18 +374,18 @@ computetuplefreqhash(struct pam * const pamP, /* Buffer for a row read from the input file; undefined (but still allocated) if input is not from a file. */ - tuple color; + tuple color; /* The color currently being added, scaled to the new maxval */ jmp_buf jmpbuf; jmp_buf * origJmpbufP; - + /* Initialize to "none" for purposes of error recovery */ tuplefreqhash = NULL; rowbuffer = NULL; color = NULL; if (setjmp(jmpbuf) != 0) { - if (color) + if (color) pnm_freepamtuple(color); if (rowbuffer) pnm_freepamrow(rowbuffer); @@ -413,24 +413,24 @@ pnm_computetuplefreqhash(struct pam * const pamP, Compute the tuple frequency hash for the tuple array tupleArray[][]. -----------------------------------------------------------------------------*/ return computetuplefreqhash(pamP, tupleArray, maxsize, - pamP->depth, pamP->maxval, + pamP->depth, pamP->maxval, sizeP); } static void -alloctupletable(const struct pam * const pamP, +alloctupletable(const struct pam * const pamP, unsigned int const size, tupletable * const tupletableP, const char ** const errorP) { - + if (UINT_MAX / sizeof(struct tupleint) < size) pm_asprintf(errorP, "size %u is too big for arithmetic", size); else { unsigned int const mainTableSize = size * sizeof(struct tupleint *); - unsigned int const tupleIntSize = - sizeof(struct tupleint) - sizeof(sample) + unsigned int const tupleIntSize = + sizeof(struct tupleint) - sizeof(sample) + pamP->depth * sizeof(sample); /* To save the enormous amount of time it could take to allocate @@ -442,7 +442,7 @@ alloctupletable(const struct pam * const pamP, else { unsigned int const allocSize = mainTableSize + size * tupleIntSize; void * pool; - + pool = malloc(allocSize); if (!pool) @@ -469,7 +469,7 @@ alloctupletable(const struct pam * const pamP, tupletable -pnm_alloctupletable(const struct pam * const pamP, +pnm_alloctupletable(const struct pam * const pamP, unsigned int const size) { tupletable retval; @@ -491,8 +491,8 @@ void pnm_freetupletable(const struct pam * const pamP, tupletable const tupletable) { - /* Note that the address 'tupletable' is, to the operating system, - the address of a larger block of memory that contains not only + /* Note that the address 'tupletable' is, to the operating system, + the address of a larger block of memory that contains not only tupletable, but all the samples to which it points (e.g. tupletable[0].tuple[0]) */ @@ -574,7 +574,7 @@ pnm_tuplehashtotable(const struct pam * const pamP, tuplehash -pnm_computetupletablehash(struct pam * const pamP, +pnm_computetupletablehash(struct pam * const pamP, tupletable const tupletable, unsigned int const tupletableSize) { /*---------------------------------------------------------------------------- @@ -591,12 +591,12 @@ pnm_computetupletablehash(struct pam * const pamP, tuplehash tupletablehash; unsigned int i; int fits; - + tupletablehash = pnm_createtuplehash(); fits = TRUE; /* initial assumption */ for (i = 0; i < tupletableSize && fits; ++i) { - pnm_addtotuplehash(pamP, tupletablehash, + pnm_addtotuplehash(pamP, tupletablehash, tupletable[i]->tuple, i, &fits); } if (!fits) { @@ -658,7 +658,7 @@ pnm_computetuplefreqtable3(struct pam * const pamP, "argument (%u) greater than input depth (%u)", newDepth, pamP->depth); - tuplefreqhash = computetuplefreqhash(pamP, tupleArray, maxsize, + tuplefreqhash = computetuplefreqhash(pamP, tupleArray, maxsize, newDepth, newMaxval, &uniqueCount); if (tuplefreqhash == NULL) tuplefreqtable = NULL; @@ -704,8 +704,8 @@ pnm_computetuplefreqtable(struct pam * const pamP, char* -pam_colorname(struct pam * const pamP, - tuple const color, +pam_colorname(struct pam * const pamP, + tuple const color, enum colornameFormat const format) { unsigned int r, g, b; @@ -726,9 +726,9 @@ pam_colorname(struct pam * const pamP, while (!done) { struct colorfile_entry const ce = pm_colorget(f); if (ce.colorname) { - unsigned int const this_diff = - abs((int)r - (int)ce.r) + - abs((int)g - (int)ce.g) + + unsigned int const this_diff = + abs((int)r - (int)ce.r) + + abs((int)g - (int)ce.g) + abs((int)b - (int)ce.b); if (this_diff < best_diff) { @@ -739,7 +739,7 @@ pam_colorname(struct pam * const pamP, done = TRUE; } fclose(f); - if (best_diff != 32767 && + if (best_diff != 32767 && (best_diff == 0 || format == PAM_COLORNAME_ENGLISH)) return colorname; } diff --git a/lib/libpamwrite.c b/lib/libpamwrite.c index 29ddeaa2..7edc90dc 100644 --- a/lib/libpamwrite.c +++ b/lib/libpamwrite.c @@ -13,7 +13,7 @@ offset stuff. */ #define _FILE_OFFSET_BITS 64 -#define _LARGE_FILES +#define _LARGE_FILES #include #include @@ -28,8 +28,8 @@ static __inline__ unsigned int -samplesPerPlainLine(sample const maxval, - unsigned int const depth, +samplesPerPlainLine(sample const maxval, + unsigned int const depth, unsigned int const lineLength) { /*---------------------------------------------------------------------------- Return the minimum number of samples that should go in a line @@ -61,7 +61,7 @@ writePamPlainPbmRow(const struct pam * const pamP, unsigned int const samplesPerLine = 70; for (col = 0; col < pamP->width; ++col) - fprintf(pamP->file, + fprintf(pamP->file, ((col+1) % samplesPerLine == 0 || col == pamP->width-1) ? "%1u\n" : "%1u", tuplerow[col][0] == PAM_PBM_BLACK ? PBM_BLACK : PBM_WHITE); @@ -73,13 +73,13 @@ static void writePamPlainRow(const struct pam * const pamP, const tuple * const tuplerow) { - int const samplesPerLine = + int const samplesPerLine = samplesPerPlainLine(pamP->maxval, pamP->depth, 79); int col; unsigned int samplesInCurrentLine; /* number of samples written from start of line */ - + samplesInCurrentLine = 0; for (col = 0; col < pamP->width; ++col) { @@ -92,7 +92,7 @@ writePamPlainRow(const struct pam * const pamP, if (samplesInCurrentLine >= samplesPerLine) { fprintf(pamP->file, "\n"); samplesInCurrentLine = 0; - } + } } } fprintf(pamP->file, "\n"); @@ -108,11 +108,11 @@ formatPbmRow(const struct pam * const pamP, unsigned char accum; int col; - + accum = 0; /* initial value */ - + for (col=0; col < pamP->width; ++col) { - accum |= + accum |= (tuplerow[col][0] == PAM_PBM_BLACK ? PBM_BLACK : PBM_WHITE) << (7-col%8); if (col%8 == 7) { @@ -138,7 +138,7 @@ formatPbmRow(const struct pam * const pamP, */ static __inline__ void -sampleToBytes2(unsigned char buf[2], +sampleToBytes2(unsigned char buf[2], sample const sampleval) { buf[0] = (sampleval >> 8) & 0xff; @@ -148,7 +148,7 @@ sampleToBytes2(unsigned char buf[2], static __inline__ void -sampleToBytes3(unsigned char buf[3], +sampleToBytes3(unsigned char buf[3], sample const sampleval) { buf[0] = (sampleval >> 16) & 0xff; @@ -159,7 +159,7 @@ sampleToBytes3(unsigned char buf[3], static __inline__ void -sampleToBytes4(unsigned char buf[4], +sampleToBytes4(unsigned char buf[4], sample const sampleval) { buf[0] = (sampleval >> 24 ) & 0xff; @@ -185,7 +185,7 @@ format1BpsRow(const struct pam * const pamP, unsigned int bufferCursor; bufferCursor = 0; /* initial value */ - + for (col = 0; col < pamP->width; ++col) { unsigned int plane; for (plane=0; plane < pamP->depth; ++plane) @@ -210,7 +210,7 @@ format2BpsRow(const struct pam * const pamP, unsigned int bufferCursor; bufferCursor = 0; /* initial value */ - + for (col=0; col < pamP->width; ++col) { unsigned int plane; for (plane = 0; plane < pamP->depth; ++plane) @@ -236,7 +236,7 @@ format3BpsRow(const struct pam * const pamP, unsigned int bufferCursor; bufferCursor = 0; /* initial value */ - + for (col=0; col < pamP->width; ++col) { unsigned int plane; for (plane = 0; plane < pamP->depth; ++plane) @@ -262,7 +262,7 @@ format4BpsRow(const struct pam * const pamP, unsigned int bufferCursor; bufferCursor = 0; /* initial value */ - + for (col=0; col < pamP->width; ++col) { unsigned int plane; for (plane = 0; plane < pamP->depth; ++plane) @@ -285,7 +285,7 @@ pnm_formatpamrow(const struct pam * const pamP, at *outbuf. 'outbuf' must be the address of space allocated with pnm_allocrowimage(). - + We return as *rowSizeP the number of bytes in the row image. -----------------------------------------------------------------------------*/ if (PAM_FORMAT_TYPE(pamP->format) == PBM_TYPE) @@ -310,7 +310,7 @@ writePamRawRow(const struct pam * const pamP, const tuple * const tuplerow, unsigned int const count) { /*---------------------------------------------------------------------------- - Write mutiple ('count') copies of the same row ('tuplerow') to the file, + Write multiple ('count') copies of the same row ('tuplerow') to the file, in raw (not plain) format. -----------------------------------------------------------------------------*/ jmp_buf jmpbuf; @@ -330,10 +330,10 @@ writePamRawRow(const struct pam * const pamP, unsigned int i; pm_setjmpbufsave(&jmpbuf, &origJmpbufP); - + for (i = 0; i < count; ++i) { size_t bytesWritten; - + bytesWritten = fwrite(outbuf, 1, rowImageSize, pamP->file); if (bytesWritten != rowImageSize) pm_error("fwrite() failed to write an image row to the file. " @@ -346,16 +346,16 @@ writePamRawRow(const struct pam * const pamP, -void -pnm_writepamrow(const struct pam * const pamP, +void +pnm_writepamrow(const struct pam * const pamP, const tuple * const tuplerow) { - /* For speed, we don't check any of the inputs for consistency + /* For speed, we don't check any of the inputs for consistency here (unless it's necessary to avoid crashing). Any consistency - checking should have been done by a prior call to + checking should have been done by a prior call to pnm_writepaminit(). */ - + if (pamP->format == PAM_FORMAT || !(pm_plain_output || pamP->plainformat)) writePamRawRow(pamP, tuplerow, 1); else { @@ -371,7 +371,7 @@ pnm_writepamrow(const struct pam * const pamP, assert(false); break; default: - pm_error("Invalid 'format' value %u in pam structure", + pm_error("Invalid 'format' value %u in pam structure", pamP->format); } } @@ -380,11 +380,11 @@ pnm_writepamrow(const struct pam * const pamP, void -pnm_writepamrowmult(const struct pam * const pamP, +pnm_writepamrowmult(const struct pam * const pamP, const tuple * const tuplerow, unsigned int const count) { /*---------------------------------------------------------------------------- - Write mutiple ('count') copies of the same row ('tuplerow') to the file. + Write multiple ('count') copies of the same row ('tuplerow') to the file. -----------------------------------------------------------------------------*/ if (pm_plain_output || pamP->plainformat) { unsigned int i; @@ -397,14 +397,16 @@ pnm_writepamrowmult(const struct pam * const pamP, -void -pnm_writepam(struct pam * const pamP, +void +pnm_writepam(struct pam * const pamP, tuple ** const tuplearray) { int row; pnm_writepaminit(pamP); - - for (row = 0; row < pamP->height; ++row) + + for (row = 0; row < pamP->height; ++row) pnm_writepamrow(pamP, tuplearray[row]); } + + diff --git a/lib/libpbm3.c b/lib/libpbm3.c index 0144abe2..456d3986 100644 --- a/lib/libpbm3.c +++ b/lib/libpbm3.c @@ -389,7 +389,7 @@ pbm_writepbmrow_bitoffset(FILE * const fileP, unsigned char * const window = &packedBits[offset/8]; /* Area of packed row buffer from which we take the image data. Aligned to nearest byte boundary to the left, so the first - few bits might be irrelvant. + few bits might be irrelevant. Also our work buffer, in which we shift bits and from which we ultimately write the bits to the file. diff --git a/lib/libpbmfont1.c b/lib/libpbmfont1.c index 2d269da7..4189f150 100644 --- a/lib/libpbmfont1.c +++ b/lib/libpbmfont1.c @@ -189,8 +189,8 @@ pbm_dissectfont(const bit ** const fontsheet, unsigned int const frows, unsigned int const fcols) { /*---------------------------------------------------------------------------- - Dissect PBM sheet font data, create a font structre, - load bitmap data into it. + Dissect PBM sheet font data, create a font structure, load bitmap data into + it. Return value is a pointer to the newly created font structure @@ -205,7 +205,7 @@ pbm_dissectfont(const bit ** const fontsheet, just a matter of filling in all the coordinates. Struct font has fields 'oldfont', 'fcols', 'frows' for backward - compability. If there is any need to load data stored in this format + compatibility. If there is any need to load data stored in this format feed the above three, in order, as arguments to this function: pbm_dissectfont(oldfont, fcols, frows); diff --git a/lib/libppmd.c b/lib/libppmd.c index a94ff107..e0654c8f 100644 --- a/lib/libppmd.c +++ b/lib/libppmd.c @@ -1,4 +1,4 @@ -/* +/* ** ** This library module contains the ppmdraw routines. ** @@ -10,7 +10,7 @@ ** copyright notice and this permission notice appear in supporting ** documentation. This software is provided "as is" without express or ** implied warranty. -** +** ** The character drawing routines are by John Walker ** Copyright (C) 1994 by John Walker, kelvin@fourmilab.ch */ @@ -85,7 +85,7 @@ pointIsWithinBounds(ppmd_point const p, return (p.x >= 0 && p.x < cols && p.y >= 0 && p.y < rows); } - + static ppmd_point vectorSum(ppmd_point const a, @@ -102,7 +102,7 @@ static long int const DDA_SCALE = 8192; /* Several factors govern the limit of x, y coordination values. - The limit must be representable as (signed) int for coordinates to + The limit must be representable as (signed) int for coordinates to be carried in struct penpos (immediately above). The following calculation, done with long ints, must not overflow: @@ -112,7 +112,7 @@ static long int const DDA_SCALE = 8192; dy = (y1 - y0) * DDA_SCALE / abs(x1 - x0); Overflow conditions for ppmd_text are rather complicated, for commands - come from an external PPMD font file. See comments below. + come from an external PPMD font file. See comments below. */ @@ -141,10 +141,10 @@ ppmd_validatePoint(ppmd_point const p) { static void drawPoint(ppmd_drawprocp drawproc, const void * const clientdata, - pixel ** const pixels, - int const cols, - int const rows, - pixval const maxval, + pixel ** const pixels, + int const cols, + int const rows, + pixval const maxval, ppmd_point const p) { /*---------------------------------------------------------------------------- Draw a single point, assuming that it is within the bounds of the @@ -152,7 +152,7 @@ drawPoint(ppmd_drawprocp drawproc, -----------------------------------------------------------------------------*/ if (drawproc == PPMD_NULLDRAWPROC) { const pixel * const pixelP = clientdata; - + assert(p.x >= 0); assert(p.x < cols); assert(p.y >= 0); assert(p.y < rows); @@ -176,7 +176,7 @@ makeDrawProcXY(ppmd_drawproc * const drawProc, retval.drawProc = drawProc; retval.clientData = clientData; - + return retval; } @@ -204,10 +204,10 @@ drawProcPointXY(pixel ** const pixels, void -ppmd_point_drawprocp(pixel ** const pixels, - unsigned int const cols, - unsigned int const rows, - pixval const maxval, +ppmd_point_drawprocp(pixel ** const pixels, + unsigned int const cols, + unsigned int const rows, + pixval const maxval, ppmd_point const p, const void * const clientdata) { @@ -218,16 +218,16 @@ ppmd_point_drawprocp(pixel ** const pixels, void -ppmd_point_drawproc(pixel** const pixels, - int const cols, - int const rows, - pixval const maxval, - int const x, - int const y, +ppmd_point_drawproc(pixel** const pixels, + int const cols, + int const rows, + pixval const maxval, + int const x, + int const y, const void* const clientdata) { ppmd_point p; - + p.x = x; p.y = y; @@ -264,14 +264,14 @@ findRectangleIntersection(struct rectangle const rect1, void -ppmd_filledrectangle(pixel ** const pixels, - int const cols, - int const rows, - pixval const maxval, - int const x, - int const y, - int const width, - int const height, +ppmd_filledrectangle(pixel ** const pixels, + int const cols, + int const rows, + pixval const maxval, + int const x, + int const y, + int const width, + int const height, ppmd_drawproc drawProc, const void * const clientdata) { @@ -437,16 +437,16 @@ clipEnd1(ppmd_point const p0, at 0. -----------------------------------------------------------------------------*/ ppmd_point c1; - /* The current clipped location of p1; we clip it multile times + /* The current clipped location of p1; we clip it multiple times to get the final location. */ /* p0 is in the frame: */ assert(p0.x >= 0 && p0.x < cols); assert(p0.y >= 0 && p0.y < rows); - + /* Clip End 1 of the line horizontally */ c1 = p1; /* initial value */ - + if (c1.x < 0) { /* We know the line isn't vertical, since End 0 is in the frame and End 1 is left of frame. @@ -460,7 +460,7 @@ clipEnd1(ppmd_point const p0, c1.y = c1.y + (p0.y - c1.y) * (cols - 1 - c1.x) / (p0.x - c1.x); c1.x = cols - 1; } - + /* Clip End 1 of the line vertically */ if (c1.y < 0) { /* We know the line isn't horizontal, since End 0 is in the frame @@ -524,10 +524,10 @@ clipLine(ppmd_point const p0, static void drawShallowLine(ppmd_drawprocp drawProc, const void * const clientdata, - pixel ** const pixels, - int const cols, - int const rows, - pixval const maxval, + pixel ** const pixels, + int const cols, + int const rows, + pixval const maxval, ppmd_point const p0, ppmd_point const p1) { /*---------------------------------------------------------------------------- @@ -571,10 +571,10 @@ drawShallowLine(ppmd_drawprocp drawProc, static void drawSteepLine(ppmd_drawprocp drawProc, const void * const clientdata, - pixel ** const pixels, - int const cols, - int const rows, - pixval const maxval, + pixel ** const pixels, + int const cols, + int const rows, + pixval const maxval, ppmd_point const p0, ppmd_point const p1) { /*---------------------------------------------------------------------------- @@ -617,10 +617,10 @@ drawSteepLine(ppmd_drawprocp drawProc, void -ppmd_linep(pixel ** const pixels, - int const cols, - int const rows, - pixval const maxval, +ppmd_linep(pixel ** const pixels, + int const cols, + int const rows, + pixval const maxval, ppmd_point const p0, ppmd_point const p1, ppmd_drawprocp drawProc, @@ -662,14 +662,14 @@ ppmd_linep(pixel ** const pixels, void -ppmd_line(pixel ** const pixels, - int const cols, - int const rows, - pixval const maxval, - int const x0, - int const y0, - int const x1, - int const y1, +ppmd_line(pixel ** const pixels, + int const cols, + int const rows, + pixval const maxval, + int const x0, + int const y0, + int const x1, + int const y1, ppmd_drawproc drawProc, const void * const clientData) { @@ -701,10 +701,10 @@ static unsigned int void -ppmd_spline3p(pixel ** const pixels, - int const cols, - int const rows, - pixval const maxval, +ppmd_spline3p(pixel ** const pixels, + int const cols, + int const rows, + pixval const maxval, ppmd_point const p0, ppmd_point const ctl, ppmd_point const p1, @@ -740,16 +740,16 @@ ppmd_spline3p(pixel ** const pixels, void -ppmd_spline3(pixel ** const pixels, - int const cols, - int const rows, - pixval const maxval, - int const x0, - int const y0, - int const x1, - int const y1, - int const x2, - int const y2, +ppmd_spline3(pixel ** const pixels, + int const cols, + int const rows, + pixval const maxval, + int const x0, + int const y0, + int const x1, + int const y1, + int const x2, + int const y2, ppmd_drawproc drawProc, const void * const clientdata) { @@ -765,10 +765,10 @@ ppmd_spline3(pixel ** const pixels, void -ppmd_polysplinep(pixel ** const pixels, - unsigned int const cols, - unsigned int const rows, - pixval const maxval, +ppmd_polysplinep(pixel ** const pixels, + unsigned int const cols, + unsigned int const rows, + pixval const maxval, ppmd_point const p0, unsigned int const nc, ppmd_point * const c, @@ -777,7 +777,7 @@ ppmd_polysplinep(pixel ** const pixels, const void * const clientdata) { ppmd_point p; - + unsigned int i; assert(nc > 0); @@ -796,17 +796,17 @@ ppmd_polysplinep(pixel ** const pixels, void -ppmd_polyspline(pixel ** const pixels, - int const cols, - int const rows, - pixval const maxval, - int const x0, - int const y0, - int const nc, - int * const xc, - int * const yc, - int const x1, - int const y1, +ppmd_polyspline(pixel ** const pixels, + int const cols, + int const rows, + pixval const maxval, + int const x0, + int const y0, + int const nc, + int * const xc, + int * const yc, + int const x1, + int const y1, ppmd_drawproc drawProc, const void * const clientdata) { @@ -837,10 +837,10 @@ ppmd_polyspline(pixel ** const pixels, void -ppmd_spline4p(pixel ** const pixels, - unsigned int const cols, - unsigned int const rows, - pixval const maxval, +ppmd_spline4p(pixel ** const pixels, + unsigned int const cols, + unsigned int const rows, + pixval const maxval, ppmd_point const endPt0, ppmd_point const endPt1, ppmd_point const ctlPt0, @@ -862,12 +862,12 @@ ppmd_spline4p(pixel ** const pixels, void -ppmd_circlep(pixel ** const pixels, - unsigned int const cols, - unsigned int const rows, - pixval const maxval, +ppmd_circlep(pixel ** const pixels, + unsigned int const cols, + unsigned int const rows, + pixval const maxval, ppmd_point const center, - unsigned int const radius, + unsigned int const radius, ppmd_drawprocp drawProc, const void * const clientData) { /*---------------------------------------------------------------------------- @@ -877,7 +877,7 @@ ppmd_circlep(pixel ** const pixels, it might maintain state that is affected by imaginary points outside the image. - Initial point is 3 o'clock. + Initial point is 3 o'clock. -----------------------------------------------------------------------------*/ if (radius >= DDA_SCALE) pm_error("Error drawing circle. Radius %d is too large.", radius); @@ -936,13 +936,13 @@ ppmd_circlep(pixel ** const pixels, void -ppmd_circle(pixel ** const pixels, - int const cols, - int const rows, - pixval const maxval, - int const cx, - int const cy, - int const radius, +ppmd_circle(pixel ** const pixels, + int const cols, + int const rows, + pixval const maxval, + int const cx, + int const cy, + int const radius, ppmd_drawproc drawProc, const void * const clientData) { @@ -1013,11 +1013,11 @@ ppmd_fill_create(void) { stateP->curedge = 0; fillObjP->stateP = stateP; - + /* Turn off line clipping. */ /* UGGH! We must eliminate this global variable */ oldclip = ppmd_setlineclip(0); - + return fillObjP; } @@ -1129,10 +1129,10 @@ continueSegment(struct fillState * const stateP, */ void -ppmd_fill_drawprocp(pixel ** const pixels, - unsigned int const cols, - unsigned int const rows, - pixval const maxval, +ppmd_fill_drawprocp(pixel ** const pixels, + unsigned int const cols, + unsigned int const rows, + pixval const maxval, ppmd_point const p, const void * const clientdata) { @@ -1174,12 +1174,12 @@ ppmd_fill_drawprocp(pixel ** const pixels, void -ppmd_fill_drawproc(pixel** const pixels, - int const cols, - int const rows, - pixval const maxval, - int const x, - int const y, +ppmd_fill_drawproc(pixel** const pixels, + int const cols, + int const rows, + pixval const maxval, + int const x, + int const y, const void * const clientData) { ppmd_fill_drawprocp(pixels, cols, rows, maxval, makePoint(x, y), @@ -1204,7 +1204,7 @@ yxCompare(const void * const c1Arg, ppmd_point const p2 = c2P->point; int retval; - + if (p1.y > p2.y) retval = 1; else if (p1.y < p2.y) @@ -1222,10 +1222,10 @@ yxCompare(const void * const c1Arg, void -ppmd_fill(pixel ** const pixels, - int const cols, - int const rows, - pixval const maxval, +ppmd_fill(pixel ** const pixels, + int const cols, + int const rows, + pixval const maxval, struct fillobj * const fillObjP, ppmd_drawproc drawProc, const void * const clientdata) { @@ -1387,7 +1387,7 @@ static long isin(int deg) static long icos(int deg) { return isin(deg + 90); -} +} static int twosCompByteValue(unsigned char const c) { @@ -1453,7 +1453,7 @@ textPosFromFontPos(ppmd_point const fontPos, /* Position relative to the top left of the whole text box, assuming the text box is horizontal and has font scale. */ - + ppmd_point const ps = makePoint((pl.x * (int)height) / Scalef, (pl.y * (int)height) / Scalef); /* Same as above, but with the text box its actual size */ @@ -1502,7 +1502,7 @@ drawGlyph(const struct ppmd_glyph * const glyphP, text box, in the coordinate system of the canvas. 'rotcos' and 'rotsin' tell how that text box is rotated with respect to the horizontal on the canvas. - + 'height' is the height in canvas pixels of a glyph. This is a scale factor to convert font coordinates to canvas coordinates. -----------------------------------------------------------------------------*/ @@ -1542,7 +1542,7 @@ drawGlyph(const struct ppmd_glyph * const glyphP, glyphOrigin, height, rotcos, rotsin); - + ppmd_linep(pixels, cols, rows, maxval, p, n, drawProc, clientdata); @@ -1565,14 +1565,14 @@ drawGlyph(const struct ppmd_glyph * const glyphP, void -ppmd_textp(pixel** const pixels, - int const cols, - int const rows, - pixval const maxval, +ppmd_textp(pixel** const pixels, + int const cols, + int const rows, + pixval const maxval, ppmd_point const pos, - int const height, - int const angle, - const char * const sArg, + int const height, + int const angle, + const char * const sArg, ppmd_drawprocp drawProc, const void * const clientdata) { /*---------------------------------------------------------------------------- @@ -1608,7 +1608,7 @@ ppmd_textp(pixel** const pixels, unsigned int cursorAdvance; - ppmd_validatePoint(p); + ppmd_validatePoint(p); drawGlyph(glyphP, p, pixels, cols, rows, maxval, height, pos, rotcos, rotsin, @@ -1625,15 +1625,15 @@ ppmd_textp(pixel** const pixels, void -ppmd_text(pixel** const pixels, - int const cols, - int const rows, - pixval const maxval, - int const xpos, - int const ypos, - int const height, - int const angle, - const char * const sArg, +ppmd_text(pixel** const pixels, + int const cols, + int const rows, + pixval const maxval, + int const xpos, + int const ypos, + int const height, + int const angle, + const char * const sArg, ppmd_drawproc drawProc, const void * const clientData) { @@ -1648,13 +1648,13 @@ ppmd_text(pixel** const pixels, /* EXTENTS_DRAWPROC -- Drawproc which just accumulates the extents rectangle bounding the text. */ -static void -extents_drawproc (pixel** const pixels, - int const cols, +static void +extents_drawproc (pixel** const pixels, + int const cols, int const rows, - pixval const maxval, - int const x, - int const y, + pixval const maxval, + int const x, + int const y, const void * const clientdata) { extleft = MIN(extleft, x); @@ -1673,22 +1673,25 @@ extents_drawproc (pixel** const pixels, */ void -ppmd_text_box(int const height, - int const angle, - const char * const s, - int * const left, - int * const top, - int * const right, +ppmd_text_box(int const height, + int const angle, + const char * const s, + int * const left, + int * const top, + int * const right, int * const bottom) { extleft = 32767; exttop = 32767; extright = -32767; extbottom = -32767; - ppmd_text(NULL, 32767, 32767, 255, 1000, 1000, height, angle, s, + ppmd_text(NULL, 32767, 32767, 255, 1000, 1000, height, angle, s, extents_drawproc, NULL); - *left = extleft - 1000; + *left = extleft - 1000; *top = exttop - 1000; *right = extright - 1000; *bottom = extbottom - 1000; } + + + diff --git a/lib/libsystem.c b/lib/libsystem.c index bf2416a4..ba48ed85 100644 --- a/lib/libsystem.c +++ b/lib/libsystem.c @@ -128,8 +128,8 @@ execProgram(const char * const progName, static void -createPipeFeeder(void pipeFeederRtn(int, void *), - void * const feederParm, +createPipeFeeder(void pipeFeederRtn(int, void *), + void * const feederParm, int * const fdP, pid_t * const pidP) { /*---------------------------------------------------------------------------- @@ -143,7 +143,7 @@ createPipeFeeder(void pipeFeederRtn(int, void *), pm_pipe(pipeToFeed); rc = fork(); if (rc < 0) { - pm_error("fork() of stdin feeder failed. errno=%d (%s)", + pm_error("fork() of stdin feeder failed. errno=%d (%s)", errno, strerror(errno)); } else if (rc == 0) { /* This is the child -- the stdin feeder process */ @@ -190,13 +190,13 @@ spawnProcessor(const char * const progName, rc = fork(); if (rc < 0) { - pm_error("fork() of processor process failed. errno=%d (%s)", + pm_error("fork() of processor process failed. errno=%d (%s)", errno, strerror(errno)); } else if (rc == 0) { /* The program child */ int stdoutFd; - + if (pipeStdout) { close(stdoutpipe[0]); stdoutFd = stdoutpipe[1]; @@ -230,7 +230,7 @@ signalName(unsigned int const signalClass) { /* There are various signal classes that are not universally defined, so we make a half-hearted attempt to determine whether they are and not try to recognize the ones that aren't. We do this by testing - whether a macro is defind with the signal class name. That could give + whether a macro is defined with the signal class name. That could give a false negative, because the signal class name isn't necessarily defined as a macro, but it's a really, really small problem to miss one of these signal classes here, so we don't bother with all the work @@ -332,7 +332,7 @@ pm_termStatusDesc(int const termStatusArg) { for a BSD 'union wait' (instead of int) argument to WIFEXITED. The magic involves defining a variable with 'typeof' the argument and assigning to that variable. - + To work around this, we make sure the argument is not constant. */ @@ -426,14 +426,14 @@ pm_system2_vp(const char * const progName, program process and the current process and have the program write its Standard Output to that pipe. The current process runs 'stdoutAccepter' to read the data from that pipe. - + But if 'stdoutFeeder' is NULL, we just tell the program process to write to the current process' Standard Output. So there are two processes when stdinFeeder is NULL and three when stdinFeeder is non-null. */ - + int progStdinFd; /* File descriptor that the processor program will get as Standard Input @@ -459,9 +459,9 @@ pm_system2_vp(const char * const progName, int progStdoutFd; /* Make a child process to run the program and pipe back to us its - Standard Output + Standard Output */ - spawnProcessor(progName, argArray, progStdinFd, + spawnProcessor(progName, argArray, progStdinFd, &progStdoutFd, &processorPid); /* Dispose of the stdout from that child */ @@ -483,7 +483,7 @@ pm_system2_vp(const char * const progName, waitpid(processorPid, &termStatus, 0); - if (feederPid) + if (feederPid) cleanupFeederProcess(feederPid); *termStatusP = termStatus; @@ -520,7 +520,7 @@ pm_system2_lp(const char * const progName, !endOfArgs; ) { const char * const arg = va_arg(args, const char *); - + REALLOCARRAY(argArray, n+1); argArray[n++] = arg; @@ -560,7 +560,7 @@ pm_system2(void stdinFeeder(int, void *), Return as *termStatusP the termination status of the processor process (the one running the program named 'progName'). -----------------------------------------------------------------------------*/ - pm_system2_lp("/bin/sh", + pm_system2_lp("/bin/sh", stdinFeeder, feederParm, stdoutAccepter, accepterParm, termStatusP, "sh", "-c", shellCommand, NULL); @@ -625,7 +625,7 @@ pm_system_lp(const char * const progName, !endOfArgs; ) { const char * const arg = va_arg(args, const char *); - + REALLOCARRAY(argArray, n+1); argArray[n++] = arg; @@ -716,15 +716,15 @@ pm_feed_from_memory(int const pipeToFeedFd, void * const feederParm) { pm_bufferDesc * const inputBufferP = feederParm; - + FILE * const outFileP = fdopen(pipeToFeedFd, "w"); - + size_t bytesTransferred; /* The following signals (and normally kills) the process with SIGPIPE if the pipe does not take all 'size' bytes. */ - bytesTransferred = + bytesTransferred = fwrite(inputBufferP->buffer, 1, inputBufferP->size, outFileP); if (inputBufferP->bytesTransferredP) @@ -740,7 +740,7 @@ pm_accept_to_memory(int const pipetosuckFd, void * const accepterParm ) { pm_bufferDesc * const outputBufferP = accepterParm; - + FILE * const inFileP = fdopen(pipetosuckFd, "r"); size_t bytesTransferred; diff --git a/lib/pam.h b/lib/pam.h index 0055858b..5edc8a01 100644 --- a/lib/pam.h +++ b/lib/pam.h @@ -240,7 +240,7 @@ typedef float * pnm_transformMap; Each transform map is an array indexed by a PAM sample value, containing 'float' values. So it must have 'maxval' - entries. The sample -> samplen tranformation is just the + entries. The sample -> samplen transformation is just the obvious table lookup. The samplen -> sample transformation is more complicated -- if the samplen value is between map[N] and map[N+1], then the sample value is N. And only transforms diff --git a/lib/util/LICENSE.txt b/lib/util/LICENSE.txt index aeb06a7f..4baac593 100644 --- a/lib/util/LICENSE.txt +++ b/lib/util/LICENSE.txt @@ -113,7 +113,7 @@ written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF -MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End diff --git a/lib/util/nstring.c b/lib/util/nstring.c index 7ef9fcfb..6d68af49 100644 --- a/lib/util/nstring.c +++ b/lib/util/nstring.c @@ -1007,47 +1007,83 @@ pm_strishex(const char * const subject) { void -pm_string_to_uint(const char * const string, - unsigned int * const uintP, +pm_string_to_long(const char * const string, + long * const longP, const char ** const errorP) { if (strlen(string) == 0) pm_asprintf(errorP, "Value is a null string"); else { char * tailptr; - long longValue; - - /* We can't use 'strtoul'. Contrary to expectations, though as - designed, it returns junk if there is a minus sign. - */ /* strtol() does a bizarre thing where if the number is out of range, it returns a clamped value but tells you about it by setting errno = ERANGE. If it is not out of range, strtol() leaves errno alone. */ - errno = 0; /* So we can tell if strtoul() overflowed */ + errno = 0; /* So we can tell if strtol() overflowed */ - longValue = strtol(string, &tailptr, 10); + *longP = strtol(string, &tailptr, 10); if (*tailptr != '\0') pm_asprintf(errorP, "Non-numeric crap in string: '%s'", tailptr); else { if (errno == ERANGE) pm_asprintf(errorP, "Number is too large for computation"); - else { - if (longValue < 0) - pm_asprintf(errorP, "Number is negative"); - else { - if ((unsigned int)longValue != longValue) - pm_asprintf(errorP, - "Number is too large for computation"); - else { - *uintP = (unsigned int)longValue; - *errorP = NULL; - } - } - } + else + *errorP = NULL; + } + } +} + + + +void +pm_string_to_int(const char * const string, + int * const intP, + const char ** const errorP) { + + long longValue; + + pm_string_to_long(string, &longValue, errorP); + + if (!*errorP) { + if ((int)longValue != longValue) + pm_asprintf(errorP, + "Number is too large for computation"); + else { + *intP = (int)longValue; + *errorP = NULL; + } + } +} + + + +void +pm_string_to_uint(const char * const string, + unsigned int * const uintP, + const char ** const errorP) { + + /* We can't use 'strtoul'. Contrary to expectations, though as + designed, it returns junk if there is a minus sign. + */ + + long longValue; + + pm_string_to_long(string, &longValue, errorP); + + if (!*errorP) { + if (longValue < 0) + pm_asprintf(errorP, "Number is negative"); + else { + if ((unsigned int)longValue != longValue) + pm_asprintf(errorP, + "Number is too large for computation"); + else { + *uintP = (unsigned int)longValue; + *errorP = NULL; + } } } } diff --git a/lib/util/nstring.h b/lib/util/nstring.h index 5159277c..8829617d 100644 --- a/lib/util/nstring.h +++ b/lib/util/nstring.h @@ -146,7 +146,7 @@ strncaseeq(const char * const comparand, - If the function can't get the memory, it returns 'pm_strsol', which is a string that is in static memory that contains text - indicating an out of memory failure has occurred, intead of + indicating an out of memory failure has occurred, instead of NULL. This makes it much easier for programs to ignore this possibility. @@ -208,6 +208,16 @@ pm_memmem(const void * const haystackArg, bool pm_strishex(const char * const subject); +void +pm_string_to_long(const char * const string, + long * const longP, + const char ** const errorP); + +void +pm_string_to_int(const char * const string, + int * const intP, + const char ** const errorP); + void pm_string_to_uint(const char * const string, unsigned int * const uintP, diff --git a/lib/util/shhopt.c b/lib/util/shhopt.c index c0b4ba47..cc8f165e 100644 --- a/lib/util/shhopt.c +++ b/lib/util/shhopt.c @@ -6,7 +6,7 @@ | or passed to functions as specified. | | REQUIREMENTS Some systems lack the ANSI C -function strtoul. If your - | system is one of those, you'll ned to write one yourself, + | system is one of those, you'll need to write one yourself, | or get the GNU liberty-library (from prep.ai.mit.edu). | | WRITTEN BY Sverre H. Huseby diff --git a/other/pamunlookup.c b/other/pamunlookup.c index 77c2807b..624951df 100644 --- a/other/pamunlookup.c +++ b/other/pamunlookup.c @@ -49,13 +49,13 @@ parseCommandLine(int argc, const char ** const argv, optStruct3 opt; unsigned int option_def_index; - + unsigned int lookupfileSpec; MALLOCARRAY_NOFAIL(option_def, 100); option_def_index = 0; /* incremented by OPTENTRY */ - OPTENT3(0, "lookupfile", OPT_STRING, &cmdlineP->lookupfile, + OPTENT3(0, "lookupfile", OPT_STRING, &cmdlineP->lookupfile, &lookupfileSpec, 0); opt.opt_table = option_def; @@ -74,17 +74,17 @@ parseCommandLine(int argc, const char ** const argv, cmdlineP->inputFileName = argv[1]; free(option_def); -} +} static void -getLookup(const char * const lookupFileName, +getLookup(const char * const lookupFileName, tuple *** const lookupP, struct pam * const lookuppamP) { /*---------------------------------------------------------------------------- Get the lookup image (the one that maps integers to tuples, e.g. a - color index / color map / palette) from the file named + color index / color map / palette) from the file named 'lookupFileName'. Return the image as *lookupP and *lookuppamP. @@ -95,14 +95,14 @@ getLookup(const char * const lookupFileName, tuple ** inputLookup; lookupfileP = pm_openr(lookupFileName); - inputLookup = pnm_readpam(lookupfileP, + inputLookup = pnm_readpam(lookupfileP, &inputLookuppam, PAM_STRUCT_SIZE(tuple_type)); pm_close(lookupfileP); - + if (inputLookuppam.height != 1) pm_error("The lookup table image must be one row. " - "Yours is %u rows.", + "Yours is %u rows.", inputLookuppam.height); *lookupP = inputLookup; @@ -129,7 +129,7 @@ makeReverseLookupHash(struct pam * const lookuppamP, for (col = 0; col < lookuppamP->width; ++col) { tuple const thisValue = lookup[0][col]; - + int found; int priorValue; @@ -181,7 +181,7 @@ doUnlookup(struct pam * const inpamP, for (row = 0; row < inpamP->height; ++row) { unsigned int col; - + pnm_readpamrow(inpamP, inrow); for (col = 0; col < inpamP->width; ++col) { @@ -214,7 +214,7 @@ main(int argc, const char ** const argv) { tuple ** lookup; tuplehash lookupHash; - + pm_proginit(&argc, argv); parseCommandLine(argc, argv, &cmdline); @@ -230,7 +230,7 @@ main(int argc, const char ** const argv) { "has depth %u. They must be the same", lookuppam.depth, inpam.depth); if (!streq(inpam.tuple_type, lookuppam.tuple_type)) - pm_error("The lookup image has tupel type '%s', " + pm_error("The lookup image has tuple type '%s', " "but the input image " "has tuple type '%s'. They must be the same", lookuppam.tuple_type, inpam.tuple_type); @@ -243,7 +243,7 @@ main(int argc, const char ** const argv) { pnm_destroytuplehash(lookupHash); pnm_freepamarray(lookup, &lookuppam); - + return 0; } diff --git a/test/Test-Order b/test/Test-Order index 2548e501..a696529b 100644 --- a/test/Test-Order +++ b/test/Test-Order @@ -27,6 +27,7 @@ ppmforge-parameters.test # Generators with random components pgmnoise.test +pgmnoise-parameters.test ppmpat-random.test ppmforge.test ppmrough.test @@ -41,12 +42,14 @@ ppmhist.test pamsumm.test pnmpsnr.test pbmminkowski.test +pgmminkowski.test pnmcolormap.test # Basic (internal) converter tests pamtopam.test +pbmtopgm.test pgmtopgm.test ppmtoppm.test pgmtoppm.test @@ -55,12 +58,17 @@ pnmtopnm-plain.test # Editor tests +pamdepth.test + pamditherbw.test pamhue.test pbmclean.test pamcut.test pnmcat.test +pamdice.test +pamundice.test + pamflip1.test pamflip2.test pnminvert.test diff --git a/test/pamchannel.ok b/test/pamchannel.ok index 79317f03..41d3f890 100644 --- a/test/pamchannel.ok +++ b/test/pamchannel.ok @@ -1,3 +1,10 @@ +Test 1 1571496937 33838 +Test 2 394856971 33838 +Test 3 3164158573 33838 +Test Invalid +Expected failure 1 1 +Expected failure 2 1 +Expected failure 3 1 diff --git a/test/pamchannel.test b/test/pamchannel.test index 3529f4fe..2e017ef2 100755 --- a/test/pamchannel.test +++ b/test/pamchannel.test @@ -1,7 +1,6 @@ #! /bin/bash # This script tests: pamchannel -# Also requires: pamtopnm - +# Also requires: pamtopam pamtopnm # Extract planes one by one. # Convert output to pgm to make it identical to ppmtorgb3 output. @@ -15,18 +14,44 @@ # Test 1. red channel # Should produce 1571496937 33838 +echo "Test 1" pamchannel -infile testimg.ppm 0 | \ pamtopnm --assume | cksum # Test 2. green channel # Should produce 394856971 33838 +echo "Test 2" pamchannel -infile testimg.ppm -tupletype="GRAYSCALE" 1 | \ pamtopnm | cksum # Test 3. blue channel # Should produce 3164158573 33838 +echo "Test 3" pamchannel -infile testimg.ppm 2 | \ pamtopnm --assume | cksum + +# Test invalid: specified channel does not exist + +echo 1>&2 +echo "Invalid command-line argument combinations." 1>&2 +echo "Error messages should appear below the line." 1>&2 +echo "-----------------------------------------------------------" 1>&2 + +tmpdir=${tmpdir:-/tmp} +test_out=${tmpdir}/test_out + +echo "Test Invalid" + +pamchannel -infile testgrid.pbm 1 > ${test_out} || \ + echo -n "Expected failure 1"; test -s ${test_out}; echo " "$? + +pamchannel -infile testimg.ppm 3 > ${test_out} || \ + echo -n "Expected failure 2"; test -s ${test_out}; echo " "$? + +pamtopam testimg.ppm | pamchannel -infile=- 4 > ${test_out} || \ + echo -n "Expected failure 3"; test -s ${test_out}; echo " "$? + +rm ${test_out} \ No newline at end of file diff --git a/test/pamcrater.ok b/test/pamcrater.ok index cfb186a6..a5571f35 100644 --- a/test/pamcrater.ok +++ b/test/pamcrater.ok @@ -1,6 +1,13 @@ +Test 1. 4 4 4 +Test 2. 2 2 2 +Test Invalid. +Expected failure 1 1 +Expected failure 2 1 +Expected failure 3 1 +Expected failure 4 1 diff --git a/test/pamcrater.test b/test/pamcrater.test index 4d3858b9..ba10ca24 100755 --- a/test/pamcrater.test +++ b/test/pamcrater.test @@ -3,8 +3,8 @@ # Also requires: pamstack pamvalidate pamcut pamflip -# We use the undocumented --test and --radius options of pamcrater. -# pamcrater --test --radius=N +# We use the undocumented -test and -radius options of pamcrater. +# pamcrater -test -radius=N # The above draws a single crater of radius N. # The resulting image should be symmetric. @@ -18,11 +18,12 @@ test100_pam=${tmpdir}/test100.pam test150_pam=${tmpdir}/test150.pam # Test 1. Should print 4 three times +echo "Test 1." -pamcrater --test --radius=10 > $test10_pam -pamcrater --test --radius=50 > $test50_pam -pamcrater --test --radius=100 > $test100_pam -pamcrater --test --radius=150 > $test150_pam +pamcrater -test -radius=10 > $test10_pam +pamcrater -test -radius=50 > $test50_pam +pamcrater -test -radius=100 > $test100_pam +pamcrater -test -radius=150 > $test150_pam pamstack ${test10_pam} ${test50_pam} ${test100_pam} ${test150_pam} | pamvalidate > ${test_pam} @@ -39,6 +40,7 @@ for i in 1 10 70 rm ${test_pam} ${test10_pam} ${test50_pam} # Test 2. Should print 2 three times +echo "Test 2." pamshadedrelief ${test100_pam} > ${testshaded_pam} @@ -51,3 +53,26 @@ pamshadedrelief ${test100_pam} > ${testshaded_pam} ) | uniq -c | awk '{print $1}' rm ${testshaded_pam} ${test100_pam} + +echo "Test Invalid." + +test_out=${tmpdir}/test_out + +echo 1>&2 +echo "Invalid command-line argument combinations." 1>&2 +echo "Error messages should appear below the line." 1>&2 +echo "------------------------------" 1>&2 + +pamcrater -width 0 > ${test_out} || \ + echo -n "Expected failure 1"; test -s ${test_out}; echo " "$? + +pamcrater -height 0 > ${test_out} || \ + echo -n "Expected failure 2"; test -s ${test_out}; echo " "$? + +pamcrater -number 0 > ${test_out} || \ + echo -n "Expected failure 3"; test -s ${test_out}; echo " "$? + +pamcrater -test -radius=10 | pamshadedrelief -gamma 0 > ${test_out} || \ + echo -n "Expected failure 4"; test -s ${test_out}; echo " "$? + +rm -f ${test_out} \ No newline at end of file diff --git a/test/pamcut.ok b/test/pamcut.ok index b08bc531..3d5c5a7f 100644 --- a/test/pamcut.ok +++ b/test/pamcut.ok @@ -15,5 +15,22 @@ Test 5. 2425386270 41 2425386270 41 2425386270 41 +2425386270 41 Test 6. 3412257956 129 +Test Invalid +Expected failure 1 1 +Expected failure 2 1 +Expected failure 3 1 +Expected failure 4 1 +Expected failure 5 1 +Expected failure 6 1 +Expected failure 7 1 +Expected failure 8 1 +Expected failure 9 1 +Expected failure 6 1 +Expected failure 10 1 +Expected failure 11 1 +Expected failure 12 1 +Expected failure 13 1 +Expected failure 14 1 diff --git a/test/pamcut.test b/test/pamcut.test index 9971b1a5..e4d8c62f 100755 --- a/test/pamcut.test +++ b/test/pamcut.test @@ -31,7 +31,7 @@ pamcut -top 10 -left 10 -bottom -11 -right -11 testimg.ppm | cksum pamcut -top 10 -left 10 -width 207 -height 129 testimg.ppm | cksum -# Test 5. Should print 2425386270 41 four times +# Test 5. Should print 2425386270 41 five times echo Test 5. pamcut -croptop 0 -cropleft 0 -cropbottom 0 -cropright 0 testgrid.pbm | \ @@ -39,9 +39,71 @@ pamcut -croptop 0 -cropleft 0 -cropbottom 0 -cropright 0 testgrid.pbm | \ pamcut -top 0 -left 0 -bottom 15 -right 13 testgrid.pbm | cksum pamcut -top 0 -left 0 -bottom -1 -right -1 testgrid.pbm | cksum pamcut -top 0 -left 0 -width 14 -height 16 testgrid.pbm | cksum - +pamcut testgrid.pbm | cksum # Test 6. Should print 3412257956 129 echo Test 6. pbmmake -g 50 50 | pamcut 5 5 30 30 | cksum + + +echo "Test Invalid" + +tmpdir=${tmpdir:-/tmp} +test_out=${tmpdir}/test_out + +echo 1>&2 +echo "Invalid command-line argument combinations." 1>&2 +echo "Error messages should appear below the line." 1>&2 +echo "-----------------------------------------------------------" 1>&2 + +# overspecification +pamcut -left=1 -right=1 -width=14 testgrid.pbm > ${test_out} || \ + echo -n "Expected failure 1"; test -s ${test_out}; echo " "$? + +pamcut -top=1 -bottom=1 -height=16 testgrid.pbm > ${test_out} || \ + echo -n "Expected failure 2"; test -s ${test_out}; echo " "$? + +pamcut -right=1 -cropright=1 testgrid.pbm > ${test_out} || \ + echo -n "Expected failure 3"; test -s ${test_out}; echo " "$? + +pamcut -top=1 -croptop=1 testgrid.pbm > ${test_out} || \ + echo -n "Expected failure 4"; test -s ${test_out}; echo " "$? + +pamcut -bottom=1 -cropbottom=1 testgrid.pbm > ${test_out} || \ + echo -n "Expected failure 5"; test -s ${test_out}; echo " "$? + +pamcut -left=1 -cropleft=1 testgrid.pbm > ${test_out} || \ + echo -n "Expected failure 6"; test -s ${test_out}; echo " "$? + +# excessive cropping +pamcut -cropleft=7 -cropright=8 testgrid.pbm > ${test_out} || \ + echo -n "Expected failure 7"; test -s ${test_out}; echo " "$? + +pamcut -left=7 -right=6 testgrid.pbm > ${test_out} || \ + echo -n "Expected failure 8"; test -s ${test_out}; echo " "$? + +pamcut -croptop=8 -cropbottom=8 testgrid.pbm > ${test_out} || \ + echo -n "Expected failure 9"; test -s ${test_out}; echo " "$? + +pamcut -top=10 -bottom=9 testgrid.pbm > ${test_out} || \ + echo -n "Expected failure 6"; test -s ${test_out}; echo " "$? + +# pad absent +pamcut -cropleft=1 -width=14 testgrid.pbm > ${test_out} || \ + echo -n "Expected failure 10"; test -s ${test_out}; echo " "$? + +pamcut -croptop=1 -height=16 testgrid.pbm > ${test_out} || \ + echo -n "Expected failure 11"; test -s ${test_out}; echo " "$? + +# legacy style: insufficient number of positional parameters +pamcut 5 testimg.ppm > ${test_out} || \ + echo -n "Expected failure 12"; test -s ${test_out}; echo " "$? + +pamcut 5 4 testimg.ppm > ${test_out} || \ + echo -n "Expected failure 13"; test -s ${test_out}; echo " "$? + +pamcut 5 5 30 testimg.ppm > ${test_out} || \ + echo -n "Expected failure 14"; test -s ${test_out}; echo " "$? + +rm -f ${test_out} \ No newline at end of file diff --git a/test/pamdepth.ok b/test/pamdepth.ok new file mode 100644 index 00000000..1bd897ac --- /dev/null +++ b/test/pamdepth.ok @@ -0,0 +1,14 @@ +Test 1 +538848130 235 +stdin: PGM RAW 14 16 1 1 GRAYSCALE +538848130 235 +stdin: PGM RAW 14 16 1 1 GRAYSCALE +831461512 289 +stdin: PAM RAW 14 16 1 1 GRAYSCALE +831461512 289 +stdin: PAM RAW 14 16 1 1 GRAYSCALE +Test 2 +0 0 : 0 +Test Invalid +Expected failure 1 1 +Expected failure 2 1 diff --git a/test/pamdepth.test b/test/pamdepth.test new file mode 100755 index 00000000..da198973 --- /dev/null +++ b/test/pamdepth.test @@ -0,0 +1,38 @@ +#! /bin/bash +# This script tests: pamdepth +# Also requires: pbmtopgm pamtopam pamfile + +tmpdir=${tmpdir:-/tmp} +test_out=${tmpdir}/test_out + +# Test 1 +echo "Test 1" +pamdepth 1 testgrid.pbm | tee ${test_out} | cksum + cat ${test_out} | pamfile -machine +pbmtopgm 1 1 testgrid.pbm | pamdepth 1 | tee ${test_out} | cksum + cat ${test_out} | pamfile -machine +pamdepth 1 testgrid.pbm | pamtopam | tee ${test_out} | cksum + cat ${test_out} | pamfile -machine +pbmtopgm 1 1 testgrid.pbm | pamtopam | pamdepth 1 | tee ${test_out} | cksum + cat ${test_out} | pamfile -machine + +# Test 2 +echo "Test 2" +pamdepth 255 testimg.ppm | cmp -s - testimg.ppm + echo ${PIPESTATUS[@]} ":" $? + +# Test Invalid +echo "Test Invalid" + +echo 1>&2 +echo "Invalid command-line argument combinations." 1>&2 +echo "Error messages should appear below the line." 1>&2 +echo "-----------------------------------------------------------" 1>&2 + +pamdepth 0 testgrid.pbm > ${test_out} || \ + echo -n "Expected failure 1"; test -s ${test_out}; echo " "$? + +pamdepth 65536 testimg.ppm > ${test_out} || \ + echo -n "Expected failure 2"; test -s ${test_out}; echo " "$? + +rm ${test_out} \ No newline at end of file diff --git a/test/pamdice-roundtrip.ok b/test/pamdice-roundtrip.ok index 82eac5a8..4a850615 100644 --- a/test/pamdice-roundtrip.ok +++ b/test/pamdice-roundtrip.ok @@ -1 +1,18 @@ +test 1 +2425386270 41 +test 2 +2425386270 41 +test 3 +2425386270 41 +test 4. +1926073387 101484 +test 4.-hoverlap=0 +1926073387 101484 +test 4.-hoverlap=2 +1926073387 101484 +test 4.-voverlap=0 +1926073387 101484 +test 4.-voverlap=2 +1926073387 101484 +test 5 1926073387 101484 diff --git a/test/pamdice-roundtrip.test b/test/pamdice-roundtrip.test index 28997742..c5ccde66 100755 --- a/test/pamdice-roundtrip.test +++ b/test/pamdice-roundtrip.test @@ -4,9 +4,35 @@ tmpdir=${tmpdir:-/tmp} -fname_stem=${tmpdir}/a +fname_stem=${tmpdir}/pamdice_part -pamdice testimg.ppm -outstem=${fname_stem} -width=50 -height=40 -pamundice ${fname_stem}_%1d_%1a.ppm -down=4 -across=5 | cksum +echo test 1 -rm ${fname_stem}_?_?.ppm +pamdice testgrid.pbm -outstem=${fname_stem} +pamundice ${fname_stem}_%1d_%1a.pbm -down=1 -across=1 | cksum +rm ${fname_stem}_0_0.pbm + +echo test 2 + +pamdice testgrid.pbm -outstem=${fname_stem} -width=3 +pamundice ${fname_stem}_%1d_%1a.pbm -across=5 | cksum +rm ${fname_stem}_0_?.pbm + +echo test 3 + +pamdice testgrid.pbm -outstem=${fname_stem} -height=4 +pamundice ${fname_stem}_%1d_%1a.pbm -down=4 | cksum +rm ${fname_stem}_?_0.pbm + +for flags in "" "-hoverlap=0" "-hoverlap=2" "-voverlap=0" "-voverlap=2" + do + echo test 4.${flags} + pamdice testimg.ppm -outstem=${fname_stem} -width=50 -height=40 + pamundice ${fname_stem}_%1d_%1a.ppm -down=4 -across=5 | cksum + rm ${fname_stem}_?_?.ppm + done + +echo test 5 +pamdice testimg.ppm -outstem=${fname_stem} -width=20 -height=10 +ls ${fname_stem}*.ppm | pamundice -listfile=- -across=12 -down=15 | cksum +rm ${fname_stem}_??_??.ppm \ No newline at end of file diff --git a/test/pamdice.ok b/test/pamdice.ok new file mode 100644 index 00000000..83db2775 --- /dev/null +++ b/test/pamdice.ok @@ -0,0 +1,21 @@ +Test 1. + 10 P1@1 1@0@ +Test 2. +P1@1 1@0@ +P1@1 1@1@ +P1@1 1@1@ +P1@1 1@0@ +P1@1 1@0@ +P1@1 1@1@ +P1@1 1@1@ +P1@1 1@0@ +P1@1 1@0@ +P1@1 1@1@ +Test Invalid +Expected failure 1 +Expected failure 2 +Expected failure 3 +Expected failure 4 +Expected failure 5 +Expected failure 6 +Expected failure (output files) diff --git a/test/pamdice.test b/test/pamdice.test new file mode 100755 index 00000000..71a9d645 --- /dev/null +++ b/test/pamdice.test @@ -0,0 +1,68 @@ +#! /bin/bash +# This script tests: pamdice +# Also requires: pbmmake + +tmpdir=${tmpdir:-/tmp} +fname_stem=${tmpdir}/pamdice_part + +# Test 1. +echo "Test 1." + +pbmmake -w 2 5 | pamdice -height=1 -width=1 -outstem=${fname_stem} -plain +ls ${fname_stem}*.pbm | while read file + do + cat ${file} | tr '\n' '@' ; echo + done | sort | uniq -c + +rm ${fname_stem}*.pbm + +# Test 1. +echo "Test 2." + +pbmmake -g 2 5 | pamdice -height=1 -width=1 -outstem=${fname_stem} -plain +ls ${fname_stem}*.pbm | while read file + do + cat ${file} | tr '\n' '@' ; echo + done + +rm ${fname_stem}*.pbm + + +# Test Invalid. +echo "Test Invalid" + +echo 1>&2 +echo "Invalid command-line argument combinations." 1>&2 +echo "Error messages should appear below the line." 1>&2 +echo "-----------------------------------------------------------" 1>&2 + +# No input file +pamdice -width=10 -height=10 -outstem=${fname_stem} /dev/null || \ +echo "Expected failure 1" + +# No -outstem +pamdice -width=10 -height=10 testgrid.pbm || \ +echo "Expected failure 2" + +# -width=0 +pamdice -width=0 -height=10 -outstem=${fname_stem} testgrid.pbm || \ +echo "Expected failure 3" + +# -height=0 +pamdice -width=10 -height=0 -outstem=${fname_stem} testgrid.pbm || \ +echo "Expected failure 4" + +# -hoverlap larger than width +pamdice -width=10 -height=10 -hoverlap=11 \ + -outstem=${fname_stem} testgrid.pbm || \ +echo "Expected failure 5" + +# -voverlap larger than height +pamdice -width=10 -height=10 -voverlap=11 \ + -outstem=${fname_stem} testgrid.pbm || \ +echo "Expected failure 6" + + +# Ensure that no output files are produced by the above +ls ${fname_stem}* || \ +echo "Expected failure (output files)" \ No newline at end of file diff --git a/test/pamditherbw.ok b/test/pamditherbw.ok index 156b9f07..02200d0f 100644 --- a/test/pamditherbw.ok +++ b/test/pamditherbw.ok @@ -3,7 +3,6 @@ Test: simple threshold Test: Hilbert 3342429190 33894 2905156049 33894 -4294967295 0 339841328 33894 1633267750 33894 Test: Dither-8 @@ -26,3 +25,4 @@ Expected failure 8 1 Expected failure 9 1 Expected failure 10 1 Expected failure 11 1 +Expected failure 12 1 diff --git a/test/pamditherbw.test b/test/pamditherbw.test index 76e175d7..40eb0a4d 100755 --- a/test/pamditherbw.test +++ b/test/pamditherbw.test @@ -17,7 +17,6 @@ pamchannel -infile=testimg.ppm -tupletype="GRAYSCALE" 0 | pamtopnm | \ echo "Test: Hilbert" pamditherbw -hilbert ${test_red} | cksum pamditherbw -hilbert -clump=4 ${test_red} | cksum -pamditherbw -hilbert -clump=4 -threshold -value=0.5 ${test_red} | cksum pamditherbw -hilbert -clump=16 ${test_red} | cksum pamditherbw -hilbert -clump=100 ${test_red} | cksum @@ -59,15 +58,17 @@ pamditherbw -cluster3 -cluster8 ${test_red} > ${test_out} || \ echo -n "Expected failure 5"; test -s ${test_out}; echo " "$? pamditherbw -cluster4 -cluster8 ${test_red} > ${test_out} || \ echo -n "Expected failure 6"; test -s ${test_out}; echo " "$? -pamditherbw -clump=8 ${test_red} > ${test_out} || \ +pamditherbw -hilbert -threshold ${test_red} > ${test_out} || \ echo -n "Expected failure 7"; test -s ${test_out}; echo " "$? -pamditherbw -fs -clump=8 ${test_red} > ${test_out} || \ +pamditherbw -clump=8 ${test_red} > ${test_out} || \ echo -n "Expected failure 8"; test -s ${test_out}; echo " "$? -pamditherbw -hilbert -clump=1 ${test_red} > ${test_out} || \ +pamditherbw -fs -clump=8 ${test_red} > ${test_out} || \ echo -n "Expected failure 9"; test -s ${test_out}; echo " "$? -pamditherbw -th -value=-1 ${test_red} > ${test_out} || \ +pamditherbw -hilbert -clump=1 ${test_red} > ${test_out} || \ echo -n "Expected failure 10"; test -s ${test_out}; echo " "$? -pamditherbw -th -value=1.1 ${test_red} > ${test_out} || \ +pamditherbw -th -value=-1 ${test_red} > ${test_out} || \ echo -n "Expected failure 11"; test -s ${test_out}; echo " "$? +pamditherbw -th -value=1.1 ${test_red} > ${test_out} || \ + echo -n "Expected failure 12"; test -s ${test_out}; echo " "$? rm ${test_red} ${test_out} diff --git a/test/pamfind.test b/test/pamfind.test index 3b4ffb81..074dde5c 100755 --- a/test/pamfind.test +++ b/test/pamfind.test @@ -37,7 +37,7 @@ tmpdir=${tmpdir:-/tmp} test_out=${tmpdir}/test_out echo 1>&2 -echo "Invalid command-line argument combination." 1>&2 +echo "Invalid command-line argument combinations." 1>&2 echo "Error messages should appear below the line." 1>&2 echo "-----------------------------------------------------------" 1>&2 diff --git a/test/pamhue.ok b/test/pamhue.ok index dbef973d..5935cc5e 100644 --- a/test/pamhue.ok +++ b/test/pamhue.ok @@ -1,4 +1,7 @@ +Test 1 1213482165 83 +1213482165 83 +Test 2 Summary: 8 colors: 1 black, 1 white, 0 gray, 6 color r g b lum count @@ -23,3 +26,11 @@ 255 0 255 105 1 255 255 0 226 1 255 255 255 255 1 +Test 3 +0 0 : 0 +0 0 : 0 +Test 4 +0 0 : 0 +0 0 : 0 +Test Invalid +Expected failure 1 1 diff --git a/test/pamhue.test b/test/pamhue.test index 18240959..d81a0acb 100755 --- a/test/pamhue.test +++ b/test/pamhue.test @@ -2,9 +2,47 @@ # This script tests: pamhue # Also requires: pamseq ppmhist pamdepth +echo "Test 1" +# Should print 1213482165 83 twice + pamseq -tupletype=RGB 3 1 | pamdepth 255 | pamhue -huechange=60 | cksum +pamseq -tupletype=RGB 3 1 | pamdepth 255 | pamhue -huechange=-300 | cksum + +echo "Test 2" pamseq -tupletype=RGB 3 1 | pamdepth 255 | ppmhist -sort=rgb -pamseq -tupletype=RGB 3 1 | pamdepth 255 | pamhue -huechange=60 | ppmhist -sort=rgb +pamseq -tupletype=RGB 3 1 | pamdepth 255 | pamhue -huechange=60 | \ + ppmhist -sort=rgb + +echo "Test 3" +# pamhue has no effect on monotone images +# Should print 2425386270 41 twice + +pamhue -huechange=45 testgrid.pbm | cmp -s - testgrid.pbm + echo ${PIPESTATUS[@]} ":" $? +pamhue -huechange=180 testgrid.pbm | cmp -s - testgrid.pbm + echo ${PIPESTATUS[@]} ":" $? + +echo "Test 4" +# spinning the color wheel by multiples of 360 leaves the image unchanged +# Should print 1926073387 101484 twice + +pamhue -huechange=0 testimg.ppm | cmp -s - testimg.ppm + echo ${PIPESTATUS[@]} ":" $? +pamhue -huechange=360 testimg.ppm | cmp -s - testimg.ppm + echo ${PIPESTATUS[@]} ":" $? + +echo "Test Invalid" + +tmpdir=${tmpdir:-/tmp} +test_out=${tmpdir}/test_out + +echo 1>&2 +echo "Omission of mandatory argument." 1>&2 +echo "An error message should appear below the line." 1>&2 +echo "-----------------------------------------------------------" 1>&2 +pamhue testimg.ppm > ${test_out} || \ + echo -n "Expected failure 1"; test -s ${test_out}; echo " "$? +rm -f ${test_out} diff --git a/test/pamundice.ok b/test/pamundice.ok new file mode 100644 index 00000000..ef0f6e13 --- /dev/null +++ b/test/pamundice.ok @@ -0,0 +1,27 @@ +Test 1. +2096818803 2818 +2096818803 2818 +Test 2. +2096818803 2818 +2096818803 2818 +Test 3. +2096818803 2818 +2096818803 2818 +Test 4. +557392151 459 +557392151 459 +557392151 459 +557392151 459 +Test Invalid +Expected failure 1 1 +Expected failure 2 1 +Expected failure 3 1 +Expected failure 4 1 +Expected failure 5 1 +Expected failure 6 1 +Expected failure 7 1 +Expected failure 8 1 +Expected failure 9 1 +Expected failure 10 1 +Expected failure 11 1 +Expected failure 12 1 diff --git a/test/pamundice.test b/test/pamundice.test new file mode 100755 index 00000000..e8add587 --- /dev/null +++ b/test/pamundice.test @@ -0,0 +1,183 @@ +#! /bin/bash +# This script tests: pamundice +# Also requires: pgmmake pnmtile pnmcat pnmpad + +tmpdir=${tmpdir:-/tmp} +fname_stem=${tmpdir}/part + +# Test 1. +echo "Test 1." + +for ((x=0; x<3; ++x)) + do for ((y=0; y<5; ++y)) + do + pgmmake "."$(( x* 25 + y )) 11 17 > ${fname_stem}_${y}_${x}.pgm + done + done + +pamundice -across=3 -down=5 ${fname_stem}"_%1d_%1a".pgm | cksum + +ls ${fname_stem}_?_?.pgm | \ + pamundice -across=3 -down=5 -listfile=- | cksum + + +# Test 2. +echo "Test 2." + +tempfile=${tmpdir}/temp + +for ((y=0; y<5; ++y)) + do + pamundice -across=3 ${fname_stem}"_"$y"_%1a".pgm > ${tempfile}_"$y" + done + +pnmcat -tb ${tempfile}_[01234] | cksum +rm ${tempfile}_[01234] + +# Note: the following 2 are valid. There should not be warning messages. + +for ((x=0; x<3; ++x)) + do + pamundice -down=5 ${fname_stem}"_%1d_"$x.pgm > ${tempfile}"_"$x + done + +pnmcat -lr ${tempfile}_[012] | cksum +rm ${tempfile}_[012] + +rm ${fname_stem}_?_?.pgm + +# Test 3. +echo "Test 3." + +for ((x=0; x<2; ++x)) + do for ((y=0; y<5; ++y)) + do + pgmmake "."$(( x* 25 + y )) 12 17 > ${fname_stem}_${y}_${x}.pgm + done + done + +for ((x=2; x<3; ++x)) + do for ((y=0; y<5; ++y)) + do + pgmmake "."$(( x* 25 + y )) 11 17 > ${fname_stem}_${y}_${x}.pgm + done + done + +pamundice -across=3 -down=5 \ + -hoverlap=1 ${fname_stem}"_%1d_%1a".pgm | cksum + +rm ${fname_stem}_?_?.pgm + +for ((x=0; x<3; ++x)) + do for ((y=0; y<4; ++y)) + do + pgmmake "."$(( x* 25 + y )) 11 18 > ${fname_stem}_${y}_${x}.pgm + done + done + +for ((x=0; x<3; ++x)) + do for ((y=4; y<5; ++y)) + do + pgmmake "."$(( x* 25 + y )) 11 17 > ${fname_stem}_${y}_${x}.pgm + done + done + +pamundice -across=3 -down=5 \ + -voverlap=1 ${fname_stem}"_%1d_%1a".pgm | cksum + +rm ${fname_stem}_?_?.pgm + + +# Test 4. +echo "Test 4." + +# Add margins to testgrid.pbm + +testimg_pbm=${tmpdir}/testimg.pbm +pnmpad -top=2 -left=3 -black testgrid.pbm > ${testimg_pbm} + +for x in `seq 0 1` + do for y in `seq 0 4` + do cp ${testimg_pbm} ${fname_stem}_${y}_${x}.pbm; done + done + +for (( i=0 ; i<=9; ++i)) + do + echo ${testimg_pbm} + done | pamundice -down=5 -across=2 -listfile=- | cksum + +pamundice -down=5 -across=2 ${fname_stem}_"%1d"_"%1a".pbm | cksum + +echo "A warning message should appear below the line." 1>&2 +echo "-----------------------------------------------------------" 1>&2 + +pamundice -down=5 -across=2 ${testimg_pbm} | cksum + +pnmtile 34 90 ${testimg_pbm} | cksum + +rm ${testimg_pbm} + +# Test Invalid. +echo "Test Invalid" + +test_out=${tmpdir}/test_out + +echo 1>&2 +echo "Invalid command-line argument combinations." 1>&2 +echo "Error messages should appear below the line." 1>&2 +echo "-----------------------------------------------------------" 1>&2 + +# No input file pattern specified +pamundice -down=5 -across=2 > ${test_out} || \ +echo -n "Expected failure 1"; test -s ${test_out}; echo " "$? + +# -down=0 +pamundice -down=0 -across=2 ${fname_stem}_"%1d"_"%1a".pbm > ${test_out} || \ +echo -n "Expected failure 2"; test -s ${test_out}; echo " "$? + +# -across=0 +pamundice -down=5 -across=0 ${fname_stem}_"%1d"_"%1a".pbm > ${test_out} || \ +echo -n "Expected failure 3"; test -s ${test_out}; echo " "$? + +# -down too large +pamundice -down=6 -across=2 ${fname_stem}_"%1d"_"%1a".pbm > ${test_out} || \ +echo -n "Expected failure 4"; test -s ${test_out}; echo " "$? + +# -across too large +pamundice -down=5 -across=3 ${fname_stem}_"%1d"_"%1a".pbm > ${test_out} || \ +echo -n "Expected failure 5"; test -s ${test_out}; echo " "$? + +# precision does not match +pamundice -down=5 -across=2 ${fname_stem}_"%2d"_"%2a".pbm > ${test_out} || \ +echo -n "Expected failure 6"; test -s ${test_out}; echo " "$? + +# precision set to zero +pamundice -down=5 -across=2 ${fname_stem}_"%0d"_"%0a".pbm > ${test_out} || \ +echo -n "Expected failure 7"; test -s ${test_out}; echo " "$? + +# no precision +pamundice -down=5 -across=2 ${fname_stem}_"%d"_"%a".pbm > ${test_out} || \ +echo -n "Expected failure 8"; test -s ${test_out}; echo " "$? + +# -hoverlap too large +pamundice -down=5 -across=2 -hoverlap=18 \ + ${fname_stem}_"%1d"_"%1a".pbm > ${test_out} || \ +echo -n "Expected failure 9"; test -s ${test_out}; echo " "$? + +# -voverlap too large +pamundice -down=5 -across=2 -voverlap=19 \ + ${fname_stem}_"%1d"_"%1a".pbm > ${test_out} || \ +echo -n "Expected failure 10"; test -s ${test_out}; echo " "$? + +# corrupt listfile : file names do not exist +seq 10 | sed -e 's/^/::::::/' -e 's/$/::::::/' | \ + pamundice -down=5 -across=2 -listfile=- > ${test_out} || \ +echo -n "Expected failure 11"; test -s ${test_out}; echo " "$? + +# listfile with insufficient lines (insufficient file entries) +ls ${fname_stem}_*_*.pbm | head -n 9 | \ + pamundice -down=5 -across=2 -listfile=- > ${test_out} || \ +echo -n "Expected failure 12"; test -s ${test_out}; echo " "$? + +rm ${fname_stem}*.pbm + diff --git a/test/pbmclean.ok b/test/pbmclean.ok index 47d6c07d..17ee0338 100644 --- a/test/pbmclean.ok +++ b/test/pbmclean.ok @@ -84,3 +84,5 @@ Test 3 2571756059 5051 436062787 5051 4188415575 5051 +Test Invalid +Expected failure 1 1 diff --git a/test/pbmclean.test b/test/pbmclean.test index b9ea0937..c0c3a759 100755 --- a/test/pbmclean.test +++ b/test/pbmclean.test @@ -34,3 +34,20 @@ for n in 1 2 3 4 5 6 7 8 9 10 done rm ${sheet_pbm} + +echo "Test Invalid" + +test_out=${tmpdir}/test_out + +echo 1>&2 +echo "Invalid command-line argument combination." 1>&2 +echo "An error message should appear below the line." 1>&2 +echo "-----------------------------------------------------------" 1>&2 + +# overspecification +pbmclean -black -white -min=1 -extended testgrid.pbm > ${test_out} || \ + echo -n "Expected failure 1"; test -s ${test_out}; echo " "$? + +# note that without -extended the above is valid. + +rm -f ${test_out} \ No newline at end of file diff --git a/test/pbmpscale.ok b/test/pbmpscale.ok index e25d4027..c26ffef3 100644 --- a/test/pbmpscale.ok +++ b/test/pbmpscale.ok @@ -48,3 +48,6 @@ P1 2150868536 457 3761734242 1065 3462719777 1803 +Expected failure 1 1 +Expected failure 2 1 +Expected failure 3 1 diff --git a/test/pbmpscale.test b/test/pbmpscale.test index 42046c74..9c34734a 100755 --- a/test/pbmpscale.test +++ b/test/pbmpscale.test @@ -10,3 +10,21 @@ do pamenlarge 2 testgrid.pbm | \ pbmpscale $i | cksum done + +test_out=${tmpdir}/test_out + +echo 1>&2 +echo "Invalid command-line argument combinations." 1>&2 +echo "Error messages should appear below the line." 1>&2 +echo "-----------------------------------------------------------" 1>&2 + +pbmpscale testgrid.pbm > ${test_out} || \ + echo -n "Expected failure 1"; test -s ${test_out}; echo " "$? + +pbmpscale 0 testgrid.pbm > ${test_out} || \ + echo -n "Expected failure 2"; test -s ${test_out}; echo " "$? + +pbmpscale 2 3 testgrid.pbm > ${test_out} || \ + echo -n "Expected failure 3"; test -s ${test_out}; echo " "$? + +rm -f ${test_out} \ No newline at end of file diff --git a/test/pbmtext.test b/test/pbmtext.test index fdecf453..515711e4 100755 --- a/test/pbmtext.test +++ b/test/pbmtext.test @@ -53,7 +53,7 @@ done # Test 4: Should print 1647614653 2027 three times -# Note: backslashes inserted in 3 locations in the rectange to make +# Note: backslashes inserted in 3 locations in the rectangle to make # possible input as a here document. fontRectangle_txt=${tmpdir}/fontRectangle.txt diff --git a/test/pbmtopgm.ok b/test/pbmtopgm.ok new file mode 100644 index 00000000..6ccf9c64 --- /dev/null +++ b/test/pbmtopgm.ok @@ -0,0 +1,25 @@ +Test 1 +P2 +14 16 +1 +0 1 0 1 0 1 0 1 0 1 0 1 0 1 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 1 0 1 0 1 0 1 0 1 0 1 0 1 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 1 0 1 0 1 0 1 0 1 0 1 0 1 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 1 0 1 0 1 0 1 0 1 0 1 0 1 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 1 0 1 0 1 0 1 0 1 0 1 0 1 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 1 0 1 0 1 0 1 0 1 0 1 0 1 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 1 0 1 0 1 0 1 0 1 0 1 0 1 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 1 0 1 0 1 0 1 0 1 0 1 0 1 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 +Test Invalid +Expected failure 1 1 +Expected failure 2 1 +Expected failure 3 1 +Expected failure 4 1 diff --git a/test/pbmtopgm.test b/test/pbmtopgm.test new file mode 100755 index 00000000..a7ba6f7c --- /dev/null +++ b/test/pbmtopgm.test @@ -0,0 +1,32 @@ +#! /bin/bash +# This script tests: pbmtopgm +# Also requires: + +#Test 1 +echo "Test 1" + +pbmtopgm -plain 1 1 testgrid.pbm + +echo "Test Invalid" + +tmpdir=${tmpdir:-/tmp} +test_out=${tmpdir}/test_out + +echo 1>&2 +echo "Invalid command-line argument combinations." 1>&2 +echo "Error messages should appear below the line." 1>&2 +echo "-----------------------------------------------------------" 1>&2 + +pbmtopgm 5 0 testgrid.pbm > ${test_out} || \ + echo -n "Expected failure 1"; test -s ${test_out}; echo " "$? + +pbmtopgm 0 9 testgrid.pbm > ${test_out} || \ + echo -n "Expected failure 2"; test -s ${test_out}; echo " "$? + +pbmtopgm 15 5 testgrid.pbm > ${test_out} || \ + echo -n "Expected failure 3"; test -s ${test_out}; echo " "$? + +pbmtopgm 5 17 testgrid.pbm > ${test_out} || \ + echo -n "Expected failure 4"; test -s ${test_out}; echo " "$? + +rm -f ${test_out} diff --git a/test/pgmminkowski.ok b/test/pgmminkowski.ok new file mode 100644 index 00000000..86f43207 --- /dev/null +++ b/test/pgmminkowski.ok @@ -0,0 +1,17 @@ +#threshold tiles x-edges y-edges vertices +#--------- ----- ------- ------- -------- +0.000000 9 12 12 16 1 1 1 +0.501961 1 2 2 4 0.111111 0.333333 1 +# check: 0 0 0 0 + +#threshold tiles x-edges y-edges vertices +#--------- ----- ------- ------- -------- +0.000000 9 12 12 16 1 1 1 +1.000000 5 10 10 16 0.555556 1.66667 1 +# check: 0 0 0 0 + +#threshold tiles x-edges y-edges vertices +#--------- ----- ------- ------- -------- +0.000000 224 240 238 255 1 1 1 +1.000000 56 112 112 224 0.25 3.73333 56 +# check: 0 0 0 0 diff --git a/test/pgmminkowski.test b/test/pgmminkowski.test new file mode 100755 index 00000000..52e02e19 --- /dev/null +++ b/test/pgmminkowski.test @@ -0,0 +1,10 @@ +#! /bin/bash +# This script tests: pgmminkowski +# Also requires: pbmmake pgmmake pnmmargin pnmpad + +pgmmake .5 1 1 | pnmmargin -b 1 | \ + pgmminkowski +echo +pbmmake -g 3 3 | pgmminkowski +echo +pgmminkowski testgrid.pbm diff --git a/test/pgmnoise-parameters.ok b/test/pgmnoise-parameters.ok new file mode 100644 index 00000000..1bb1cd59 --- /dev/null +++ b/test/pgmnoise-parameters.ok @@ -0,0 +1,5 @@ +Expected failure 1 1 +Expected failure 2 1 +Expected failure 3 1 +Expected failure 4 1 +Expected failure 5 1 diff --git a/test/pgmnoise-parameters.test b/test/pgmnoise-parameters.test new file mode 100755 index 00000000..1682afca --- /dev/null +++ b/test/pgmnoise-parameters.test @@ -0,0 +1,26 @@ +#! /bin/bash +# This script tests: pgmnoise +# Also requires: + +tmpdir=${tmpdir:-/tmp} +test_out=${tmpdir}/test_out + +echo 1>&2 +echo "Invalid command-line argument combinations." 1>&2 +echo "Error messages should appear below the line." 1>&2 +echo "-----------------------------------------------------------" 1>&2 + +pgmnoise -maxval=255 -randomseed=1 > ${test_out} || \ + echo -n "Expected failure 1"; test -s ${test_out}; echo " "$? + +pgmnoise 100 -randomseed=1 > ${test_out} || \ + echo -n "Expected failure 2"; test -s ${test_out}; echo " "$? + +pgmnoise 100 0 -randomseed=1 > ${test_out} || \ + echo -n "Expected failure 3"; test -s ${test_out}; echo " "$? + +pgmnoise 0 100 -randomseed=1 > ${test_out} || \ + echo -n "Expected failure 4"; test -s ${test_out}; echo " "$? + +pgmnoise 100 100 100 -randomseed=1 > ${test_out} || \ + echo -n "Expected failure 5"; test -s ${test_out}; echo " "$? diff --git a/test/pnmcat.ok b/test/pnmcat.ok index 68052957..b92a1420 100644 --- a/test/pnmcat.ok +++ b/test/pnmcat.ok @@ -1,4 +1,20 @@ +Test 1. 1704087873 73 4150323653 73 1522490272 202953 2862441566 202953 +Test Invalid +Expected failure 1 1 +Expected failure 2 1 +Expected failure 3 1 +Expected failure 4 1 +Expected failure 5 1 +Expected failure 6 1 +Expected failure 7 1 +Expected failure 8 1 +Expected failure 9 1 +Expected failure 10 1 +Expected failure 11 1 +Expected failure 12 1 +Expected failure 13 1 +Expected failure 14 1 diff --git a/test/pnmcat.test b/test/pnmcat.test index c643320d..40c29f50 100755 --- a/test/pnmcat.test +++ b/test/pnmcat.test @@ -2,9 +2,70 @@ # This script tests: pnmcat # Also requires: +echo "Test 1." pnmcat -lr testgrid.pbm testgrid.pbm | cksum pnmcat -tb testgrid.pbm testgrid.pbm | cksum pnmcat -lr testimg.ppm testimg.ppm | cksum pnmcat -tb testimg.ppm testimg.ppm | cksum + +echo "Test Invalid" + +tmpdir=${tmpdir:-/tmp} +test_out=${tmpdir}/test_out + +echo 1>&2 +echo "Invalid command-line argument combinations." 1>&2 +echo "Error messages should appear below the line." 1>&2 +echo "-----------------------------------------------------------" 1>&2 + +# direction not specified +pnmcat testgrid.pbm testimg.ppm > ${test_out} || \ + echo -n "Expected failure 1"; test -s ${test_out}; echo " "$? + +# both directions specified +pnmcat -topbottom -leftright testgrid.pbm testimg.ppm > ${test_out} || \ + echo -n "Expected failure 2"; test -s ${test_out}; echo " "$? + +# both pad colors specified +pnmcat -topbottom -white -black testgrid.pbm testimg.ppm > ${test_out} || \ + echo -n "Expected failure 3"; test -s ${test_out}; echo " "$? + +# justification parameters overspecified +pnmcat -lr -jtop -jbottom testgrid.pbm testimg.ppm > ${test_out} || \ + echo -n "Expected failure 4"; test -s ${test_out}; echo " "$? + +pnmcat -lr -jtop -jcenter testgrid.pbm testimg.ppm > ${test_out} || \ + echo -n "Expected failure 5"; test -s ${test_out}; echo " "$? + +pnmcat -lr -jcenter -jbottom testgrid.pbm testimg.ppm > ${test_out} || \ + echo -n "Expected failure 6"; test -s ${test_out}; echo " "$? + +pnmcat -tb -jleft -jright testgrid.pbm testimg.ppm > ${test_out} || \ + echo -n "Expected failure 7"; test -s ${test_out}; echo " "$? + +pnmcat -tb -jleft -jcenter testgrid.pbm testimg.ppm > ${test_out} || \ + echo -n "Expected failure 8"; test -s ${test_out}; echo " "$? + +pnmcat -tb -jcenter -jright testgrid.pbm testimg.ppm > ${test_out} || \ + echo -n "Expected failure 9"; test -s ${test_out}; echo " "$? + +# justification parameter in the wrong direction +pnmcat -lr -jleft testgrid.pbm testimg.ppm > ${test_out} || \ + echo -n "Expected failure 10"; test -s ${test_out}; echo " "$? + +pnmcat -lr -jright testgrid.pbm testimg.ppm > ${test_out} || \ + echo -n "Expected failure 11"; test -s ${test_out}; echo " "$? + +pnmcat -tb -jtop testgrid.pbm testimg.ppm > ${test_out} || \ + echo -n "Expected failure 12"; test -s ${test_out}; echo " "$? + +pnmcat -tb -jbottom testgrid.pbm testimg.ppm > ${test_out} || \ + echo -n "Expected failure 13"; test -s ${test_out}; echo " "$? + +# more than one input image from standard input +cat testgrid.pbm | pnmcat -lr - - testimg.ppm > ${test_out} || \ + echo -n "Expected failure 14"; test -s ${test_out}; echo " "$? + +rm -f ${test_out} diff --git a/test/pnmquantall.ok b/test/pnmquantall.ok index 172eb0aa..5885d370 100644 --- a/test/pnmquantall.ok +++ b/test/pnmquantall.ok @@ -1,5 +1,9 @@ -got color map 2373957371 33838 3892560659 33838 1383839923 33838 1 +Expected failure 1 +Expected failure 1.rm +Expected failure 2 +Expected failure 2.rm +Expected failure 3 diff --git a/test/pnmquantall.test b/test/pnmquantall.test index b735b623..4c1bb77f 100755 --- a/test/pnmquantall.test +++ b/test/pnmquantall.test @@ -24,4 +24,24 @@ done pnmcat ${test_red} ${test_grn} ${test_blu} -tb | \ pgmhist -m | awk '$2>0 {s++}; END { print (s<=20) }' + +tmpdir=${tmpdir:-/tmp} +test_out=${tmpdir}/test_out + +echo 1>&2 +echo "Invalid command-line argument combinations." 1>&2 +echo "Error messages should appear below the line." 1>&2 +echo "-----------------------------------------------------------" 1>&2 + +pnmquantall -ext xx 0 ${test_red} ${test_grn} ${test_blu} || \ + echo "Expected failure 1" +rm ${test_red}xx ${test_grn}xx ${test_blu}xx || \ + echo "Expected failure 1.rm" +pnmquantall -ext xx 1 ${test_red} ${test_grn} ${test_blu} || \ + echo "Expected failure 2" +rm ${test_red}xx ${test_grn}xx ${test_blu}xx || \ + echo "Expected failure 2.rm" +pnmquantall -ext xx 2 || \ + echo "Expected failure 3" + rm ${test_red} ${test_grn} ${test_blu} ${test_ppm} \ No newline at end of file diff --git a/test/pnmtile.ok b/test/pnmtile.ok index 4a29e0dc..279251b8 100644 --- a/test/pnmtile.ok +++ b/test/pnmtile.ok @@ -1,2 +1,6 @@ 4228632379 259 0 0 : 0 +Expected failure 1 1 +Expected failure 2 1 +Expected failure 3 1 +Expected failure 4 1 diff --git a/test/pnmtile.test b/test/pnmtile.test index e297da66..11f576bd 100755 --- a/test/pnmtile.test +++ b/test/pnmtile.test @@ -20,3 +20,24 @@ cmp -s - ${testimg4_ppm} echo ${PIPESTATUS[@]} ":" $? rm ${testimg2_ppm} ${testimg4_ppm} + +test_out=${tmpdir}/test_out + +echo 1>&2 +echo "Invalid command-line argument combinations." 1>&2 +echo "Error messages should appear below the line." 1>&2 +echo "-----------------------------------------------------------" 1>&2 + +pnmtile 100 testgrid.pbm > ${test_out} || \ + echo -n "Expected failure 1"; test -s ${test_out}; echo " "$? + +pnmtile 100 0 testgrid.pbm > ${test_out} || \ + echo -n "Expected failure 2"; test -s ${test_out}; echo " "$? + +pnmtile 0 100 testgrid.pbm > ${test_out} || \ + echo -n "Expected failure 3"; test -s ${test_out}; echo " "$? + +pnmtile 100 100 100 testgrid.pbm > ${test_out} || \ + echo -n "Expected failure 4"; test -s ${test_out}; echo " "$? + +rm -f ${test_out} \ No newline at end of file diff --git a/test/ppmwheel.ok b/test/ppmwheel.ok index 24756d1e..0b0a7746 100644 --- a/test/ppmwheel.ok +++ b/test/ppmwheel.ok @@ -1,2 +1,8 @@ +Test 1. 1537578995 59 875938089 86 +Test Invalid. +Expected failure 1 1 +Expected failure 2 1 +Expected failure 3 1 +Expected failure 4 1 diff --git a/test/ppmwheel.test b/test/ppmwheel.test index f528e209..fd401951 100755 --- a/test/ppmwheel.test +++ b/test/ppmwheel.test @@ -6,6 +6,8 @@ # For values 6 and above, x86(-32) and x86-64 produce different output. # SSE floating-point math is the probable cause. +echo "Test 1." + for i in 4 5 do ppmwheel $i | cksum @@ -108,3 +110,27 @@ done # 98: 4086203619 28825 1961862620 28825 # 99: 3656777902 29416 2475351252 29416 # 100: 2246720411 30015 4055518595 30015 + +echo "Test Invalid." + +tmpdir=${tmpdir:-/tmp} +test_out=${tmpdir}/test_out + +echo 1>&2 +echo "Invalid command-line argument combinations." 1>&2 +echo "Error messages should appear below the line." 1>&2 +echo "-----------------------------------------------------------" 1>&2 + +ppmwheel 10 -huevalue -huesaturation > ${test_out} || \ + echo -n "Expected failure 1"; test -s ${test_out}; echo " "$? + +ppmwheel 0 > ${test_out} || \ + echo -n "Expected failure 2"; test -s ${test_out}; echo " "$? + +ppmwheel > ${test_out} || \ + echo -n "Expected failure 3"; test -s ${test_out}; echo " "$? + +ppmwheel 10 10 > ${test_out} || \ + echo -n "Expected failure 4"; test -s ${test_out}; echo " "$? + +rm -f ${test_out} \ No newline at end of file diff --git a/test/ps-alt-roundtrip.test b/test/ps-alt-roundtrip.test index af7f7222..8fc08f2b 100755 --- a/test/ps-alt-roundtrip.test +++ b/test/ps-alt-roundtrip.test @@ -5,7 +5,7 @@ # This script is for testing alternative (or minor) utilities that # read/write Postscript and encapsulated Postscript: -# pbmtoepsi, pbmtopsg3, pbmtolps and psidtopgm. +# pbmtoepsi, pbmtopsg3 and psidtopgm. # # We keep these tests separate from those for pnmtops and pstopnm # which are far more popular. diff --git a/test/ps-flate-roundtrip.test b/test/ps-flate-roundtrip.test index de1105f0..08d1500c 100755 --- a/test/ps-flate-roundtrip.test +++ b/test/ps-flate-roundtrip.test @@ -5,7 +5,7 @@ # This script tests the optional flate (zlib) compression feature of # pstopnm. # Flate compression allows you to make smaller output (.ps) files: -# it is useful, but not essential. Flate compression is not neccessary for +# it is useful, but not essential. Flate compression is not necessary for # printing pages with postscript printers - which is why many people need # pnmtops on their systems. diff --git a/urt/rle_open_f.c b/urt/rle_open_f.c index ae8548b9..1aeb6448 100644 --- a/urt/rle_open_f.c +++ b/urt/rle_open_f.c @@ -1,7 +1,7 @@ -/* +/* * rle_open_f.c - Open a file with defaults. - * - * Author : Jerry Winters + * + * Author : Jerry Winters * EECS Dept. * University of Michigan * Date: 11/14/89 @@ -37,8 +37,8 @@ static FILE * -my_popen(const char * const cmd, - const char * const mode, +my_popen(const char * const cmd, + const char * const mode, int * const pid) { FILE *retfile; @@ -55,7 +55,7 @@ my_popen(const char * const cmd, if (pm_pipe(pipefd) < 0 ) return NULL; - + /* Flush known files. */ fflush(stdout); fflush(stderr); @@ -86,7 +86,7 @@ my_popen(const char * const cmd, if ( execl("/bin/sh", "sh", "-c", cmd, NULL) < 0 ) exit(127); /* NOTREACHED */ - } + } /* Close file descriptors, and gen up a FILE ptr */ if ( *mode == 'r' ) @@ -173,10 +173,10 @@ dealWithSubprocess(const char * const file_name, /* Real file, not stdin or stdout. If name ends in ".Z", * pipe from/to un/compress (depending on r/w mode). - * + * * If it starts with "|", popen that command. */ - + cp = file_name + strlen(file_name) - 2; /* Pipe case. */ if (file_name[0] == '|') { @@ -198,14 +198,14 @@ dealWithSubprocess(const char * const file_name, const char * command; *noSubprocessP = FALSE; - + if (*mode == 'w') pm_asprintf(&command, "compress > %s", file_name); else if (*mode == 'a') pm_asprintf(&command, "compress >> %s", file_name); else pm_asprintf(&command, "compress -d < %s", file_name); - + *fpP = my_popen(command, mode, &thepid); if (*fpP == NULL) @@ -227,8 +227,8 @@ dealWithSubprocess(const char * const file_name, -/* - * Purpose : Open a file for input or ouput as controlled by the mode +/* + * Purpose : Open a file for input or output as controlled by the mode * parameter. If no file name is specified (ie. file_name is null) then * a pointer to stdin or stdout will be returned. The calling routine may * call this routine with a file name of "-". For this case rle_open_f @@ -246,11 +246,11 @@ dealWithSubprocess(const char * const file_name, * * output: * a file pointer - * + * */ FILE * -rle_open_f_noexit(const char * const prog_name, - const char * const file_name, +rle_open_f_noexit(const char * const prog_name, + const char * const file_name, const char * const mode ) { FILE * retval; @@ -265,12 +265,12 @@ rle_open_f_noexit(const char * const prog_name, fp = stdout; /* Set the default value */ else fp = stdin; - + if (file_name != NULL && !streq(file_name, "-")) { bool noSubprocess; dealWithSubprocess(file_name, mode, &catching_children, pids, &fp, &noSubprocess, &err_str); - + if (!err_str) { if (noSubprocess) { /* Ordinary, boring file case. */ @@ -286,7 +286,7 @@ rle_open_f_noexit(const char * const prog_name, mode_string[0] = mode[0]; mode_string[1] = 'b'; strcpy( mode_string + 2, mode + 1 ); - + fp = fopen(file_name, mode_string); if (fp == NULL ) err_str = "%s: can't open %s for %s: "; @@ -325,7 +325,7 @@ rle_open_f(const char * prog_name, const char * file_name, const char * mode) /***************************************************************** * TAG( rle_close_f ) - * + * * Close a file opened by rle_open_f. If the file is stdin or stdout, * it will not be closed. * Inputs: @@ -347,3 +347,6 @@ rle_close_f( fd ) else fclose( fd ); } + + + diff --git a/urt/vaxshort.c b/urt/vaxshort.c index 4b57b516..9a83cecb 100644 --- a/urt/vaxshort.c +++ b/urt/vaxshort.c @@ -8,14 +8,14 @@ * * Author - * Michael John Muuss - * + * * Source - * SECAD/VLD Computing Consortium, Bldg 394 * The U. S. Army Ballistic Research Laboratory * Aberdeen Proving Ground, Maryland 21005-5066 - * + * * Distribution Status - - * Public Domain, Distribution Unlimitied. + * Public Domain, Distribution Unlimited. */ #include "vaxshort.h" @@ -48,3 +48,6 @@ vax_pshort(char *msgp, unsigned short s) msgp[1] = s >> 8; return(msgp+2); } + + + diff --git a/version.mk b/version.mk index 03e242d2..d5cf97ad 100644 --- a/version.mk +++ b/version.mk @@ -1,3 +1,3 @@ NETPBM_MAJOR_RELEASE = 10 -NETPBM_MINOR_RELEASE = 89 -NETPBM_POINT_RELEASE = 3 +NETPBM_MINOR_RELEASE = 90 +NETPBM_POINT_RELEASE = 0 -- cgit 1.4.1